Fix various code.

This commit is contained in:
James Cole
2025-05-27 17:06:15 +02:00
parent d8f512ca3a
commit 2cb14f6b72
123 changed files with 581 additions and 500 deletions

View File

@@ -31,24 +31,13 @@ return RectorConfig::configure()
ChangeOrIfContinueToMultiContinueRector::class,
])
->withPaths([
// __DIR__ . '/../app',
__DIR__ . '/../app/Api',
__DIR__ . '/../app/Casts',
__DIR__ . '/../app/Console',
__DIR__ . '/../app/Entities',
__DIR__ . '/../app/Enums',
__DIR__ . '/../app/Enums',
__DIR__ . '/../app/Events',
__DIR__ . '/../app/Exceptions',
__DIR__ . '/../app/Factory',
__DIR__ . '/../app/Generator',
__DIR__ . '/../app/Http',
// __DIR__ . '/../bootstrap',
// __DIR__ . '/../config',
// __DIR__ . '/../public',
// __DIR__ . '/../resources',
// __DIR__ . '/../routes',
// __DIR__ . '/../tests',
__DIR__ . '/../app',
__DIR__ . '/../bootstrap',
__DIR__ . '/../config',
__DIR__ . '/../public',
__DIR__ . '/../resources',
__DIR__ . '/../routes',
__DIR__ . '/../tests',
])
// uncomment to reach your current PHP version
->withPhpSets()

View File

@@ -204,7 +204,7 @@ class BudgetLimitHandler
if (!$limitPeriod->equals($abPeriod) && !$abPeriod->contains($limitPeriod) && $abPeriod->overlapsWith($limitPeriod)) {
Log::debug('This budget limit is something else entirely!');
$overlap = $abPeriod->overlap($limitPeriod);
if (null !== $overlap) {
if ($overlap instanceof Period) {
$length = $overlap->length();
$daily = bcmul($this->getDailyAmount($budgetLimit), (string) $length);
$newAmount = bcadd($newAmount, $daily);

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Events\Model;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Events\Model\PiggyBank\ChangedAmount;
use FireflyIII\Models\PiggyBankEvent;
@@ -36,7 +37,7 @@ class PiggyBankEventHandler
{
// find journal if group is present.
$journal = $event->transactionJournal;
if (null !== $event->transactionGroup) {
if ($event->transactionGroup instanceof TransactionGroup) {
$journal = $event->transactionGroup->transactionJournals()->first();
}
$date = $journal->date ?? today(config('app.timezone'));

View File

@@ -108,13 +108,12 @@ class PreferencesEventHandler
/** @var Budget $budget */
foreach ($set as $budget) {
foreach ($budget->autoBudgets as $autoBudget) {
if (null !== $autoBudget->native_amount) {
if (null !== $autoBudget->native_amount) {
Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id));
$autoBudget->native_amount = null;
$autoBudget->saveQuietly();
}
if (null === $autoBudget->native_amount) {
continue;
}
Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id));
$autoBudget->native_amount = null;
$autoBudget->saveQuietly();
}
foreach ($budget->budgetlimits as $limit) {
if (null !== $limit->native_amount) {

View File

@@ -484,7 +484,7 @@ class UserEventHandler
}
// clean up old entries (6 months)
$carbon = Carbon::createFromFormat('Y-m-d H:i:s', $preference[$index]['time']);
if (null !== $carbon && $carbon->diffInMonths(today(), true) > 6) {
if ($carbon instanceof Carbon && $carbon->diffInMonths(today(), true) > 6) {
app('log')->debug(sprintf('Entry for %s is very old, remove it.', $row['ip']));
unset($preference[$index]);
}

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Handlers\Events;
use Carbon\Carbon;
use FireflyIII\Events\RequestedVersionCheckStatus;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Update\UpdateTrait;
@@ -68,12 +69,12 @@ class VersionCheckEventHandler
}
/** @var Configuration $lastCheckTime */
$lastCheckTime = app('fireflyconfig')->get('last_update_check', time());
$now = time();
$lastCheckTime = app('fireflyconfig')->get('last_update_check', Carbon::now()->getTimestamp());
$now = Carbon::now()->getTimestamp();
$diff = $now - $lastCheckTime->data;
Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff));
if ($diff < 604800) {
Log::debug(sprintf('Checked for updates less than a week ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data)));
Log::debug(sprintf('Checked for updates less than a week ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s')));
return;
}
@@ -82,7 +83,7 @@ class VersionCheckEventHandler
$release = $this->getLatestRelease();
session()->flash($release['level'], $release['message']);
app('fireflyconfig')->set('last_update_check', time());
app('fireflyconfig')->set('last_update_check', Carbon::now()->getTimestamp());
}
/**
@@ -100,12 +101,12 @@ class VersionCheckEventHandler
}
/** @var Configuration $lastCheckTime */
$lastCheckTime = app('fireflyconfig')->get('last_update_warning', time());
$now = time();
$lastCheckTime = app('fireflyconfig')->get('last_update_warning', Carbon::now()->getTimestamp());
$now = Carbon::now()->getTimestamp();
$diff = $now - $lastCheckTime->data;
Log::debug(sprintf('Last warning time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff));
if ($diff < 604800 * 4) {
Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data)));
Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s')));
return;
}
@@ -113,6 +114,6 @@ class VersionCheckEventHandler
Log::debug('Have warned about a new version in four weeks!');
session()->flash('info', (string) trans('firefly.disabled_but_check'));
app('fireflyconfig')->set('last_update_warning', time());
app('fireflyconfig')->set('last_update_warning', Carbon::now()->getTimestamp());
}
}

View File

@@ -37,6 +37,12 @@ use Illuminate\Support\Facades\Storage;
use Illuminate\Support\MessageBag;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use function Safe\tmpfile;
use function Safe\fwrite;
use function Safe\finfo_open;
use function Safe\fclose;
use function Safe\md5_file;
use const DIRECTORY_SEPARATOR;
/**
@@ -120,7 +126,7 @@ class AttachmentHelper implements AttachmentHelperInterface
public function saveAttachmentFromApi(Attachment $attachment, string $content): bool
{
Log::debug(sprintf('Now in %s', __METHOD__));
$resource = \Safe\tmpfile();
$resource = tmpfile();
if (false === $resource) {
Log::error('Cannot create temp-file for file upload.');
@@ -135,17 +141,17 @@ class AttachmentHelper implements AttachmentHelperInterface
$path = stream_get_meta_data($resource)['uri'];
Log::debug(sprintf('Path is %s', $path));
$result = \Safe\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 = \Safe\finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if (false === $finfo) {
Log::error('Could not open finfo.');
\Safe\fclose($resource);
fclose($resource);
return false;
}
@@ -153,7 +159,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$allowedMime = config('firefly.allowedMimes');
if (!in_array($mime, $allowedMime, true)) {
Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime));
\Safe\fclose($resource);
fclose($resource);
return false;
}
@@ -165,7 +171,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$this->uploadDisk->put($file, $content);
// update attachment.
$attachment->md5 = (string) \Safe\md5_file($path);
$attachment->md5 = (string) md5_file($path);
$attachment->mime = $mime;
$attachment->size = strlen($content);
$attachment->uploaded = true;
@@ -227,7 +233,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$attachment = new Attachment(); // create Attachment object.
$attachment->user()->associate($user);
$attachment->attachable()->associate($model);
$attachment->md5 = (string) \Safe\md5_file($file->getRealPath());
$attachment->md5 = (string) md5_file($file->getRealPath());
$attachment->filename = $file->getClientOriginalName();
$attachment->mime = $file->getMimeType();
$attachment->size = $file->getSize();
@@ -282,7 +288,7 @@ class AttachmentHelper implements AttachmentHelperInterface
}
if (true === $result && $this->hasFile($file, $model)) {
$result = false;
return false;
}
return $result;
@@ -335,7 +341,7 @@ class AttachmentHelper implements AttachmentHelperInterface
*/
protected function hasFile(UploadedFile $file, Model $model): bool
{
$md5 = \Safe\md5_file($file->getRealPath());
$md5 = md5_file($file->getRealPath());
$name = $file->getClientOriginalName();
$class = $model::class;
$count = 0;

View File

@@ -36,6 +36,8 @@ use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use function Safe\json_encode;
/**
* Trait MetaCollection
*/
@@ -167,7 +169,7 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'external_id');
$this->query->where('journal_meta.data', '!=', sprintf('%s', \Safe\json_encode($externalId)));
$this->query->where('journal_meta.data', '!=', sprintf('%s', json_encode($externalId)));
$this->query->whereNull('journal_meta.deleted_at');
return $this;
@@ -190,14 +192,14 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'external_url');
$this->query->where('journal_meta.data', '!=', \Safe\json_encode($url));
$this->query->where('journal_meta.data', '!=', json_encode($url));
return $this;
}
public function excludeInternalReference(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
@@ -211,14 +213,14 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'recurrence_id');
$this->query->where('journal_meta.data', '!=', sprintf('%s', \Safe\json_encode($recurringId)));
$this->query->where('journal_meta.data', '!=', sprintf('%s', json_encode($recurringId)));
return $this;
}
public function externalIdContains(string $externalId): GroupCollectorInterface
{
$externalId = (string) \Safe\json_encode($externalId);
$externalId = (string) json_encode($externalId);
$externalId = str_replace('\\', '\\\\', trim($externalId, '"'));
$this->joinMetaDataTables();
@@ -230,7 +232,7 @@ trait MetaCollection
public function externalIdDoesNotContain(string $externalId): GroupCollectorInterface
{
$externalId = (string) \Safe\json_encode($externalId);
$externalId = (string) json_encode($externalId);
$externalId = str_replace('\\', '\\\\', trim($externalId, '"'));
$this->joinMetaDataTables();
@@ -242,7 +244,7 @@ trait MetaCollection
public function externalIdDoesNotEnd(string $externalId): GroupCollectorInterface
{
$externalId = (string) \Safe\json_encode($externalId);
$externalId = (string) json_encode($externalId);
$externalId = str_replace('\\', '\\\\', trim($externalId, '"'));
$this->joinMetaDataTables();
@@ -254,7 +256,7 @@ trait MetaCollection
public function externalIdDoesNotStart(string $externalId): GroupCollectorInterface
{
$externalId = (string) \Safe\json_encode($externalId);
$externalId = (string) json_encode($externalId);
$externalId = str_replace('\\', '\\\\', trim($externalId, '"'));
$this->joinMetaDataTables();
@@ -266,7 +268,7 @@ trait MetaCollection
public function externalIdEnds(string $externalId): GroupCollectorInterface
{
$externalId = (string) \Safe\json_encode($externalId);
$externalId = (string) json_encode($externalId);
$externalId = str_replace('\\', '\\\\', trim($externalId, '"'));
$this->joinMetaDataTables();
@@ -278,7 +280,7 @@ trait MetaCollection
public function externalIdStarts(string $externalId): GroupCollectorInterface
{
$externalId = (string) \Safe\json_encode($externalId);
$externalId = (string) json_encode($externalId);
$externalId = str_replace('\\', '\\\\', trim($externalId, '"'));
$this->joinMetaDataTables();
@@ -291,7 +293,7 @@ trait MetaCollection
public function externalUrlContains(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
$url = (string) \Safe\json_encode($url);
$url = (string) json_encode($url);
$url = str_replace('\\', '\\\\', trim($url, '"'));
$this->query->where('journal_meta.name', '=', 'external_url');
$this->query->whereLike('journal_meta.data', sprintf('%%%s%%', $url));
@@ -302,7 +304,7 @@ trait MetaCollection
public function externalUrlDoesNotContain(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
$url = (string) \Safe\json_encode($url);
$url = (string) json_encode($url);
$url = str_replace('\\', '\\\\', trim($url, '"'));
$this->query->where('journal_meta.name', '=', 'external_url');
$this->query->whereNotLike('journal_meta.data', sprintf('%%%s%%', $url));
@@ -313,7 +315,7 @@ trait MetaCollection
public function externalUrlDoesNotEnd(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
$url = (string) \Safe\json_encode($url);
$url = (string) json_encode($url);
$url = str_replace('\\', '\\\\', ltrim($url, '"'));
$this->query->where('journal_meta.name', '=', 'external_url');
$this->query->whereNotLike('journal_meta.data', sprintf('%%%s', $url));
@@ -324,7 +326,7 @@ trait MetaCollection
public function externalUrlDoesNotStart(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
$url = (string) \Safe\json_encode($url);
$url = (string) json_encode($url);
$url = str_replace('\\', '\\\\', rtrim($url, '"'));
// var_dump($url);
@@ -337,7 +339,7 @@ trait MetaCollection
public function externalUrlEnds(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
$url = (string) \Safe\json_encode($url);
$url = (string) json_encode($url);
$url = str_replace('\\', '\\\\', ltrim($url, '"'));
$this->query->where('journal_meta.name', '=', 'external_url');
$this->query->whereLike('journal_meta.data', sprintf('%%%s', $url));
@@ -348,7 +350,7 @@ trait MetaCollection
public function externalUrlStarts(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
$url = (string) \Safe\json_encode($url);
$url = (string) json_encode($url);
$url = str_replace('\\', '\\\\', rtrim($url, '"'));
// var_dump($url);
@@ -399,7 +401,7 @@ trait MetaCollection
public function internalReferenceContains(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
// var_dump($internalReference);
// exit;
@@ -414,7 +416,7 @@ trait MetaCollection
public function internalReferenceDoesNotContain(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
@@ -427,7 +429,7 @@ trait MetaCollection
public function internalReferenceDoesNotEnd(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
@@ -440,7 +442,7 @@ trait MetaCollection
public function internalReferenceDoesNotStart(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
@@ -453,7 +455,7 @@ trait MetaCollection
public function internalReferenceEnds(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
@@ -466,7 +468,7 @@ trait MetaCollection
public function internalReferenceStarts(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
@@ -704,7 +706,7 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'external_id');
$this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($externalId)));
$this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($externalId)));
$this->query->whereNull('journal_meta.deleted_at');
return $this;
@@ -714,7 +716,7 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'external_url');
$this->query->where('journal_meta.data', '=', \Safe\json_encode($url));
$this->query->where('journal_meta.data', '=', json_encode($url));
$this->query->whereNull('journal_meta.deleted_at');
return $this;
@@ -722,12 +724,12 @@ trait MetaCollection
public function setInternalReference(string $internalReference): GroupCollectorInterface
{
$internalReference = (string) \Safe\json_encode($internalReference);
$internalReference = (string) json_encode($internalReference);
$internalReference = str_replace('\\', '\\\\', trim($internalReference, '"'));
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'internal_reference');
$this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($internalReference)));
$this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($internalReference)));
$this->query->whereNull('journal_meta.deleted_at');
return $this;
@@ -737,7 +739,7 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'recurrence_id');
$this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($recurringId)));
$this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($recurringId)));
$this->query->whereNull('journal_meta.deleted_at');
return $this;
@@ -747,7 +749,7 @@ trait MetaCollection
{
$this->joinMetaDataTables();
$this->query->where('journal_meta.name', '=', 'sepa_ct_id');
$this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($sepaCT)));
$this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($sepaCT)));
$this->query->whereNull('journal_meta.deleted_at');
return $this;

View File

@@ -73,7 +73,11 @@ trait TimeCollection
$filter = static function (array $object) use ($field, $start, $end): bool {
foreach ($object['transactions'] as $transaction) {
if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) {
return $transaction[$field]->lt($start) || $transaction[$field]->gt($end);
if ($transaction[$field]->lt($start)) {
return true;
}
return $transaction[$field]->gt($end);
}
}
@@ -589,17 +593,17 @@ trait TimeCollection
*/
public function setRange(?Carbon $start, ?Carbon $end): GroupCollectorInterface
{
if (null !== $start && null !== $end && $end < $start) {
if ($start instanceof Carbon && $end instanceof Carbon && $end < $start) {
[$start, $end] = [$end, $start];
}
// always got to end of day / start of day for ranges.
$startStr = $start?->format('Y-m-d 00:00:00');
$endStr = $end?->format('Y-m-d 23:59:59');
if (null !== $start) {
if ($start instanceof Carbon) {
$this->query->where('transaction_journals.date', '>=', $startStr);
}
if (null !== $end) {
if ($end instanceof Carbon) {
$this->query->where('transaction_journals.date', '<=', $endStr);
}

View File

@@ -48,6 +48,8 @@ use Illuminate\Support\Facades\Log;
use Closure;
use Override;
use function Safe\json_decode;
/**
* Class GroupCollector
*/
@@ -595,7 +597,7 @@ class GroupCollector implements GroupCollectorInterface
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']) {
$result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) \Safe\json_decode($result['meta_data']), 0, 10));
$result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) json_decode((string) $result['meta_data']), 0, 10));
}
}
@@ -1046,7 +1048,7 @@ class GroupCollector implements GroupCollectorInterface
*/
public function setUser(User $user): GroupCollectorInterface
{
if (null === $this->user) {
if (!$this->user instanceof User) {
$this->user = $user;
$this->startQuery();
}
@@ -1106,7 +1108,7 @@ class GroupCollector implements GroupCollectorInterface
*/
public function setUserGroup(UserGroup $userGroup): GroupCollectorInterface
{
if (null === $this->userGroup) {
if (!$this->userGroup instanceof UserGroup) {
$this->userGroup = $userGroup;
$this->startQueryForGroup();
}

View File

@@ -149,10 +149,10 @@ class PopupReport implements PopupReportInterface
->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation()
;
if (null !== $category) {
if ($category instanceof Category) {
$collector->setCategory($category);
}
if (null === $category) {
if (!$category instanceof Category) {
$collector->withoutCategory();
}

View File

@@ -24,10 +24,13 @@ declare(strict_types=1);
namespace FireflyIII\Helpers\Webhook;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\WebhookMessage;
use JsonException;
use function Safe\json_encode;
/**
* Class Sha3SignatureGenerator
*/
@@ -47,7 +50,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface
$json = '';
try {
$json = \Safe\json_encode($message->message, JSON_THROW_ON_ERROR);
$json = json_encode($message->message, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
app('log')->error('Could not generate hash.');
app('log')->error(sprintf('JSON value: %s', $json));
@@ -63,7 +66,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface
// The character .
// The character .
// The actual JSON payload (i.e., the request body)
$timestamp = time();
$timestamp = Carbon::now()->getTimestamp();
$payload = sprintf('%s.%s', $timestamp, $json);
$signature = hash_hmac('sha3-256', $payload, (string) $message->webhook->secret, false);

View File

@@ -55,7 +55,7 @@ class CreateAutoBudgetLimits implements ShouldQueue
*/
public function __construct(?Carbon $date)
{
if (null !== $date) {
if ($date instanceof Carbon) {
$newDate = clone $date;
$newDate->startOfDay();
$this->date = $newDate;
@@ -127,7 +127,7 @@ class CreateAutoBudgetLimits implements ShouldQueue
// find budget limit:
$budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end);
if (null === $budgetLimit && AutoBudgetType::AUTO_BUDGET_RESET->value === (int) $autoBudget->auto_budget_type) {
if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_RESET->value === (int) $autoBudget->auto_budget_type) {
// that's easy: create one.
// do nothing else.
$this->createBudgetLimit($autoBudget, $start, $end);
@@ -136,14 +136,14 @@ class CreateAutoBudgetLimits implements ShouldQueue
return;
}
if (null === $budgetLimit && AutoBudgetType::AUTO_BUDGET_ROLLOVER->value === (int) $autoBudget->auto_budget_type) {
if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ROLLOVER->value === (int) $autoBudget->auto_budget_type) {
// budget limit exists already,
$this->createRollover($autoBudget);
app('log')->debug(sprintf('Done with auto budget #%d', $autoBudget->id));
return;
}
if (null === $budgetLimit && AutoBudgetType::AUTO_BUDGET_ADJUSTED->value === (int) $autoBudget->auto_budget_type) {
if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ADJUSTED->value === (int) $autoBudget->auto_budget_type) {
// budget limit exists already,
$this->createAdjustedLimit($autoBudget);
app('log')->debug(sprintf('Done with auto budget #%d', $autoBudget->id));
@@ -256,7 +256,7 @@ class CreateAutoBudgetLimits implements ShouldQueue
// has budget limit in previous period?
$budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd);
if (null === $budgetLimit) {
if (!$budgetLimit instanceof BudgetLimit) {
app('log')->debug('No budget limit exists in previous period, so create one.');
// if not, create it and we're done.
$this->createBudgetLimit($autoBudget, $start, $end);
@@ -316,7 +316,7 @@ class CreateAutoBudgetLimits implements ShouldQueue
// has budget limit in previous period?
$budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd);
if (null === $budgetLimit) {
if (!$budgetLimit instanceof BudgetLimit) {
app('log')->debug('No budget limit exists in previous period, so create one.');
// if not, create standard amount, and we're done.
$this->createBudgetLimit($autoBudget, $start, $end);

View File

@@ -74,7 +74,7 @@ class CreateRecurringTransactions implements ShouldQueue
$newDate->startOfDay();
$this->date = $newDate;
if (null !== $date) {
if ($date instanceof Carbon) {
$newDate = clone $date;
$newDate->startOfDay();
$this->date = $newDate;
@@ -257,7 +257,7 @@ class CreateRecurringTransactions implements ShouldQueue
{
$startDate = clone $recurrence->first_date;
if (null !== $recurrence->latest_date && $recurrence->latest_date->gte($startDate)) {
$startDate = clone $recurrence->latest_date;
return clone $recurrence->latest_date;
}
return $startDate;
@@ -321,7 +321,7 @@ class CreateRecurringTransactions implements ShouldQueue
/** @var Carbon $date */
foreach ($occurrences as $date) {
$result = $this->handleOccurrence($recurrence, $repetition, $date);
if (null !== $result) {
if ($result instanceof TransactionGroup) {
$collection->push($result);
}
}

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Jobs;
use FireflyIII\Models\CurrencyExchangeRate;
use Carbon\Carbon;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
@@ -39,6 +40,8 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use function Safe\json_decode;
/**
* Class DownloadExchangeRates
*/
@@ -67,7 +70,7 @@ class DownloadExchangeRates implements ShouldQueue
$userRepository = app(UserRepositoryInterface::class);
$this->users = $userRepository->all();
if (null !== $date) {
if ($date instanceof Carbon) {
$newDate = clone $date;
$newDate->startOfDay();
$this->date = $newDate;
@@ -113,14 +116,14 @@ class DownloadExchangeRates implements ShouldQueue
return;
}
$body = (string) $res->getBody();
$json = \Safe\json_decode($body, true);
$json = json_decode($body, true);
if (false === $json || null === $json) {
app('log')->warning(sprintf('Trying to grab "%s" resulted in bad JSON.', $url));
return;
}
$date = Carbon::createFromFormat('Y-m-d', $json['date'], config('app.timezone'));
if (null === $date) {
if (!$date instanceof Carbon) {
return;
}
$this->saveRates($currency, $date, $json['rates']);
@@ -130,7 +133,7 @@ class DownloadExchangeRates implements ShouldQueue
{
foreach ($rates as $code => $rate) {
$to = $this->getCurrency($code);
if (null === $to) {
if (!$to instanceof TransactionCurrency) {
app('log')->debug(sprintf('Currency %s is not in use, do not save rate.', $code));
continue;
@@ -150,7 +153,7 @@ class DownloadExchangeRates implements ShouldQueue
}
// find it in the database.
$currency = $this->repository->findByCode($code);
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
app('log')->debug(sprintf('Did not find currency %s.', $code));
$this->active[$code] = null;
@@ -173,7 +176,7 @@ class DownloadExchangeRates implements ShouldQueue
foreach ($this->users as $user) {
$this->repository->setUser($user);
$existing = $this->repository->getExchangeRate($from, $to, $date);
if (null === $existing) {
if (!$existing instanceof CurrencyExchangeRate) {
app('log')->debug(sprintf('Saved rate from %s to %s for user #%d.', $from->code, $to->code, $user->id));
$this->repository->setExchangeRate($from, $to, $date, $rate);
}

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Jobs;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Message;
use Illuminate\Queue\InteractsWithQueue;
@@ -32,6 +33,11 @@ use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Exception\TransportException;
use Exception;
use function Safe\json_encode;
use function Safe\file_put_contents;
use function Safe\json_decode;
use function Safe\file_get_contents;
/**
* Class MailError.
*/
@@ -48,7 +54,7 @@ class MailError extends Job implements ShouldQueue
$debug = $this->exception;
unset($debug['stackTrace'], $debug['headers']);
app('log')->error(sprintf('Exception is: %s', \Safe\json_encode($debug)));
app('log')->error(sprintf('Exception is: %s', json_encode($debug)));
}
/**
@@ -119,11 +125,11 @@ class MailError extends Job implements ShouldQueue
if (!file_exists($file)) {
Log::debug(sprintf('Wrote new file in "%s"', $file));
\Safe\file_put_contents($file, \Safe\json_encode($limits, JSON_PRETTY_PRINT));
file_put_contents($file, json_encode($limits, JSON_PRETTY_PRINT));
}
if (file_exists($file)) {
Log::debug(sprintf('Read file in "%s"', $file));
$limits = \Safe\json_decode((string) \Safe\file_get_contents($file), true);
$limits = json_decode((string) file_get_contents($file), true);
}
// limit reached?
foreach ($types as $type => $info) {
@@ -131,15 +137,15 @@ class MailError extends Job implements ShouldQueue
if (!array_key_exists($type, $limits)) {
Log::debug(sprintf('Limit "%s" reset to zero, did not exist yet.', $type));
$limits[$type] = [
'time' => time(),
'time' => Carbon::now()->getTimestamp(),
'sent' => 0,
];
}
if (time() - $limits[$type]['time'] > $info['reset']) {
Log::debug(sprintf('Time past for this limit is %d seconds, exceeding %d seconds. Reset to zero.', time() - $limits[$type]['time'], $info['reset']));
if (Carbon::now()->getTimestamp() - $limits[$type]['time'] > $info['reset']) {
Log::debug(sprintf('Time past for this limit is %d seconds, exceeding %d seconds. Reset to zero.', Carbon::now()->getTimestamp() - $limits[$type]['time'], $info['reset']));
$limits[$type] = [
'time' => time(),
'time' => Carbon::now()->getTimestamp(),
'sent' => 0,
];
}
@@ -151,7 +157,7 @@ class MailError extends Job implements ShouldQueue
}
++$limits[$type]['sent'];
}
\Safe\file_put_contents($file, \Safe\json_encode($limits, JSON_PRETTY_PRINT));
file_put_contents($file, json_encode($limits, JSON_PRETTY_PRINT));
Log::debug('No limits reached, return FALSE.');
return false;

View File

@@ -55,7 +55,7 @@ class WarnAboutBills implements ShouldQueue
$newDate->startOfDay();
$this->date = $newDate;
if (null !== $date) {
if ($date instanceof Carbon) {
$newDate = clone $date;
$newDate->startOfDay();
$this->date = $newDate;

View File

@@ -28,6 +28,8 @@ use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use function Safe\parse_url;
/**
* Class InvitationMail
*/
@@ -43,7 +45,7 @@ class InvitationMail extends Mailable
*/
public function __construct(public string $invitee, public string $admin, public string $url)
{
$this->host = (string) \Safe\parse_url($this->url, PHP_URL_HOST);
$this->host = (string) parse_url($this->url, PHP_URL_HOST);
}
/**

View File

@@ -27,6 +27,9 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use function Safe\json_decode;
use function Safe\json_encode;
class AccountMeta extends Model
{
use ReturnsIntegerIdTrait;
@@ -47,11 +50,11 @@ class AccountMeta extends Model
public function getDataAttribute(mixed $value): string
{
return (string) \Safe\json_decode($value, true);
return (string) json_decode((string) $value, true);
}
public function setDataAttribute(mixed $value): void
{
$this->attributes['data'] = \Safe\json_encode($value);
$this->attributes['data'] = json_encode($value);
}
}

View File

@@ -27,6 +27,9 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use function Safe\json_decode;
use function Safe\json_encode;
class Configuration extends Model
{
use ReturnsIntegerIdTrait;
@@ -50,7 +53,7 @@ class Configuration extends Model
*/
public function getDataAttribute($value)
{
return \Safe\json_decode($value);
return json_decode((string) $value);
}
/**
@@ -58,6 +61,6 @@ class Configuration extends Model
*/
public function setDataAttribute($value): void
{
$this->attributes['data'] = \Safe\json_encode($value);
$this->attributes['data'] = json_encode($value);
}
}

View File

@@ -29,6 +29,9 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use function Safe\json_decode;
use function Safe\json_encode;
class TransactionJournalMeta extends Model
{
use ReturnsIntegerIdTrait;
@@ -52,7 +55,7 @@ class TransactionJournalMeta extends Model
*/
public function getDataAttribute($value)
{
return \Safe\json_decode($value, false);
return json_decode((string) $value, false);
}
/**
@@ -60,7 +63,7 @@ class TransactionJournalMeta extends Model
*/
public function setDataAttribute($value): void
{
$data = \Safe\json_encode($value);
$data = json_encode($value);
$this->attributes['data'] = $data;
$this->attributes['hash'] = hash('sha256', (string) $data);
}

View File

@@ -39,7 +39,7 @@ class ReturnsAvailableChannels
if ('owner' === $type) {
return self::returnOwnerChannels();
}
if ('user' === $type && null !== $user) {
if ('user' === $type && $user instanceof User) {
return self::returnUserChannels($user);
}

View File

@@ -52,7 +52,7 @@ class ReturnsSettings
'ntfy_pass' => '',
];
if ('user' === $type && null !== $user) {
if ('user' === $type && $user instanceof User) {
$settings['ntfy_server'] = Preferences::getEncryptedForUser($user, 'ntfy_server', 'https://ntfy.sh')->data;
$settings['ntfy_topic'] = Preferences::getEncryptedForUser($user, 'ntfy_topic', '')->data;
$settings['ntfy_auth'] = '1' === Preferences::getForUser($user, 'ntfy_auth', false)->data;

View File

@@ -66,12 +66,11 @@ class BillReminder extends Notification
private function getSubject(): string
{
$message = (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
if (0 === $this->diff) {
$message = (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
return (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
}
return $message;
return (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
}
public function toNtfy(User $notifiable): Message

View File

@@ -31,6 +31,8 @@ use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Passport;
use Override;
use function Safe\preg_match;
/**
* Class AppServiceProvider
*/
@@ -48,7 +50,7 @@ class AppServiceProvider extends ServiceProvider
'Cache-Control' => 'no-store',
];
$uuid = (string) request()->header('X-Trace-Id');
if ('' !== trim($uuid) && (1 === \Safe\preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid)))) {
if ('' !== trim($uuid) && (1 === preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid)))) {
$headers['X-Trace-Id'] = $uuid;
}

View File

@@ -47,6 +47,8 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Override;
use function Safe\json_encode;
/**
* Class AccountRepository.
*/
@@ -109,7 +111,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
->where('accounts.active', true)
->where(
static function (EloquentBuilder $q1) use ($number): void {
$json = \Safe\json_encode($number);
$json = json_encode($number);
$q1->where('account_meta.name', '=', 'account_number');
$q1->where('account_meta.data', '=', $json);
}

View File

@@ -150,51 +150,51 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
// depends on transaction type:
if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
if (null !== $accounts) {
if ($accounts instanceof Collection) {
$collector->setSourceAccounts($accounts);
}
if (null !== $opposing) {
if ($opposing instanceof Collection) {
$collector->setDestinationAccounts($opposing);
}
}
if (TransactionTypeEnum::DEPOSIT->value === $type) {
if (null !== $accounts) {
if ($accounts instanceof Collection) {
$collector->setDestinationAccounts($accounts);
}
if (null !== $opposing) {
if ($opposing instanceof Collection) {
$collector->setSourceAccounts($opposing);
}
}
// supports only accounts, not opposing.
if (TransactionTypeEnum::TRANSFER->value === $type && null !== $accounts) {
if (TransactionTypeEnum::TRANSFER->value === $type && $accounts instanceof Collection) {
$collector->setAccounts($accounts);
}
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
$collector->setCurrency($currency);
}
$journals = $collector->getExtractedJournals();
// same but for foreign currencies:
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([$type])->withAccountInformation()
->setForeignCurrency($currency)
;
if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
if (null !== $accounts) {
if ($accounts instanceof Collection) {
$collector->setSourceAccounts($accounts);
}
if (null !== $opposing) {
if ($opposing instanceof Collection) {
$collector->setDestinationAccounts($opposing);
}
}
if (TransactionTypeEnum::DEPOSIT->value === $type) {
if (null !== $accounts) {
if ($accounts instanceof Collection) {
$collector->setDestinationAccounts($accounts);
}
if (null !== $opposing) {
if ($opposing instanceof Collection) {
$collector->setSourceAccounts($opposing);
}
}

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\Bill;
use FireflyIII\Models\ObjectGroup;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\BillFactory;
@@ -119,7 +120,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
{
if (null !== $billId) {
$searchResult = $this->find($billId);
if (null !== $searchResult) {
if ($searchResult instanceof Bill) {
app('log')->debug(sprintf('Found bill based on #%d, will return it.', $billId));
return $searchResult;
@@ -127,7 +128,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
}
if (null !== $billName) {
$searchResult = $this->findByName($billName);
if (null !== $searchResult) {
if ($searchResult instanceof Bill) {
app('log')->debug(sprintf('Found bill based on "%s", will return it.', $billName));
return $searchResult;
@@ -503,7 +504,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
public function setObjectGroup(Bill $bill, string $objectGroupTitle): Bill
{
$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
if (null !== $objectGroup) {
if ($objectGroup instanceof ObjectGroup) {
$bill->objectGroups()->sync([$objectGroup->id]);
}

View File

@@ -65,7 +65,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
public function get(?Carbon $start = null, ?Carbon $end = null): Collection
{
$query = $this->user->availableBudgets()->with(['transactionCurrency']);
if (null !== $start && null !== $end) {
if ($start instanceof Carbon && $end instanceof Carbon) {
$query->where(
static function (Builder $q1) use ($start, $end): void {
$q1->where('start_date', '=', $start->format('Y-m-d'));
@@ -123,7 +123,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
->where('end_date', $end->format('Y-m-d'))->first()
;
if (null !== $availableBudget) {
$amount = $availableBudget->amount;
return $availableBudget->amount;
}
return $amount;
@@ -172,10 +172,10 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
{
$query = $this->user->availableBudgets();
if (null !== $start) {
if ($start instanceof Carbon) {
$query->where('start_date', '>=', $start->format('Y-m-d'));
}
if (null !== $end) {
if ($end instanceof Carbon) {
$query->where('end_date', '<=', $end->format('Y-m-d'));
}

View File

@@ -88,7 +88,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
->where('budgets.active', true)
->where('budgets.user_id', $this->user->id)
;
if (null !== $budgets && $budgets->count() > 0) {
if ($budgets instanceof Collection && $budgets->count() > 0) {
$query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray());
}
@@ -135,7 +135,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection
{
// both are NULL:
if (null === $start && null === $end) {
if (!$start instanceof Carbon && !$end instanceof Carbon) {
return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->with(['budget'])
->where('budgets.user_id', $this->user->id)
@@ -144,17 +144,17 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
;
}
// one of the two is NULL.
if (null === $start xor null === $end) {
if (!$start instanceof Carbon xor !$end instanceof Carbon) {
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->with(['budget'])
->whereNull('budgets.deleted_at')
->where('budgets.user_id', $this->user->id)
;
if (null !== $end) {
if ($end instanceof Carbon) {
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
}
if (null !== $start) {
if ($start instanceof Carbon) {
// start date must be after $start.
$query->where('start_date', '>=', $start->format('Y-m-d 00:00:00'));
}
@@ -201,17 +201,17 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection
{
if (null === $end && null === $start) {
if (!$end instanceof Carbon && !$start instanceof Carbon) {
return $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']);
}
if (null === $end xor null === $start) {
if (!$end instanceof Carbon xor !$start instanceof Carbon) {
$query = $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC');
// one of the two is null
if (null !== $end) {
if ($end instanceof Carbon) {
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
}
if (null !== $start) {
if ($start instanceof Carbon) {
// start date must be after $start.
$query->where('start_date', '>=', $start->format('Y-m-d 00:00:00'));
}

View File

@@ -303,16 +303,16 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
// first things first: delete when no longer required:
$autoBudgetType = array_key_exists('auto_budget_type', $data) ? $data['auto_budget_type'] : null;
if (0 === $autoBudgetType && null !== $autoBudget) {
if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) {
// delete!
$autoBudget->delete();
return $budget;
}
if (0 === $autoBudgetType && null === $autoBudget) {
if (0 === $autoBudgetType && !$autoBudget instanceof AutoBudget) {
return $budget;
}
if (null === $autoBudgetType && null === $autoBudget) {
if (null === $autoBudgetType && !$autoBudget instanceof AutoBudget) {
return $budget;
}
$this->updateAutoBudget($budget, $data);
@@ -393,7 +393,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
// grab default currency:
$currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup);
if (null === $autoBudget) {
if (!$autoBudget instanceof AutoBudget) {
// at this point it's a blind assumption auto_budget_type is 1 or 2.
$autoBudget = new AutoBudget();
$autoBudget->auto_budget_type = $data['auto_budget_type'];
@@ -488,14 +488,14 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
app('log')->debug('Now in findBudget()');
app('log')->debug(sprintf('Searching for budget with ID #%d...', $budgetId));
$result = $this->find((int) $budgetId);
if (null === $result && null !== $budgetName && '' !== $budgetName) {
if (!$result instanceof Budget && null !== $budgetName && '' !== $budgetName) {
app('log')->debug(sprintf('Searching for budget with name %s...', $budgetName));
$result = $this->findByName($budgetName);
}
if (null !== $result) {
if ($result instanceof Budget) {
app('log')->debug(sprintf('Found budget #%d: %s', $result->id, $result->name));
}
app('log')->debug(sprintf('Found result is null? %s', var_export(null === $result, true)));
app('log')->debug(sprintf('Found result is null? %s', var_export(!$result instanceof Budget, true)));
return $result;
}

View File

@@ -85,10 +85,10 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
$collector->setCurrency($currency);
}
$collector->withoutBudget();

View File

@@ -126,13 +126,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null !== $budgets && $budgets->count() > 0) {
if ($budgets instanceof Collection && $budgets->count() > 0) {
$collector->setBudgets($budgets);
}
if (null === $budgets || 0 === $budgets->count()) {
if (!$budgets instanceof Collection || 0 === $budgets->count()) {
$collector->setBudgets($this->getBudgets());
}
$collector->withBudgetInformation()->withAccountInformation()->withCategoryInformation();
@@ -229,13 +229,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
;
if (null !== $accounts) {
if ($accounts instanceof Collection) {
$collector->setAccounts($accounts);
}
if (null === $budgets) {
if (!$budgets instanceof Collection) {
$budgets = $this->getBudgets();
}
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
Log::debug(sprintf('Limit to normal currency %s', $currency->code));
$collector->setNormalCurrency($currency);
}
@@ -245,7 +245,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$journals = $collector->getExtractedJournals();
// same but for transactions in the foreign currency:
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
Log::debug('STOP looking for transactions in the foreign currency.');
}
$summarizer = new TransactionSummarizer($this->user);

View File

@@ -111,18 +111,18 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
app('log')->debug('Now in findCategory()');
app('log')->debug(sprintf('Searching for category with ID #%d...', $categoryId));
$result = $this->find((int) $categoryId);
if (null === $result) {
if (!$result instanceof Category) {
app('log')->debug(sprintf('Searching for category with name %s...', $categoryName));
$result = $this->findByName((string) $categoryName);
if (null === $result && '' !== (string) $categoryName) {
if (!$result instanceof Category && '' !== (string) $categoryName) {
// create it!
$result = $this->store(['name' => $categoryName]);
}
}
if (null !== $result) {
if ($result instanceof Category) {
app('log')->debug(sprintf('Found category #%d: %s', $result->id, $result->name));
}
app('log')->debug(sprintf('Found category result is null? %s', var_export(null === $result, true)));
app('log')->debug(sprintf('Found category result is null? %s', var_export(!$result instanceof Category, true)));
return $result;
}
@@ -191,13 +191,13 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
$firstJournalDate = $this->getFirstJournalDate($category);
$firstTransactionDate = $this->getFirstTransactionDate($category);
if (null === $firstTransactionDate && null === $firstJournalDate) {
if (!$firstTransactionDate instanceof Carbon && !$firstJournalDate instanceof Carbon) {
return null;
}
if (null === $firstTransactionDate) {
if (!$firstTransactionDate instanceof Carbon) {
return $firstJournalDate;
}
if (null === $firstJournalDate) {
if (!$firstJournalDate instanceof Carbon) {
return $firstTransactionDate;
}
@@ -279,13 +279,13 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
$lastJournalDate = $this->getLastJournalDate($category, $accounts);
$lastTransactionDate = $this->getLastTransactionDate($category, $accounts);
if (null === $lastTransactionDate && null === $lastJournalDate) {
if (!$lastTransactionDate instanceof Carbon && !$lastJournalDate instanceof Carbon) {
return null;
}
if (null === $lastTransactionDate) {
if (!$lastTransactionDate instanceof Carbon) {
return $lastJournalDate;
}
if (null === $lastJournalDate) {
if (!$lastJournalDate instanceof Carbon) {
return $lastTransactionDate;
}

View File

@@ -49,7 +49,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->withoutCategory();
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
$journals = $collector->getExtractedJournals();
@@ -95,7 +95,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->withoutCategory();
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
$journals = $collector->getExtractedJournals();
@@ -140,7 +140,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->withoutCategory();
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
$journals = $collector->getExtractedJournals();
@@ -158,7 +158,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->withoutCategory();
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
$journals = $collector->getExtractedJournals();
@@ -186,7 +186,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value])->withoutCategory();
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
$journals = $collector->getExtractedJournals();

View File

@@ -53,14 +53,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
$collector->excludeDestinationAccounts($accounts); // to exclude withdrawals to liabilities.
}
if (null !== $categories && $categories->count() > 0) {
if ($categories instanceof Collection && $categories->count() > 0) {
$collector->setCategories($categories);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
@@ -131,14 +131,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]);
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
$collector->excludeSourceAccounts($accounts); // to prevent income from liabilities.
}
if (null !== $categories && $categories->count() > 0) {
if ($categories instanceof Collection && $categories->count() > 0) {
$collector->setCategories($categories);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation();
@@ -197,10 +197,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value])
->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts)
;
if (null !== $categories && $categories->count() > 0) {
if ($categories instanceof Collection && $categories->count() > 0) {
$collector->setCategories($categories);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
@@ -260,10 +260,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value])
->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts)
;
if (null !== $categories && $categories->count() > 0) {
if ($categories instanceof Collection && $categories->count() > 0) {
$collector->setCategories($categories);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
@@ -325,10 +325,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$categories = $this->getCategories();
}
$collector->setCategories($categories);
@@ -350,10 +350,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
->setTypes([TransactionTypeEnum::DEPOSIT->value])
;
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$categories = $this->getCategories();
}
$collector->setCategories($categories);
@@ -419,10 +419,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
->setTypes([TransactionTypeEnum::TRANSFER->value])
;
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null === $categories || 0 === $categories->count()) {
if (!$categories instanceof Collection || 0 === $categories->count()) {
$categories = $this->getCategories();
}
$collector->setCategories($categories);

View File

@@ -44,6 +44,8 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Override;
use function Safe\json_encode;
/**
* Class CurrencyRepository.
*/
@@ -82,7 +84,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
}
// is being used in accounts:
$meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\json_encode((string) $currency->id))->count();
$meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string) $currency->id))->count();
if ($meta > 0) {
Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta));
@@ -90,7 +92,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
}
// second search using integer check.
$meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\json_encode((int) $currency->id))->count();
$meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((int) $currency->id))->count();
if ($meta > 0) {
Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta));
@@ -118,7 +120,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
// is being used in accounts (as integer)
$meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
->whereNull('accounts.deleted_at')
->where('account_meta.name', 'currency_id')->where('account_meta.data', \Safe\json_encode($currency->id))->count()
->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode($currency->id))->count()
;
if ($meta > 0) {
Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta));
@@ -237,7 +239,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
{
$result = $this->findCurrencyNull($currencyId, $currencyCode);
if (null === $result) {
if (!$result instanceof TransactionCurrency) {
Log::debug('Grabbing default currency for this user...');
/** @var null|TransactionCurrency $result */
@@ -260,7 +262,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
{
Log::debug(sprintf('Now in findCurrencyNull(%s, "%s")', var_export($currencyId, true), $currencyCode));
$result = $this->find((int) $currencyId);
if (null !== $result) {
if ($result instanceof TransactionCurrency) {
Log::debug(sprintf('Found currency by ID: %s', $result->code));
return $result;
@@ -269,7 +271,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
Log::debug(sprintf('Searching for currency with code "%s"...', $currencyCode));
$result = $this->findByCode((string) $currencyCode);
}
if (null !== $result && false === $result->enabled) {
if ($result instanceof TransactionCurrency && false === $result->enabled) {
Log::debug(sprintf('Also enabled currency %s', $result->code));
$this->enable($result);
}

View File

@@ -105,7 +105,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro
public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate
{
$object->rate = $rate;
if (null !== $date) {
if ($date instanceof Carbon) {
$object->date = $date;
}
$object->save();

View File

@@ -77,13 +77,12 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
public function firstNull(): ?TransactionJournal
{
/** @var null|TransactionJournal $entry */
$entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']);
$result = null;
$entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']);
if (null !== $entry) {
$result = $entry;
return $entry;
}
return $result;
return null;
}
public function getDestinationAccount(TransactionJournal $journal): Account
@@ -120,13 +119,12 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
public function getLast(): ?TransactionJournal
{
/** @var null|TransactionJournal $entry */
$entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']);
$result = null;
$entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']);
if (null !== $entry) {
$result = $entry;
return $entry;
}
return $result;
return null;
}
public function getLinkNoteText(TransactionJournalLink $link): string

View File

@@ -47,7 +47,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
public function destroy(LinkType $linkType, ?LinkType $moveTo = null): bool
{
if (null !== $moveTo) {
if ($moveTo instanceof LinkType) {
TransactionJournalLink::where('link_type_id', $linkType->id)->update(['link_type_id' => $moveTo->id]);
}
$linkType->delete();
@@ -125,7 +125,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
->whereNull('dest_journals.deleted_at')
;
if (null !== $linkType) {
if ($linkType instanceof LinkType) {
$query->where('journal_links.link_type_id', $linkType->id);
}
@@ -177,17 +177,17 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
{
$linkType = $this->find((int) ($information['link_type_id'] ?? 0));
if (null === $linkType) {
if (!$linkType instanceof LinkType) {
$linkType = $this->findByName($information['link_type_name']);
}
if (null === $linkType) {
if (!$linkType instanceof LinkType) {
return null;
}
// might exist already:
$existing = $this->findSpecificLink($linkType, $inward, $outward);
if (null !== $existing) {
if ($existing instanceof TransactionJournalLink) {
return $existing;
}

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\PiggyBank;
use FireflyIII\User;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\PiggyBankFactory;
@@ -69,7 +70,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
if (null !== $piggyBankId) {
$searchResult = $this->find($piggyBankId);
if (null !== $searchResult) {
if ($searchResult instanceof PiggyBank) {
app('log')->debug(sprintf('Found piggy based on #%d, will return it.', $piggyBankId));
return $searchResult;
@@ -77,7 +78,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
}
if (null !== $piggyBankName) {
$searchResult = $this->findByName($piggyBankName);
if (null !== $searchResult) {
if ($searchResult instanceof PiggyBank) {
app('log')->debug(sprintf('Found piggy based on "%s", will return it.', $piggyBankName));
return $searchResult;
@@ -133,7 +134,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
{
$sum = '0';
foreach ($piggyBank->accounts as $current) {
if (null !== $account && $account->id !== $current->id) {
if ($account instanceof Account && $account->id !== $current->id) {
continue;
}
$amount = (string) $current->pivot->native_current_amount;
@@ -267,7 +268,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
{
$sum = '0';
foreach ($piggyBank->accounts as $current) {
if (null !== $account && $account->id !== $current->id) {
if ($account instanceof Account && $account->id !== $current->id) {
continue;
}
$amount = (string) $current->pivot->current_amount;
@@ -311,10 +312,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
$query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
;
if (null === $this->user) {
if (!$this->user instanceof User) {
$query->where('accounts.user_group_id', $this->userGroup->id);
}
if (null !== $this->user) {
if ($this->user instanceof User) {
$query->where('accounts.user_id', $this->user->id);
}

View File

@@ -50,6 +50,9 @@ use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use function Safe\json_encode;
use function Safe\json_decode;
/**
* Class RecurringRepository
*/
@@ -68,16 +71,16 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
$set
= TransactionJournalMeta::where(static function (Builder $q1) use ($recurrence): void {
$q1->where('name', 'recurrence_id');
$q1->where('data', \Safe\json_encode((string) $recurrence->id));
$q1->where('data', json_encode((string) $recurrence->id));
})->get(['journal_meta.transaction_journal_id']);
// there are X journals made for this recurrence. Any of them meant for today?
foreach ($set as $journalMeta) {
$count = TransactionJournalMeta::where(static function (Builder $q2) use ($date): void {
$string = (string) $date;
app('log')->debug(sprintf('Search for date: %s', \Safe\json_encode($string)));
app('log')->debug(sprintf('Search for date: %s', json_encode($string)));
$q2->where('name', 'recurrence_date');
$q2->where('data', \Safe\json_encode($string));
$q2->where('data', json_encode($string));
})
->where('transaction_journal_id', $journalMeta->transaction_journal_id)
->count()
@@ -212,10 +215,10 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
->where('journal_meta.name', 'recurrence_id')
->where('journal_meta.data', '"'.$recurrence->id.'"')
;
if (null !== $start) {
if ($start instanceof Carbon) {
$query->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'));
}
if (null !== $end) {
if ($end instanceof Carbon) {
$query->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00'));
}
$count = $query->count('transaction_journals.id');
@@ -232,7 +235,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return TransactionJournalMeta::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id')
->where('transaction_journals.user_id', $this->user->id)
->where('journal_meta.name', '=', 'recurrence_id')
->where('journal_meta.data', '=', \Safe\json_encode((string) $recurrence->id))
->where('journal_meta.data', '=', json_encode((string) $recurrence->id))
->get(['journal_meta.transaction_journal_id'])->pluck('transaction_journal_id')->toArray()
;
}
@@ -272,7 +275,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
/** @var RecurrenceMeta $meta */
foreach ($transaction->recurrenceTransactionMeta as $meta) {
if ('tags' === $meta->name && '' !== $meta->value) {
$tags = \Safe\json_decode($meta->value, true, 512, JSON_THROW_ON_ERROR);
$tags = json_decode((string) $meta->value, true, 512, JSON_THROW_ON_ERROR);
}
}
@@ -285,7 +288,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
->whereNull('transaction_journals.deleted_at')
->where('transaction_journals.user_id', $this->user->id)
->where('name', 'recurrence_id')
->where('data', \Safe\json_encode((string) $recurrence->id))
->where('data', json_encode((string) $recurrence->id))
->get()->pluck('transaction_journal_id')->toArray()
;
$search = [];
@@ -311,7 +314,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
->whereNull('transaction_journals.deleted_at')
->where('transaction_journals.user_id', $this->user->id)
->where('name', 'recurrence_id')
->where('data', \Safe\json_encode((string) $recurrence->id))
->where('data', json_encode((string) $recurrence->id))
->get()->pluck('transaction_journal_id')->toArray()
;
$search = [];
@@ -406,7 +409,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
private function filterMaxDate(?Carbon $max, array $occurrences): array
{
$filtered = [];
if (null === $max) {
if (!$max instanceof Carbon) {
foreach ($occurrences as $date) {
if ($date->gt(today())) {
$filtered[] = $date;
@@ -476,7 +479,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
if ('yearly' === $repetition->repetition_type) {
$today = today(config('app.timezone'))->endOfYear();
$repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment);
if (null === $repDate) {
if (!$repDate instanceof Carbon) {
$repDate = clone $today;
}
$diffInYears = (int) $today->diffInYears($repDate, true);

View File

@@ -79,7 +79,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
{
/** @var Rule $rule */
foreach ($ruleGroup->rules as $rule) {
if (null === $moveTo) {
if (!$moveTo instanceof RuleGroup) {
$rule->delete();
continue;
@@ -92,7 +92,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
$ruleGroup->delete();
$this->resetOrder();
if (null !== $moveTo) {
if ($moveTo instanceof RuleGroup) {
$this->resetRuleOrder($moveTo);
}

View File

@@ -50,14 +50,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
$tagIds = [];
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null !== $tags && $tags->count() > 0) {
if ($tags instanceof Collection && $tags->count() > 0) {
$collector->setTags($tags);
$tagIds = $tags->pluck('id')->toArray();
}
if (null === $tags || 0 === $tags->count()) {
if (!$tags instanceof Collection || 0 === $tags->count()) {
$collector->setTags($this->getTags());
$tagIds = $this->getTags()->pluck('id')->toArray();
}
@@ -133,14 +133,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]);
$tagIds = [];
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null !== $tags && $tags->count() > 0) {
if ($tags instanceof Collection && $tags->count() > 0) {
$collector->setTags($tags);
$tagIds = $tags->pluck('id')->toArray();
}
if (null === $tags || 0 === $tags->count()) {
if (!$tags instanceof Collection || 0 === $tags->count()) {
$collector->setTags($this->getTags());
$tagIds = $this->getTags()->pluck('id')->toArray();
}

View File

@@ -231,7 +231,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
if (null !== $start && null !== $end) {
if ($start instanceof Carbon && $end instanceof Carbon) {
$collector->setRange($start, $end);
}
@@ -354,7 +354,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
// otherwise, update or create.
if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) {
$location = $this->getLocation($tag);
if (null === $location) {
if (!$location instanceof Location) {
$location = new Location();
$location->locatable()->associate($tag);
}

View File

@@ -50,6 +50,8 @@ use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Exception;
use function Safe\json_decode;
/**
* Class TransactionGroupRepository
*/
@@ -245,15 +247,14 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
$currency = $transaction->transactionCurrency;
$type = $journal->transactionType->type;
$amount = app('steam')->positive($transaction->amount);
$return = '';
if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
$return = app('amount')->formatAnything($currency, app('steam')->negative($amount));
return app('amount')->formatAnything($currency, app('steam')->negative($amount));
}
if (TransactionTypeEnum::WITHDRAWAL->value !== $type) {
$return = app('amount')->formatAnything($currency, $amount);
return app('amount')->formatAnything($currency, $amount);
}
return $return;
return '';
}
private function getFormattedForeignAmount(TransactionJournal $journal): string
@@ -269,15 +270,14 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
$currency = $transaction->foreignCurrency;
$type = $journal->transactionType->type;
$amount = app('steam')->positive($transaction->foreign_amount);
$return = '';
if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
$return = app('amount')->formatAnything($currency, app('steam')->negative($amount));
return app('amount')->formatAnything($currency, app('steam')->negative($amount));
}
if (TransactionTypeEnum::WITHDRAWAL->value !== $type) {
$return = app('amount')->formatAnything($currency, $amount);
return app('amount')->formatAnything($currency, $amount);
}
return $return;
return '';
}
public function getLocation(int $journalId): ?Location
@@ -305,7 +305,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
$return = [];
foreach ($query as $row) {
$return[$row->name] = new Carbon(\Safe\json_decode($row->data, true, 512, JSON_THROW_ON_ERROR));
$return[$row->name] = new Carbon(json_decode((string) $row->data, true, 512, JSON_THROW_ON_ERROR));
}
return new NullArrayObject($return);
@@ -325,7 +325,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
$return = [];
foreach ($query as $row) {
$return[$row->name] = \Safe\json_decode($row->data);
$return[$row->name] = json_decode((string) $row->data);
}
return new NullArrayObject($return);

View File

@@ -36,14 +36,14 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface
public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType
{
app('log')->debug('Now looking for a transaction type.');
if (null !== $type) {
if ($type instanceof TransactionType) {
app('log')->debug(sprintf('Found $type in parameters, its %s. Will return it.', $type->type));
return $type;
}
$typeString ??= TransactionTypeEnum::WITHDRAWAL->value;
$search = $this->findByType($typeString);
if (null === $search) {
if (!$search instanceof TransactionType) {
$search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value);
}
app('log')->debug(sprintf('Tried to search for "%s", came up with "%s". Will return it.', $typeString, $search->type));

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\User;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\GroupMembership;
@@ -56,7 +57,7 @@ class UserRepository implements UserRepositoryInterface
// save old email as pref
app('preferences')->setForUser($user, 'previous_email_latest', $oldEmail);
app('preferences')->setForUser($user, 'previous_email_'.date('Y-m-d-H-i-s'), $oldEmail);
app('preferences')->setForUser($user, 'previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail);
// set undo and confirm token:
app('preferences')->setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16)));
@@ -230,7 +231,7 @@ class UserRepository implements UserRepositoryInterface
public function hasRole(null|Authenticatable|User $user, string $role): bool
{
if (null === $user) {
if (!$user instanceof Authenticatable) {
return false;
}
if ($user instanceof User) {
@@ -391,7 +392,7 @@ class UserRepository implements UserRepositoryInterface
// save old email as pref
app('preferences')->setForUser($user, 'admin_previous_email_latest', $oldEmail);
app('preferences')->setForUser($user, 'admin_previous_email_'.date('Y-m-d-H-i-s'), $oldEmail);
app('preferences')->setForUser($user, 'admin_previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail);
$user->email = $newEmail;
$user->save();
@@ -405,7 +406,7 @@ class UserRepository implements UserRepositoryInterface
public function removeRole(User $user, string $role): void
{
$roleObj = $this->getRole($role);
if (null === $roleObj) {
if (!$roleObj instanceof Role) {
return;
}
$user->roles()->detach($roleObj->id);

View File

@@ -134,7 +134,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
$existingGroup = null;
while ($exists && $loop < 10) {
$existingGroup = $this->findByName($groupName);
if (null === $existingGroup) {
if (!$existingGroup instanceof UserGroup) {
$exists = false;
/** @var null|UserGroup $existingGroup */

View File

@@ -40,6 +40,8 @@ use Illuminate\Support\Facades\DB;
use Override;
use stdClass;
use function Safe\json_encode;
/**
* Class AccountRepository
*
@@ -68,7 +70,7 @@ class AccountRepository implements AccountRepositoryInterface
->where('accounts.active', true)
->where(
static function (EloquentBuilder $q1) use ($number): void {
$json = \Safe\json_encode($number);
$json = json_encode($number);
$q1->where('account_meta.name', '=', 'account_number');
$q1->where('account_meta.data', '=', $json);
}
@@ -167,7 +169,7 @@ class AccountRepository implements AccountRepositoryInterface
{
$account = $this->user->accounts()->find($accountId);
if (null === $account) {
$account = $this->userGroup->accounts()->find($accountId);
return $this->userGroup->accounts()->find($accountId);
}
/** @var null|Account */

View File

@@ -49,13 +49,13 @@ class OperationsRepository implements OperationsRepositoryInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUserGroup($this->userGroup)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
if (null !== $accounts && $accounts->count() > 0) {
if ($accounts instanceof Collection && $accounts->count() > 0) {
$collector->setAccounts($accounts);
}
if (null !== $budgets && $budgets->count() > 0) {
if ($budgets instanceof Collection && $budgets->count() > 0) {
$collector->setBudgets($budgets);
}
if (null === $budgets || (0 === $budgets->count())) {
if (!$budgets instanceof Collection || (0 === $budgets->count())) {
$collector->setBudgets($this->getBudgets());
}
$collector->withBudgetInformation()->withAccountInformation()->withCategoryInformation();

View File

@@ -41,6 +41,8 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use function Safe\json_encode;
/**
* Class CurrencyRepository
*
@@ -81,7 +83,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface
}
// is being used in accounts:
$meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\json_encode((string) $currency->id))->count();
$meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string) $currency->id))->count();
if ($meta > 0) {
Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta));
@@ -89,7 +91,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface
}
// second search using integer check.
$meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\json_encode((int) $currency->id))->count();
$meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((int) $currency->id))->count();
if ($meta > 0) {
Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta));
@@ -117,7 +119,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface
// is being used in accounts (as integer)
$meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
->whereNull('accounts.deleted_at')
->where('account_meta.name', 'currency_id')->where('account_meta.data', \Safe\json_encode($currency->id))->count()
->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode($currency->id))->count()
;
if ($meta > 0) {
Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta));
@@ -239,7 +241,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface
{
$result = $this->findCurrencyNull($currencyId, $currencyCode);
if (null === $result) {
if (!$result instanceof TransactionCurrency) {
Log::debug('Grabbing default currency for this user...');
/** @var null|TransactionCurrency $result */
@@ -262,11 +264,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface
{
Log::debug(sprintf('Now in findCurrencyNull("%s", "%s")', $currencyId, $currencyCode));
$result = $this->find((int) $currencyId);
if (null === $result) {
if (!$result instanceof TransactionCurrency) {
Log::debug(sprintf('Searching for currency with code "%s"...', $currencyCode));
$result = $this->findByCode((string) $currencyCode);
}
if (null !== $result && false === $result->enabled) {
if ($result instanceof TransactionCurrency && false === $result->enabled) {
Log::debug(sprintf('Also enabled currency %s', $result->code));
$this->enable($result);
}

View File

@@ -109,7 +109,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface
public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate
{
$object->rate = $rate;
if (null !== $date) {
if ($date instanceof Carbon) {
$object->date = $date;
}
$object->save();

View File

@@ -29,6 +29,8 @@ use Illuminate\Support\Facades\Validator;
use Closure;
use JsonException;
use function Safe\json_decode;
/**
* Class IsValidBulkClause
*/
@@ -65,7 +67,7 @@ class IsValidBulkClause implements ValidationRule
private function basicValidation(string $value): bool
{
try {
$array = \Safe\json_decode($value, true, 8, JSON_THROW_ON_ERROR);
$array = json_decode($value, true, 8, JSON_THROW_ON_ERROR);
} catch (JsonException) {
$this->error = (string) trans('validation.json');

View File

@@ -30,6 +30,8 @@ use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Log;
use Closure;
use function Safe\json_encode;
class IsValidPositiveAmount implements ValidationRule
{
use ValidatesAmountsTrait;
@@ -41,7 +43,7 @@ class IsValidPositiveAmount implements ValidationRule
{
if (is_array($value)) {
$fail('validation.numeric')->translate();
$message = sprintf('IsValidPositiveAmount: "%s" is not a number.', \Safe\json_encode($value));
$message = sprintf('IsValidPositiveAmount: "%s" is not a number.', json_encode($value));
Log::debug($message);
Log::channel('audit')->info($message);

View File

@@ -30,6 +30,8 @@ use FireflyIII\Models\AccountMeta;
use Illuminate\Contracts\Validation\ValidationRule;
use Closure;
use function Safe\json_encode;
/**
* Class UniqueAccountNumber
*/
@@ -134,10 +136,10 @@ class UniqueAccountNumber implements ValidationRule
->where('accounts.user_id', auth()->user()->id)
->where('account_types.type', $type)
->where('account_meta.name', '=', 'account_number')
->where('account_meta.data', \Safe\json_encode($accountNumber))
->where('account_meta.data', json_encode($accountNumber))
;
if (null !== $this->account) {
if ($this->account instanceof Account) {
$query->where('accounts.id', '!=', $this->account->id);
}

View File

@@ -160,7 +160,7 @@ class UniqueIban implements ValidationRule
->whereIn('account_types.type', $typesArray)
;
if (null !== $this->account) {
if ($this->account instanceof Account) {
$query->where('accounts.id', '!=', $this->account->id);
}

View File

@@ -31,6 +31,8 @@ use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use JsonException;
use function Safe\json_decode;
/**
* Class UpdateRequest
*/
@@ -100,7 +102,7 @@ class UpdateRequest implements UpdateRequestInterface
$body = (string) $res->getBody();
try {
$json = \Safe\json_decode($body, true, 512, JSON_THROW_ON_ERROR);
$json = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
Log::error('Body is not valid JSON');
Log::error($body);
@@ -118,7 +120,7 @@ class UpdateRequest implements UpdateRequestInterface
// parse response a bit. No message yet.
$response = $json['firefly_iii'][$channel];
$date = Carbon::createFromFormat('Y-m-d', $response['date']);
if (null === $date) {
if (!$date instanceof Carbon) {
$date = today(config('app.timezone'));
}
$return['version'] = $response['version'];

View File

@@ -44,12 +44,12 @@ class AccountDestroyService
// find and delete opening balance journal + opposing account
$this->destroyOpeningBalance($account);
if (null !== $moveTo) {
if ($moveTo instanceof Account) {
$this->moveTransactions($account, $moveTo);
$this->updateRecurrences($account, $moveTo);
}
// delete recurring transactions with this account:
if (null === $moveTo) {
if (!$moveTo instanceof Account) {
$this->destroyRecurrences($account);
}

View File

@@ -60,10 +60,10 @@ class CreditRecalculateService
if (true !== config('firefly.feature_flags.handle_debts')) {
return;
}
if (null !== $this->group && null === $this->account) {
if ($this->group instanceof TransactionGroup && !$this->account instanceof Account) {
$this->processGroup();
}
if (null !== $this->account && null === $this->group) {
if ($this->account instanceof Account && !$this->group instanceof TransactionGroup) {
// work based on account.
$this->processAccount();
}
@@ -163,7 +163,7 @@ class CreditRecalculateService
$this->repository->setUser($account->user);
$direction = (string) $this->repository->getMetaValue($account, 'liability_direction');
$openingBalance = $this->repository->getOpeningBalance($account);
if (null !== $openingBalance) {
if ($openingBalance instanceof TransactionJournal) {
// Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id));
// if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account:
if ('debit' === $direction) {
@@ -358,7 +358,7 @@ class CreditRecalculateService
{
$usedAmount = $transaction->amount;
// Log::debug(sprintf('Amount of transaction is %s', app('steam')->bcround($usedAmount, 2)));
if (null !== $foreignCurrency && $foreignCurrency->id === $accountCurrency->id) {
if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $accountCurrency->id) {
$usedAmount = $transaction->foreign_amount;
// Log::debug(sprintf('Overruled by foreign amount. Amount of transaction is now %s', app('steam')->bcround($usedAmount, 2)));
}

View File

@@ -39,6 +39,8 @@ use FireflyIII\Rules\UniqueIban;
use FireflyIII\Support\NullArrayObject;
use Illuminate\Support\Facades\Log;
use function Safe\json_encode;
/**
* Trait JournalServiceTrait
*/
@@ -140,7 +142,7 @@ trait JournalServiceTrait
private function findAccountByIban(?Account $account, array $data, array $types): ?Account
{
if (null !== $account) {
if ($account instanceof Account) {
Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
return $account;
@@ -167,7 +169,7 @@ trait JournalServiceTrait
private function findAccountByNumber(?Account $account, array $data, array $types): ?Account
{
if (null !== $account) {
if ($account instanceof Account) {
Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
return $account;
@@ -196,7 +198,7 @@ trait JournalServiceTrait
private function findAccountByName(?Account $account, array $data, array $types): ?Account
{
if (null !== $account) {
if ($account instanceof Account) {
Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
return $account;
@@ -247,7 +249,7 @@ trait JournalServiceTrait
{
Log::debug('Now in createAccount()', $data);
// return new account.
if (null !== $account) {
if ($account instanceof Account) {
Log::debug(
sprintf(
'Was given %s account #%d ("%s") so will simply return that.',
@@ -257,10 +259,10 @@ trait JournalServiceTrait
)
);
}
if (null === $account) {
if (!$account instanceof Account) {
// final attempt, create it.
if (AccountTypeEnum::ASSET->value === $preferredType) {
throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with these values: %s', \Safe\json_encode($data)));
throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with these values: %s', json_encode($data)));
}
// fix name of account if only IBAN is given:
if ('' === (string) $data['name'] && '' !== (string) $data['iban']) {
@@ -320,7 +322,7 @@ trait JournalServiceTrait
private function getCashAccount(?Account $account, array $data, array $types): ?Account
{
// return cash account.
if (null === $account && '' === (string) $data['name']
if (!$account instanceof Account && '' === (string) $data['name']
&& in_array(AccountTypeEnum::CASH->value, $types, true)) {
$account = $this->accountRepository->getCashAccount();
}

View File

@@ -43,6 +43,8 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Validation\AccountValidator;
use Illuminate\Support\Facades\Log;
use function Safe\json_encode;
/**
* Trait RecurringTransactionTrait
*/
@@ -307,9 +309,9 @@ trait RecurringTransactionTrait
/** @var null|RecurrenceMeta $entry */
$entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first();
if (null === $entry) {
$entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => \Safe\json_encode($tags)]);
$entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]);
}
$entry->value = \Safe\json_encode($tags);
$entry->value = json_encode($tags);
$entry->save();
}
if (0 === count($tags)) {

View File

@@ -238,7 +238,7 @@ class AccountUpdateService
// otherwise, update or create.
if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) {
$location = $this->accountRepository->getLocation($account);
if (null === $location) {
if (!$location instanceof Location) {
$location = new Location();
$location->locatable()->associate($account);
}

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update;
use FireflyIII\Models\ObjectGroup;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\Bill;
@@ -100,7 +101,7 @@ class BillUpdateService
$objectGroupTitle = $data['object_group_title'] ?? '';
if ('' !== $objectGroupTitle) {
$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
if (null !== $objectGroup) {
if ($objectGroup instanceof ObjectGroup) {
$bill->objectGroups()->sync([$objectGroup->id]);
$bill->save();
}
@@ -116,7 +117,7 @@ class BillUpdateService
$objectGroupId = (int) ($data['object_group_id'] ?? 0);
if (0 !== $objectGroupId) {
$objectGroup = $this->findObjectGroupById($objectGroupId);
if (null !== $objectGroup) {
if ($objectGroup instanceof ObjectGroup) {
$bill->objectGroups()->sync([$objectGroup->id]);
$bill->save();
}
@@ -232,14 +233,14 @@ class BillUpdateService
/** @var Rule $rule */
foreach ($rules as $rule) {
$trigger = $this->getRuleTrigger($rule, $key);
if (null !== $trigger && $trigger->trigger_value === $oldValue) {
if ($trigger instanceof RuleTrigger && $trigger->trigger_value === $oldValue) {
app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue));
$trigger->trigger_value = $newValue;
$trigger->save();
continue;
}
if (null !== $trigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true)
if ($trigger instanceof RuleTrigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true)
&& 0 === bccomp($trigger->trigger_value, $oldValue)) {
app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue));
$trigger->trigger_value = $newValue;

View File

@@ -187,10 +187,10 @@ class GroupUpdateService
Log::debug('Call createTransactionJournal');
$newJournal = $this->createTransactionJournal($transactionGroup, $transaction);
Log::debug('Done calling createTransactionJournal');
if (null !== $newJournal) {
if ($newJournal instanceof TransactionJournal) {
$updated[] = $newJournal->id;
}
if (null === $newJournal) {
if (!$newJournal instanceof TransactionJournal) {
Log::error('createTransactionJournal returned NULL, indicating something went wrong.');
}
}

View File

@@ -226,7 +226,7 @@ class JournalUpdateService
private function getOriginalSourceAccount(): Account
{
if (null === $this->sourceAccount) {
if (!$this->sourceAccount instanceof Account) {
$source = $this->getSourceTransaction();
$this->sourceAccount = $source->account;
}
@@ -236,7 +236,7 @@ class JournalUpdateService
private function getSourceTransaction(): Transaction
{
if (null === $this->sourceTransaction) {
if (!$this->sourceTransaction instanceof Transaction) {
/** @var null|Transaction $result */
$result = $this->transactionJournal->transactions()->with(['account'])->where('amount', '<', 0)->first();
$this->sourceTransaction = $result;
@@ -304,7 +304,7 @@ class JournalUpdateService
private function getOriginalDestinationAccount(): Account
{
if (null === $this->destinationAccount) {
if (!$this->destinationAccount instanceof Account) {
$destination = $this->getDestinationTransaction();
$this->destinationAccount = $destination->account;
}
@@ -317,7 +317,7 @@ class JournalUpdateService
*/
private function getDestinationTransaction(): Transaction
{
if (null === $this->destinationTransaction) {
if (!$this->destinationTransaction instanceof Transaction) {
/** @var null|Transaction $result */
$result = $this->transactionJournal->transactions()->where('amount', '>', 0)->first();
$this->destinationTransaction = $result;

View File

@@ -145,7 +145,7 @@ class RecurrenceUpdateService
app('log')->debug('Loop and find');
foreach ($repetitions as $current) {
$match = $this->matchRepetition($recurrence, $current);
if (null === $match) {
if (!$match instanceof RecurrenceRepetition) {
throw new FireflyException('Cannot match recurring repetition to existing repetition. Not sure what to do. Break.');
}
$fields = [

View File

@@ -34,6 +34,8 @@ use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use JsonException;
use function Safe\json_encode;
/**
* Class StandardWebhookSender
*/
@@ -81,7 +83,7 @@ class StandardWebhookSender implements WebhookSenderInterface
app('log')->debug(sprintf('Trying to send webhook message #%d', $this->message->id));
try {
$json = \Safe\json_encode($this->message->message, JSON_THROW_ON_ERROR);
$json = json_encode($this->message->message, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
app('log')->error('Did not send message because of a JSON error.');
app('log')->error($e->getMessage());

View File

@@ -115,7 +115,7 @@ class Amount
public function convertToNative(?User $user = null): bool
{
if (null === $user) {
if (!$user instanceof User) {
return true === Preferences::get('convert_to_native', false)->data && true === config('cer.enabled');
// Log::debug(sprintf('convertToNative [a]: %s', var_export($result, true)));
}
@@ -286,7 +286,7 @@ class Amount
public static function getAmountJsConfig(bool $sepBySpace, int $signPosn, string $sign, bool $csPrecedes): string
{
// negative first:
$space = ' ';
$space = ' ';
// require space between symbol and amount?
if (false === $sepBySpace) {
@@ -295,11 +295,11 @@ class Amount
// there are five possible positions for the "+" or "-" sign (if it is even used)
// pos_a and pos_e could be the ( and ) symbol.
$posA = ''; // before everything
$posB = ''; // before currency symbol
$posC = ''; // after currency symbol
$posD = ''; // before amount
$posE = ''; // after everything
$posA = ''; // before everything
$posB = ''; // before currency symbol
$posC = ''; // after currency symbol
$posD = ''; // before amount
$posE = ''; // after everything
// format would be (currency before amount)
// AB%sC_D%vE
@@ -340,14 +340,10 @@ class Amount
$posC = $sign;
}
// default is amount before currency
$format = $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE;
if ($csPrecedes) {
// alternative is currency before amount
$format = $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE;
return $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE;
}
return $format;
return $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE;
}
}

View File

@@ -56,7 +56,7 @@ class RemoteUserGuard implements Guard
public function authenticate(): void
{
Log::debug(sprintf('Now at %s', __METHOD__));
if (null !== $this->user) {
if ($this->user instanceof User) {
Log::debug(sprintf('%s is found: #%d, "%s".', $this->user::class, $this->user->id, $this->user->email));
return;
@@ -112,14 +112,14 @@ class RemoteUserGuard implements Guard
{
Log::debug(sprintf('Now at %s', __METHOD__));
return null !== $this->user();
return $this->user() instanceof User;
}
public function user(): ?User
{
Log::debug(sprintf('Now at %s', __METHOD__));
$user = $this->user;
if (null === $user) {
if (!$user instanceof User) {
Log::debug('User is NULL');
return null;

View File

@@ -23,10 +23,13 @@ declare(strict_types=1);
namespace FireflyIII\Support;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use JsonException;
use function Safe\json_encode;
/**
* Class CacheProperties.
*/
@@ -80,10 +83,10 @@ class CacheProperties
$content = '';
foreach ($this->properties as $property) {
try {
$content = sprintf('%s%s', $content, \Safe\json_encode($property, JSON_THROW_ON_ERROR));
$content = sprintf('%s%s', $content, json_encode($property, JSON_THROW_ON_ERROR));
} catch (JsonException) {
// @ignoreException
$content = sprintf('%s%s', $content, hash('sha256', (string) time()));
$content = sprintf('%s%s', $content, hash('sha256', (string) Carbon::now()->getTimestamp()));
}
}
$this->hash = substr(hash('sha256', $content), 0, 16);

View File

@@ -65,7 +65,7 @@ class Calculator
private static function loadIntervalMap(): SplObjectStorage
{
if (null !== self::$intervalMap) {
if (self::$intervalMap instanceof SplObjectStorage) {
return self::$intervalMap;
}
self::$intervalMap = new SplObjectStorage();

View File

@@ -124,7 +124,7 @@ class WholePeriodChartGenerator
$step = '1M';
}
if ($months > 100) {
$step = '1Y';
return '1Y';
}
return $step;

View File

@@ -38,7 +38,7 @@ class AutoBudgetCronjob extends AbstractCronjob
/** @var Configuration $config */
$config = app('fireflyconfig')->get('last_ab_job', 0);
$lastTime = (int) $config->data;
$diff = time() - $lastTime;
$diff = Carbon::now()->getTimestamp() - $lastTime;
$diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);
if (0 === $lastTime) {
app('log')->info('Auto budget cron-job has never fired before.');

View File

@@ -44,7 +44,7 @@ class BillWarningCronjob extends AbstractCronjob
/** @var Configuration $config */
$config = app('fireflyconfig')->get('last_bw_job', 0);
$lastTime = (int) $config->data;
$diff = time() - $lastTime;
$diff = Carbon::now()->getTimestamp() - $lastTime;
$diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);
if (0 === $lastTime) {

View File

@@ -39,7 +39,7 @@ class ExchangeRatesCronjob extends AbstractCronjob
/** @var Configuration $config */
$config = app('fireflyconfig')->get('last_cer_job', 0);
$lastTime = (int) $config->data;
$diff = time() - $lastTime;
$diff = Carbon::now()->getTimestamp() - $lastTime;
$diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);
if (0 === $lastTime) {
Log::info('Exchange rates cron-job has never fired before.');

View File

@@ -44,7 +44,7 @@ class RecurringCronjob extends AbstractCronjob
/** @var Configuration $config */
$config = app('fireflyconfig')->get('last_rt_job', 0);
$lastTime = (int) $config->data;
$diff = time() - $lastTime;
$diff = Carbon::now()->getTimestamp() - $lastTime;
$diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);
if (0 === $lastTime) {

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Cronjobs;
use Carbon\Carbon;
use FireflyIII\Helpers\Update\UpdateTrait;
use FireflyIII\Models\Configuration;
use FireflyIII\Support\Facades\FireflyConfig;
@@ -55,8 +56,8 @@ class UpdateCheckCronjob extends AbstractCronjob
// TODO this is duplicate.
/** @var Configuration $lastCheckTime */
$lastCheckTime = FireflyConfig::get('last_update_check', time());
$now = time();
$lastCheckTime = FireflyConfig::get('last_update_check', Carbon::now()->getTimestamp());
$now = Carbon::now()->getTimestamp();
$diff = $now - $lastCheckTime->data;
Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff));
if ($diff < 604800 && false === $this->force) {
@@ -64,7 +65,7 @@ class UpdateCheckCronjob extends AbstractCronjob
$this->jobFired = false;
$this->jobErrored = false;
$this->jobSucceeded = true;
$this->message = sprintf('Checked for updates less than a week ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data));
$this->message = sprintf('Checked for updates less than a week ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s'));
return;
}

View File

@@ -54,7 +54,7 @@ class FireflyConfig
public function getEncrypted(string $name, mixed $default = null): ?Configuration
{
$result = $this->get($name, $default);
if (null === $result) {
if (!$result instanceof Configuration) {
return null;
}
if ('' === $result->data) {

View File

@@ -59,7 +59,7 @@ class AccountForm
private function getAccountsGrouped(array $types, ?AccountRepositoryInterface $repository = null): array
{
if (null === $repository) {
if (!$repository instanceof AccountRepositoryInterface) {
$repository = $this->getAccountRepository();
}
$accountList = $repository->getActiveAccountsByType($types);

View File

@@ -85,14 +85,13 @@ trait FormSupport
{
// Get errors from session:
/** @var null|MessageBag $errors */
$errors = session('errors');
$classes = 'form-group';
$errors = session('errors');
if (null !== $errors && $errors->has($name)) {
$classes = 'form-group has-error has-feedback';
return 'form-group has-error has-feedback';
}
return $classes;
return 'form-group';
}
/**
@@ -112,7 +111,7 @@ trait FormSupport
}
if ($value instanceof Carbon) {
$value = $value->format('Y-m-d');
return $value->format('Y-m-d');
}
return $value;

View File

@@ -215,7 +215,6 @@ class AccountBalanceGrouped
private function getDataKey(array $journal): string
{
$key = 'spent';
// deposit = incoming
// transfer or reconcile or opening balance, and these accounts are the destination.
if (
@@ -230,10 +229,10 @@ class AccountBalanceGrouped
&& in_array($journal['destination_account_id'], $this->accountIds, true)
)
) {
$key = 'earned';
return 'earned';
}
return $key;
return 'spent';
}
private function getRate(TransactionCurrency $currency, Carbon $date): string

View File

@@ -33,6 +33,8 @@ use Illuminate\Support\Facades\Log;
use Laravel\Passport\Passport;
use phpseclib3\Crypt\RSA;
use function Safe\file_put_contents;
/**
* Trait CreateStuff
*/
@@ -106,8 +108,8 @@ trait CreateStuff
Log::alert('NO OAuth keys were found. They have been created.');
\Safe\file_put_contents($publicKey, (string) $key->getPublicKey());
\Safe\file_put_contents($privateKey, $key->toString('PKCS1'));
file_put_contents($publicKey, (string) $key->getPublicKey());
file_put_contents($privateKey, $key->toString('PKCS1'));
}
/**

View File

@@ -77,7 +77,7 @@ trait DateCalculation
$step = '1M';
}
if ($months > 100) {
$step = '1Y';
return '1Y';
}
return $step;

View File

@@ -207,7 +207,7 @@ trait GetConfigurationData
{
$config = app('fireflyconfig')->get('last_rt_job', 0);
$lastTime = (int) $config?->data;
$now = time();
$now = Carbon::now()->getTimestamp();
app('log')->debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config?->data, $now));
if (0 === $lastTime) {
request()->session()->flash('info', trans('firefly.recurring_never_cron'));

View File

@@ -36,6 +36,8 @@ use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Route as RouteFacade;
use Hash;
use function Safe\parse_url;
/**
* Trait RequestInformation
*/
@@ -47,7 +49,7 @@ trait RequestInformation
final protected function getDomain(): string // get request info
{
$url = url()->to('/');
$parts = \Safe\parse_url($url);
$parts = parse_url($url);
return $parts['host'] ?? '';
}
@@ -95,7 +97,7 @@ trait RequestInformation
$shownDemo = app('preferences')->get($key, false)->data;
}
if (!is_bool($shownDemo)) {
$shownDemo = true;
return true;
}
return $shownDemo;
@@ -123,20 +125,19 @@ trait RequestInformation
final protected function notInSessionRange(Carbon $date): bool // Validate a preference
{
/** @var Carbon $start */
$start = session('start', today(config('app.timezone'))->startOfMonth());
$start = session('start', today(config('app.timezone'))->startOfMonth());
/** @var Carbon $end */
$end = session('end', today(config('app.timezone'))->endOfMonth());
$result = false;
$end = session('end', today(config('app.timezone'))->endOfMonth());
if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) {
$result = true;
return true;
}
// start and end in the past? use $end
if ($start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date)) {
$result = true;
return true;
}
return $result;
return false;
}
/**
@@ -147,14 +148,14 @@ trait RequestInformation
$attributes['location'] ??= '';
$attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', []));
$date = Carbon::createFromFormat('Ymd', $attributes['startDate']);
if (null === $date) {
if (!$date instanceof Carbon) {
$date = today(config('app.timezone'));
}
$date->startOfMonth();
$attributes['startDate'] = $date;
$date2 = Carbon::createFromFormat('Ymd', $attributes['endDate']);
if (null === $date2) {
if (!$date2 instanceof Carbon) {
$date2 = today(config('app.timezone'));
}
$date2->endOfDay();

View File

@@ -83,7 +83,7 @@ class AccountBalanceCalculator
if ($accounts->count() > 0) {
$query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray());
}
if (null !== $notBefore) {
if ($notBefore instanceof Carbon) {
$notBefore->startOfDay();
$query->where('transaction_journals.date', '>=', $notBefore);
}
@@ -124,7 +124,7 @@ class AccountBalanceCalculator
private function getLatestBalance(int $accountId, int $currencyId, ?Carbon $notBefore): string
{
if (null === $notBefore) {
if (!$notBefore instanceof Carbon) {
return '0';
}
Log::debug(sprintf('getLatestBalance: notBefore date is "%s", calculating', $notBefore->format('Y-m-d')));

View File

@@ -83,7 +83,7 @@ class BillDateCalculator
// AND date is after last paid date
if (
$nextExpectedMatch->gte($earliest) // date is after "earliest possible date"
&& (null === $lastPaid || $nextExpectedMatch->gt($lastPaid)) // date is after last paid date, if that date is not NULL
&& (!$lastPaid instanceof Carbon || $nextExpectedMatch->gt($lastPaid)) // date is after last paid date, if that date is not NULL
) {
Log::debug('Add date to set, because it is after earliest possible date and after last paid date.');
$set->push(clone $nextExpectedMatch);

View File

@@ -421,7 +421,7 @@ class Navigation
$currentEnd->{$function}(); // @phpstan-ignore-line
}
if (null !== $maxDate && $currentEnd > $maxDate) {
if ($maxDate instanceof Carbon && $currentEnd > $maxDate) {
return clone $maxDate;
}
@@ -502,7 +502,7 @@ class Navigation
if ($diff >= 12.001) {
// Log::debug(sprintf('Return Y because %s', $diff));
$format = 'Y';
return 'Y';
}
return $format;
@@ -565,16 +565,15 @@ class Navigation
public function preferredCarbonLocalizedFormat(Carbon $start, Carbon $end): string
{
$locale = app('steam')->getLocale();
$format = (string) trans('config.month_and_day_js', [], $locale);
if ($start->diffInMonths($end, true) > 1) {
$format = (string) trans('config.month_js', [], $locale);
return (string) trans('config.month_js', [], $locale);
}
if ($start->diffInMonths($end, true) > 12) {
$format = (string) trans('config.year_js', [], $locale);
return (string) trans('config.year_js', [], $locale);
}
return $format;
return (string) trans('config.month_and_day_js', [], $locale);
}
/**
@@ -583,16 +582,15 @@ class Navigation
*/
public function preferredEndOfPeriod(Carbon $start, Carbon $end): string
{
$format = 'endOfDay';
if ((int) $start->diffInMonths($end, true) > 1) {
$format = 'endOfMonth';
return 'endOfMonth';
}
if ((int) $start->diffInMonths($end, true) > 12) {
$format = 'endOfYear';
return 'endOfYear';
}
return $format;
return 'endOfDay';
}
/**
@@ -601,16 +599,15 @@ class Navigation
*/
public function preferredRangeFormat(Carbon $start, Carbon $end): string
{
$format = '1D';
if ((int) $start->diffInMonths($end, true) > 1) {
$format = '1M';
return '1M';
}
if ((int) $start->diffInMonths($end, true) > 12) {
$format = '1Y';
return '1Y';
}
return $format;
return '1D';
}
/**
@@ -619,16 +616,15 @@ class Navigation
*/
public function preferredSqlFormat(Carbon $start, Carbon $end): string
{
$format = '%Y-%m-%d';
if ((int) $start->diffInMonths($end, true) > 1) {
$format = '%Y-%m';
return '%Y-%m';
}
if ((int) $start->diffInMonths($end, true) > 12) {
$format = '%Y';
return '%Y';
}
return $format;
return '%Y-%m-%d';
}
/**

View File

@@ -30,6 +30,8 @@ use Carbon\Exceptions\InvalidFormatException;
use FireflyIII\Exceptions\FireflyException;
use Illuminate\Support\Facades\Log;
use function Safe\preg_match;
/**
* Class ParseDateString
*/
@@ -85,7 +87,7 @@ class ParseDateString
// if regex for YYYY-MM-DD:
$pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
return $this->parseDefaultDate($date);
}
@@ -148,7 +150,7 @@ class ParseDateString
Log::error(sprintf('parseDefaultDate("%s") ran into an error, but dont mind: %s', $date, $e->getMessage()));
}
if (false === $result) {
$result = today(config('app.timezone'))->startOfDay();
return today(config('app.timezone'))->startOfDay();
}
return $result;
@@ -182,7 +184,7 @@ class ParseDateString
// verify if correct
$pattern = '/[+-]\d+[wqmdy]/';
$result = \Safe\preg_match($pattern, $part);
$result = preg_match($pattern, $part);
if (0 === $result || false === $result) {
app('log')->error(sprintf('Part "%s" does not match regular expression. Will be skipped.', $part));
@@ -256,7 +258,7 @@ class ParseDateString
protected function isDayRange(string $date): bool
{
$pattern = '/^xxxx-xx-(0[1-9]|[12]\d|3[01])$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a day range.', $date));
@@ -283,7 +285,7 @@ class ParseDateString
{
// if regex for xxxx-MM-xx:
$pattern = '/^xxxx-(0[1-9]|1[012])-xx$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a month range.', $date));
@@ -311,7 +313,7 @@ class ParseDateString
{
// if regex for YYYY-xx-xx:
$pattern = '/^(19|20)\d\d-xx-xx$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a year range.', $date));
@@ -339,7 +341,7 @@ class ParseDateString
{
// if regex for xxxx-MM-DD:
$pattern = '/^xxxx-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a month/day range.', $date));
@@ -368,7 +370,7 @@ class ParseDateString
{
// if regex for YYYY-xx-DD:
$pattern = '/^(19|20)\d\d-xx-(0[1-9]|[12]\d|3[01])$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a day/year range.', $date));
@@ -397,7 +399,7 @@ class ParseDateString
{
// if regex for YYYY-MM-xx:
$pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-xx$/';
$result = \Safe\preg_match($pattern, $date);
$result = preg_match($pattern, $date);
if (false !== $result && 0 !== $result) {
app('log')->debug(sprintf('"%s" is a month/year range.', $date));

View File

@@ -110,7 +110,7 @@ class Preferences
$groupId = null;
$items = config('firefly.admin_specific_prefs') ?? [];
if (in_array($preferenceName, $items, true)) {
$groupId = (int) $user->user_group_id;
return (int) $user->user_group_id;
}
return $groupId;
@@ -215,7 +215,7 @@ class Preferences
public function getEncrypted(string $name, mixed $default = null): ?Preference
{
$result = $this->get($name, $default);
if (null === $result) {
if (!$result instanceof Preference) {
return null;
}
if ('' === $result->data) {
@@ -286,7 +286,7 @@ class Preferences
$lastActivity = microtime();
$preference = $this->get('lastActivity', microtime());
if (null !== $preference && null !== $preference->data) {
if ($preference instanceof Preference && null !== $preference->data) {
$lastActivity = $preference->data;
}
if (is_array($lastActivity)) {

View File

@@ -37,7 +37,7 @@ class TransactionSummarizer
public function __construct(?User $user = null)
{
if (null !== $user) {
if ($user instanceof User) {
$this->setUser($user);
}
}

View File

@@ -32,6 +32,8 @@ use FireflyIII\Support\Facades\Steam;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use function Safe\preg_replace;
/**
* Trait ConvertsDataTypes
*/
@@ -125,7 +127,7 @@ trait ConvertsDataTypes
$string = str_replace($this->characters, "\x20", $string);
// clear zalgo text (TODO also in API v2)
$string = \Safe\preg_replace('/(\pM{2})\pM+/u', '\1', $string);
$string = preg_replace('/(\pM{2})\pM+/u', '\1', $string);
return trim((string) $string);
}
@@ -263,7 +265,7 @@ trait ConvertsDataTypes
return null;
}
if (null === $carbon) {
if (!$carbon instanceof Carbon) {
app('log')->error(sprintf('[2] "%s" is of an invalid format.', $value));
return null;
@@ -316,7 +318,7 @@ trait ConvertsDataTypes
} catch (InvalidFormatException) {
// @ignoreException
}
if (null === $carbon) {
if (!$carbon instanceof Carbon) {
app('log')->debug(sprintf('Invalid date: %s', $string));
return null;
@@ -380,7 +382,7 @@ trait ConvertsDataTypes
// @ignoreException
Log::debug(sprintf('Exception when parsing date "%s".', $this->get($field)));
}
if (null === $result) {
if (!$result instanceof Carbon) {
app('log')->debug(sprintf('Exception when parsing date "%s".', $this->get($field)));
}

View File

@@ -29,6 +29,8 @@ use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use function Safe\json_encode;
/**
* Class AccountSearch
*/
@@ -81,7 +83,7 @@ class AccountSearch implements GenericSearchInterface
// meta data:
$searchQuery->orWhere(
static function (Builder $q) use ($originalQuery): void {
$json = \Safe\json_encode($originalQuery, JSON_THROW_ON_ERROR);
$json = json_encode($originalQuery, JSON_THROW_ON_ERROR);
$q->where('account_meta.name', '=', 'account_number');
$q->whereLike('account_meta.data', $json);
}
@@ -108,7 +110,7 @@ class AccountSearch implements GenericSearchInterface
// meta data:
$searchQuery->Where(
static function (Builder $q) use ($originalQuery): void {
$json = \Safe\json_encode($originalQuery, JSON_THROW_ON_ERROR);
$json = json_encode($originalQuery, JSON_THROW_ON_ERROR);
$q->where('account_meta.name', 'account_number');
$q->where('account_meta.data', $json);
}

View File

@@ -719,10 +719,10 @@ class OperatorQuerySearch implements SearchInterface
//
case 'currency_is':
$currency = $this->findCurrency($value);
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
$this->collector->setCurrency($currency);
}
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
$this->collector->findNothing();
}
@@ -730,10 +730,10 @@ class OperatorQuerySearch implements SearchInterface
case '-currency_is':
$currency = $this->findCurrency($value);
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
$this->collector->excludeCurrency($currency);
}
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
$this->collector->findNothing();
}
@@ -741,10 +741,10 @@ class OperatorQuerySearch implements SearchInterface
case 'foreign_currency_is':
$currency = $this->findCurrency($value);
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
$this->collector->setForeignCurrency($currency);
}
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
$this->collector->findNothing();
}
@@ -752,10 +752,10 @@ class OperatorQuerySearch implements SearchInterface
case '-foreign_currency_is':
$currency = $this->findCurrency($value);
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
$this->collector->excludeForeignCurrency($currency);
}
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
$this->collector->findNothing();
}
@@ -2109,7 +2109,7 @@ class OperatorQuerySearch implements SearchInterface
}
$result = $this->currencyRepository->findByCode($value);
if (null === $result) {
$result = $this->currencyRepository->findByName($value);
return $this->currencyRepository->findByName($value);
}
return $result;

View File

@@ -33,6 +33,8 @@ use Illuminate\Support\Facades\Log;
use LogicException;
use TypeError;
use function Safe\fwrite;
class GdbotsQueryParser implements QueryParserInterface
{
private readonly BaseQueryParser $parser;
@@ -56,7 +58,7 @@ class GdbotsQueryParser implements QueryParserInterface
return new NodeGroup($nodes);
} catch (LogicException|TypeError $e) {
\Safe\fwrite(STDERR, "Setting up GdbotsQueryParserTest\n");
fwrite(STDERR, "Setting up GdbotsQueryParserTest\n");
app('log')->error($e->getMessage());
app('log')->error(sprintf('Could not parse search: "%s".', $query));

View File

@@ -51,7 +51,7 @@ class QueryParser implements QueryParserInterface
$nodes = [];
$nodeResult = $this->buildNextNode($isSubquery);
while (null !== $nodeResult->node) {
while ($nodeResult->node instanceof Node) {
$nodes[] = $nodeResult->node;
if ($nodeResult->isSubqueryEnd) {
break;

View File

@@ -37,6 +37,9 @@ use Illuminate\Support\Str;
use Exception;
use ValueError;
use function Safe\preg_replace;
use function Safe\parse_url;
/**
* Class Steam.
*/
@@ -97,25 +100,25 @@ class Steam
unset($set[$defaultCurrency->code]);
}
// todo rethink this logic.
if (null !== $currency && $defaultCurrency->id !== $currency->id) {
if ($currency instanceof TransactionCurrency && $defaultCurrency->id !== $currency->id) {
Log::debug(sprintf('Unset balance for account #%d', $account->id));
unset($set['balance']);
}
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
Log::debug(sprintf('Unset balance for account #%d', $account->id));
unset($set['balance']);
}
}
if (!$convertToNative) {
if (null === $currency) {
if (!$currency instanceof TransactionCurrency) {
Log::debug(sprintf('Unset native_balance and make defaultCurrency balance the balance for account #%d', $account->id));
$set['balance'] = $set[$defaultCurrency->code] ?? '0';
unset($set[$defaultCurrency->code]);
}
if (null !== $currency) {
if ($currency instanceof TransactionCurrency) {
Log::debug(sprintf('Unset [%s] + [%s] balance for account #%d', $defaultCurrency->code, $currency->code, $account->id));
unset($set[$defaultCurrency->code], $set[$currency->code]);
}
@@ -186,8 +189,8 @@ class Steam
];
// clear zalgo text
$string = \Safe\preg_replace('/(\pM{2})\pM+/u', '\1', $string);
$string = \Safe\preg_replace('/\s+/', '', $string);
$string = preg_replace('/(\pM{2})\pM+/u', '\1', $string);
$string = preg_replace('/\s+/', '', $string);
return str_replace($search, '', $string);
}
@@ -223,7 +226,7 @@ class Steam
$startBalance = $this->finalAccountBalance($account, $request);
$nativeCurrency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup);
$accountCurrency = $this->getAccountCurrency($account);
$hasCurrency = null !== $accountCurrency;
$hasCurrency = $accountCurrency instanceof TransactionCurrency;
$currency = $accountCurrency ?? $nativeCurrency;
Log::debug(sprintf('Currency is %s', $currency->code));
@@ -341,7 +344,7 @@ class Steam
if (null === $convertToNative) {
$convertToNative = Amount::convertToNative($account->user);
}
if (null === $native) {
if (!$native instanceof TransactionCurrency) {
$native = Amount::getNativeCurrencyByUserGroup($account->user->userGroup);
}
// account balance thing.
@@ -516,7 +519,7 @@ class Steam
// Check for Windows to replace the locale correctly.
if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) {
$locale = str_replace('_', '-', $locale);
return str_replace('_', '-', $locale);
}
return $locale;
@@ -568,8 +571,8 @@ class Steam
{
// Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl));
$returnUrl = $safeUrl;
$unknownHost = \Safe\parse_url($unknownUrl, PHP_URL_HOST);
$safeHost = \Safe\parse_url($safeUrl, PHP_URL_HOST);
$unknownHost = parse_url($unknownUrl, PHP_URL_HOST);
$safeHost = parse_url($safeUrl, PHP_URL_HOST);
if (null !== $unknownHost && $unknownHost === $safeHost) {
$returnUrl = $unknownUrl;
@@ -578,7 +581,7 @@ class Steam
// URL must not lead to weird pages
$forbiddenWords = ['jscript', 'json', 'debug', 'serviceworker', 'offline', 'delete', '/login', '/attachments/view'];
if (Str::contains($returnUrl, $forbiddenWords)) {
$returnUrl = $safeUrl;
return $safeUrl;
}
return $returnUrl;
@@ -592,7 +595,7 @@ class Steam
$amount = $this->floatalize($amount);
if (1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
return bcmul($amount, '-1');
}
return $amount;

View File

@@ -32,6 +32,9 @@ use Laravel\Passport\Console\KeysCommand;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use function Safe\file_get_contents;
use function Safe\file_put_contents;
/**
* Class OAuthKeys
*/
@@ -97,8 +100,8 @@ class OAuthKeys
{
$private = storage_path('oauth-private.key');
$public = storage_path('oauth-public.key');
app('fireflyconfig')->set(self::PRIVATE_KEY, Crypt::encrypt(\Safe\file_get_contents($private)));
app('fireflyconfig')->set(self::PUBLIC_KEY, Crypt::encrypt(\Safe\file_get_contents($public)));
app('fireflyconfig')->set(self::PRIVATE_KEY, Crypt::encrypt(file_get_contents($private)));
app('fireflyconfig')->set(self::PUBLIC_KEY, Crypt::encrypt(file_get_contents($public)));
}
/**
@@ -124,8 +127,8 @@ class OAuthKeys
}
$private = storage_path('oauth-private.key');
$public = storage_path('oauth-public.key');
\Safe\file_put_contents($private, $privateContent);
\Safe\file_put_contents($public, $publicContent);
file_put_contents($private, $privateContent);
file_put_contents($public, $publicContent);
return true;
}

View File

@@ -39,6 +39,8 @@ use Twig\TwigFilter;
use Twig\TwigFunction;
use Override;
use function Safe\parse_url;
/**
* Class TwigSupport.
*/
@@ -64,7 +66,7 @@ class General extends AbstractExtension
return new TwigFilter(
'balance',
static function (?Account $account): string {
if (null === $account) {
if (!$account instanceof Account) {
return '0';
}
@@ -180,8 +182,8 @@ class General extends AbstractExtension
return new TwigFilter(
'phphost',
static function (string $string): string {
$proto = (string) \Safe\parse_url($string, PHP_URL_SCHEME);
$host = (string) \Safe\parse_url($string, PHP_URL_HOST);
$proto = (string) parse_url($string, PHP_URL_SCHEME);
$host = (string) parse_url($string, PHP_URL_HOST);
return e(sprintf('%s://%s', $proto, $host));
}

Some files were not shown because too many files have changed in this diff Show More