Various code cleanup

This commit is contained in:
James Cole
2023-10-29 12:10:03 +01:00
parent 9a17a11b37
commit 5e32878d01
21 changed files with 87 additions and 77 deletions

View File

@@ -11,6 +11,7 @@ parameters:
- '#has a nullable return type declaration#'
- '#with a nullable type declaration#'
- '#with null as default value#'
- 'No error to ignore is reported on#'
- '#is not covariant with PHPDoc type array#'
-
message: '#but containers should not be injected#'

View File

@@ -30,8 +30,6 @@ use FireflyIII\Support\Request\GetRuleConfiguration;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use function is_array;
/**
* Class StoreRequest
*/

View File

@@ -31,8 +31,6 @@ use FireflyIII\Support\Request\GetRuleConfiguration;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use function is_array;
/**
* Class UpdateRequest
*/

View File

@@ -27,6 +27,9 @@ namespace FireflyIII\Api\V2\Controllers\Summary;
use FireflyIII\Api\V2\Controllers\Controller;
use FireflyIII\Api\V2\Request\Generic\SingleDateRequest;
use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Support\Http\Api\ConvertsExchangeRates;
use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait;
use Illuminate\Http\JsonResponse;
@@ -39,7 +42,8 @@ class NetWorthController extends Controller
use ValidatesUserGroupTrait;
use ConvertsExchangeRates;
private NetWorthInterface $netWorth;
private NetWorthInterface $netWorth;
private AccountRepositoryInterface $repository;
/**
*
@@ -49,12 +53,13 @@ class NetWorthController extends Controller
parent::__construct();
$this->middleware(
function ($request, $next) {
$this->netWorth = app(NetWorthInterface::class);
$this->netWorth = app(NetWorthInterface::class);
$this->repository = app(AccountRepositoryInterface::class);
// new way of user group validation
$userGroup = $this->validateUserGroup($request);
if (null !== $userGroup) {
$this->netWorth->setUserGroup($userGroup);
$this->repository->setUserGroup($userGroup);
}
return $next($request);
@@ -72,10 +77,21 @@ class NetWorthController extends Controller
*/
public function get(SingleDateRequest $request): JsonResponse
{
$date = $request->getDate();
$result = $this->netWorth->sumNetWorthByCurrency($date);
$converted = $this->cerSum($result);
$date = $request->getDate();
$accounts = $this->repository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
return response()->api($converted);
// filter list on preference of being included.
$filtered = $accounts->filter(
function (Account $account) {
$includeNetWorth = $this->repository->getMetaValue($account, 'include_net_worth');
return null === $includeNetWorth || '1' === $includeNetWorth;
}
);
// skip accounts that should not be in the net worth
$result = $this->netWorth->byAccounts($filtered, $date);
return response()->api($result);
}
}

View File

@@ -87,6 +87,6 @@ class FixFrontpageAccounts extends Command
}
}
}
Preferences::setForUser($preference->user, 'frontPageAccounts', $fixed);
app('preferences')->setForUser($preference->user, 'frontPageAccounts', $fixed);
}
}

View File

@@ -53,8 +53,8 @@ class ForceDecimalSize extends Command
{
use ShowsFriendlyMessages;
protected $description = 'This command resizes DECIMAL columns in MySQL or PostgreSQL and correct amounts (only MySQL).';
protected $signature = 'firefly-iii:force-decimal-size';
protected $description = 'This command resizes DECIMAL columns in MySQL or PostgreSQL and correct amounts (only MySQL).';
protected $signature = 'firefly-iii:force-decimal-size';
private string $cast;
private array $classes
= [
@@ -183,7 +183,7 @@ class ForceDecimalSize extends Command
* @var array $fields
*/
foreach ($this->tables as $name => $fields) {
switch ($name) {
switch ($name) { // @phpstan-ignore-line
default:
$message = sprintf('Cannot handle table "%s"', $name);
$this->friendlyError($message);
@@ -558,22 +558,18 @@ class ForceDecimalSize extends Command
/** @var string $field */
foreach ($fields as $field) {
$this->friendlyLine(sprintf('Updating table "%s", field "%s"...', $name, $field));
switch ($type) {
default:
$this->friendlyError(sprintf('Cannot handle database type "%s".', $type));
return;
case 'pgsql':
$query = sprintf('ALTER TABLE %s ALTER COLUMN %s TYPE DECIMAL(32,12);', $name, $field);
break;
case 'mysql':
$query = sprintf('ALTER TABLE %s CHANGE COLUMN %s %s DECIMAL(32, 12);', $name, $field, $field);
break;
if ('pgsql' === $type) {
DB::select(sprintf('ALTER TABLE %s ALTER COLUMN %s TYPE DECIMAL(32,12);', $name, $field));
sleep(1);
return;
}
if ('mysql' === $type) {
DB::select(sprintf('ALTER TABLE %s CHANGE COLUMN %s %s DECIMAL(32, 12);', $name, $field, $field));
sleep(1);
return;
}
$this->friendlyError(sprintf('Cannot handle database type "%s".', $type));
DB::select($query);
sleep(1);
}
}
}

View File

@@ -50,7 +50,7 @@ class APIEventHandler
if (null !== $user) {
try {
Notification::send($user, new NewAccessToken());
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');

View File

@@ -46,7 +46,7 @@ class AdminEventHandler
*/
public function sendInvitationNotification(InvitationCreated $event): void
{
$sendMail = FireflyConfig::get('notification_invite_created', true)->data;
$sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data;
if (false === $sendMail) {
return;
}
@@ -58,7 +58,7 @@ class AdminEventHandler
if ($repository->hasRole($user, 'owner')) {
try {
Notification::send($user, new UserInvitation($event->invitee));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
@@ -84,7 +84,7 @@ class AdminEventHandler
*/
public function sendNewVersion(NewVersionAvailable $event): void
{
$sendMail = FireflyConfig::get('notification_new_version', true)->data;
$sendMail = app('fireflyconfig')->get('notification_new_version', true)->data;
if (false === $sendMail) {
return;
}
@@ -96,7 +96,7 @@ class AdminEventHandler
if ($repository->hasRole($user, 'owner')) {
try {
Notification::send($user, new VersionCheckResult($event->message));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
@@ -130,7 +130,7 @@ class AdminEventHandler
}
try {
Notification::send($event->user, new TestNotification($event->user->email));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');

View File

@@ -74,7 +74,7 @@ class AutomationHandler
}
try {
Notification::send($user, new TransactionCreation($groups));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');

View File

@@ -51,7 +51,7 @@ class BillEventHandler
app('log')->debug('Bill reminder is true!');
try {
Notification::send($bill->user, new BillReminder($bill, $event->field, $event->diff));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');

View File

@@ -203,7 +203,7 @@ class UserEventHandler
if (false === $entry['notified']) {
try {
Notification::send($user, new UserLogin($ipAddress));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
@@ -228,7 +228,7 @@ class UserEventHandler
*/
public function sendAdminRegistrationNotification(RegisteredUser $event): void
{
$sendMail = FireflyConfig::get('notification_admin_new_reg', true)->data;
$sendMail = app('fireflyconfig')->get('notification_admin_new_reg', true)->data;
if ($sendMail) {
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
@@ -237,7 +237,7 @@ class UserEventHandler
if ($repository->hasRole($user, 'owner')) {
try {
Notification::send($user, new AdminRegistrationNotification($event->user));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
@@ -273,7 +273,7 @@ class UserEventHandler
try {
Mail::to($newEmail)->send(new ConfirmEmailChangeMail($newEmail, $oldEmail, $url));
} catch (Exception $e) { // intentional generic exception
} catch (Exception $e) {
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
@@ -298,7 +298,7 @@ class UserEventHandler
$url = route('profile.undo-email-change', [$token->data, $hashed]);
try {
Mail::to($oldEmail)->send(new UndoEmailChangeMail($newEmail, $oldEmail, $url));
} catch (Exception $e) { // intentional generic exception
} catch (Exception $e) {
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
@@ -314,7 +314,7 @@ class UserEventHandler
{
try {
Notification::send($event->user, new UserNewPassword(route('password.reset', [$event->token])));
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');
@@ -342,7 +342,7 @@ class UserEventHandler
$url = route('invite', [$event->invitee->invite_code]);
try {
Mail::to($invitee)->send(new InvitationMail($invitee, $admin, $url));
} catch (Exception $e) { // intentional generic exception
} catch (Exception $e) {
app('log')->error($e->getMessage());
app('log')->error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
@@ -358,11 +358,11 @@ class UserEventHandler
*/
public function sendRegistrationMail(RegisteredUser $event): void
{
$sendMail = FireflyConfig::get('notification_user_new_reg', true)->data;
$sendMail = app('fireflyconfig')->get('notification_user_new_reg', true)->data;
if ($sendMail) {
try {
Notification::send($event->user, new UserRegistrationNotification());
} catch (Exception $e) {
} catch (Exception $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.');

View File

@@ -226,7 +226,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$validation = $this->validateUpload($file, $model);
$attachment = null;
if (false !== $validation) {
$user = $model->user; // @phpstan-ignore-line
$user = $model->user;
// ignore lines about polymorphic calls.
if ($model instanceof PiggyBank) {
$user = $model->account->user;
@@ -370,7 +370,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
}
if (!($model instanceof PiggyBank)) {
$count = $model->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count(); // @phpstan-ignore-line
$count = $model->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
}
$result = false;
if ($count > 0) {

View File

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

View File

@@ -75,9 +75,9 @@ class HomeController extends Controller
// admin notification settings:
$notifications = [];
foreach (config('firefly.admin_notifications') as $item) {
$notifications[$item] = FireflyConfig::get(sprintf('notification_%s', $item), true)->data;
$notifications[$item] = app('fireflyconfig')->get(sprintf('notification_%s', $item), true)->data;
}
$slackUrl = FireflyConfig::get('slack_webhook_url', '')->data;
$slackUrl = app('fireflyconfig')->get('slack_webhook_url', '')->data;
return view('admin.index', compact('title', 'mainTitleIcon', 'email', 'notifications', 'slackUrl'));
}
@@ -94,14 +94,14 @@ class HomeController extends Controller
if ($request->has(sprintf('notification_%s', $item))) {
$value = true;
}
FireflyConfig::set(sprintf('notification_%s', $item), $value);
app('fireflyconfig')->set(sprintf('notification_%s', $item), $value);
}
$url = (string)$request->get('slackUrl');
if ('' === $url) {
FireflyConfig::delete('slack_webhook_url');
app('fireflyconfig')->delete('slack_webhook_url');
}
if (UrlValidator::isValidWebhookURL($url)) {
FireflyConfig::set('slack_webhook_url', $url);
app('fireflyconfig')->set('slack_webhook_url', $url);
}
session()->flash('success', (string)trans('firefly.notification_settings_saved'));

View File

@@ -61,7 +61,7 @@ class TwoFactorController extends Controller
public function submitMFA(Request $request)
{
/** @var array $mfaHistory */
$mfaHistory = Preferences::get('mfa_history', [])->data;
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$mfaCode = (string)$request->get('one_time_password');
// is in history? then refuse to use it.
@@ -127,7 +127,7 @@ class TwoFactorController extends Controller
private function filterMFAHistory(): void
{
/** @var array $mfaHistory */
$mfaHistory = Preferences::get('mfa_history', [])->data;
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$newHistory = [];
$now = time();
foreach ($mfaHistory as $entry) {
@@ -140,7 +140,7 @@ class TwoFactorController extends Controller
];
}
}
Preferences::set('mfa_history', $newHistory);
app('preferences')->set('mfa_history', $newHistory);
}
/**
@@ -149,14 +149,14 @@ class TwoFactorController extends Controller
private function addToMFAHistory(string $mfaCode): void
{
/** @var array $mfaHistory */
$mfaHistory = Preferences::get('mfa_history', [])->data;
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$entry = [
'time' => time(),
'code' => $mfaCode,
];
$mfaHistory[] = $entry;
Preferences::set('mfa_history', $mfaHistory);
app('preferences')->set('mfa_history', $mfaHistory);
$this->filterMFAHistory();
}
@@ -169,7 +169,7 @@ class TwoFactorController extends Controller
*/
private function isBackupCode(string $mfaCode): bool
{
$list = Preferences::get('mfa_recovery', [])->data;
$list = app('preferences')->get('mfa_recovery', [])->data;
if (in_array($mfaCode, $list, true)) {
return true;
}
@@ -184,8 +184,8 @@ class TwoFactorController extends Controller
*/
private function removeFromBackupCodes(string $mfaCode): void
{
$list = Preferences::get('mfa_recovery', [])->data;
$list = app('preferences')->get('mfa_recovery', [])->data;
$newList = array_values(array_diff($list, [$mfaCode]));
Preferences::set('mfa_recovery', $newList);
app('preferences')->set('mfa_recovery', $newList);
}
}

View File

@@ -201,7 +201,7 @@ class DebugController extends Controller
if (file_exists('/var/www/counter-main.txt')) {
$return['build'] = trim(file_get_contents('/var/www/counter-main.txt'));
}
} catch (Exception $e) { // generic catch for open basedir.
} catch (Exception $e) { // @phpstan-ignore-line
app('log')->debug('Could not check build counter, but thats ok.');
app('log')->warning($e->getMessage());
}
@@ -209,7 +209,7 @@ class DebugController extends Controller
if (file_exists('/var/www/build-date-main.txt')) {
$return['build_date'] = trim(file_get_contents('/var/www/build-date-main.txt'));
}
} catch (Exception $e) { // generic catch for open basedir.
} catch (Exception $e) { // @phpstan-ignore-line
app('log')->debug('Could not check build date, but thats ok.');
app('log')->warning($e->getMessage());
}

View File

@@ -67,6 +67,8 @@ class HomeController extends Controller
*/
public function dateRange(Request $request): JsonResponse
{
$stringStart = '';
$stringEnd = '';
try {
$stringStart = e((string)$request->get('start'));
$start = Carbon::createFromFormat('Y-m-d', $stringStart);

View File

@@ -84,7 +84,7 @@ class EditController extends Controller
$startDate = $piggyBank->startdate?->format('Y-m-d');
$currency = $this->accountRepository->getAccountCurrency($piggyBank->account);
if (null === $currency) {
$currency = Amount::getDefaultCurrency();
$currency = app('amount')->getDefaultCurrency();
}
$preFilled = [

View File

@@ -114,14 +114,14 @@ class ProfileController extends Controller
return redirect(route('profile.index'));
}
$domain = $this->getDomain();
$secretPreference = Preferences::get('temp-mfa-secret');
$codesPreference = Preferences::get('temp-mfa-codes');
$secretPreference = app('preferences')->get('temp-mfa-secret');
$codesPreference = app('preferences')->get('temp-mfa-codes');
// generate secret if not in session
if (null === $secretPreference) {
// generate secret + store + flash
$secret = Google2FA::generateSecretKey();
Preferences::set('temp-mfa-secret', $secret);
app('preferences')->set('temp-mfa-secret', $secret);
}
// re-use secret if in session
@@ -137,7 +137,7 @@ class ProfileController extends Controller
// generate codes + store + flash:
$recovery = app(Recovery::class);
$recoveryCodes = $recovery->lowercase()->setCount(8)->setBlocks(2)->setChars(6)->toArray();
Preferences::set('temp-mfa-codes', $recoveryCodes);
app('preferences')->set('temp-mfa-codes', $recoveryCodes);
}
// get codes from session if present already:
@@ -227,8 +227,8 @@ class ProfileController extends Controller
/** @var User $user */
$user = auth()->user();
Preferences::delete('temp-mfa-secret');
Preferences::delete('temp-mfa-codes');
app('preferences')->delete('temp-mfa-secret');
app('preferences')->delete('temp-mfa-codes');
$repository->setMFACode($user, null);
app('preferences')->mark();
@@ -498,12 +498,12 @@ class ProfileController extends Controller
$user = auth()->user();
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$secret = Preferences::get('temp-mfa-secret')?->data;
$secret = app('preferences')->get('temp-mfa-secret')?->data;
$repository->setMFACode($user, $secret);
Preferences::delete('temp-mfa-secret');
Preferences::delete('temp-mfa-codes');
app('preferences')->delete('temp-mfa-secret');
app('preferences')->delete('temp-mfa-codes');
session()->flash('success', (string)trans('firefly.saved_preferences'));
app('preferences')->mark();

View File

@@ -91,7 +91,7 @@ class MailError extends Job implements ShouldQueue
}
}
);
} catch (Exception | TransportException $e) { // intentional generic exception
} catch (Exception | TransportException $e) { // @phpstan-ignore-line
$message = $e->getMessage();
if (str_contains($message, 'Bcc')) {
app('log')->warning('[Bcc] Could not email or log the error. Please validate your email settings, use the .env.example file as a guide.');

View File

@@ -47,7 +47,6 @@ use PragmaRX\Google2FA\Exceptions\InvalidCharactersException;
use PragmaRX\Google2FA\Exceptions\SecretKeyTooShortException;
use ValueError;
use function is_string;
/**
* Class FireflyValidator.
@@ -73,7 +72,7 @@ class FireflyValidator extends Validator
app('log')->error('No user during validate2faCode');
return false;
}
$secretPreference = Preferences::get('temp-mfa-secret');
$secretPreference = app('preferences')->get('temp-mfa-secret');
$secret = $secretPreference?->data ?? '';
return Google2FA::verifyKey($secret, $value);