Various code cleanup.

This commit is contained in:
James Cole 2022-12-30 09:28:03 +01:00
parent 03e176bd16
commit ee0116f112
No known key found for this signature in database
GPG Key ID: B49A324B7EAD6D80
17 changed files with 171 additions and 125 deletions

View File

@ -63,6 +63,7 @@ class NetWorth implements NetWorthInterface
* @return array
* @throws JsonException
* @throws FireflyException
* @deprecated
*/
public function getNetWorthByCurrency(Collection $accounts, Carbon $date): array
{

View File

@ -34,6 +34,8 @@ use Illuminate\Support\Collection;
interface NetWorthInterface
{
/**
* TODO unsure why this is deprecated.
*
* Returns the user's net worth in an array with the following layout:
*
* -

View File

@ -71,6 +71,7 @@ class RecurrenceController extends Controller
*/
public function events(Request $request): JsonResponse
{
$occurrences = [];
$return = [];
$start = Carbon::createFromFormat('Y-m-d', $request->get('start'));
$end = Carbon::createFromFormat('Y-m-d', $request->get('end'));
@ -106,20 +107,19 @@ class RecurrenceController extends Controller
$repetition->weekend = (int)$request->get('weekend');
$actualEnd = clone $end;
switch ($endsAt) {
default:
case 'forever':
// simply generate up until $end. No change from default behavior.
$occurrences = $this->recurring->getOccurrencesInRange($repetition, $actualStart, $actualEnd);
break;
case 'until_date':
if('until_date' === $endsAt) {
$actualEnd = $endDate ?? clone $end;
$occurrences = $this->recurring->getOccurrencesInRange($repetition, $actualStart, $actualEnd);
break;
case 'times':
$occurrences = $this->recurring->getXOccurrences($repetition, $actualStart, $repetitions);
break;
}
if('times' === $endsAt) {
$occurrences = $this->recurring->getXOccurrences($repetition, $actualStart, $repetitions);
}
if('times' !== $endsAt && 'until_date' !== $endsAt) {
// 'forever'
$occurrences = $this->recurring->getOccurrencesInRange($repetition, $actualStart, $actualEnd);
}
/** @var Carbon $current */
foreach ($occurrences as $current) {
if ($current->gte($start)) {

View File

@ -67,7 +67,7 @@ class TriggerController extends Controller
foreach ($groups as $group) {
/** @var TransactionJournal $journal */
foreach ($group->transactionJournals as $journal) {
Log::debug(sprintf('Set date of journal #%d to today!', $journal->id, $date));
Log::debug(sprintf('Set date of journal #%d to today!', $journal->id));
$journal->date = Carbon::today();
$journal->save();
}

View File

@ -170,9 +170,10 @@ class EditController extends Controller
]
)->render();
} catch (Throwable $e) {
Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage()));
$message = sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage());
Log::debug($message);
Log::error($e->getTraceAsString());
throw new FireflyException($result, 0, $e);
throw new FireflyException($message, 0, $e);
}
$index++;
}

View File

@ -26,6 +26,7 @@ namespace FireflyIII\Http\Controllers\System;
use Artisan;
use Cache;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Support\Facades\Preferences;
use FireflyIII\Support\Http\Controllers\GetConfigurationData;
@ -165,7 +166,17 @@ class InstallController extends Controller
$index++;
continue;
}
try {
$result = $this->executeCommand($command, $args);
} catch (FireflyException $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
if (strpos($e->getMessage(), 'open_basedir restriction in effect')) {
$this->lastError = self::BASEDIR_ERROR;
}
$result = false;
$this->lastError = sprintf('%s %s', self::OTHER_ERROR, $e->getMessage());
}
if (false === $result) {
$response['errorMessage'] = $this->lastError;
$response['error'] = true;
@ -184,7 +195,7 @@ class InstallController extends Controller
/**
* @param string $command
* @param array $args
*
* @throws FireflyException
* @return bool
*/
private function executeCommand(string $command, array $args): bool
@ -199,16 +210,7 @@ class InstallController extends Controller
Log::debug(Artisan::output());
}
} catch (Exception $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
if (strpos($e->getMessage(), 'open_basedir restriction in effect')) {
$this->lastError = self::BASEDIR_ERROR;
return false;
}
$this->lastError = sprintf('%s %s', self::OTHER_ERROR, $e->getMessage());
return false;
throw new FireflyException($e->getMessage(), 0, $e);
}
// clear cache as well.
Cache::clear();

View File

@ -109,27 +109,34 @@ class RecurrenceFormRequest extends FormRequest
$return['transactions'][0]['source_name'] = null;
$return['transactions'][0]['destination_id'] = null;
$return['transactions'][0]['destination_name'] = null;
// fill in source and destination account data
switch ($this->convertString('transaction_type')) {
default:
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->convertString('transaction_type')));
case 'withdrawal':
$throwError = true;
$type = $this->convertString('transaction_type');
if ('withdrawal' === $type) {
$throwError = false;
$return['transactions'][0]['source_id'] = $this->convertInteger('source_id');
$return['transactions'][0]['destination_id'] = $this->convertInteger('withdrawal_destination_id');
break;
case 'deposit':
}
if ('deposit' === $type) {
$throwError = false;
$return['transactions'][0]['source_id'] = $this->convertInteger('deposit_source_id');
$return['transactions'][0]['destination_id'] = $this->convertInteger('destination_id');
break;
case 'transfer':
}
if ('transfer' === $type) {
$throwError = false;
$return['transactions'][0]['source_id'] = $this->convertInteger('source_id');
$return['transactions'][0]['destination_id'] = $this->convertInteger('destination_id');
break;
}
if (true === $throwError) {
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->convertString('transaction_type')));
}
// replace category name with a new category:
$factory = app(CategoryFactory::class);
$factory->setUser(auth()->user());
/**
* @var int $index
* @var array $transaction
*/
foreach ($return['transactions'] as $index => $transaction) {
$categoryName = $transaction['category_name'] ?? null;
if (null !== $categoryName) {
@ -239,23 +246,19 @@ class RecurrenceFormRequest extends FormRequest
}
// switch on type to expand rules for source and destination accounts:
switch ($this->convertString('transaction_type')) {
case strtolower(TransactionType::WITHDRAWAL):
$type = strtolower($this->convertString('transaction_type'));
if (strtolower(TransactionType::WITHDRAWAL) === $type) {
$rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts';
$rules['destination_name'] = 'between:1,255|nullable';
break;
case strtolower(TransactionType::DEPOSIT):
}
if (strtolower(TransactionType::DEPOSIT) === $type) {
$rules['source_name'] = 'between:1,255|nullable';
$rules['destination_id'] = 'required|exists:accounts,id|belongsToUser:accounts';
break;
case strtolower(TransactionType::TRANSFER):
}
if (strtolower(TransactionType::TRANSFER) === $type) {
// this may not work:
$rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:destination_id';
$rules['destination_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:source_id';
break;
default:
throw new FireflyException(sprintf('Cannot handle transaction type of type "%s"', $this->convertString('transaction_type')));
}
// update some rules in case the user is editing a post:
@ -309,23 +312,28 @@ class RecurrenceFormRequest extends FormRequest
$destinationId = null;
// TODO typeOverrule: the account validator may have another opinion the transaction type.
switch ($this->convertString('transaction_type')) {
default:
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->convertString('transaction_type')));
case 'withdrawal':
// TODO either use 'withdrawal' or the strtolower() variant, not both.
$type = $this->convertString('transaction_type');
$throwError = true;
if('withdrawal' === $type) {
$throwError = false;
$sourceId = (int)$data['source_id'];
$destinationId = (int)$data['withdrawal_destination_id'];
break;
case 'deposit':
}
if('deposit' === $type) {
$throwError = false;
$sourceId = (int)$data['deposit_source_id'];
$destinationId = (int)$data['destination_id'];
break;
case 'transfer':
}
if('transfer' === $type) {
$throwError = false;
$sourceId = (int)$data['source_id'];
$destinationId = (int)$data['destination_id'];
break;
}
if(true === $throwError) {
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->convertString('transaction_type')));
}
// validate source account.
$validSource = $accountValidator->validateSource(['id' => $sourceId,]);

View File

@ -160,33 +160,36 @@ class CreateAutoBudgetLimits implements ShouldQueue
*/
private function isMagicDay(AutoBudget $autoBudget): bool
{
switch ($autoBudget->period) {
default:
throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period));
case 'daily':
// every day is magic!
if ('daily' === $autoBudget->period) {
return true;
case 'weekly':
// fire on Monday.
}
if ('weekly' === $autoBudget->period) {
return $this->date->isMonday();
case 'monthly':
}
if ('monthly' === $autoBudget->period) {
return 1 === $this->date->day;
case 'quarterly':
}
if ('quarterly' === $autoBudget->period) {
$format = 'm-d';
$value = $this->date->format($format);
return in_array($value, ['01-01', '04-01', '07-01', '10-01'], true);
case 'half_year':
}
if ('half_year' === $autoBudget->period) {
$format = 'm-d';
$value = $this->date->format($format);
return in_array($value, ['01-01', '07-01'], true);
case 'yearly':
}
if ('yearly' === $autoBudget->period) {
$format = 'm-d';
$value = $this->date->format($format);
return '01-01' === $value;
}
throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period));
}
/**

View File

@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Jobs;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Message;
use Illuminate\Queue\InteractsWithQueue;
@ -68,6 +69,7 @@ class MailError extends Job implements ShouldQueue
/**
* Execute the job.
* @throws FireflyException
*/
public function handle()
{
@ -89,7 +91,7 @@ class MailError extends Job implements ShouldQueue
}
);
} catch (Exception $e) {
Log::error('Exception when mailing: '.$e->getMessage());
throw new FireflyException($e->getMessage(), 0, $e);
}
}
}

View File

@ -24,10 +24,11 @@ declare(strict_types=1);
namespace FireflyIII\Mail;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Log;
/**
* Class NewIPAddressWarningMail
@ -61,8 +62,9 @@ class NewIPAddressWarningMail extends Mailable
$this->time = now(config('app.timezone'))->isoFormat((string)trans('config.date_time_js'));
$this->host = '';
try {
$hostName = gethostbyaddr($this->ipAddress);
} catch (Exception $e) {
$hostName = app('steam')->getHostName($this->ipAddress);
} catch (FireflyException $e) {
Log::error($e->getMessage());
$hostName = $this->ipAddress;
}
if ($hostName !== $this->ipAddress) {

View File

@ -25,10 +25,12 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\User;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
class UserLogin extends Notification
{
@ -70,8 +72,9 @@ class UserLogin extends Notification
$time = now(config('app.timezone'))->isoFormat((string)trans('config.date_time_js'));
$host = '';
try {
$hostName = gethostbyaddr($this->ip);
} catch (Exception $e) {
$hostName = app('steam')->getHostName($this->ip);
} catch (FireflyException $e) {
Log::error($e->getMessage());
$hostName = $this->ip;
}
if ($hostName !== $this->ip) {
@ -93,8 +96,9 @@ class UserLogin extends Notification
{
$host = '';
try {
$hostName = gethostbyaddr($this->ip);
} catch (Exception $e) {
$hostName = app('steam')->getHostName($this->ip);
} catch (FireflyException $e) {
Log::error($e->getMessage());
$hostName = $this->ip;
}
if ($hostName !== $this->ip) {

View File

@ -34,6 +34,9 @@ use FireflyIII\User;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\UnableToDeleteFile;
use LogicException;
use Log;
/**
* Class AttachmentRepository.
@ -58,7 +61,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface
$path = $helper->getAttachmentLocation($attachment);
try {
Storage::disk('upload')->delete($path);
} catch (Exception $e) {
} catch (UnableToDeleteFile $e) {
// @ignoreException
}
$attachment->delete();
@ -161,7 +164,6 @@ class AttachmentRepository implements AttachmentRepositoryInterface
* @param array $data
*
* @return Attachment
* @throws Exception
*/
public function update(Attachment $attachment, array $data): Attachment
{
@ -193,7 +195,6 @@ class AttachmentRepository implements AttachmentRepositoryInterface
* @param string $note
*
* @return bool
* @throws Exception
*/
public function updateNote(Attachment $attachment, string $note): bool
{
@ -202,8 +203,8 @@ class AttachmentRepository implements AttachmentRepositoryInterface
if (null !== $dbNote) {
try {
$dbNote->delete();
} catch (Exception $e) {
// @ignoreException
} catch (LogicException $e) {
Log::error($e->getMessage());
}
}

View File

@ -383,6 +383,8 @@ class BillRepository implements BillRepositoryInterface
}
/**
* TODO unsure why this is deprecated.
*
* Get the total amount of money paid for the users active bills in the date range given.
* This amount will be negative (they're expenses). This method is equal to
* getBillsUnpaidInRange. So the debug comments are gone.
@ -412,6 +414,8 @@ class BillRepository implements BillRepositoryInterface
}
/**
* TODO unsure why this is deprecated.
*
* Get the total amount of money paid for the users active bills in the date range given,
* grouped per currency.
* @param Carbon $start
@ -442,6 +446,8 @@ class BillRepository implements BillRepositoryInterface
}
/**
* TODO unsure why this is deprecated.
*
* Get the total amount of money due for the users active bills in the date range given. This amount will be positive.
*
* @param Carbon $start
@ -474,6 +480,8 @@ class BillRepository implements BillRepositoryInterface
}
/**
* TODO unsure why this is deprecated.
*
* Get the total amount of money due for the users active bills in the date range given.
*
* @param Carbon $start

View File

@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\Budget;
use Carbon\Carbon;
use Exception;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\User;
@ -52,11 +51,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface
*/
public function destroyAvailableBudget(AvailableBudget $availableBudget): void
{
try {
$availableBudget->delete();
} catch (Exception $e) {
// @ignoreException
}
}
/**

View File

@ -89,6 +89,7 @@ interface OperationsRepositoryInterface
public function spentInPeriodMc(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end): array;
/**
* TODO this method was marked as deprecated but I'm not sure why.
* @param Carbon $start
* @param Carbon $end
* @param Collection|null $accounts
@ -96,7 +97,7 @@ interface OperationsRepositoryInterface
* @param TransactionCurrency|null $currency
*
* @return array
* @deprecated
*
*/
public function sumExpenses(
Carbon $start,

View File

@ -25,6 +25,7 @@ namespace FireflyIII\Support;
use Carbon\Carbon;
use DB;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\Transaction;
@ -667,4 +668,19 @@ class Steam
return $amount;
}
/**
* @param string $ipAddress
* @return string
* @throws FireflyException
*/
public function getHostName(string $ipAddress): string
{
try {
$hostName = gethostbyaddr($ipAddress);
} catch (Exception $e) {
throw new FireflyException($e->getMessage(), 0, $e);
}
return $hostName;
}
}

View File

@ -126,9 +126,9 @@ class FireflyValidator extends Validator
*
* @return bool
*/
public function validateIban($attribute, $value): bool
public function validateIban(mixed $attribute, mixed $value): bool
{
if (null === $value || !is_string($value) || strlen($value) < 6) {
if (!is_string($value) || strlen($value) < 6) {
return false;
}
// strip spaces