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

@@ -89,7 +89,7 @@ class AttachmentController extends Controller
*/ */
public function download(Attachment $attachment): LaravelResponse public function download(Attachment $attachment): LaravelResponse
{ {
if ($attachment->uploaded === false) { if (false === $attachment->uploaded) {
throw new FireflyException('No file has been uploaded for this attachment (yet).'); throw new FireflyException('No file has been uploaded for this attachment (yet).');
} }
if ($this->repository->exists($attachment)) { if ($this->repository->exists($attachment)) {

View File

@@ -48,6 +48,7 @@ class ConfigurationController extends Controller
parent::__construct(); parent::__construct();
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
/** @noinspection UnusedConstructorDependenciesInspection */
$this->repository = app(UserRepositoryInterface::class); $this->repository = app(UserRepositoryInterface::class);
/** @var User $admin */ /** @var User $admin */
$admin = auth()->user(); $admin = auth()->user();
@@ -62,9 +63,9 @@ class ConfigurationController extends Controller
} }
/** /**
* @throws FireflyException * @return JsonResponse
*/ */
public function index() public function index(): JsonResponse
{ {
$configData = $this->getConfigData(); $configData = $this->getConfigData();
@@ -90,7 +91,7 @@ class ConfigurationController extends Controller
switch ($name) { switch ($name) {
case 'is_demo_site': case 'is_demo_site':
case 'single_user_mode': case 'single_user_mode':
$configValue = $value === 'true'; $configValue = 'true' === $value;
break; break;
case 'permission_update_check': case 'permission_update_check':
$configValue = (int)$value >= -1 && (int)$value <= 1 ? (int)$value : -1; $configValue = (int)$value >= -1 && (int)$value <= 1 ? (int)$value : -1;

View File

@@ -66,7 +66,7 @@ class Controller extends BaseController
$return = '?'; $return = '?';
$params = []; $params = [];
foreach ($this->parameters as $key => $value) { foreach ($this->parameters as $key => $value) {
if ($key === 'page') { if ('page' === $key) {
continue; continue;
} }
if ($value instanceof Carbon) { if ($value instanceof Carbon) {
@@ -88,7 +88,7 @@ class Controller extends BaseController
{ {
$bag = new ParameterBag; $bag = new ParameterBag;
$page = (int)request()->get('page'); $page = (int)request()->get('page');
if ($page === 0) { if (0 === $page) {
$page = 1; $page = 1;
} }
$bag->set('page', $page); $bag->set('page', $page);

View File

@@ -162,7 +162,7 @@ class CurrencyController extends Controller
$currency = $this->repository->store($request->getAll()); $currency = $this->repository->store($request->getAll());
if (null !== $currency) { if (null !== $currency) {
if ($request->boolean('default') === true) { if (true === $request->boolean('default')) {
app('preferences')->set('currencyPreference', $currency->code); app('preferences')->set('currencyPreference', $currency->code);
app('preferences')->mark(); app('preferences')->mark();
} }
@@ -192,7 +192,7 @@ class CurrencyController extends Controller
$data = $request->getAll(); $data = $request->getAll();
$currency = $this->repository->update($currency, $data); $currency = $this->repository->update($currency, $data);
if ($request->boolean('default') === true) { if (true === $request->boolean('default')) {
app('preferences')->set('currencyPreference', $currency->code); app('preferences')->set('currencyPreference', $currency->code);
app('preferences')->mark(); app('preferences')->mark();
} }

View File

@@ -78,7 +78,7 @@ class LinkTypeController extends Controller
*/ */
public function delete(LinkType $linkType): JsonResponse public function delete(LinkType $linkType): JsonResponse
{ {
if ($linkType->editable === false) { if (false === $linkType->editable) {
throw new FireflyException(sprintf('You cannot delete this link type (#%d, "%s")', $linkType->id, $linkType->name)); throw new FireflyException(sprintf('You cannot delete this link type (#%d, "%s")', $linkType->id, $linkType->name));
} }
$this->repository->destroy($linkType, null); $this->repository->destroy($linkType, null);
@@ -180,7 +180,7 @@ class LinkTypeController extends Controller
*/ */
public function update(LinkTypeRequest $request, LinkType $linkType): JsonResponse public function update(LinkTypeRequest $request, LinkType $linkType): JsonResponse
{ {
if ($linkType->editable === false) { if (false === $linkType->editable) {
throw new FireflyException(sprintf('You cannot edit this link type (#%d, "%s")', $linkType->id, $linkType->name)); throw new FireflyException(sprintf('You cannot edit this link type (#%d, "%s")', $linkType->id, $linkType->name));
} }

View File

@@ -125,7 +125,7 @@ class PreferenceController extends Controller
break; break;
case 'customFiscalYear': case 'customFiscalYear':
case 'twoFactorAuthEnabled': case 'twoFactorAuthEnabled':
$newValue = (int)$data['data'] === 1; $newValue = 1 === (int)$data['data'];
break; break;
} }
$result = Preferences::set($preference->name, $newValue); $result = Preferences::set($preference->name, $newValue);

View File

@@ -62,14 +62,14 @@ class RuleRequest extends Request
$data['rule-triggers'][] = [ $data['rule-triggers'][] = [
'name' => $trigger['name'], 'name' => $trigger['name'],
'value' => $trigger['value'], 'value' => $trigger['value'],
'stop-processing' => (int)($trigger['stop-processing'] ?? 0) === 1, 'stop-processing' => 1 === (int)($trigger['stop-processing'] ?? 0),
]; ];
} }
foreach ($this->get('rule-actions') as $action) { foreach ($this->get('rule-actions') as $action) {
$data['rule-actions'][] = [ $data['rule-actions'][] = [
'name' => $action['name'], 'name' => $action['name'],
'value' => $action['value'], 'value' => $action['value'],
'stop-processing' => (int)($action['stop-processing'] ?? 0) === 1, 'stop-processing' => 1 === (int)($action['stop-processing'] ?? 0),
]; ];
} }
@@ -134,7 +134,7 @@ class RuleRequest extends Request
$data = $validator->getData(); $data = $validator->getData();
$repetitions = $data['rule-actions'] ?? []; $repetitions = $data['rule-actions'] ?? [];
// need at least one transaction // need at least one transaction
if (\count($repetitions) === 0) { if (0 === \count($repetitions)) {
$validator->errors()->add('title', trans('validation.at_least_one_action')); $validator->errors()->add('title', trans('validation.at_least_one_action'));
} }
} }
@@ -149,7 +149,7 @@ class RuleRequest extends Request
$data = $validator->getData(); $data = $validator->getData();
$repetitions = $data['rule-triggers'] ?? []; $repetitions = $data['rule-triggers'] ?? [];
// need at least one transaction // need at least one transaction
if (\count($repetitions) === 0) { if (0 === \count($repetitions)) {
$validator->errors()->add('title', trans('validation.at_least_one_trigger')); $validator->errors()->add('title', trans('validation.at_least_one_trigger'));
} }
} }

View File

@@ -124,7 +124,7 @@ class TransactionRequest extends Request
'transactions.*.destination_name' => 'between:1,255|nullable', 'transactions.*.destination_name' => 'between:1,255|nullable',
]; ];
if ($this->method() === 'PUT') { if ('PUT' === $this->method()) {
unset($rules['type'], $rules['piggy_bank_id'], $rules['piggy_bank_name']); unset($rules['type'], $rules['piggy_bank_id'], $rules['piggy_bank_name']);
} }

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
<?php <?php /** @noinspection PhpDynamicAsStaticMethodCallInspection */
/** /**
* Import.php * Import.php
@@ -27,8 +27,8 @@ namespace FireflyIII\Console\Commands;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Routine\RoutineInterface; use FireflyIII\Import\Routine\RoutineInterface;
use FireflyIII\Models\ImportJob; use FireflyIII\Models\ImportJob;
use FireflyIII\Models\Tag;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\MessageBag;
use Log; use Log;
/** /**
@@ -55,7 +55,7 @@ class Import extends Command
* *
* @throws FireflyException * @throws FireflyException
*/ */
public function handle() public function handle(): void
{ {
Log::debug('Start start-import command'); Log::debug('Start start-import command');
$jobKey = $this->argument('key'); $jobKey = $this->argument('key');
@@ -83,17 +83,25 @@ class Import extends Command
/** @var RoutineInterface $routine */ /** @var RoutineInterface $routine */
$routine = app($className); $routine = app($className);
$routine->setJob($job); $routine->setImportJob($job);
$routine->run(); $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->errorLine(sprintf('Error importing line #%d: %s', $index, $error));
} }
$this->infoLine( /** @var Tag $tag */
sprintf('The import has finished. %d transactions have been imported out of %d records.', $routine->getJournals()->count(), $routine->getLines()) $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 * ScanAttachments.php
@@ -53,7 +53,7 @@ class ScanAttachments extends Command
/** /**
* Execute the console command. * Execute the console command.
*/ */
public function handle() public function handle(): void
{ {
$attachments = Attachment::get(); $attachments = Attachment::get();
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');

View File

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

View File

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

View File

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

View File

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

View File

@@ -34,15 +34,6 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
*/ */
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
{ {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands
= [
];
/** /**
* Register the commands for the application. * Register the commands for the application.
*/ */
@@ -50,6 +41,7 @@ class Kernel extends ConsoleKernel
{ {
$this->load(__DIR__ . '/Commands'); $this->load(__DIR__ . '/Commands');
/** @noinspection PhpIncludeInspection */
require base_path('routes/console.php'); require base_path('routes/console.php');
} }

View File

@@ -50,6 +50,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property int $skip * @property int $skip
* @property bool $automatch * @property bool $automatch
* @property User $user * @property User $user
* @property string $match
*/ */
class Bill extends Model class Bill extends Model
{ {

View File

@@ -35,6 +35,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property int $id * @property int $id
* @property string $name * @property string $name
* @property bool $active * @property bool $active
* @property int $user_id
* @property-read string $email
*/ */
class Budget extends Model class Budget extends Model
{ {

View File

@@ -40,6 +40,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property string $file_type * @property string $file_type
* @property int $tag_id * @property int $tag_id
* @property Tag $tag * @property Tag $tag
* @property array $errors
*/ */
class ImportJob extends Model class ImportJob extends Model
{ {

View File

@@ -27,7 +27,9 @@ use Illuminate\Database\Eloquent\Model;
/** /**
* Class PiggyBankEvent. * Class PiggyBankEvent.
* *
* @property $piggyBank * @property PiggyBank $piggyBank
* @property int $transaction_journal_id
* @property int $piggy_bank_id
*/ */
class PiggyBankEvent extends Model class PiggyBankEvent extends Model
{ {

View File

@@ -32,52 +32,57 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
* Class Transaction. * Class Transaction.
* *
* @property int $journal_id * @property int $journal_id
* @property Carbon $date * @property Carbon $date
* @property string $transaction_description * @property string $transaction_description
* @property string $transaction_amount * @property string $transaction_amount
* @property string $transaction_foreign_amount * @property string $transaction_foreign_amount
* @property string $transaction_type_type * @property string $transaction_type_type
* @property string $foreign_currency_symbol * @property string $foreign_currency_symbol
* @property int $foreign_currency_dp * @property int $foreign_currency_dp
* @property int $account_id * @property int $account_id
* @property string $account_name * @property string $account_name
* @property string $account_iban * @property string $account_iban
* @property string $account_number * @property string $account_number
* @property string $account_bic * @property string $account_bic
* @property string $account_type * @property string $account_type
* @property string $account_currency_code * @property string $account_currency_code
* @property int $opposing_account_id * @property int $opposing_account_id
* @property string $opposing_account_name * @property string $opposing_account_name
* @property string $opposing_account_iban * @property string $opposing_account_iban
* @property string $opposing_account_number * @property string $opposing_account_number
* @property string $opposing_account_bic * @property string $opposing_account_bic
* @property string $opposing_account_type * @property string $opposing_account_type
* @property string $opposing_currency_code * @property string $opposing_currency_code
* @property int $transaction_budget_id * @property int $transaction_budget_id
* @property string $transaction_budget_name * @property string $transaction_budget_name
* @property int $transaction_journal_budget_id * @property int $transaction_journal_budget_id
* @property string $transaction_journal_budget_name * @property string $transaction_journal_budget_name
* @property int $transaction_category_id * @property int $transaction_category_id
* @property string $transaction_category_name * @property string $transaction_category_name
* @property int $transaction_journal_category_id * @property int $transaction_journal_category_id
* @property string $transaction_journal_category_name * @property string $transaction_journal_category_name
* @property int $bill_id * @property int $bill_id
* @property string $bill_name * @property string $bill_name
* @property string $notes * @property string $notes
* @property string $tags * @property string $tags
* @property string $transaction_currency_symbol * @property string $transaction_currency_symbol
* @property int $transaction_currency_dp * @property int $transaction_currency_dp
* @property string $transaction_currency_code * @property string $transaction_currency_code
* @property string $description * @property string $description
* @property bool $is_split * @property bool $is_split
* @property int $attachmentCount * @property int $attachmentCount
* @property int $transaction_currency_id * @property int $transaction_currency_id
* @property int $foreign_currency_id * @property int $foreign_currency_id
* @property string $amount * @property string $amount
* @property string $foreign_amount * @property string $foreign_amount
* @property TransactionJournal $transactionJournal * @property TransactionJournal $transactionJournal
* @property Account $account * @property Account $account
* @property int $identifier
* @property int $id
* @property TransactionCurrency $transactionCurrency
* @property int $transaction_journal_id
* @property TransactionCurrency $foreignCurrency
*/ */
class Transaction extends Model class Transaction extends Model
{ {

View File

@@ -40,12 +40,14 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
* Class TransactionJournal. * Class TransactionJournal.
* *
* @property User $user * @property User $user
* @property int $bill_id * @property int $bill_id
* @property Collection $categories * @property Collection $categories
* @property bool $completed * @property bool $completed
* @property string $description * @property string $description
* @property string $transaction_type_id * @property int $transaction_type_id
* @property int transaction_currency_id
* @property TransactionCurrency $transactionCurrency
*/ */
class TransactionJournal extends Model class TransactionJournal extends Model
{ {

View File

@@ -29,8 +29,11 @@ use Illuminate\Database\Eloquent\SoftDeletes;
/** /**
* Class TransactionJournalMeta. * Class TransactionJournalMeta.
* *
* @property string $name * @property string $name
* @property int $transaction_journal_id * @property int $transaction_journal_id
* @property TransactionJournal $transactionJournal
* @property string $data
* @property int $id
*/ */
class TransactionJournalMeta extends Model class TransactionJournalMeta extends Model
{ {

View File

@@ -104,7 +104,9 @@ class TransactionJournal extends Twig_Extension
if (TransactionType::WITHDRAWAL === $type) { if (TransactionType::WITHDRAWAL === $type) {
$total['amount'] = bcmul($total['amount'], '-1'); $total['amount'] = bcmul($total['amount'], '-1');
} }
$array[] = app('amount')->formatAnything($total['currency'], $total['amount']); if (null !== $total['currency']) {
$array[] = app('amount')->formatAnything($total['currency'], $total['amount']);
}
} }
return implode(' / ', $array); return implode(' / ', $array);