Code optimalisations.

This commit is contained in:
James Cole
2018-07-05 21:18:53 +02:00
parent 1675a0d442
commit c99b7e927d
26 changed files with 216 additions and 150 deletions

View File

@@ -42,6 +42,7 @@ use Storage;
class CreateExport extends Command
{
use VerifiesAccessToken;
/**
* The console command description.
*
@@ -66,7 +67,7 @@ class CreateExport extends Command
*
* @return mixed
*/
public function handle()
public function handle(): int
{
if (!$this->verifyAccessToken()) {
$this->error('Invalid access token.');
@@ -86,6 +87,9 @@ class CreateExport extends Command
// set user
$user = $userRepository->findNull((int)$this->option('user'));
if (null === $user) {
return 1;
}
$jobRepository->setUser($user);
$journalRepository->setUser($user);
$accountRepository->setUser($user);

View File

@@ -81,10 +81,15 @@ class CreateImport extends Command
$configuration = (string)$this->argument('configuration');
$user = $userRepository->findNull((int)$this->option('user'));
$cwd = getcwd();
$type = strtolower((string)$this->option('type'));
$provider = strtolower((string)$this->option('provider'));
$configurationData = [];
if (null === $user) {
$this->errorLine('User is NULL.');
return 1;
}
if (!$this->validArguments()) {
$this->errorLine('Invalid arguments.');
@@ -182,7 +187,7 @@ class CreateImport extends Command
}
$count++;
}
if ($importJob->status === 'provider_finished') {
if ('provider_finished' === $importJob->status) {
$this->infoLine('Import has finished. Please wait for storage of data.');
// set job to be storing data:
$jobRepository->setStatus($importJob, 'storing_data');
@@ -274,19 +279,19 @@ class CreateImport extends Command
return false;
}
if ($provider === 'file' && !\in_array($type, $validTypes, true)) {
if ('file' === $provider && !\in_array($type, $validTypes, true)) {
$this->errorLine(sprintf('Cannot import file of type "%s"', $type));
return false;
}
if ($provider === 'file' && !file_exists($file)) {
if ('file' === $provider && !file_exists($file)) {
$this->errorLine(sprintf('Firefly III cannot find file "%s" (working directory: "%s").', $file, $cwd));
return false;
}
if ($provider === 'file' && !file_exists($configuration)) {
if ('file' === $provider && !file_exists($configuration)) {
$this->errorLine(sprintf('Firefly III cannot find configuration file "%s" (working directory: "%s").', $configuration, $cwd));
return false;

View File

@@ -52,7 +52,7 @@ class DecryptAttachment extends Command
/**
* Execute the console command.
*/
public function handle()
public function handle(): void
{
/** @var AttachmentRepositoryInterface $repository */
$repository = app(AttachmentRepositoryInterface::class);

View File

@@ -1,4 +1,4 @@
<?php
<?php /** @noinspection PhpDynamicAsStaticMethodCallInspection */
/**
* Import.php
@@ -27,8 +27,8 @@ namespace FireflyIII\Console\Commands;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Routine\RoutineInterface;
use FireflyIII\Models\ImportJob;
use FireflyIII\Models\Tag;
use Illuminate\Console\Command;
use Illuminate\Support\MessageBag;
use Log;
/**
@@ -55,7 +55,7 @@ class Import extends Command
*
* @throws FireflyException
*/
public function handle()
public function handle(): void
{
Log::debug('Start start-import command');
$jobKey = $this->argument('key');
@@ -83,17 +83,25 @@ class Import extends Command
/** @var RoutineInterface $routine */
$routine = app($className);
$routine->setJob($job);
$routine->setImportJob($job);
$routine->run();
/** @var MessageBag $error */
foreach ($routine->getErrors() as $index => $error) {
/**
* @var int $index
* @var string $error
*/
foreach ($job->errors as $index => $error) {
$this->errorLine(sprintf('Error importing line #%d: %s', $index, $error));
}
$this->infoLine(
sprintf('The import has finished. %d transactions have been imported out of %d records.', $routine->getJournals()->count(), $routine->getLines())
);
/** @var Tag $tag */
$tag = $job->tag()->first();
$count = 0;
if (null === $tag) {
$count = $tag->transactionJournals()->count();
}
$this->infoLine(sprintf('The import has finished. %d transactions have been imported.', $count));
}

View File

@@ -1,4 +1,4 @@
<?php
<?php /** @noinspection PhpDynamicAsStaticMethodCallInspection */
/**
* ScanAttachments.php
@@ -53,7 +53,7 @@ class ScanAttachments extends Command
/**
* Execute the console command.
*/
public function handle()
public function handle(): void
{
$attachments = Attachment::get();
$disk = Storage::disk('upload');

View File

@@ -1,4 +1,5 @@
<?php
<?php /** @noinspection PhpStaticAsDynamicMethodCallInspection */
/** @noinspection PhpDynamicAsStaticMethodCallInspection */
/**
* UpgradeDatabase.php
@@ -42,7 +43,9 @@ use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionJournalMeta;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
@@ -50,6 +53,7 @@ use Illuminate\Support\Collection;
use Log;
use Preferences;
use Schema;
use UnexpectedValueException;
/**
* Class UpgradeDatabase.
@@ -74,7 +78,7 @@ class UpgradeDatabase extends Command
/**
* Execute the console command.
*/
public function handle()
public function handle(): void
{
$this->setTransactionIdentifier();
$this->updateAccountCurrencies();
@@ -90,7 +94,7 @@ class UpgradeDatabase extends Command
$this->info('Firefly III database is up to date.');
}
public function migrateBillsToRules()
public function migrateBillsToRules(): void
{
foreach (User::get() as $user) {
/** @var Preference $lang */
@@ -98,12 +102,17 @@ class UpgradeDatabase extends Command
$groupName = (string)trans('firefly.rulegroup_for_bills_title', [], $lang->data);
$ruleGroup = $user->ruleGroups()->where('title', $groupName)->first();
$currencyPreference = Preferences::getForUser($user, 'currencyPreference', config('firefly.default_currency', 'EUR'));
$currency = TransactionCurrency::where('code', $currencyPreference->data)->first();
if (null === $currencyPreference) {
return;
}
$currency = TransactionCurrency::where('code', $currencyPreference->data)->first();
if (null === $currency) {
$currency = app('amount')->getDefaultCurrency();
}
if ($ruleGroup === null) {
if (null === $ruleGroup) {
$array = RuleGroup::get(['order'])->pluck('order')->toArray();
$order = \count($array) > 0 ? max($array) + 1 : 1;
$ruleGroup = RuleGroup::create(
@@ -123,7 +132,7 @@ class UpgradeDatabase extends Command
$collection = $user->bills()->get();
/** @var Bill $bill */
foreach ($collection as $bill) {
if ($bill->match !== 'MIGRATED_TO_RULES') {
if ('MIGRATED_TO_RULES' !== $bill->match) {
$rule = Rule::create(
[
'user_id' => $user->id,
@@ -261,16 +270,22 @@ class UpgradeDatabase extends Command
{
$accounts = Account::leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->whereIn('account_types.type', [AccountType::DEFAULT, AccountType::ASSET])->get(['accounts.*']);
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$accounts->each(
function (Account $account) {
function (Account $account) use ($repository) {
$repository->setUser($account->user);
// get users preference, fall back to system pref.
$defaultCurrencyCode = Preferences::getForUser($account->user, 'currencyPreference', config('firefly.default_currency', 'EUR'))->data;
$defaultCurrency = TransactionCurrency::where('code', $defaultCurrencyCode)->first();
$accountCurrency = (int)$account->getMeta('currency_id');
$accountCurrency = (int)$repository->getMetaValue($account, 'currency_id');
$openingBalance = $account->getOpeningBalance();
$obCurrency = (int)$openingBalance->transaction_currency_id;
if (null === $defaultCurrency) {
throw new UnexpectedValueException('The default currency is NULL, and this is more or less impossible.');
}
// both 0? set to default currency:
if (0 === $accountCurrency && 0 === $obCurrency) {
AccountMeta::where('account_id', $account->id)->where('name', 'currency_id')->forceDelete();
@@ -315,13 +330,15 @@ class UpgradeDatabase extends Command
{
/** @var CurrencyRepositoryInterface $repository */
$repository = app(CurrencyRepositoryInterface::class);
$set = TransactionJournal
/** @var AccountRepositoryInterface $accountRepos */
$accountRepos = app(AccountRepositoryInterface::class);
$set = TransactionJournal
::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->whereIn('transaction_types.type', [TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE])
->get(['transaction_journals.*']);
$set->each(
function (TransactionJournal $journal) use ($repository) {
function (TransactionJournal $journal) use ($repository, $accountRepos) {
// get the transaction with the asset account in it:
/** @var Transaction $transaction */
$transaction = $journal->transactions()
@@ -331,9 +348,13 @@ class UpgradeDatabase extends Command
if (null === $transaction) {
return;
}
$accountRepos->setUser($journal->user);
/** @var Account $account */
$account = $transaction->account;
$currency = $repository->find((int)$account->getMeta('currency_id'));
$account = $transaction->account;
$currency = $repository->findNull((int)$accountRepos->getMetaValue($account, 'currency_id'));
if (null === $currency) {
return;
}
$transactions = $journal->transactions()->get();
$transactions->each(
function (Transaction $transaction) use ($currency) {
@@ -369,7 +390,7 @@ class UpgradeDatabase extends Command
* Both source and destination must match the respective currency preference. So FF3 must verify ALL
* transactions.
*/
public function updateTransferCurrencies()
public function updateTransferCurrencies(): void
{
$set = TransactionJournal
::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
@@ -441,6 +462,7 @@ class UpgradeDatabase extends Command
*/
private function migrateNotes(): void
{
/** @noinspection PhpUndefinedMethodInspection */
$set = TransactionJournalMeta::whereName('notes')->get();
/** @var TransactionJournalMeta $meta */
foreach ($set as $meta) {
@@ -471,8 +493,15 @@ class UpgradeDatabase extends Command
{
/** @var CurrencyRepositoryInterface $repository */
$repository = app(CurrencyRepositoryInterface::class);
$currency = $repository->find((int)$transaction->account->getMeta('currency_id'));
$journal = $transaction->transactionJournal;
/** @var AccountRepositoryInterface $accountRepos */
$accountRepos = app(AccountRepositoryInterface::class);
$accountRepos->setUser($transaction->account->user);
$currency = $repository->findNull((int)$accountRepos->getMetaValue($transaction->account, 'currency_id'));
$journal = $transaction->transactionJournal;
if (null === $currency) {
return;
}
if (!((int)$currency->id === (int)$journal->transaction_currency_id)) {
$this->line(
@@ -549,7 +578,14 @@ class UpgradeDatabase extends Command
{
/** @var CurrencyRepositoryInterface $repository */
$repository = app(CurrencyRepositoryInterface::class);
$currency = $repository->findNull((int)$transaction->account->getMeta('currency_id'));
/** @var AccountRepositoryInterface $accountRepos */
$accountRepos = app(AccountRepositoryInterface::class);
/** @var JournalRepositoryInterface $journalRepos */
$journalRepos = app(JournalRepositoryInterface::class);
$accountRepos->setUser($transaction->account->user);
$journalRepos->setUser($transaction->account->user);
$currency = $repository->findNull((int)$accountRepos->getMetaValue($transaction->account, 'currency_id'));
if (null === $currency) {
Log::error(sprintf('Account #%d ("%s") must have currency preference but has none.', $transaction->account->id, $transaction->account->name));
@@ -585,7 +621,7 @@ class UpgradeDatabase extends Command
$journal = $transaction->transactionJournal;
/** @var Transaction $opposing */
$opposing = $journal->transactions()->where('amount', '>', 0)->where('identifier', $transaction->identifier)->first();
$opposingCurrency = $repository->findNull((int)$opposing->account->getMeta('currency_id'));
$opposingCurrency = $repository->findNull((int)$accountRepos->getMetaValue($opposing->account, 'currency_id'));
if (null === $opposingCurrency) {
Log::error(sprintf('Account #%d ("%s") must have currency preference but has none.', $opposing->account->id, $opposing->account->name));
@@ -641,7 +677,7 @@ class UpgradeDatabase extends Command
// when both are zero, try to grab it from journal:
if (null === $opposing->foreign_amount && null === $transaction->foreign_amount) {
$foreignAmount = $journal->getMeta('foreign_amount');
$foreignAmount = $journalRepos->getMetaField($journal, 'foreign_amount');
if (null === $foreignAmount) {
Log::debug(sprintf('Journal #%d has missing foreign currency data, forced to do 1:1 conversion :(.', $transaction->transaction_journal_id));
$transaction->foreign_amount = bcmul((string)$transaction->amount, '-1');

View File

@@ -47,7 +47,7 @@ class UpgradeFireflyInstructions extends Command
/**
* Execute the console command.
*/
public function handle()
public function handle(): void
{
if ('update' === $this->argument('task')) {
$this->updateInstructions();
@@ -62,7 +62,7 @@ class UpgradeFireflyInstructions extends Command
*
* @param string $text
*/
private function boxed(string $text)
private function boxed(string $text): void
{
$parts = explode("\n", wordwrap($text));
foreach ($parts as $string) {
@@ -75,7 +75,7 @@ class UpgradeFireflyInstructions extends Command
*
* @param string $text
*/
private function boxedInfo(string $text)
private function boxedInfo(string $text): void
{
$parts = explode("\n", wordwrap($text));
foreach ($parts as $string) {
@@ -86,7 +86,7 @@ class UpgradeFireflyInstructions extends Command
/**
* Render instructions.
*/
private function installInstructions()
private function installInstructions(): void
{
/** @var string $version */
$version = config('firefly.version');
@@ -94,8 +94,7 @@ class UpgradeFireflyInstructions extends Command
$text = '';
foreach (array_keys($config) as $compare) {
// if string starts with:
$len = \strlen($compare);
if (substr($version, 0, $len) === $compare) {
if (0 === strpos($version, $compare)) {
$text = $config[$compare];
}
}
@@ -120,7 +119,7 @@ class UpgradeFireflyInstructions extends Command
/**
* Show a line.
*/
private function showLine()
private function showLine(): void
{
$line = '+';
for ($i = 0; $i < 78; ++$i) {
@@ -133,7 +132,7 @@ class UpgradeFireflyInstructions extends Command
/**
* Render upgrade instructions.
*/
private function updateInstructions()
private function updateInstructions(): void
{
/** @var string $version */
$version = config('firefly.version');
@@ -141,8 +140,7 @@ class UpgradeFireflyInstructions extends Command
$text = '';
foreach (array_keys($config) as $compare) {
// if string starts with:
$len = \strlen($compare);
if (substr($version, 0, $len) === $compare) {
if (0 === strpos($version, $compare)) {
$text = $config[$compare];
}
}

View File

@@ -48,12 +48,12 @@ class UseEncryption extends Command
/**
* Execute the console command.
*/
public function handle()
public function handle(): void
{
if (config('firefly.encryption') === true) {
if (true === config('firefly.encryption')) {
$this->info('Firefly III configuration calls for encrypted data.');
}
if (config('firefly.encryption') === false) {
if (false === config('firefly.encryption')) {
$this->info('Firefly III configuration calls for unencrypted data.');
}
$this->handleObjects('Account', 'name', 'encrypted');
@@ -72,18 +72,21 @@ class UseEncryption extends Command
* @param string $field
* @param string $indicator
*/
public function handleObjects(string $class, string $field, string $indicator)
public function handleObjects(string $class, string $field, string $indicator): void
{
$fqn = sprintf('FireflyIII\Models\%s', $class);
$encrypt = config('firefly.encryption') === true ? 0 : 1;
$set = $fqn::where($indicator, $encrypt)->get();
$encrypt = true === config('firefly.encryption') ? 0 : 1;
/** @noinspection PhpUndefinedMethodInspection */
$set = $fqn::where($indicator, $encrypt)->get();
foreach ($set as $entry) {
$newName = $entry->$field;
$entry->$field = $newName;
/** @noinspection PhpUndefinedMethodInspection */
$entry->save();
}
/** @noinspection PhpUndefinedMethodInspection */
$this->line(sprintf('Updated %d %s.', $set->count(), strtolower(Str::plural($class))));
}
}

View File

@@ -1,4 +1,4 @@
<?php
<?php /** @noinspection PhpDynamicAsStaticMethodCallInspection */
/**
* VerifyDatabase.php
@@ -65,7 +65,7 @@ class VerifyDatabase extends Command
/**
* Execute the console command.
*/
public function handle()
public function handle(): void
{
// if table does not exist, return false
if (!Schema::hasTable('users')) {
@@ -304,7 +304,7 @@ class VerifyDatabase extends Command
/**
* Reports on accounts with no transactions.
*/
private function reportAccounts()
private function reportAccounts(): void
{
$set = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')
->leftJoin('users', 'accounts.user_id', '=', 'users.id')
@@ -401,7 +401,7 @@ class VerifyDatabase extends Command
// also count the transactions:
$countTransactions = DB::table('budget_transaction')->where('budget_id', $entry->id)->count();
if ($countTransactions === 0) {
if (0 === $countTransactions) {
$line = sprintf(
'User #%d (%s) has budget #%d ("%s") which has no transactions.',
$entry->user_id,
@@ -420,11 +420,11 @@ class VerifyDatabase extends Command
private function reportEmptyCategories(): void
{
$set = Category::leftJoin('category_transaction_journal', 'categories.id', '=', 'category_transaction_journal.category_id')
->leftJoin('users', 'categories.user_id', '=', 'users.id')
->distinct()
->whereNull('category_transaction_journal.category_id')
->whereNull('categories.deleted_at')
->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']);
->leftJoin('users', 'categories.user_id', '=', 'users.id')
->distinct()
->whereNull('category_transaction_journal.category_id')
->whereNull('categories.deleted_at')
->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']);
/** @var stdClass $entry */
foreach ($set as $entry) {
@@ -438,7 +438,7 @@ class VerifyDatabase extends Command
// also count the transactions:
$countTransactions = DB::table('category_transaction')->where('category_id', $entry->id)->count();
if ($countTransactions === 0) {
if (0 === $countTransactions) {
$line = sprintf(
'User #%d (%s) has category #%d ("%s") which has no transactions.',
$entry->user_id,
@@ -556,12 +556,13 @@ class VerifyDatabase extends Command
$plural = str_plural($name);
$class = sprintf('FireflyIII\Models\%s', ucfirst($name));
$field = 'tag' === $name ? 'tag' : 'name';
$set = $class::leftJoin($name . '_transaction_journal', $plural . '.id', '=', $name . '_transaction_journal.' . $name . '_id')
->leftJoin('users', $plural . '.user_id', '=', 'users.id')
->distinct()
->whereNull($name . '_transaction_journal.' . $name . '_id')
->whereNull($plural . '.deleted_at')
->get([$plural . '.id', $plural . '.' . $field . ' as name', $plural . '.user_id', 'users.email']);
/** @noinspection PhpUndefinedMethodInspection */
$set = $class::leftJoin($name . '_transaction_journal', $plural . '.id', '=', $name . '_transaction_journal.' . $name . '_id')
->leftJoin('users', $plural . '.user_id', '=', 'users.id')
->distinct()
->whereNull($name . '_transaction_journal.' . $name . '_id')
->whereNull($plural . '.deleted_at')
->get([$plural . '.id', $plural . '.' . $field . ' as name', $plural . '.user_id', 'users.email']);
/** @var stdClass $entry */
foreach ($set as $entry) {