Code cleanup

This commit is contained in:
James Cole
2021-03-21 09:15:40 +01:00
parent da1751940e
commit 206845575c
317 changed files with 7418 additions and 7362 deletions

View File

@@ -24,10 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Validation\Account;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\User;
/**
* I have no idea what made me do this. I'll reverse it some day.
*

View File

@@ -32,22 +32,6 @@ use Log;
*/
trait DepositValidation
{
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param array $validTypes
* @param int $accountId
* @param string $accountName
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, int $accountId, string $accountName): ?Account;
/**
* @param int|null $accountId
* @param $accountName
@@ -64,7 +48,7 @@ trait DepositValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false,
// because the destination of a deposit can't be created.
$this->destError = (string) trans('validation.deposit_dest_need_data');
$this->destError = (string)trans('validation.deposit_dest_need_data');
Log::error('Both values are NULL, cant create deposit destination.');
$result = false;
}
@@ -76,10 +60,10 @@ trait DepositValidation
if (null === $result) {
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int) $accountId, (string) $accountName);
$search = $this->findExistingAccount($validTypes, (int)$accountId, (string)$accountName);
if (null === $search) {
Log::debug('findExistingAccount() returned NULL, so the result is false.');
$this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$this->destError = (string)trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$result = false;
}
if (null !== $search) {
@@ -94,6 +78,22 @@ trait DepositValidation
return $result;
}
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param array $validTypes
* @param int $accountId
* @param string $accountName
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, int $accountId, string $accountName): ?Account;
/**
* @param int|null $accountId
* @param string|null $accountName
@@ -110,7 +110,7 @@ trait DepositValidation
// if both values are NULL return false,
// because the source of a deposit can't be created.
// (this never happens).
$this->sourceError = (string) trans('validation.deposit_source_need_data');
$this->sourceError = (string)trans('validation.deposit_source_need_data');
$result = false;
}
@@ -134,6 +134,7 @@ trait DepositValidation
$account->accountType = $accountType;
$this->source = $account;
}
return $result ?? false;
}
}

View File

@@ -33,13 +33,6 @@ use Log;
*/
trait OBValidation
{
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param int|null $accountId
* @param $accountName
@@ -56,7 +49,7 @@ trait OBValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false,
// because the destination of a deposit can't be created.
$this->destError = (string) trans('validation.ob_dest_need_data');
$this->destError = (string)trans('validation.ob_dest_need_data');
Log::error('Both values are NULL, cant create OB destination.');
$result = false;
}
@@ -68,10 +61,10 @@ trait OBValidation
if (null === $result) {
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int) $accountId, (string) $accountName);
$search = $this->findExistingAccount($validTypes, (int)$accountId, (string)$accountName);
if (null === $search) {
Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes);
$this->destError = (string) trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$this->destError = (string)trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$result = false;
}
if (null !== $search) {
@@ -86,6 +79,13 @@ trait OBValidation
return $result;
}
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* Source of an opening balance can either be an asset account
* or an "initial balance account". The latter can be created.
@@ -107,7 +107,7 @@ trait OBValidation
// if both values are NULL return false,
// because the source of a deposit can't be created.
// (this never happens).
$this->sourceError = (string) trans('validation.ob_source_need_data');
$this->sourceError = (string)trans('validation.ob_source_need_data');
$result = false;
}
@@ -143,6 +143,7 @@ trait OBValidation
$account->accountType = $accountType;
$this->source = $account;
}
return $result ?? false;
}
}

View File

@@ -24,8 +24,8 @@ declare(strict_types=1);
namespace FireflyIII\Validation\Account;
use Log;
use FireflyIII\Models\AccountType;
use Log;
/**
* Trait ReconciliationValidation
@@ -89,20 +89,24 @@ trait ReconciliationValidation
Log::debug('In validateReconciliationSource');
if (null === $accountId) {
Log::debug('Return FALSE');
return false;
}
$result = $this->accountRepository->findNull($accountId);
$types = [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, AccountType::RECONCILIATION];
if (null === $result) {
Log::debug('Return FALSE');
return false;
}
if (in_array($result->accountType->type, $types, true)) {
$this->source = $result;
Log::debug('Return TRUE');
return true;
}
Log::debug('Return FALSE');
return false;
}

View File

@@ -31,22 +31,6 @@ use Log;
*/
trait TransferValidation
{
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param array $validTypes
* @param int $accountId
* @param string $accountName
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, int $accountId, string $accountName): ?Account;
/**
* @param int|null $accountId
* @param $accountName
@@ -61,16 +45,16 @@ trait TransferValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false,
// because the destination of a transfer can't be created.
$this->destError = (string) trans('validation.transfer_dest_need_data');
$this->destError = (string)trans('validation.transfer_dest_need_data');
Log::error('Both values are NULL, cant create transfer destination.');
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int) $accountId, (string) $accountName);
$search = $this->findExistingAccount($validTypes, (int)$accountId, (string)$accountName);
if (null === $search) {
$this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$this->destError = (string)trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
return false;
}
@@ -87,6 +71,22 @@ trait TransferValidation
return true;
}
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param array $validTypes
* @param int $accountId
* @param string $accountName
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, int $accountId, string $accountName): ?Account;
/**
* @param int|null $accountId
* @param string|null $accountName
@@ -101,16 +101,16 @@ trait TransferValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false,
// because the source of a withdrawal can't be created.
$this->sourceError = (string) trans('validation.transfer_source_need_data');
$this->sourceError = (string)trans('validation.transfer_source_need_data');
Log::warning('Not a valid source, need more data.');
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int) $accountId, (string) $accountName);
$search = $this->findExistingAccount($validTypes, (int)$accountId, (string)$accountName);
if (null === $search) {
$this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
$this->sourceError = (string)trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source, cant find it.', $validTypes);
return false;

View File

@@ -33,20 +33,38 @@ use Log;
trait WithdrawalValidation
{
/**
* @param array $accountTypes
* @param int|null $accountId
* @param string|null $accountName
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
protected function validateGenericSource(?int $accountId, ?string $accountName): bool
{
Log::debug(sprintf('Now in validateGenericSource(%d, "%s")', $accountId, $accountName));
// source can be any of the following types.
$validTypes = [AccountType::ASSET, AccountType::REVENUE, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE];
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return TRUE
// because we assume the user doesnt want to submit / change anything.
$this->sourceError = (string)trans('validation.withdrawal_source_need_data');
Log::warning('Not a valid source. Need more data.');
/**
* @param array $validTypes
* @param int $accountId
* @param string $accountName
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, int $accountId, string $accountName): ?Account;
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int)$accountId, (string)$accountName);
if (null === $search) {
$this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source. Cant find it.', $validTypes);
return false;
}
$this->source = $search;
Log::debug('Valid source account!');
return true;
}
/**
* @param int|null $accountId
@@ -62,7 +80,7 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL return false,
// because the destination of a withdrawal can never be created automatically.
$this->destError = (string) trans('validation.withdrawal_dest_need_data');
$this->destError = (string)trans('validation.withdrawal_dest_need_data');
return false;
}
@@ -75,7 +93,7 @@ trait WithdrawalValidation
if (in_array($type, $validTypes, true)) {
return true;
}
$this->destError = (string) trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
$this->destError = (string)trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
return false;
}
@@ -85,6 +103,13 @@ trait WithdrawalValidation
return true === $this->canCreateTypes($validTypes);
}
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param int|null $accountId
* @param string|null $accountName
@@ -99,16 +124,16 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false,
// because the source of a withdrawal can't be created.
$this->sourceError = (string) trans('validation.withdrawal_source_need_data');
$this->sourceError = (string)trans('validation.withdrawal_source_need_data');
Log::warning('Not a valid source. Need more data.');
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int) $accountId, (string) $accountName);
$search = $this->findExistingAccount($validTypes, (int)$accountId, (string)$accountName);
if (null === $search) {
$this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
$this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source. Cant find it.', $validTypes);
return false;
@@ -120,36 +145,11 @@ trait WithdrawalValidation
}
/**
* @param int|null $accountId
* @param string|null $accountName
* @param array $validTypes
* @param int $accountId
* @param string $accountName
*
* @return bool
* @return Account|null
*/
protected function validateGenericSource(?int $accountId, ?string $accountName): bool
{
Log::debug(sprintf('Now in validateGenericSource(%d, "%s")', $accountId, $accountName));
// source can be any of the following types.
$validTypes = [AccountType::ASSET, AccountType::REVENUE, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE];
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return TRUE
// because we assume the user doesnt want to submit / change anything.
$this->sourceError = (string) trans('validation.withdrawal_source_need_data');
Log::warning('Not a valid source. Need more data.');
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, (int) $accountId, (string) $accountName);
if (null === $search) {
$this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
Log::warning('Not a valid source. Cant find it.', $validTypes);
return false;
}
$this->source = $search;
Log::debug('Valid source account!');
return true;
}
abstract protected function findExistingAccount(array $validTypes, int $accountId, string $accountName): ?Account;
}

View File

@@ -45,8 +45,8 @@ class AccountValidator
public bool $createMode;
public string $destError;
public ?Account $destination;
public ?Account $source;
public ?Account $destination;
public ?Account $source;
public string $sourceError;
private AccountRepositoryInterface $accountRepository;
private array $combinations;
@@ -69,6 +69,14 @@ class AccountValidator
$this->accountRepository = app(AccountRepositoryInterface::class);
}
/**
* @return Account|null
*/
public function getSource(): ?Account
{
return $this->source;
}
/**
* @param string $transactionType
*/
@@ -167,21 +175,6 @@ class AccountValidator
return $result;
}
/**
* @param string $accountType
*
* @return bool
*/
protected function canCreateType(string $accountType): bool
{
$canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE];
if (in_array($accountType, $canCreate, true)) {
return true;
}
return false;
}
/**
* @param array $accountTypes
*
@@ -203,6 +196,21 @@ class AccountValidator
return false;
}
/**
* @param string $accountType
*
* @return bool
*/
protected function canCreateType(string $accountType): bool
{
$canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE];
if (in_array($accountType, $canCreate, true)) {
return true;
}
return false;
}
/**
* @param array $validTypes
* @param int $accountId
@@ -228,12 +236,4 @@ class AccountValidator
return null;
}
/**
* @return Account|null
*/
public function getSource(): ?Account
{
return $this->source;
}
}

View File

@@ -39,27 +39,27 @@ trait ValidatesAutoBudgetRequest
$data = $validator->getData();
$type = $data['auto_budget_type'] ?? '';
$amount = $data['auto_budget_amount'] ?? '';
$period = (string) ($data['auto_budget_period'] ?? '');
$period = (string)($data['auto_budget_period'] ?? '');
$currencyId = $data['auto_budget_currency_id'] ?? '';
$currencyCode = $data['auto_budget_currency_code'] ?? '';
if (is_numeric($type)) {
$type = (int) $type;
$type = (int)$type;
}
if (0 === $type || 'none' === $type || '' === $type) {
return;
}
// basic float check:
if ('' === $amount) {
$validator->errors()->add('auto_budget_amount', (string) trans('validation.amount_required_for_auto_budget'));
$validator->errors()->add('auto_budget_amount', (string)trans('validation.amount_required_for_auto_budget'));
}
if (1 !== bccomp((string) $amount, '0')) {
$validator->errors()->add('auto_budget_amount', (string) trans('validation.auto_budget_amount_positive'));
if (1 !== bccomp((string)$amount, '0')) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.auto_budget_amount_positive'));
}
if ('' === $period) {
$validator->errors()->add('auto_budget_period', (string) trans('validation.auto_budget_period_mandatory'));
$validator->errors()->add('auto_budget_period', (string)trans('validation.auto_budget_period_mandatory'));
}
if ('' === $currencyCode && '' === $currencyId) {
$validator->errors()->add('auto_budget_amount', (string) trans('validation.require_currency_info'));
$validator->errors()->add('auto_budget_amount', (string)trans('validation.require_currency_info'));
}
}
}

View File

@@ -35,13 +35,6 @@ use Log;
*/
trait CurrencyValidation
{
/**
* @param Validator $validator
*
* @return array
*/
abstract protected function getTransactionsArray(Validator $validator): array;
/**
* If the transactions contain foreign amounts, there must also be foreign currency information.
*
@@ -59,16 +52,23 @@ trait CurrencyValidation
) {
$validator->errors()->add(
'transactions.' . $index . '.foreign_amount',
(string) trans('validation.require_currency_info')
(string)trans('validation.require_currency_info')
);
}
// if the currency is present, then the amount must be present as well.
if ((isset($transaction['foreign_currency_id']) || isset($transaction['foreign_currency_code'])) && !isset($transaction['foreign_amount'])) {
$validator->errors()->add(
'transactions.' . $index . '.foreign_amount',
(string) trans('validation.require_currency_amount')
(string)trans('validation.require_currency_amount')
);
}
}
}
/**
* @param Validator $validator
*
* @return array
*/
abstract protected function getTransactionsArray(Validator $validator): array;
}

View File

@@ -44,6 +44,7 @@ use Google2FA;
use Illuminate\Support\Collection;
use Illuminate\Validation\Validator;
use Log;
use function is_string;
/**
* Class FireflyValidator.
@@ -58,7 +59,7 @@ class FireflyValidator extends Validator
*/
public function validate2faCode($attribute, $value): bool
{
if (!\is_string($value) || null === $value || 6 !== strlen($value)) {
if (!is_string($value) || null === $value || 6 !== strlen($value)) {
return false;
}
@@ -114,7 +115,7 @@ class FireflyValidator extends Validator
*/
public function validateIban($attribute, $value): bool
{
if (!\is_string($value) || null === $value || strlen($value) < 6) {
if (!is_string($value) || null === $value || strlen($value) < 6) {
return false;
}
// strip spaces
@@ -431,6 +432,141 @@ class FireflyValidator extends Validator
return $this->validateByAccountName($value);
}
/**
* @return bool
*/
private function validateAccountAnonymously(): bool
{
if (!isset($this->data['user_id'])) {
return false;
}
$user = User::find($this->data['user_id']);
$type = AccountType::find($this->data['account_type_id'])->first();
$value = $this->data['name'];
$set = $user->accounts()->where('account_type_id', $type->id)->get();
// TODO no longer need to loop like this
/** @var Account $entry */
foreach ($set as $entry) {
if ($entry->name === $value) {
return false;
}
}
return true;
}
/**
* @param string $value
* @param array $parameters
* @param string $type
*
* @return bool
*/
private function validateByAccountTypeString(string $value, array $parameters, string $type): bool
{
/** @var array $search */
$search = Config::get('firefly.accountTypeByIdentifier.' . $type);
if (null === $search) {
return false;
}
/** @var Collection $accountTypes */
$accountTypes = AccountType::whereIn('type', $search)->get();
$ignore = (int)($parameters[0] ?? 0.0);
$accountTypeIds = $accountTypes->pluck('id')->toArray();
/** @var Collection $set */
$set = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->get();
// TODO no longer need to loop like this
/** @var Account $entry */
foreach ($set as $entry) {
if ($entry->name === $value) {
return false;
}
}
return true;
}
/**
* @param $value
* @param $parameters
*
* @return bool
*/
private function validateByAccountTypeId($value, $parameters): bool
{
$type = AccountType::find($this->data['account_type_id'])->first();
$ignore = (int)($parameters[0] ?? 0.0);
/** @var Collection $set */
$set = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->get();
// TODO no longer need to loop like this
/** @var Account $entry */
foreach ($set as $entry) {
// TODO no longer need to loop like this.
if ($entry->name === $value) {
return false;
}
}
return true;
}
/**
* @param $value
*
* @return bool
*/
private function validateByParameterId(int $accountId, $value): bool
{
/** @var Account $existingAccount */
$existingAccount = Account::find($accountId);
$type = $existingAccount->accountType;
$ignore = $existingAccount->id;
/** @var Collection $set */
$entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)
->where('name', $value)
->first();
return null === $entry;
}
/**
* @param $value
*
* @return bool
*/
private function validateByAccountId($value): bool
{
/** @var Account $existingAccount */
$existingAccount = Account::find($this->data['id']);
$type = $existingAccount->accountType;
$ignore = $existingAccount->id;
/** @var Collection $set */
$entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)
->where('name', $value)
->first();
return null === $entry;
}
/**
* @param string $value
*
* @return bool
*/
private function validateByAccountName(string $value): bool
{
return auth()->user()->accounts()->where('name', $value)->count() === 0;
}
/**
* @param $attribute
* @param $value
@@ -466,6 +602,49 @@ class FireflyValidator extends Validator
return true;
}
public function validateUniqueExistingWebhook($value, $parameters, $something): bool
{
$existingId = (int)($something[0] ?? 0);
$trigger = 0;
$response = 0;
$delivery = 0;
$triggers = array_flip(config('firefly.webhooks.triggers'));
$responses = array_flip(config('firefly.webhooks.responses'));
$deliveries = array_flip(config('firefly.webhooks.deliveries'));
if (auth()->check()) {
// get existing webhook value:
if (0 !== $existingId) {
/** @var Webhook $webhook */
$webhook = auth()->user()->webhooks()->find($existingId);
if (null === $webhook) {
return false;
}
// set triggers etc.
$trigger = $triggers[$webhook->trigger] ?? 0;
$response = $responses[$webhook->response] ?? 0;
$delivery = $deliveries[$webhook->delivery] ?? 0;
}
if (0 === $existingId) {
$trigger = $triggers[$this->data['trigger']] ?? 0;
$response = $responses[$this->data['response']] ?? 0;
$delivery = $deliveries[$this->data['delivery']] ?? 0;
}
$url = $this->data['url'];
$userId = auth()->user()->id;
return 0 === Webhook::whereUserId($userId)
->where('trigger', $trigger)
->where('response', $response)
->where('delivery', $delivery)
->where('id', '!=', $existingId)
->where('url', $url)->count();
}
return false;
}
/**
*
* Validate an object and its unicity. Checks for encryption / encrypted values as well.
@@ -531,7 +710,6 @@ class FireflyValidator extends Validator
return 0 === $query->count();
}
/**
* @param $attribute
* @param $value
@@ -563,118 +741,6 @@ class FireflyValidator extends Validator
return true;
}
/**
* @return bool
*/
private function validateAccountAnonymously(): bool
{
if (!isset($this->data['user_id'])) {
return false;
}
$user = User::find($this->data['user_id']);
$type = AccountType::find($this->data['account_type_id'])->first();
$value = $this->data['name'];
$set = $user->accounts()->where('account_type_id', $type->id)->get();
// TODO no longer need to loop like this
/** @var Account $entry */
foreach ($set as $entry) {
if ($entry->name === $value) {
return false;
}
}
return true;
}
/**
* @param $value
*
* @return bool
*/
private function validateByAccountId($value): bool
{
/** @var Account $existingAccount */
$existingAccount = Account::find($this->data['id']);
$type = $existingAccount->accountType;
$ignore = $existingAccount->id;
/** @var Collection $set */
$entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)
->where('name', $value)
->first();
return null === $entry;
}
/**
* @param $value
*
* @return bool
*/
private function validateByParameterId(int $accountId, $value): bool
{
/** @var Account $existingAccount */
$existingAccount = Account::find($accountId);
$type = $existingAccount->accountType;
$ignore = $existingAccount->id;
/** @var Collection $set */
$entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)
->where('name', $value)
->first();
return null === $entry;
}
public function validateUniqueExistingWebhook($value, $parameters, $something): bool
{
$existingId = (int)($something[0] ?? 0);
$trigger = 0;
$response = 0;
$delivery = 0;
$triggers = array_flip(config('firefly.webhooks.triggers'));
$responses = array_flip(config('firefly.webhooks.responses'));
$deliveries = array_flip(config('firefly.webhooks.deliveries'));
if (auth()->check()) {
// get existing webhook value:
if(0!== $existingId) {
/** @var Webhook $webhook */
$webhook = auth()->user()->webhooks()->find($existingId);
if(null === $webhook) {
return false;
}
// set triggers etc.
$trigger = $triggers[$webhook->trigger] ?? 0;
$response = $responses[$webhook->response] ?? 0;
$delivery = $deliveries[$webhook->delivery] ?? 0;
}
if(0=== $existingId) {
$trigger = $triggers[$this->data['trigger']] ?? 0;
$response = $responses[$this->data['response']] ?? 0;
$delivery = $deliveries[$this->data['delivery']] ?? 0;
}
$url = $this->data['url'];
$userId = auth()->user()->id;
return 0 === Webhook::whereUserId($userId)
->where('trigger', $trigger)
->where('response', $response)
->where('delivery', $delivery)
->where('id', '!=', $existingId)
->where('url', $url)->count();
}
return false;
}
/**
* @param $value
* @param $parameters
@@ -708,72 +774,4 @@ class FireflyValidator extends Validator
return false;
}
/**
* @param $value
* @param $parameters
*
* @return bool
*/
private function validateByAccountTypeId($value, $parameters): bool
{
$type = AccountType::find($this->data['account_type_id'])->first();
$ignore = (int)($parameters[0] ?? 0.0);
/** @var Collection $set */
$set = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->get();
// TODO no longer need to loop like this
/** @var Account $entry */
foreach ($set as $entry) {
// TODO no longer need to loop like this.
if ($entry->name === $value) {
return false;
}
}
return true;
}
/**
* @param string $value
* @param array $parameters
* @param string $type
*
* @return bool
*/
private function validateByAccountTypeString(string $value, array $parameters, string $type): bool
{
/** @var array $search */
$search = Config::get('firefly.accountTypeByIdentifier.' . $type);
if (null === $search) {
return false;
}
/** @var Collection $accountTypes */
$accountTypes = AccountType::whereIn('type', $search)->get();
$ignore = (int)($parameters[0] ?? 0.0);
$accountTypeIds = $accountTypes->pluck('id')->toArray();
/** @var Collection $set */
$set = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->get();
// TODO no longer need to loop like this
/** @var Account $entry */
foreach ($set as $entry) {
if ($entry->name === $value) {
return false;
}
}
return true;
}
/**
* @param string $value
*
* @return bool
*/
private function validateByAccountName(string $value): bool
{
return auth()->user()->accounts()->where('name', $value)->count() === 0;
}
}

View File

@@ -36,40 +36,6 @@ use Log;
trait GroupValidation
{
/**
* @param Validator $validator
*
* @return array
*/
abstract protected function getTransactionsArray(Validator $validator): array;
/**
* This method validates if the user has submitted transaction journal ID's for each array they submit, if they've submitted more than 1 transaction
* journal. This check is necessary because Firefly III isn't able to distinguish between journals without the ID.
*
* @param Validator $validator
* @param TransactionGroup $transactionGroup
*/
protected function validateJournalIds(Validator $validator, TransactionGroup $transactionGroup): void
{
Log::debug(sprintf('Now in GroupValidation::validateJournalIds(%d)', $transactionGroup->id));
$transactions = $this->getTransactionsArray($validator);
if (count($transactions) < 2) {
// no need for validation.
Log::debug(sprintf('%d transaction(s) in submission, can skip this check.', count($transactions)));
return;
}
// check each array:
/**
* @var int $index
* @var array $transaction
*/
foreach ($transactions as $index => $transaction) {
$this->validateJournalId($validator, $index, $transaction, $transactionGroup);
}
}
/**
* Adds an error to the "description" field when the user has submitted no descriptions and no
* journal description.
@@ -95,6 +61,56 @@ trait GroupValidation
}
}
/**
* @param Validator $validator
*/
protected function validateGroupDescription(Validator $validator): void
{
Log::debug('Now in validateGroupDescription()');
$data = $validator->getData();
$transactions = $this->getTransactionsArray($validator);
$groupTitle = $data['group_title'] ?? '';
if ('' === $groupTitle && count($transactions) > 1) {
$validator->errors()->add('group_title', (string)trans('validation.group_title_mandatory'));
}
}
/**
* This method validates if the user has submitted transaction journal ID's for each array they submit, if they've submitted more than 1 transaction
* journal. This check is necessary because Firefly III isn't able to distinguish between journals without the ID.
*
* @param Validator $validator
* @param TransactionGroup $transactionGroup
*/
protected function validateJournalIds(Validator $validator, TransactionGroup $transactionGroup): void
{
Log::debug(sprintf('Now in GroupValidation::validateJournalIds(%d)', $transactionGroup->id));
$transactions = $this->getTransactionsArray($validator);
if (count($transactions) < 2) {
// no need for validation.
Log::debug(sprintf('%d transaction(s) in submission, can skip this check.', count($transactions)));
return;
}
// check each array:
/**
* @var int $index
* @var array $transaction
*/
foreach ($transactions as $index => $transaction) {
$this->validateJournalId($validator, $index, $transaction, $transactionGroup);
}
}
/**
* @param Validator $validator
*
* @return array
*/
abstract protected function getTransactionsArray(Validator $validator): array;
/**
* Do the validation required by validateJournalIds.
*
@@ -110,27 +126,11 @@ trait GroupValidation
$journalId = $transaction['transaction_journal_id'] ?? null;
Log::debug(sprintf('Now in validateJournalId(%d, %d)', $index, $journalId));
$journalId = null === $journalId ? null : (int) $journalId;
$journalId = null === $journalId ? null : (int)$journalId;
$count = $transactionGroup->transactionJournals()->where('id', $journalId)->count();
if (null === $journalId || (null !== $journalId && 0 !== $journalId && 0 === $count)) {
Log::warning('Invalid submission: Each split must have transaction_journal_id (either valid ID or 0).');
$validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string) trans('validation.need_id_in_edit'));
}
}
/**
* @param Validator $validator
*/
protected function validateGroupDescription(Validator $validator): void
{
Log::debug('Now in validateGroupDescription()');
$data = $validator->getData();
$transactions = $this->getTransactionsArray($validator);
$groupTitle = $data['group_title'] ?? '';
if ('' === $groupTitle && count($transactions) > 1) {
$validator->errors()->add('group_title', (string) trans('validation.group_title_mandatory'));
$validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string)trans('validation.need_id_in_edit'));
}
}

View File

@@ -38,26 +38,6 @@ use Log;
*/
trait RecurrenceValidation
{
public function validateRecurringConfig(Validator $validator)
{
$data = $validator->getData();
$reps = array_key_exists('nr_of_repetitions', $data) ? (int)$data['nr_of_repetitions'] : null;
$repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null;
if (null === $reps && null === $repeatUntil) {
$validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until'));
$validator->errors()->add('repeat_until', trans('validation.require_repeat_until'));
return;
}
if ($reps > 0 && null !== $repeatUntil) {
$validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until'));
$validator->errors()->add('repeat_until', trans('validation.require_repeat_until'));
return;
}
}
/**
* Validate account information input for recurrences which are being updated.
*
@@ -85,7 +65,7 @@ trait RecurrenceValidation
$transactionType = $first->transactionType ? $first->transactionType->type : 'withdrawal';
Log::debug(sprintf('Determined type to be %s.', $transactionType));
}
if(null === $first) {
if (null === $first) {
Log::warning('Just going to assume type is a withdrawal.');
$transactionType = 'withdrawal';
}
@@ -102,11 +82,11 @@ trait RecurrenceValidation
$transactionType = $transaction['type'] ?? $transactionType;
$accountValidator->setTransactionType($transactionType);
if(
!array_key_exists('source_id', $transaction) &&
!array_key_exists('destination_id', $transaction) &&
!array_key_exists('source_name', $transaction) &&
!array_key_exists('destination_name', $transaction)
if (
!array_key_exists('source_id', $transaction)
&& !array_key_exists('destination_id', $transaction)
&& !array_key_exists('source_name', $transaction)
&& !array_key_exists('destination_name', $transaction)
) {
continue;
}
@@ -189,6 +169,26 @@ trait RecurrenceValidation
}
}
public function validateRecurringConfig(Validator $validator)
{
$data = $validator->getData();
$reps = array_key_exists('nr_of_repetitions', $data) ? (int)$data['nr_of_repetitions'] : null;
$repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null;
if (null === $reps && null === $repeatUntil) {
$validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until'));
$validator->errors()->add('repeat_until', trans('validation.require_repeat_until'));
return;
}
if ($reps > 0 && null !== $repeatUntil) {
$validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until'));
$validator->errors()->add('repeat_until', trans('validation.require_repeat_until'));
return;
}
}
/**
* @param Validator $validator
*/

View File

@@ -61,6 +61,30 @@ trait TransactionValidation
}
}
/**
* @param Validator $validator
*
* @return array
*/
protected function getTransactionsArray(Validator $validator): array
{
$data = $validator->getData();
$transactions = $data['transactions'] ?? [];
if (!is_countable($transactions)) {
Log::error(sprintf('Transactions array is not countable, because its a %s', gettype($transactions)));
return [];
}
// a superfluous check but you never know.
if (!is_array($transactions)) {
Log::error(sprintf('Transactions array is not an array, because its a %s', gettype($transactions)));
return [];
}
return $transactions;
}
/**
* @param Validator $validator
* @param int $index
@@ -193,6 +217,40 @@ trait TransactionValidation
Log::debug('Done with validateSingleUpdate().');
}
/**
* @param TransactionGroup $group
* @param array $transactions
*
* @return string
*/
private function getTransactionType(TransactionGroup $group, array $transactions): string
{
return $transactions[0]['type'] ?? strtolower($group->transactionJournals()->first()->transactionType->type);
}
/**
* @param array $transaction
* @param TransactionGroup $transactionGroup
*
* @return Account|null
*/
private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account
{
if (1 === $transactionGroup->transactionJournals->count()) {
$journal = $transactionGroup->transactionJournals->first();
return $journal->transactions()->where('amount', '<', 0)->first()->account;
}
/** @var TransactionJournal $journal */
foreach ($transactionGroup->transactionJournals as $journal) {
if ((int)$journal->id === (int)$transaction['transaction_journal_id']) {
return $journal->transactions()->where('amount', '<', 0)->first()->account;
}
}
return null;
}
/**
* Adds an error to the validator when there are no transactions in the array of data.
*
@@ -209,22 +267,6 @@ trait TransactionValidation
}
}
/**
* @param Validator $validator
*/
public function validateTransactionArray(Validator $validator): void
{
$transactions = $this->getTransactionsArray($validator);
foreach ($transactions as $key => $value) {
if (!is_int($key)) {
$validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction'));
Log::debug('Added error: at_least_one_transaction.');
return;
}
}
}
/**
* Adds an error to the validator when there are no transactions in the array of data.
*
@@ -244,6 +286,22 @@ trait TransactionValidation
Log::debug('Added NO errors.');
}
/**
* @param Validator $validator
*/
public function validateTransactionArray(Validator $validator): void
{
$transactions = $this->getTransactionsArray($validator);
foreach ($transactions as $key => $value) {
if (!is_int($key)) {
$validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction'));
Log::debug('Added error: at_least_one_transaction.');
return;
}
}
}
/**
* All types of splits must be equal.
*
@@ -296,48 +354,6 @@ trait TransactionValidation
Log::debug('No errors in validateTransactionTypesForUpdate()');
}
/**
* @param array $array
*
* @return bool
*/
private function arrayEqual(array $array): bool
{
return 1 === count(array_unique($array));
}
/**
* @param int $journalId
*
* @return array
*/
private function getOriginalData(int $journalId): array
{
$return = [
'source_id' => 0,
'source_name' => '',
'destination_id' => 0,
'destination_name' => '',
];
if (0 === $journalId) {
return $return;
}
/** @var Transaction $source */
$source = Transaction::where('transaction_journal_id', $journalId)->where('amount', '<', 0)->with(['account'])->first();
if (null !== $source) {
$return['source_id'] = $source->account_id;
$return['source_name'] = $source->account->name;
}
/** @var Transaction $destination */
$destination = Transaction::where('transaction_journal_id', $journalId)->where('amount', '>', 0)->with(['account'])->first();
if (null !== $source) {
$return['destination_id'] = $destination->account_id;
$return['destination_name'] = $destination->account->name;
}
return $return;
}
/**
* @param int $journalId
*
@@ -357,30 +373,6 @@ trait TransactionValidation
return 'invalid';
}
/**
* @param Validator $validator
*
* @return array
*/
protected function getTransactionsArray(Validator $validator): array
{
$data = $validator->getData();
$transactions = $data['transactions'] ?? [];
if (!is_countable($transactions)) {
Log::error(sprintf('Transactions array is not countable, because its a %s', gettype($transactions)));
return [];
}
// a superfluous check but you never know.
if (!is_array($transactions)) {
Log::error(sprintf('Transactions array is not an array, because its a %s', gettype($transactions)));
return [];
}
return $transactions;
}
/**
* @param Validator $validator
*/
@@ -423,125 +415,6 @@ trait TransactionValidation
}
}
/**
* @param TransactionGroup $group
* @param array $transactions
*
* @return string
*/
private function getTransactionType(TransactionGroup $group, array $transactions): string
{
return $transactions[0]['type'] ?? strtolower($group->transactionJournals()->first()->transactionType->type);
}
/**
* @param array $transactions
*
* @return array
*/
private function collectComparisonData(array $transactions): array
{
$fields = ['source_id', 'destination_id', 'source_name', 'destination_name'];
$comparison = [];
foreach ($fields as $field) {
$comparison[$field] = [];
/** @var array $transaction */
foreach ($transactions as $transaction) {
// source or destination may be omitted. If this is the case, use the original source / destination name + ID.
$originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0));
// get field.
$comparison[$field][] = $transaction[$field] ?? $originalData[$field];
}
}
return $comparison;
}
/**
* @param string $type
* @param array $comparison
*
* @return bool
*/
private function compareAccountData(string $type, array $comparison): bool
{
switch ($type) {
default:
case 'withdrawal':
return $this->compareAccountDataWithdrawal($comparison);
case 'deposit':
return $this->compareAccountDataDeposit($comparison);
case 'transfer':
return $this->compareAccountDataTransfer($comparison);
}
}
/**
* @param array $comparison
*
* @return bool
*/
private function compareAccountDataTransfer(array $comparison): bool
{
if ($this->arrayEqual($comparison['source_id'])) {
// source ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['source_name'])) {
// source names are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['destination_id'])) {
// destination ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['destination_name'])) {
// destination names are equal, return void.
return true;
}
return false;
}
/**
* @param array $comparison
*
* @return bool
*/
private function compareAccountDataWithdrawal(array $comparison): bool
{
if ($this->arrayEqual($comparison['source_id'])) {
// source ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['source_name'])) {
// source names are equal, return void.
return true;
}
return false;
}
/**
* @param array $comparison
*
* @return bool
*/
private function compareAccountDataDeposit(array $comparison): bool
{
if ($this->arrayEqual($comparison['destination_id'])) {
// destination ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['destination_name'])) {
// destination names are equal, return void.
return true;
}
return false;
}
/**
* @param Validator $validator
* @param TransactionGroup $transactionGroup
@@ -584,25 +457,152 @@ trait TransactionValidation
}
/**
* @param array $transaction
* @param TransactionGroup $transactionGroup
* @param array $transactions
*
* @return Account|null
* @return array
*/
private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account
private function collectComparisonData(array $transactions): array
{
if (1 === $transactionGroup->transactionJournals->count()) {
$journal = $transactionGroup->transactionJournals->first();
$fields = ['source_id', 'destination_id', 'source_name', 'destination_name'];
$comparison = [];
foreach ($fields as $field) {
$comparison[$field] = [];
/** @var array $transaction */
foreach ($transactions as $transaction) {
// source or destination may be omitted. If this is the case, use the original source / destination name + ID.
$originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0));
return $journal->transactions()->where('amount', '<', 0)->first()->account;
}
/** @var TransactionJournal $journal */
foreach ($transactionGroup->transactionJournals as $journal) {
if ((int)$journal->id === (int)$transaction['transaction_journal_id']) {
return $journal->transactions()->where('amount', '<', 0)->first()->account;
// get field.
$comparison[$field][] = $transaction[$field] ?? $originalData[$field];
}
}
return null;
return $comparison;
}
/**
* @param int $journalId
*
* @return array
*/
private function getOriginalData(int $journalId): array
{
$return = [
'source_id' => 0,
'source_name' => '',
'destination_id' => 0,
'destination_name' => '',
];
if (0 === $journalId) {
return $return;
}
/** @var Transaction $source */
$source = Transaction::where('transaction_journal_id', $journalId)->where('amount', '<', 0)->with(['account'])->first();
if (null !== $source) {
$return['source_id'] = $source->account_id;
$return['source_name'] = $source->account->name;
}
/** @var Transaction $destination */
$destination = Transaction::where('transaction_journal_id', $journalId)->where('amount', '>', 0)->with(['account'])->first();
if (null !== $source) {
$return['destination_id'] = $destination->account_id;
$return['destination_name'] = $destination->account->name;
}
return $return;
}
/**
* @param string $type
* @param array $comparison
*
* @return bool
*/
private function compareAccountData(string $type, array $comparison): bool
{
switch ($type) {
default:
case 'withdrawal':
return $this->compareAccountDataWithdrawal($comparison);
case 'deposit':
return $this->compareAccountDataDeposit($comparison);
case 'transfer':
return $this->compareAccountDataTransfer($comparison);
}
}
/**
* @param array $comparison
*
* @return bool
*/
private function compareAccountDataWithdrawal(array $comparison): bool
{
if ($this->arrayEqual($comparison['source_id'])) {
// source ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['source_name'])) {
// source names are equal, return void.
return true;
}
return false;
}
/**
* @param array $array
*
* @return bool
*/
private function arrayEqual(array $array): bool
{
return 1 === count(array_unique($array));
}
/**
* @param array $comparison
*
* @return bool
*/
private function compareAccountDataDeposit(array $comparison): bool
{
if ($this->arrayEqual($comparison['destination_id'])) {
// destination ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['destination_name'])) {
// destination names are equal, return void.
return true;
}
return false;
}
/**
* @param array $comparison
*
* @return bool
*/
private function compareAccountDataTransfer(array $comparison): bool
{
if ($this->arrayEqual($comparison['source_id'])) {
// source ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['source_name'])) {
// source names are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['destination_id'])) {
// destination ID's are equal, return void.
return true;
}
if ($this->arrayEqual($comparison['destination_name'])) {
// destination names are equal, return void.
return true;
}
return false;
}
}