Various code cleanup and fixed alignments.

This commit is contained in:
James Cole
2024-01-01 14:43:56 +01:00
parent 1368aafe5f
commit f963ac63f1
443 changed files with 3668 additions and 3672 deletions

View File

@@ -117,7 +117,7 @@ class AttachmentHelper implements AttachmentHelperInterface
public function saveAttachmentFromApi(Attachment $attachment, string $content): bool
{
Log::debug(sprintf('Now in %s', __METHOD__));
$resource = tmpfile();
$resource = tmpfile();
if (false === $resource) {
Log::error('Cannot create temp-file for file upload.');
@@ -130,24 +130,24 @@ class AttachmentHelper implements AttachmentHelperInterface
return false;
}
$path = stream_get_meta_data($resource)['uri'];
$path = stream_get_meta_data($resource)['uri'];
Log::debug(sprintf('Path is %s', $path));
$result = fwrite($resource, $content);
$result = fwrite($resource, $content);
if (false === $result) {
Log::error('Could not write temp file.');
return false;
}
Log::debug(sprintf('Wrote %d bytes to temp file.', $result));
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if (false === $finfo) {
Log::error('Could not open finfo.');
fclose($resource);
return false;
}
$mime = (string)finfo_file($finfo, $path);
$allowedMime = config('firefly.allowedMimes');
$mime = (string)finfo_file($finfo, $path);
$allowedMime = config('firefly.allowedMimes');
if (!in_array($mime, $allowedMime, true)) {
Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime));
fclose($resource);
@@ -156,8 +156,8 @@ class AttachmentHelper implements AttachmentHelperInterface
}
Log::debug(sprintf('Found mime "%s" in file "%s"', $mime, $path));
// is allowed? Save the file, without encryption.
$parts = explode('/', $attachment->fileName());
$file = $parts[count($parts) - 1];
$parts = explode('/', $attachment->fileName());
$file = $parts[count($parts) - 1];
Log::debug(sprintf('Write file to disk in file named "%s"', $file));
$this->uploadDisk->put($file, $content);
@@ -215,13 +215,13 @@ class AttachmentHelper implements AttachmentHelperInterface
$validation = $this->validateUpload($file, $model);
$attachment = null;
if (false !== $validation) {
$user = $model->user;
$user = $model->user;
// ignore lines about polymorphic calls.
if ($model instanceof PiggyBank) {
$user = $model->account->user;
}
$attachment = new Attachment(); // create Attachment object.
$attachment = new Attachment(); // create Attachment object.
$attachment->user()->associate($user);
$attachment->attachable()->associate($model);
$attachment->md5 = (string)md5_file($file->getRealPath());
@@ -232,14 +232,14 @@ class AttachmentHelper implements AttachmentHelperInterface
$attachment->save();
Log::debug('Created attachment:', $attachment->toArray());
$fileObject = $file->openFile();
$fileObject = $file->openFile();
$fileObject->rewind();
if (0 === $file->getSize()) {
throw new FireflyException('Cannot upload empty or non-existent file.');
}
$content = (string)$fileObject->fread($file->getSize());
$content = (string)$fileObject->fread($file->getSize());
Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize()));
// store it without encryption.
@@ -248,8 +248,8 @@ class AttachmentHelper implements AttachmentHelperInterface
$attachment->save();
$this->attachments->push($attachment);
$name = e($file->getClientOriginalName()); // add message:
$msg = (string)trans('validation.file_attached', ['name' => $name]);
$name = e($file->getClientOriginalName()); // add message:
$msg = (string)trans('validation.file_attached', ['name' => $name]);
$this->messages->add('attachments', $msg);
}
@@ -289,14 +289,14 @@ class AttachmentHelper implements AttachmentHelperInterface
protected function validMime(UploadedFile $file): bool
{
Log::debug('Now in validMime()');
$mime = e($file->getMimeType());
$name = e($file->getClientOriginalName());
$mime = e($file->getMimeType());
$name = e($file->getClientOriginalName());
Log::debug(sprintf('Name is %s, and mime is %s', $name, $mime));
Log::debug('Valid mimes are', $this->allowedMimes);
$result = true;
if (!in_array($mime, $this->allowedMimes, true)) {
$msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]);
$msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]);
$this->errors->add('attachments', $msg);
Log::error($msg);
@@ -315,7 +315,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$name = e($file->getClientOriginalName());
$result = true;
if ($size > $this->maxUploadSize) {
$msg = (string)trans('validation.file_too_large', ['name' => $name]);
$msg = (string)trans('validation.file_too_large', ['name' => $name]);
$this->errors->add('attachments', $msg);
Log::error($msg);
@@ -330,10 +330,10 @@ class AttachmentHelper implements AttachmentHelperInterface
*/
protected function hasFile(UploadedFile $file, Model $model): bool
{
$md5 = md5_file($file->getRealPath());
$name = $file->getClientOriginalName();
$class = get_class($model);
$count = 0;
$md5 = md5_file($file->getRealPath());
$name = $file->getClientOriginalName();
$class = get_class($model);
$count = 0;
// ignore lines about polymorphic calls.
if ($model instanceof PiggyBank) {
$count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
@@ -343,7 +343,7 @@ class AttachmentHelper implements AttachmentHelperInterface
}
$result = false;
if ($count > 0) {
$msg = (string)trans('validation.file_already_attached', ['name' => $name]);
$msg = (string)trans('validation.file_already_attached', ['name' => $name]);
$this->errors->add('attachments', $msg);
Log::error($msg);
$result = true;

View File

@@ -211,9 +211,9 @@ trait AccountCollection
$this->query->leftJoin('account_types as source_account_type', 'source_account_type.id', '=', 'source_account.account_type_id');
// add source account fields:
$this->fields[] = 'source_account.name as source_account_name';
$this->fields[] = 'source_account.iban as source_account_iban';
$this->fields[] = 'source_account_type.type as source_account_type';
$this->fields[] = 'source_account.name as source_account_name';
$this->fields[] = 'source_account.iban as source_account_iban';
$this->fields[] = 'source_account_type.type as source_account_type';
// same for dest
$this->query->leftJoin('accounts as dest_account', 'dest_account.id', '=', 'destination.account_id');

View File

@@ -682,12 +682,12 @@ trait MetaCollection
$list = $tags->pluck('tag')->toArray();
$list = array_map('strtolower', $list);
$filter = static function (array $object) use ($list): bool|array {
$return = $object;
$return = $object;
unset($return['transactions']);
$return['transactions'] = [];
Log::debug(sprintf('Now in setAllTags(%s) filter', implode(', ', $list)));
$expectedTagCount = count($list);
$foundTagCount = 0;
$expectedTagCount = count($list);
$foundTagCount = 0;
foreach ($object['transactions'] as $transaction) {
$transactionTagCount = count($transaction['tags']);
app('log')->debug(sprintf('Transaction #%d has %d tag(s)', $transaction['transaction_journal_id'], $transactionTagCount));
@@ -708,7 +708,7 @@ trait MetaCollection
Log::debug(sprintf('Found %d tags, need at least %d.', $foundTagCount, $expectedTagCount));
// found at least the expected tags.
$result = $foundTagCount >= $expectedTagCount;
$result = $foundTagCount >= $expectedTagCount;
if (true === $result) {
return $return;
}
@@ -941,8 +941,8 @@ trait MetaCollection
if (false === $this->hasJoinedMetaTables) {
$this->hasJoinedMetaTables = true;
$this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
$this->fields[] = 'journal_meta.name as meta_name';
$this->fields[] = 'journal_meta.data as meta_data';
$this->fields[] = 'journal_meta.name as meta_name';
$this->fields[] = 'journal_meta.data as meta_data';
}
}

View File

@@ -65,7 +65,7 @@ trait TimeCollection
if ($end < $start) {
[$start, $end] = [$end, $start];
}
$end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object.
$end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object.
$end->endOfDay();
$start->startOfDay();
$this->withMetaDate($field);
@@ -536,7 +536,7 @@ trait TimeCollection
if ($end < $start) {
[$start, $end] = [$end, $start];
}
$end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object.
$end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object.
$end->endOfDay();
$start->startOfDay();
$this->withMetaDate($field);

View File

@@ -62,12 +62,12 @@ class GroupCollector implements GroupCollectorInterface
*/
public function __construct()
{
$this->postFilters = [];
$this->tags = [];
$this->user = null;
$this->userGroup = null;
$this->limit = null;
$this->page = null;
$this->postFilters = [];
$this->tags = [];
$this->user = null;
$this->userGroup = null;
$this->limit = null;
$this->page = null;
$this->hasAccountInfo = false;
$this->hasCatInformation = false;
@@ -287,7 +287,7 @@ class GroupCollector implements GroupCollectorInterface
if (is_int($param)) {
$replace = (string)$param;
}
$pos = strpos($query, '?');
$pos = strpos($query, '?');
if (false !== $pos) {
$query = substr_replace($query, $replace, $pos, 1);
}
@@ -455,13 +455,13 @@ class GroupCollector implements GroupCollectorInterface
// add to query:
$this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds);
}
$result = $this->query->get($this->fields);
$result = $this->query->get($this->fields);
// now to parse this into an array.
$collection = $this->parseArray($result);
$collection = $this->parseArray($result);
// filter the array using all available post filters:
$collection = $this->postFilterCollection($collection);
$collection = $this->postFilterCollection($collection);
// count it and continue:
$this->total = $collection->count();
@@ -691,12 +691,12 @@ class GroupCollector implements GroupCollectorInterface
/** @var TransactionJournal $augumentedJournal */
foreach ($collection as $augumentedJournal) {
$groupId = (int)$augumentedJournal->transaction_group_id;
$groupId = (int)$augumentedJournal->transaction_group_id;
if (!array_key_exists($groupId, $groups)) {
// make new array
$parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
$groupArray = [
$parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
$groupArray = [
'id' => (int)$augumentedJournal->transaction_group_id,
'user_id' => $augumentedJournal->user_id,
'user_group_id' => $augumentedJournal->user_group_id,
@@ -766,7 +766,7 @@ class GroupCollector implements GroupCollectorInterface
}
// try to process meta date value (if present)
$dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date'];
$dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date'];
if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) {
$name = $result['meta_name'];
if (array_key_exists('meta_data', $result) && '' !== (string)$result['meta_data']) {
@@ -775,15 +775,15 @@ class GroupCollector implements GroupCollectorInterface
}
// convert values to integers:
$result = $this->convertToInteger($result);
$result = $this->convertToInteger($result);
// convert back to strings because SQLite is dumb like that.
$result = $this->convertToStrings($result);
$result = $this->convertToStrings($result);
$result['reconciled'] = 1 === (int)$result['reconciled'];
$result['reconciled'] = 1 === (int)$result['reconciled'];
if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well.
$tagId = (int)$augumentedJournal['tag_id'];
$tagDate = null;
$tagId = (int)$augumentedJournal['tag_id'];
$tagDate = null;
try {
$tagDate = Carbon::parse($augumentedJournal['tag_date']);
@@ -847,9 +847,9 @@ class GroupCollector implements GroupCollectorInterface
{
$newArray = $newJournal->toArray();
if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well.
$tagId = (int)$newJournal['tag_id'];
$tagId = (int)$newJournal['tag_id'];
$tagDate = null;
$tagDate = null;
try {
$tagDate = Carbon::parse($newArray['tag_date']);
@@ -872,7 +872,7 @@ class GroupCollector implements GroupCollectorInterface
{
$newArray = $newJournal->toArray();
if (array_key_exists('attachment_id', $newArray)) {
$attachmentId = (int)$newJournal['attachment_id'];
$attachmentId = (int)$newJournal['attachment_id'];
$existingJournal['attachments'][$attachmentId] = [
'id' => $attachmentId,
@@ -891,7 +891,7 @@ class GroupCollector implements GroupCollectorInterface
foreach ($groups as $groudId => $group) {
/** @var array $transaction */
foreach ($group['transactions'] as $transaction) {
$currencyId = (int)$transaction['currency_id'];
$currencyId = (int)$transaction['currency_id'];
if (null === $transaction['amount']) {
throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId));
}
@@ -907,7 +907,7 @@ class GroupCollector implements GroupCollectorInterface
$groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']);
if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
$currencyId = (int)$transaction['foreign_currency_id'];
$currencyId = (int)$transaction['foreign_currency_id'];
// set default:
if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
@@ -936,7 +936,7 @@ class GroupCollector implements GroupCollectorInterface
*/
foreach ($this->postFilters as $function) {
app('log')->debug('Applying filter...');
$nextCollection = new Collection();
$nextCollection = new Collection();
// loop everything in the current collection
// and save it (or not) in the new collection.

View File

@@ -74,7 +74,7 @@ class FiscalHelper implements FiscalHelperInterface
$prefStartStr = '01-01';
}
$prefStartStr = (string)$prefStartStr;
[$mth, $day] = explode('-', $prefStartStr);
[$mth, $day] = explode('-', $prefStartStr);
$startDate->day((int)$day)->month((int)$mth);
// if start date is after passed date, sub 1 year.

View File

@@ -64,8 +64,8 @@ class NetWorth implements NetWorthInterface
public function byAccounts(Collection $accounts, Carbon $date): array
{
// start in the past, end in the future? use $date
$ids = implode(',', $accounts->pluck('id')->toArray());
$cache = new CacheProperties();
$ids = implode(',', $accounts->pluck('id')->toArray());
$cache = new CacheProperties();
$cache->addProperty($date);
$cache->addProperty('net-worth-by-accounts');
$cache->addProperty($ids);
@@ -78,7 +78,7 @@ class NetWorth implements NetWorthInterface
$converter = new ExchangeRateConverter();
// default "native" currency has everything twice, for consistency.
$netWorth = [
$netWorth = [
'native' => [
'balance' => '0',
'native_balance' => '0',
@@ -94,25 +94,25 @@ class NetWorth implements NetWorthInterface
'native_currency_decimal_places' => $default->decimal_places,
],
];
$balances = app('steam')->balancesByAccountsConverted($accounts, $date);
$balances = app('steam')->balancesByAccountsConverted($accounts, $date);
/** @var Account $account */
foreach ($accounts as $account) {
app('log')->debug(sprintf('Now at account #%d ("%s")', $account->id, $account->name));
$currency = $this->getRepository()->getAccountCurrency($account);
$currency = $this->getRepository()->getAccountCurrency($account);
if (null === $currency) {
$currency = app('amount')->getDefaultCurrency();
}
$currencyCode = $currency->code;
$balance = '0';
$nativeBalance = '0';
$currencyCode = $currency->code;
$balance = '0';
$nativeBalance = '0';
if (array_key_exists($account->id, $balances)) {
$balance = $balances[$account->id]['balance'] ?? '0';
$nativeBalance = $balances[$account->id]['native_balance'] ?? '0';
}
app('log')->debug(sprintf('Balance is %s, native balance is %s', $balance, $nativeBalance));
// always subtract virtual balance
$virtualBalance = $account->virtual_balance;
$virtualBalance = $account->virtual_balance;
if ('' !== $virtualBalance) {
$balance = bcsub($balance, $virtualBalance);
$nativeVirtualBalance = $converter->convert($default, $currency, $account->created_at, $virtualBalance);
@@ -149,14 +149,14 @@ class NetWorth implements NetWorthInterface
if (!$user instanceof User) {
return;
}
$this->user = $user;
$this->userGroup = null;
$this->user = $user;
$this->userGroup = null;
// make repository:
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->accountRepository->setUser($this->user);
$this->currencyRepos = app(CurrencyRepositoryInterface::class);
$this->currencyRepos = app(CurrencyRepositoryInterface::class);
$this->currencyRepos->setUser($this->user);
}
@@ -179,16 +179,16 @@ class NetWorth implements NetWorthInterface
$return = [];
$balances = app('steam')->balancesByAccounts($accounts, $date);
foreach ($accounts as $account) {
$currency = $this->getRepository()->getAccountCurrency($account);
$balance = $balances[$account->id] ?? '0';
$currency = $this->getRepository()->getAccountCurrency($account);
$balance = $balances[$account->id] ?? '0';
// always subtract virtual balance.
$virtualBalance = $account->virtual_balance;
$virtualBalance = $account->virtual_balance;
if ('' !== $virtualBalance) {
$balance = bcsub($balance, $virtualBalance);
}
$return[$currency->id] ??= [
$return[$currency->id] ??= [
'id' => (string) $currency->id,
'name' => $currency->name,
'symbol' => $currency->symbol,

View File

@@ -70,7 +70,7 @@ class PopupReport implements PopupReportInterface
}
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector
->setAccounts(new Collection([$account]))
->setTypes([TransactionType::WITHDRAWAL])
@@ -102,7 +102,7 @@ class PopupReport implements PopupReportInterface
}
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts($attributes['accounts'])
->withAccountInformation()
->withBudgetInformation()
@@ -139,7 +139,7 @@ class PopupReport implements PopupReportInterface
}
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts($attributes['accounts'])
->setTypes([TransactionType::WITHDRAWAL, TransactionType::TRANSFER, TransactionType::DEPOSIT])
@@ -169,8 +169,8 @@ class PopupReport implements PopupReportInterface
public function byExpenses(Account $account, array $attributes): array
{
// filter by currency, if set.
$currencyId = $attributes['currencyId'] ?? null;
$currency = null;
$currencyId = $attributes['currencyId'] ?? null;
$currency = null;
if (null !== $currencyId) {
/** @var CurrencyRepositoryInterface $repos */
$repos = app(CurrencyRepositoryInterface::class);
@@ -178,14 +178,14 @@ class PopupReport implements PopupReportInterface
}
/** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class);
$repository = app(JournalRepositoryInterface::class);
$repository->setUser($account->user);
$accountRepository = app(AccountRepositoryInterface::class);
$accountRepository->setUser($account->user);
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
// set report accounts + the request accounts:
// $set = $attributes['accounts'] ?? new Collection;
@@ -216,7 +216,7 @@ class PopupReport implements PopupReportInterface
$repository->setUser($account->user);
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector
->setSourceAccounts(new Collection([$account]))
->setDestinationAccounts($attributes['accounts'])

View File

@@ -64,10 +64,10 @@ class ReportHelper implements ReportHelperInterface
/** @var Bill $bill */
foreach ($bills as $bill) {
$expectedDates = $repository->getPayDatesInRange($bill, $start, $end);
$billId = $bill->id;
$currency = $bill->transactionCurrency;
$current = [
$expectedDates = $repository->getPayDatesInRange($bill, $start, $end);
$billId = $bill->id;
$currency = $bill->transactionCurrency;
$current = [
'id' => $bill->id,
'name' => $bill->name,
'active' => $bill->active,
@@ -84,11 +84,11 @@ class ReportHelper implements ReportHelperInterface
/** @var Carbon $expectedStart */
foreach ($expectedDates as $expectedStart) {
$expectedEnd = app('navigation')->endOfX($expectedStart, $bill->repeat_freq, null);
$expectedEnd = app('navigation')->endOfX($expectedStart, $bill->repeat_freq, null);
// is paid in this period maybe?
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($expectedStart, $expectedEnd)->setBill($bill);
$current['paid_moments'][] = $collector->getExtractedJournals();
}
@@ -109,12 +109,12 @@ class ReportHelper implements ReportHelperInterface
$fiscalHelper = app(FiscalHelperInterface::class);
$start = clone $date;
$start->startOfMonth();
$end = today(config('app.timezone'));
$end = today(config('app.timezone'));
$end->endOfMonth();
$months = [];
$months = [];
while ($start <= $end) {
$year = $fiscalHelper->endOfFiscalYear($start)->year; // current year
$year = $fiscalHelper->endOfFiscalYear($start)->year; // current year
if (!array_key_exists($year, $months)) {
$months[$year] = [
'fiscal_start' => $fiscalHelper->startOfFiscalYear($start)->format('Y-m-d'),
@@ -125,7 +125,7 @@ class ReportHelper implements ReportHelperInterface
];
}
$currentEnd = clone $start;
$currentEnd = clone $start;
$currentEnd->endOfMonth();
$months[$year]['months'][] = [
'formatted' => $start->isoFormat((string)trans('config.month_js')),
@@ -135,7 +135,7 @@ class ReportHelper implements ReportHelperInterface
'year' => $year,
];
$start = clone $currentEnd; // to make the hop to the next month properly
$start = clone $currentEnd; // to make the hop to the next month properly
$start->addDay();
}

View File

@@ -42,7 +42,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface
if (null === $message->webhook) {
throw new FireflyException('Part of a deleted webhook.');
}
$json = '';
$json = '';
try {
$json = json_encode($message->message, JSON_THROW_ON_ERROR);