Various PSR12 code cleanup

This commit is contained in:
James Cole
2022-12-29 19:42:40 +01:00
parent 6cfdc58cb1
commit 56b9b66352
38 changed files with 763 additions and 691 deletions

View File

@@ -78,7 +78,7 @@ class BudgetLimitTransformer extends AbstractTransformer
$currencySymbol = null; $currencySymbol = null;
if (null !== $currency) { if (null !== $currency) {
$amount = $budgetLimit->amount; $amount = $budgetLimit->amount;
$currencyId = (int) $currency->id; $currencyId = (int)$currency->id;
$currencyName = $currency->name; $currencyName = $currency->name;
$currencyCode = $currency->code; $currencyCode = $currency->code;
$currencySymbol = $currency->symbol; $currencySymbol = $currency->symbol;
@@ -87,13 +87,13 @@ class BudgetLimitTransformer extends AbstractTransformer
$amount = app('steam')->bcround($amount, $currencyDecimalPlaces); $amount = app('steam')->bcround($amount, $currencyDecimalPlaces);
return [ return [
'id' => (string) $budgetLimit->id, 'id' => (string)$budgetLimit->id,
'created_at' => $budgetLimit->created_at->toAtomString(), 'created_at' => $budgetLimit->created_at->toAtomString(),
'updated_at' => $budgetLimit->updated_at->toAtomString(), 'updated_at' => $budgetLimit->updated_at->toAtomString(),
'start' => $budgetLimit->start_date->toAtomString(), 'start' => $budgetLimit->start_date->toAtomString(),
'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(),
'budget_id' => (string) $budgetLimit->budget_id, 'budget_id' => (string)$budgetLimit->budget_id,
'currency_id' => (string) $currencyId, 'currency_id' => (string)$currencyId,
'currency_code' => $currencyCode, 'currency_code' => $currencyCode,
'currency_name' => $currencyName, 'currency_name' => $currencyName,
'currency_decimal_places' => $currencyDecimalPlaces, 'currency_decimal_places' => $currencyDecimalPlaces,
@@ -104,7 +104,7 @@ class BudgetLimitTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/budgets/limits/' . $budgetLimit->id, 'uri' => '/budgets/limits/'.$budgetLimit->id,
], ],
], ],
]; ];

View File

@@ -81,7 +81,7 @@ class BudgetTransformer extends AbstractTransformer
]; ];
if (null !== $autoBudget) { if (null !== $autoBudget) {
$abCurrencyId = (string) $autoBudget->transactionCurrency->id; $abCurrencyId = (string)$autoBudget->transactionCurrency->id;
$abCurrencyCode = $autoBudget->transactionCurrency->code; $abCurrencyCode = $autoBudget->transactionCurrency->code;
$abType = $types[$autoBudget->auto_budget_type]; $abType = $types[$autoBudget->auto_budget_type];
$abAmount = app('steam')->bcround($autoBudget->amount, $autoBudget->transactionCurrency->decimal_places); $abAmount = app('steam')->bcround($autoBudget->amount, $autoBudget->transactionCurrency->decimal_places);
@@ -89,7 +89,7 @@ class BudgetTransformer extends AbstractTransformer
} }
return [ return [
'id' => (string) $budget->id, 'id' => (string)$budget->id,
'created_at' => $budget->created_at->toAtomString(), 'created_at' => $budget->created_at->toAtomString(),
'updated_at' => $budget->updated_at->toAtomString(), 'updated_at' => $budget->updated_at->toAtomString(),
'active' => $budget->active, 'active' => $budget->active,
@@ -105,7 +105,7 @@ class BudgetTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/budgets/' . $budget->id, 'uri' => '/budgets/'.$budget->id,
], ],
], ],
]; ];
@@ -120,7 +120,7 @@ class BudgetTransformer extends AbstractTransformer
{ {
$return = []; $return = [];
foreach ($array as $data) { foreach ($array as $data) {
$data['sum'] = app('steam')->bcround($data['sum'], (int) $data['currency_decimal_places']); $data['sum'] = app('steam')->bcround($data['sum'], (int)$data['currency_decimal_places']);
$return[] = $data; $return[] = $data;
} }

View File

@@ -70,7 +70,7 @@ class CategoryTransformer extends AbstractTransformer
$notes = $this->repository->getNoteText($category); $notes = $this->repository->getNoteText($category);
return [ return [
'id' => (int) $category->id, 'id' => (int)$category->id,
'created_at' => $category->created_at->toAtomString(), 'created_at' => $category->created_at->toAtomString(),
'updated_at' => $category->updated_at->toAtomString(), 'updated_at' => $category->updated_at->toAtomString(),
'name' => $category->name, 'name' => $category->name,
@@ -80,7 +80,7 @@ class CategoryTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/categories/' . $category->id, 'uri' => '/categories/'.$category->id,
], ],
], ],
]; ];
@@ -95,7 +95,7 @@ class CategoryTransformer extends AbstractTransformer
{ {
$return = []; $return = [];
foreach ($array as $data) { foreach ($array as $data) {
$data['sum'] = app('steam')->bcround($data['sum'], (int) $data['currency_decimal_places']); $data['sum'] = app('steam')->bcround($data['sum'], (int)$data['currency_decimal_places']);
$return[] = $data; $return[] = $data;
} }

View File

@@ -42,11 +42,11 @@ class CurrencyTransformer extends AbstractTransformer
$isDefault = false; $isDefault = false;
$defaultCurrency = $this->parameters->get('defaultCurrency'); $defaultCurrency = $this->parameters->get('defaultCurrency');
if (null !== $defaultCurrency) { if (null !== $defaultCurrency) {
$isDefault = (int) $defaultCurrency->id === (int) $currency->id; $isDefault = (int)$defaultCurrency->id === (int)$currency->id;
} }
return [ return [
'id' => (int) $currency->id, 'id' => (int)$currency->id,
'created_at' => $currency->created_at->toAtomString(), 'created_at' => $currency->created_at->toAtomString(),
'updated_at' => $currency->updated_at->toAtomString(), 'updated_at' => $currency->updated_at->toAtomString(),
'default' => $isDefault, 'default' => $isDefault,
@@ -54,11 +54,11 @@ class CurrencyTransformer extends AbstractTransformer
'name' => $currency->name, 'name' => $currency->name,
'code' => $currency->code, 'code' => $currency->code,
'symbol' => $currency->symbol, 'symbol' => $currency->symbol,
'decimal_places' => (int) $currency->decimal_places, 'decimal_places' => (int)$currency->decimal_places,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/currencies/' . $currency->id, 'uri' => '/currencies/'.$currency->id,
], ],
], ],
]; ];

View File

@@ -41,7 +41,7 @@ class LinkTypeTransformer extends AbstractTransformer
public function transform(LinkType $linkType): array public function transform(LinkType $linkType): array
{ {
return [ return [
'id' => (int) $linkType->id, 'id' => (int)$linkType->id,
'created_at' => $linkType->created_at->toAtomString(), 'created_at' => $linkType->created_at->toAtomString(),
'updated_at' => $linkType->updated_at->toAtomString(), 'updated_at' => $linkType->updated_at->toAtomString(),
'name' => $linkType->name, 'name' => $linkType->name,
@@ -51,7 +51,7 @@ class LinkTypeTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/link_types/' . $linkType->id, 'uri' => '/link_types/'.$linkType->id,
], ],
], ],
]; ];

View File

@@ -56,15 +56,15 @@ class ObjectGroupTransformer extends AbstractTransformer
$this->repository->setUser($objectGroup->user); $this->repository->setUser($objectGroup->user);
return [ return [
'id' => (string) $objectGroup->id, 'id' => (string)$objectGroup->id,
'created_at' => $objectGroup->created_at?->toAtomString(), 'created_at' => $objectGroup->created_at?->toAtomString(),
'updated_at' => $objectGroup->updated_at?->toAtomString(), 'updated_at' => $objectGroup->updated_at?->toAtomString(),
'title' => $objectGroup->title, 'title' => $objectGroup->title,
'order' => (int) $objectGroup->order, 'order' => (int)$objectGroup->order,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/object_groups/' . $objectGroup->id, 'uri' => '/object_groups/'.$objectGroup->id,
], ],
], ],
]; ];

View File

@@ -23,10 +23,12 @@ declare(strict_types=1);
namespace FireflyIII\Transformers; namespace FireflyIII\Transformers;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\PiggyBankEvent; use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use JsonException;
/** /**
* Class PiggyBankEventTransformer * Class PiggyBankEventTransformer
@@ -55,8 +57,8 @@ class PiggyBankEventTransformer extends AbstractTransformer
* @param PiggyBankEvent $event * @param PiggyBankEvent $event
* *
* @return array * @return array
* @throws \FireflyIII\Exceptions\FireflyException * @throws FireflyException
* @throws \JsonException * @throws JsonException
*/ */
public function transform(PiggyBankEvent $event): array public function transform(PiggyBankEvent $event): array
{ {
@@ -74,26 +76,26 @@ class PiggyBankEventTransformer extends AbstractTransformer
// get associated journal and transaction, if any: // get associated journal and transaction, if any:
$journalId = $event->transaction_journal_id; $journalId = $event->transaction_journal_id;
$groupId = null; $groupId = null;
if (0 !== (int) $journalId) { if (0 !== (int)$journalId) {
$groupId = (int) $event->transactionJournal->transaction_group_id; $groupId = (int)$event->transactionJournal->transaction_group_id;
$journalId = (int) $journalId; $journalId = (int)$journalId;
} }
return [ return [
'id' => (string) $event->id, 'id' => (string)$event->id,
'created_at' => $event->created_at->toAtomString(), 'created_at' => $event->created_at->toAtomString(),
'updated_at' => $event->updated_at->toAtomString(), 'updated_at' => $event->updated_at->toAtomString(),
'amount' => app('steam')->bcround($event->amount, $currency->decimal_places), 'amount' => app('steam')->bcround($event->amount, $currency->decimal_places),
'currency_id' => (string) $currency->id, 'currency_id' => (string)$currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => (int) $currency->decimal_places, 'currency_decimal_places' => (int)$currency->decimal_places,
'transaction_journal_id' => $journalId ? (string) $journalId : null, 'transaction_journal_id' => $journalId ? (string)$journalId : null,
'transaction_group_id' => $groupId ? (string) $groupId : null, 'transaction_group_id' => $groupId ? (string)$groupId : null,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/piggy_bank_events/' . $event->id, 'uri' => '/piggy_bank_events/'.$event->id,
], ],
], ],
]; ];

View File

@@ -23,11 +23,13 @@ declare(strict_types=1);
namespace FireflyIII\Transformers; namespace FireflyIII\Transformers;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\ObjectGroup;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use JsonException;
/** /**
* Class PiggyBankTransformer * Class PiggyBankTransformer
@@ -56,8 +58,8 @@ class PiggyBankTransformer extends AbstractTransformer
* @param PiggyBank $piggyBank * @param PiggyBank $piggyBank
* *
* @return array * @return array
* @throws \FireflyIII\Exceptions\FireflyException * @throws FireflyException
* @throws \JsonException * @throws JsonException
*/ */
public function transform(PiggyBank $piggyBank): array public function transform(PiggyBank $piggyBank): array
{ {

View File

@@ -40,7 +40,7 @@ class PreferenceTransformer extends AbstractTransformer
public function transform(Preference $preference): array public function transform(Preference $preference): array
{ {
return [ return [
'id' => (int) $preference->id, 'id' => (int)$preference->id,
'created_at' => $preference->created_at->toAtomString(), 'created_at' => $preference->created_at->toAtomString(),
'updated_at' => $preference->updated_at->toAtomString(), 'updated_at' => $preference->updated_at->toAtomString(),
'name' => $preference->name, 'name' => $preference->name,

View File

@@ -79,14 +79,14 @@ class RecurrenceTransformer extends AbstractTransformer
$this->budgetRepos->setUser($recurrence->user); $this->budgetRepos->setUser($recurrence->user);
Log::debug('Set user.'); Log::debug('Set user.');
$shortType = (string) config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type)); $shortType = (string)config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type));
$notes = $this->repository->getNoteText($recurrence); $notes = $this->repository->getNoteText($recurrence);
$reps = 0 === (int) $recurrence->repetitions ? null : (int) $recurrence->repetitions; $reps = 0 === (int)$recurrence->repetitions ? null : (int)$recurrence->repetitions;
Log::debug('Get basic data.'); Log::debug('Get basic data.');
// basic data. // basic data.
return [ return [
'id' => (string) $recurrence->id, 'id' => (string)$recurrence->id,
'created_at' => $recurrence->created_at->toAtomString(), 'created_at' => $recurrence->created_at->toAtomString(),
'updated_at' => $recurrence->updated_at->toAtomString(), 'updated_at' => $recurrence->updated_at->toAtomString(),
'type' => $shortType, 'type' => $shortType,
@@ -104,7 +104,7 @@ class RecurrenceTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/recurring/' . $recurrence->id, 'uri' => '/recurring/'.$recurrence->id,
], ],
], ],
]; ];
@@ -125,13 +125,13 @@ class RecurrenceTransformer extends AbstractTransformer
/** @var RecurrenceRepetition $repetition */ /** @var RecurrenceRepetition $repetition */
foreach ($recurrence->recurrenceRepetitions as $repetition) { foreach ($recurrence->recurrenceRepetitions as $repetition) {
$repetitionArray = [ $repetitionArray = [
'id' => (string) $repetition->id, 'id' => (string)$repetition->id,
'created_at' => $repetition->created_at->toAtomString(), 'created_at' => $repetition->created_at->toAtomString(),
'updated_at' => $repetition->updated_at->toAtomString(), 'updated_at' => $repetition->updated_at->toAtomString(),
'type' => $repetition->repetition_type, 'type' => $repetition->repetition_type,
'moment' => $repetition->repetition_moment, 'moment' => $repetition->repetition_moment,
'skip' => (int) $repetition->repetition_skip, 'skip' => (int)$repetition->repetition_skip,
'weekend' => (int) $repetition->weekend, 'weekend' => (int)$repetition->weekend,
'description' => $this->repository->repetitionDescription($repetition), 'description' => $this->repository->repetitionDescription($repetition),
'occurrences' => [], 'occurrences' => [],
]; ];
@@ -169,10 +169,10 @@ class RecurrenceTransformer extends AbstractTransformer
$foreignCurrencyDp = null; $foreignCurrencyDp = null;
$foreignCurrencyId = null; $foreignCurrencyId = null;
if (null !== $transaction->foreign_currency_id) { if (null !== $transaction->foreign_currency_id) {
$foreignCurrencyId = (int) $transaction->foreign_currency_id; $foreignCurrencyId = (int)$transaction->foreign_currency_id;
$foreignCurrencyCode = $transaction->foreignCurrency->code; $foreignCurrencyCode = $transaction->foreignCurrency->code;
$foreignCurrencySymbol = $transaction->foreignCurrency->symbol; $foreignCurrencySymbol = $transaction->foreignCurrency->symbol;
$foreignCurrencyDp = (int) $transaction->foreignCurrency->decimal_places; $foreignCurrencyDp = (int)$transaction->foreignCurrency->decimal_places;
} }
// source info: // source info:
@@ -182,7 +182,7 @@ class RecurrenceTransformer extends AbstractTransformer
$sourceIban = null; $sourceIban = null;
if (null !== $sourceAccount) { if (null !== $sourceAccount) {
$sourceName = $sourceAccount->name; $sourceName = $sourceAccount->name;
$sourceId = (int) $sourceAccount->id; $sourceId = (int)$sourceAccount->id;
$sourceType = $sourceAccount->accountType->type; $sourceType = $sourceAccount->accountType->type;
$sourceIban = $sourceAccount->iban; $sourceIban = $sourceAccount->iban;
} }
@@ -192,7 +192,7 @@ class RecurrenceTransformer extends AbstractTransformer
$destinationIban = null; $destinationIban = null;
if (null !== $destinationAccount) { if (null !== $destinationAccount) {
$destinationName = $destinationAccount->name; $destinationName = $destinationAccount->name;
$destinationId = (int) $destinationAccount->id; $destinationId = (int)$destinationAccount->id;
$destinationType = $destinationAccount->accountType->type; $destinationType = $destinationAccount->accountType->type;
$destinationIban = $destinationAccount->iban; $destinationIban = $destinationAccount->iban;
} }
@@ -202,19 +202,19 @@ class RecurrenceTransformer extends AbstractTransformer
$foreignAmount = app('steam')->bcround($transaction->foreign_amount, $foreignCurrencyDp); $foreignAmount = app('steam')->bcround($transaction->foreign_amount, $foreignCurrencyDp);
} }
$transactionArray = [ $transactionArray = [
'currency_id' => (string) $transaction->transaction_currency_id, 'currency_id' => (string)$transaction->transaction_currency_id,
'currency_code' => $transaction->transactionCurrency->code, 'currency_code' => $transaction->transactionCurrency->code,
'currency_symbol' => $transaction->transactionCurrency->symbol, 'currency_symbol' => $transaction->transactionCurrency->symbol,
'currency_decimal_places' => (int) $transaction->transactionCurrency->decimal_places, 'currency_decimal_places' => (int)$transaction->transactionCurrency->decimal_places,
'foreign_currency_id' => null === $foreignCurrencyId ? null : (string) $foreignCurrencyId, 'foreign_currency_id' => null === $foreignCurrencyId ? null : (string)$foreignCurrencyId,
'foreign_currency_code' => $foreignCurrencyCode, 'foreign_currency_code' => $foreignCurrencyCode,
'foreign_currency_symbol' => $foreignCurrencySymbol, 'foreign_currency_symbol' => $foreignCurrencySymbol,
'foreign_currency_decimal_places' => $foreignCurrencyDp, 'foreign_currency_decimal_places' => $foreignCurrencyDp,
'source_id' => (string) $sourceId, 'source_id' => (string)$sourceId,
'source_name' => $sourceName, 'source_name' => $sourceName,
'source_iban' => $sourceIban, 'source_iban' => $sourceIban,
'source_type' => $sourceType, 'source_type' => $sourceType,
'destination_id' => (string) $destinationId, 'destination_id' => (string)$destinationId,
'destination_name' => $destinationName, 'destination_name' => $destinationName,
'destination_iban' => $destinationIban, 'destination_iban' => $destinationIban,
'destination_type' => $destinationType, 'destination_type' => $destinationType,
@@ -262,9 +262,9 @@ class RecurrenceTransformer extends AbstractTransformer
default: default:
throw new FireflyException(sprintf('Recurrence transformer cant handle field "%s"', $transactionMeta->name)); throw new FireflyException(sprintf('Recurrence transformer cant handle field "%s"', $transactionMeta->name));
case 'bill_id': case 'bill_id':
$bill = $this->billRepos->find((int) $transactionMeta->value); $bill = $this->billRepos->find((int)$transactionMeta->value);
if (null !== $bill) { if (null !== $bill) {
$array['bill_id'] = (string) $bill->id; $array['bill_id'] = (string)$bill->id;
$array['bill_name'] = $bill->name; $array['bill_name'] = $bill->name;
} }
break; break;
@@ -272,30 +272,30 @@ class RecurrenceTransformer extends AbstractTransformer
$array['tags'] = json_decode($transactionMeta->value); $array['tags'] = json_decode($transactionMeta->value);
break; break;
case 'piggy_bank_id': case 'piggy_bank_id':
$piggy = $this->piggyRepos->find((int) $transactionMeta->value); $piggy = $this->piggyRepos->find((int)$transactionMeta->value);
if (null !== $piggy) { if (null !== $piggy) {
$array['piggy_bank_id'] = (string) $piggy->id; $array['piggy_bank_id'] = (string)$piggy->id;
$array['piggy_bank_name'] = $piggy->name; $array['piggy_bank_name'] = $piggy->name;
} }
break; break;
case 'category_id': case 'category_id':
$category = $this->factory->findOrCreate((int) $transactionMeta->value, null); $category = $this->factory->findOrCreate((int)$transactionMeta->value, null);
if (null !== $category) { if (null !== $category) {
$array['category_id'] = (string) $category->id; $array['category_id'] = (string)$category->id;
$array['category_name'] = $category->name; $array['category_name'] = $category->name;
} }
break; break;
case 'category_name': case 'category_name':
$category = $this->factory->findOrCreate(null, $transactionMeta->value); $category = $this->factory->findOrCreate(null, $transactionMeta->value);
if (null !== $category) { if (null !== $category) {
$array['category_id'] = (string) $category->id; $array['category_id'] = (string)$category->id;
$array['category_name'] = $category->name; $array['category_name'] = $category->name;
} }
break; break;
case 'budget_id': case 'budget_id':
$budget = $this->budgetRepos->find((int) $transactionMeta->value); $budget = $this->budgetRepos->find((int)$transactionMeta->value);
if (null !== $budget) { if (null !== $budget) {
$array['budget_id'] = (string) $budget->id; $array['budget_id'] = (string)$budget->id;
$array['budget_name'] = $budget->name; $array['budget_name'] = $budget->name;
} }
break; break;

View File

@@ -40,7 +40,7 @@ class RuleGroupTransformer extends AbstractTransformer
public function transform(RuleGroup $ruleGroup): array public function transform(RuleGroup $ruleGroup): array
{ {
return [ return [
'id' => (int) $ruleGroup->id, 'id' => (int)$ruleGroup->id,
'created_at' => $ruleGroup->created_at->toAtomString(), 'created_at' => $ruleGroup->created_at->toAtomString(),
'updated_at' => $ruleGroup->updated_at->toAtomString(), 'updated_at' => $ruleGroup->updated_at->toAtomString(),
'title' => $ruleGroup->title, 'title' => $ruleGroup->title,
@@ -50,7 +50,7 @@ class RuleGroupTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/rule_groups/' . $ruleGroup->id, 'uri' => '/rule_groups/'.$ruleGroup->id,
], ],
], ],
]; ];

View File

@@ -60,14 +60,14 @@ class RuleTransformer extends AbstractTransformer
$this->ruleRepository->setUser($rule->user); $this->ruleRepository->setUser($rule->user);
return [ return [
'id' => (string) $rule->id, 'id' => (string)$rule->id,
'created_at' => $rule->created_at->toAtomString(), 'created_at' => $rule->created_at->toAtomString(),
'updated_at' => $rule->updated_at->toAtomString(), 'updated_at' => $rule->updated_at->toAtomString(),
'rule_group_id' => (string) $rule->rule_group_id, 'rule_group_id' => (string)$rule->rule_group_id,
'rule_group_title' => (string) $rule->ruleGroup->title, 'rule_group_title' => (string)$rule->ruleGroup->title,
'title' => $rule->title, 'title' => $rule->title,
'description' => $rule->description, 'description' => $rule->description,
'order' => (int) $rule->order, 'order' => (int)$rule->order,
'active' => $rule->active, 'active' => $rule->active,
'strict' => $rule->strict, 'strict' => $rule->strict,
'stop_processing' => $rule->stop_processing, 'stop_processing' => $rule->stop_processing,
@@ -77,7 +77,7 @@ class RuleTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/rules/' . $rule->id, 'uri' => '/rules/'.$rule->id,
], ],
], ],
]; ];
@@ -121,7 +121,7 @@ class RuleTransformer extends AbstractTransformer
continue; continue;
} }
$result[] = [ $result[] = [
'id' => (string) $ruleTrigger->id, 'id' => (string)$ruleTrigger->id,
'created_at' => $ruleTrigger->created_at->toAtomString(), 'created_at' => $ruleTrigger->created_at->toAtomString(),
'updated_at' => $ruleTrigger->updated_at->toAtomString(), 'updated_at' => $ruleTrigger->updated_at->toAtomString(),
'type' => $ruleTrigger->trigger_type, 'type' => $ruleTrigger->trigger_type,
@@ -147,7 +147,7 @@ class RuleTransformer extends AbstractTransformer
/** @var RuleAction $ruleAction */ /** @var RuleAction $ruleAction */
foreach ($actions as $ruleAction) { foreach ($actions as $ruleAction) {
$result[] = [ $result[] = [
'id' => (string) $ruleAction->id, 'id' => (string)$ruleAction->id,
'created_at' => $ruleAction->created_at->toAtomString(), 'created_at' => $ruleAction->created_at->toAtomString(),
'updated_at' => $ruleAction->updated_at->toAtomString(), 'updated_at' => $ruleAction->updated_at->toAtomString(),
'type' => $ruleAction->action_type, 'type' => $ruleAction->action_type,

View File

@@ -51,11 +51,11 @@ class TagTransformer extends AbstractTransformer
if (null !== $location) { if (null !== $location) {
$latitude = $location->latitude; $latitude = $location->latitude;
$longitude = $location->longitude; $longitude = $location->longitude;
$zoomLevel = (int) $location->zoom_level; $zoomLevel = (int)$location->zoom_level;
} }
return [ return [
'id' => (int) $tag->id, 'id' => (int)$tag->id,
'created_at' => $tag->created_at->toAtomString(), 'created_at' => $tag->created_at->toAtomString(),
'updated_at' => $tag->updated_at->toAtomString(), 'updated_at' => $tag->updated_at->toAtomString(),
'tag' => $tag->tag, 'tag' => $tag->tag,
@@ -67,7 +67,7 @@ class TagTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/tags/' . $tag->id, 'uri' => '/tags/'.$tag->id,
], ],
], ],
]; ];

View File

@@ -56,10 +56,23 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$this->groupRepos = app(TransactionGroupRepositoryInterface::class); $this->groupRepos = app(TransactionGroupRepositoryInterface::class);
$this->metaFields = [ $this->metaFields = [
'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', 'sepa_db', 'sepa_country', 'sepa_ep', 'sepa_cc',
'sepa_ci', 'sepa_batch_id', 'internal_reference', 'bunq_payment_id', 'import_hash_v2', 'sepa_ct_op',
'recurrence_id', 'external_id', 'original_source', 'external_url', 'sepa_ct_id',
'recurrence_count', 'recurrence_total', 'sepa_db',
'sepa_country',
'sepa_ep',
'sepa_ci',
'sepa_batch_id',
'internal_reference',
'bunq_payment_id',
'import_hash_v2',
'recurrence_id',
'external_id',
'original_source',
'external_url',
'recurrence_count',
'recurrence_total',
]; ];
$this->metaDateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; $this->metaDateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date'];
} }
@@ -75,16 +88,16 @@ class TransactionGroupTransformer extends AbstractTransformer
$first = new NullArrayObject(reset($group['transactions'])); $first = new NullArrayObject(reset($group['transactions']));
return [ return [
'id' => (int) $first['transaction_group_id'], 'id' => (int)$first['transaction_group_id'],
'created_at' => $first['created_at']->toAtomString(), 'created_at' => $first['created_at']->toAtomString(),
'updated_at' => $first['updated_at']->toAtomString(), 'updated_at' => $first['updated_at']->toAtomString(),
'user' => (string) $data['user_id'], 'user' => (string)$data['user_id'],
'group_title' => $data['title'], 'group_title' => $data['title'],
'transactions' => $this->transformTransactions($data), 'transactions' => $this->transformTransactions($data),
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/transactions/' . $first['transaction_group_id'], 'uri' => '/transactions/'.$first['transaction_group_id'],
], ],
], ],
]; ];
@@ -116,21 +129,21 @@ class TransactionGroupTransformer extends AbstractTransformer
$row = new NullArrayObject($transaction); $row = new NullArrayObject($transaction);
// amount: // amount:
$amount = app('steam')->positive((string) ($row['amount'] ?? '0')); $amount = app('steam')->positive((string)($row['amount'] ?? '0'));
$foreignAmount = null; $foreignAmount = null;
if (null !== $row['foreign_amount'] && '' !== $row['foreign_amount'] && bccomp('0', $row['foreign_amount']) !== 0) { if (null !== $row['foreign_amount'] && '' !== $row['foreign_amount'] && bccomp('0', $row['foreign_amount']) !== 0) {
$foreignAmount = app('steam')->positive($row['foreign_amount']); $foreignAmount = app('steam')->positive($row['foreign_amount']);
} }
$metaFieldData = $this->groupRepos->getMetaFields((int) $row['transaction_journal_id'], $this->metaFields); $metaFieldData = $this->groupRepos->getMetaFields((int)$row['transaction_journal_id'], $this->metaFields);
$metaDateData = $this->groupRepos->getMetaDateFields((int) $row['transaction_journal_id'], $this->metaDateFields); $metaDateData = $this->groupRepos->getMetaDateFields((int)$row['transaction_journal_id'], $this->metaDateFields);
$type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL); $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL);
$longitude = null; $longitude = null;
$latitude = null; $latitude = null;
$zoomLevel = null; $zoomLevel = null;
$location = $this->getLocationById((int) $row['transaction_journal_id']); $location = $this->getLocationById((int)$row['transaction_journal_id']);
if (null !== $location) { if (null !== $location) {
$longitude = $location->longitude; $longitude = $location->longitude;
$latitude = $location->latitude; $latitude = $location->latitude;
@@ -138,17 +151,17 @@ class TransactionGroupTransformer extends AbstractTransformer
} }
return [ return [
'user' => (string) $row['user_id'], 'user' => (string)$row['user_id'],
'transaction_journal_id' => (string) $row['transaction_journal_id'], 'transaction_journal_id' => (string)$row['transaction_journal_id'],
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $row['date']->toAtomString(), 'date' => $row['date']->toAtomString(),
'order' => $row['order'], 'order' => $row['order'],
'currency_id' => (string) $row['currency_id'], 'currency_id' => (string)$row['currency_id'],
'currency_code' => $row['currency_code'], 'currency_code' => $row['currency_code'],
'currency_name' => $row['currency_name'], 'currency_name' => $row['currency_name'],
'currency_symbol' => $row['currency_symbol'], 'currency_symbol' => $row['currency_symbol'],
'currency_decimal_places' => (int) $row['currency_decimal_places'], 'currency_decimal_places' => (int)$row['currency_decimal_places'],
'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null),
'foreign_currency_code' => $row['foreign_currency_code'], 'foreign_currency_code' => $row['foreign_currency_code'],
@@ -160,12 +173,12 @@ class TransactionGroupTransformer extends AbstractTransformer
'description' => $row['description'], 'description' => $row['description'],
'source_id' => (string) $row['source_account_id'], 'source_id' => (string)$row['source_account_id'],
'source_name' => $row['source_account_name'], 'source_name' => $row['source_account_name'],
'source_iban' => $row['source_account_iban'], 'source_iban' => $row['source_account_iban'],
'source_type' => $row['source_account_type'], 'source_type' => $row['source_account_type'],
'destination_id' => (string) $row['destination_account_id'], 'destination_id' => (string)$row['destination_account_id'],
'destination_name' => $row['destination_account_name'], 'destination_name' => $row['destination_account_name'],
'destination_iban' => $row['destination_account_iban'], 'destination_iban' => $row['destination_account_iban'],
'destination_type' => $row['destination_account_type'], 'destination_type' => $row['destination_account_type'],
@@ -180,8 +193,8 @@ class TransactionGroupTransformer extends AbstractTransformer
'bill_name' => $row['bill_name'], 'bill_name' => $row['bill_name'],
'reconciled' => $row['reconciled'], 'reconciled' => $row['reconciled'],
'notes' => $this->groupRepos->getNoteText((int) $row['transaction_journal_id']), 'notes' => $this->groupRepos->getNoteText((int)$row['transaction_journal_id']),
'tags' => $this->groupRepos->getTags((int) $row['transaction_journal_id']), 'tags' => $this->groupRepos->getTags((int)$row['transaction_journal_id']),
'internal_reference' => $metaFieldData['internal_reference'], 'internal_reference' => $metaFieldData['internal_reference'],
'external_id' => $metaFieldData['external_id'], 'external_id' => $metaFieldData['external_id'],
@@ -214,7 +227,7 @@ class TransactionGroupTransformer extends AbstractTransformer
'latitude' => $latitude, 'latitude' => $latitude,
'zoom_level' => $zoomLevel, 'zoom_level' => $zoomLevel,
'has_attachments' => $this->hasAttachments((int) $row['transaction_journal_id']), 'has_attachments' => $this->hasAttachments((int)$row['transaction_journal_id']),
]; ];
} }
@@ -231,11 +244,11 @@ class TransactionGroupTransformer extends AbstractTransformer
return null; return null;
} }
if (array_key_exists($key, $array) && null !== $array[$key]) { if (array_key_exists($key, $array) && null !== $array[$key]) {
return (string) $array[$key]; return (string)$array[$key];
} }
if (null !== $default) { if (null !== $default) {
return (string) $default; return (string)$default;
} }
return null; return null;
@@ -251,6 +264,16 @@ class TransactionGroupTransformer extends AbstractTransformer
return $this->groupRepos->getLocation($journalId); return $this->groupRepos->getLocation($journalId);
} }
/**
* @param TransactionJournal $journal
*
* @return Location|null
*/
private function getLocation(TransactionJournal $journal): ?Location
{
return $journal->locations()->first();
}
/** /**
* @param array $array * @param array $array
* @param string $key * @param string $key
@@ -260,7 +283,7 @@ class TransactionGroupTransformer extends AbstractTransformer
private function integerFromArray(array $array, string $key): ?int private function integerFromArray(array $array, string $key): ?int
{ {
if (array_key_exists($key, $array)) { if (array_key_exists($key, $array)) {
return (int) $array[$key]; return (int)$array[$key];
} }
return null; return null;
@@ -301,16 +324,16 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
try { try {
$result = [ $result = [
'id' => (int) $group->id, 'id' => (int)$group->id,
'created_at' => $group->created_at->toAtomString(), 'created_at' => $group->created_at->toAtomString(),
'updated_at' => $group->updated_at->toAtomString(), 'updated_at' => $group->updated_at->toAtomString(),
'user' => (int) $group->user_id, 'user' => (int)$group->user_id,
'group_title' => $group->title, 'group_title' => $group->title,
'transactions' => $this->transformJournals($group->transactionJournals), 'transactions' => $this->transformJournals($group->transactionJournals),
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/transactions/' . $group->id, 'uri' => '/transactions/'.$group->id,
], ],
], ],
]; ];
@@ -353,8 +376,8 @@ class TransactionGroupTransformer extends AbstractTransformer
$source = $this->getSourceTransaction($journal); $source = $this->getSourceTransaction($journal);
$destination = $this->getDestinationTransaction($journal); $destination = $this->getDestinationTransaction($journal);
$type = $journal->transactionType->type; $type = $journal->transactionType->type;
$amount = $this->getAmount($type, (string) $source->amount); $amount = $this->getAmount($type, (string)$source->amount);
$foreignAmount = $this->getForeignAmount($type, null === $source->foreign_amount ? null : (string) $source->foreign_amount); $foreignAmount = $this->getForeignAmount($type, null === $source->foreign_amount ? null : (string)$source->foreign_amount);
$metaFieldData = $this->groupRepos->getMetaFields($journal->id, $this->metaFields); $metaFieldData = $this->groupRepos->getMetaFields($journal->id, $this->metaFields);
$metaDates = $this->getDates($this->groupRepos->getMetaDateFields($journal->id, $this->metaDateFields)); $metaDates = $this->getDates($this->groupRepos->getMetaDateFields($journal->id, $this->metaDateFields));
$currency = $source->transactionCurrency; $currency = $source->transactionCurrency;
@@ -378,16 +401,16 @@ class TransactionGroupTransformer extends AbstractTransformer
} }
return [ return [
'user' => (int) $journal->user_id, 'user' => (int)$journal->user_id,
'transaction_journal_id' => (int) $journal->id, 'transaction_journal_id' => (int)$journal->id,
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $journal->date->toAtomString(), 'date' => $journal->date->toAtomString(),
'order' => $journal->order, 'order' => $journal->order,
'currency_id' => (int) $currency->id, 'currency_id' => (int)$currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => (int) $currency->decimal_places, 'currency_decimal_places' => (int)$currency->decimal_places,
'foreign_currency_id' => $foreignCurrency['id'], 'foreign_currency_id' => $foreignCurrency['id'],
'foreign_currency_code' => $foreignCurrency['code'], 'foreign_currency_code' => $foreignCurrency['code'],
@@ -399,12 +422,12 @@ class TransactionGroupTransformer extends AbstractTransformer
'description' => $journal->description, 'description' => $journal->description,
'source_id' => (int) $source->account_id, 'source_id' => (int)$source->account_id,
'source_name' => $source->account->name, 'source_name' => $source->account->name,
'source_iban' => $source->account->iban, 'source_iban' => $source->account->iban,
'source_type' => $source->account->accountType->type, 'source_type' => $source->account->accountType->type,
'destination_id' => (int) $destination->account_id, 'destination_id' => (int)$destination->account_id,
'destination_name' => $destination->account->name, 'destination_name' => $destination->account->name,
'destination_iban' => $destination->account->iban, 'destination_iban' => $destination->account->iban,
'destination_type' => $destination->account->accountType->type, 'destination_type' => $destination->account->accountType->type,
@@ -462,7 +485,7 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$result = $journal->transactions->first( $result = $journal->transactions->first(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return (float) $transaction->amount < 0; // lame but it works. return (float)$transaction->amount < 0; // lame but it works.
} }
); );
if (null === $result) { if (null === $result) {
@@ -482,7 +505,7 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$result = $journal->transactions->first( $result = $journal->transactions->first(
static function (Transaction $transaction) { static function (Transaction $transaction) {
return (float) $transaction->amount > 0; // lame but it works return (float)$transaction->amount > 0; // lame but it works
} }
); );
if (null === $result) { if (null === $result) {
@@ -566,10 +589,10 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $currency) { if (null === $currency) {
return $array; return $array;
} }
$array['id'] = (int) $currency->id; $array['id'] = (int)$currency->id;
$array['code'] = $currency->code; $array['code'] = $currency->code;
$array['symbol'] = $currency->symbol; $array['symbol'] = $currency->symbol;
$array['decimal_places'] = (int) $currency->decimal_places; $array['decimal_places'] = (int)$currency->decimal_places;
return $array; return $array;
} }
@@ -588,7 +611,7 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $budget) { if (null === $budget) {
return $array; return $array;
} }
$array['id'] = (int) $budget->id; $array['id'] = (int)$budget->id;
$array['name'] = $budget->name; $array['name'] = $budget->name;
return $array; return $array;
@@ -608,7 +631,7 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $category) { if (null === $category) {
return $array; return $array;
} }
$array['id'] = (int) $category->id; $array['id'] = (int)$category->id;
$array['name'] = $category->name; $array['name'] = $category->name;
return $array; return $array;
@@ -628,19 +651,9 @@ class TransactionGroupTransformer extends AbstractTransformer
if (null === $bill) { if (null === $bill) {
return $array; return $array;
} }
$array['id'] = (string) $bill->id; $array['id'] = (string)$bill->id;
$array['name'] = $bill->name; $array['name'] = $bill->name;
return $array; return $array;
} }
/**
* @param TransactionJournal $journal
*
* @return Location|null
*/
private function getLocation(TransactionJournal $journal): ?Location
{
return $journal->locations()->first();
}
} }

View File

@@ -55,17 +55,17 @@ class TransactionLinkTransformer extends AbstractTransformer
$notes = $this->repository->getLinkNoteText($link); $notes = $this->repository->getLinkNoteText($link);
return [ return [
'id' => (string) $link->id, 'id' => (string)$link->id,
'created_at' => $link->created_at->toAtomString(), 'created_at' => $link->created_at->toAtomString(),
'updated_at' => $link->updated_at->toAtomString(), 'updated_at' => $link->updated_at->toAtomString(),
'inward_id' => (string) $link->source_id, 'inward_id' => (string)$link->source_id,
'outward_id' => (string) $link->destination_id, 'outward_id' => (string)$link->destination_id,
'link_type_id' => (string) $link->link_type_id, 'link_type_id' => (string)$link->link_type_id,
'notes' => '' === $notes ? null : $notes, 'notes' => '' === $notes ? null : $notes,
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/transaction_links/' . $link->id, 'uri' => '/transaction_links/'.$link->id,
], ],
], ],
]; ];

View File

@@ -46,17 +46,17 @@ class UserTransformer extends AbstractTransformer
$this->repository = $this->repository ?? app(UserRepositoryInterface::class); $this->repository = $this->repository ?? app(UserRepositoryInterface::class);
return [ return [
'id' => (int) $user->id, 'id' => (int)$user->id,
'created_at' => $user->created_at->toAtomString(), 'created_at' => $user->created_at->toAtomString(),
'updated_at' => $user->updated_at->toAtomString(), 'updated_at' => $user->updated_at->toAtomString(),
'email' => $user->email, 'email' => $user->email,
'blocked' => 1 === (int) $user->blocked, 'blocked' => 1 === (int)$user->blocked,
'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code, 'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code,
'role' => $this->repository->getRoleByUser($user), 'role' => $this->repository->getRoleByUser($user),
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/users/' . $user->id, 'uri' => '/users/'.$user->id,
], ],
], ],
]; ];

View File

@@ -37,10 +37,41 @@ use Illuminate\Support\Collection;
*/ */
class AccountTransformer extends AbstractTransformer class AccountTransformer extends AbstractTransformer
{ {
private array $currencies;
private array $accountMeta; private array $accountMeta;
private ?TransactionCurrency $currency;
private array $balances; private array $balances;
private array $currencies;
private ?TransactionCurrency $currency;
/**
* @inheritDoc
* @throws FireflyException
*/
public function collectMetaData(Collection $objects): void
{
$this->currency = null;
$this->currencies = [];
$this->accountMeta = [];
$this->balances = app('steam')->balancesByAccounts($objects, $this->getDate());
$repository = app(CurrencyRepositoryInterface::class);
$this->currency = app('amount')->getDefaultCurrency();
// get currencies:
$accountIds = $objects->pluck('id')->toArray();
$meta = AccountMeta::whereIn('account_id', $accountIds)
->where('name', 'currency_id')
->get(['account_meta.id', 'account_meta.account_id', 'account_meta.name', 'account_meta.data']);
$currencyIds = $meta->pluck('data')->toArray();
$currencies = $repository->getByIds($currencyIds);
foreach ($currencies as $currency) {
$id = (int)$currency->id;
$this->currencies[$id] = $currency;
}
foreach ($meta as $entry) {
$id = (int)$entry->account_id;
$this->accountMeta[$id][$entry->name] = $entry->data;
}
}
/** /**
* Transform the account. * Transform the account.
@@ -53,16 +84,16 @@ class AccountTransformer extends AbstractTransformer
{ {
//$fullType = $account->accountType->type; //$fullType = $account->accountType->type;
//$accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $fullType)); //$accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $fullType));
$id = (int) $account->id; $id = (int)$account->id;
// no currency? use default // no currency? use default
$currency = $this->currency; $currency = $this->currency;
if (0 !== (int) $this->accountMeta[$id]['currency_id']) { if (0 !== (int)$this->accountMeta[$id]['currency_id']) {
$currency = $this->currencies[(int) $this->accountMeta[$id]['currency_id']]; $currency = $this->currencies[(int)$this->accountMeta[$id]['currency_id']];
} }
return [ return [
'id' => (string) $account->id, 'id' => (string)$account->id,
'created_at' => $account->created_at->toAtomString(), 'created_at' => $account->created_at->toAtomString(),
'updated_at' => $account->updated_at->toAtomString(), 'updated_at' => $account->updated_at->toAtomString(),
'active' => $account->active, 'active' => $account->active,
@@ -97,7 +128,7 @@ class AccountTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/accounts/' . $account->id, 'uri' => '/accounts/'.$account->id,
], ],
], ],
]; ];
@@ -115,35 +146,4 @@ class AccountTransformer extends AbstractTransformer
return $date; return $date;
} }
/**
* @inheritDoc
* @throws FireflyException
*/
public function collectMetaData(Collection $objects): void
{
$this->currency = null;
$this->currencies = [];
$this->accountMeta = [];
$this->balances = app('steam')->balancesByAccounts($objects, $this->getDate());
$repository = app(CurrencyRepositoryInterface::class);
$this->currency = app('amount')->getDefaultCurrency();
// get currencies:
$accountIds = $objects->pluck('id')->toArray();
$meta = AccountMeta::whereIn('account_id', $accountIds)
->where('name', 'currency_id')
->get(['account_meta.id', 'account_meta.account_id', 'account_meta.name', 'account_meta.data']);
$currencyIds = $meta->pluck('data')->toArray();
$currencies = $repository->getByIds($currencyIds);
foreach ($currencies as $currency) {
$id = (int) $currency->id;
$this->currencies[$id] = $currency;
}
foreach ($meta as $entry) {
$id = (int) $entry->account_id;
$this->accountMeta[$id][$entry->name] = $entry->data;
}
}
} }

View File

@@ -24,7 +24,6 @@ declare(strict_types=1);
namespace FireflyIII\Transformers\V2; namespace FireflyIII\Transformers\V2;
use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\BudgetLimit;
use FireflyIII\Repositories\Budget\OperationsRepository;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use League\Fractal\Resource\Item; use League\Fractal\Resource\Item;
@@ -39,6 +38,14 @@ class BudgetLimitTransformer extends AbstractTransformer
'budget', 'budget',
]; ];
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// TODO: Implement collectMetaData() method.
}
/** /**
* Include Budget * Include Budget
* *
@@ -74,22 +81,22 @@ class BudgetLimitTransformer extends AbstractTransformer
$currencySymbol = null; $currencySymbol = null;
if (null !== $currency) { if (null !== $currency) {
$amount = $budgetLimit->amount; $amount = $budgetLimit->amount;
$currencyId = (int) $currency->id; $currencyId = (int)$currency->id;
$currencyName = $currency->name; $currencyName = $currency->name;
$currencyCode = $currency->code; $currencyCode = $currency->code;
$currencySymbol = $currency->symbol; $currencySymbol = $currency->symbol;
$currencyDecimalPlaces = $currency->decimal_places; $currencyDecimalPlaces = $currency->decimal_places;
} }
$amount = number_format((float) $amount, $currencyDecimalPlaces, '.', ''); $amount = number_format((float)$amount, $currencyDecimalPlaces, '.', '');
return [ return [
'id' => (string) $budgetLimit->id, 'id' => (string)$budgetLimit->id,
'created_at' => $budgetLimit->created_at->toAtomString(), 'created_at' => $budgetLimit->created_at->toAtomString(),
'updated_at' => $budgetLimit->updated_at->toAtomString(), 'updated_at' => $budgetLimit->updated_at->toAtomString(),
'start' => $budgetLimit->start_date->toAtomString(), 'start' => $budgetLimit->start_date->toAtomString(),
'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(),
'budget_id' => (string) $budgetLimit->budget_id, 'budget_id' => (string)$budgetLimit->budget_id,
'currency_id' => (string) $currencyId, 'currency_id' => (string)$currencyId,
'currency_code' => $currencyCode, 'currency_code' => $currencyCode,
'currency_name' => $currencyName, 'currency_name' => $currencyName,
'currency_decimal_places' => $currencyDecimalPlaces, 'currency_decimal_places' => $currencyDecimalPlaces,
@@ -105,12 +112,4 @@ class BudgetLimitTransformer extends AbstractTransformer
], ],
]; ];
} }
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// TODO: Implement collectMetaData() method.
}
} }

View File

@@ -47,6 +47,14 @@ class BudgetTransformer extends AbstractTransformer
$this->parameters = new ParameterBag(); $this->parameters = new ParameterBag();
} }
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// TODO: Implement collectMetaData() method.
}
/** /**
* Transform a budget. * Transform a budget.
* *
@@ -86,7 +94,7 @@ class BudgetTransformer extends AbstractTransformer
// } // }
return [ return [
'id' => (string) $budget->id, 'id' => (string)$budget->id,
'created_at' => $budget->created_at->toAtomString(), 'created_at' => $budget->created_at->toAtomString(),
'updated_at' => $budget->updated_at->toAtomString(), 'updated_at' => $budget->updated_at->toAtomString(),
'active' => $budget->active, 'active' => $budget->active,
@@ -117,18 +125,10 @@ class BudgetTransformer extends AbstractTransformer
{ {
$return = []; $return = [];
foreach ($array as $data) { foreach ($array as $data) {
$data['sum'] = number_format((float) $data['sum'], (int) $data['currency_decimal_places'], '.', ''); $data['sum'] = number_format((float)$data['sum'], (int)$data['currency_decimal_places'], '.', '');
$return[] = $data; $return[] = $data;
} }
return $return; return $return;
} }
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// TODO: Implement collectMetaData() method.
}
} }

View File

@@ -31,6 +31,14 @@ use Illuminate\Support\Collection;
*/ */
class PreferenceTransformer extends AbstractTransformer class PreferenceTransformer extends AbstractTransformer
{ {
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// TODO: Implement collectMetaData() method.
}
/** /**
* Transform the preference * Transform the preference
* *
@@ -41,19 +49,11 @@ class PreferenceTransformer extends AbstractTransformer
public function transform(Preference $preference): array public function transform(Preference $preference): array
{ {
return [ return [
'id' => (int) $preference->id, 'id' => (int)$preference->id,
'created_at' => $preference->created_at->toAtomString(), 'created_at' => $preference->created_at->toAtomString(),
'updated_at' => $preference->updated_at->toAtomString(), 'updated_at' => $preference->updated_at->toAtomString(),
'name' => $preference->name, 'name' => $preference->name,
'data' => $preference->data, 'data' => $preference->data,
]; ];
} }
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// TODO: Implement collectMetaData() method.
}
} }

View File

@@ -25,8 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Transformers\V2; namespace FireflyIII\Transformers\V2;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Factory\TransactionFactory;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournalMeta; use FireflyIII\Models\TransactionJournalMeta;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
@@ -45,6 +43,41 @@ class TransactionGroupTransformer extends AbstractTransformer
private TransactionCurrency $default; private TransactionCurrency $default;
private array $meta; private array $meta;
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// start with currencies:
$currencies = [];
$journals = [];
/** @var array $object */
foreach ($objects as $object) {
foreach ($object['sums'] as $sum) {
$id = $sum['currency_id'];
if (!array_key_exists($id, $currencies)) {
$currencyObject = TransactionCurrency::find($sum['currency_id']);
$currencies[$id] = $currencyObject;
}
}
/** @var array $transaction */
foreach ($object['transactions'] as $transaction) {
$id = $transaction['transaction_journal_id'];
$journals[$id] = [];
}
}
$this->currencies = $currencies;
$this->default = app('amount')->getDefaultCurrency();
// grab meta for all journals:
$meta = TransactionJournalMeta::whereIn('transaction_journal_id', array_keys($journals))->get();
/** @var TransactionJournalMeta $entry */
foreach ($meta as $entry) {
$id = (int)$entry->transaction_journal_id;
$this->meta[$id][$entry->name] = $entry->data;
}
}
/** /**
* @param array $group * @param array $group
* *
@@ -54,10 +87,10 @@ class TransactionGroupTransformer extends AbstractTransformer
{ {
$first = reset($group['transactions']); $first = reset($group['transactions']);
return [ return [
'id' => (string) $group['id'], 'id' => (string)$group['id'],
'created_at' => $first['created_at']->toAtomString(), 'created_at' => $first['created_at']->toAtomString(),
'updated_at' => $first['updated_at']->toAtomString(), 'updated_at' => $first['updated_at']->toAtomString(),
'user' => (string) $first['user_id'], 'user' => (string)$first['user_id'],
'group_title' => $group['title'] ?? null, 'group_title' => $group['title'] ?? null,
'transactions' => $this->transformTransactions($group['transactions'] ?? []), 'transactions' => $this->transformTransactions($group['transactions'] ?? []),
'links' => [ 'links' => [
@@ -86,10 +119,10 @@ class TransactionGroupTransformer extends AbstractTransformer
private function transformTransaction(array $transaction): array private function transformTransaction(array $transaction): array
{ {
$transaction = new NullArrayObject($transaction); $transaction = new NullArrayObject($transaction);
$journalId = (int) $transaction['transaction_journal_id']; $journalId = (int)$transaction['transaction_journal_id'];
$meta = new NullArrayObject($this->meta[$journalId] ?? []); $meta = new NullArrayObject($this->meta[$journalId] ?? []);
$type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL); $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionType::WITHDRAWAL);
$amount = app('steam')->positive((string) ($transaction['amount'] ?? '0')); $amount = app('steam')->positive((string)($transaction['amount'] ?? '0'));
$foreignAmount = null; $foreignAmount = null;
$nativeForeignAmount = null; $nativeForeignAmount = null;
if (null !== $transaction['foreign_amount']) { if (null !== $transaction['foreign_amount']) {
@@ -108,24 +141,24 @@ class TransactionGroupTransformer extends AbstractTransformer
} }
return [ return [
'user' => (string) $transaction['user_id'], 'user' => (string)$transaction['user_id'],
'transaction_journal_id' => (string) $transaction['transaction_journal_id'], 'transaction_journal_id' => (string)$transaction['transaction_journal_id'],
'type' => strtolower($type), 'type' => strtolower($type),
'date' => $transaction['date']->toAtomString(), 'date' => $transaction['date']->toAtomString(),
'order' => $transaction['order'], 'order' => $transaction['order'],
'currency_id' => (string) $transaction['currency_id'], 'currency_id' => (string)$transaction['currency_id'],
'currency_code' => $transaction['currency_code'], 'currency_code' => $transaction['currency_code'],
'currency_name' => $transaction['currency_name'], 'currency_name' => $transaction['currency_name'],
'currency_symbol' => $transaction['currency_symbol'], 'currency_symbol' => $transaction['currency_symbol'],
'currency_decimal_places' => (int) $transaction['currency_decimal_places'], 'currency_decimal_places' => (int)$transaction['currency_decimal_places'],
// converted to native currency // converted to native currency
'native_currency_converted' => $transaction['currency_id'] !== $this->default->id, 'native_currency_converted' => $transaction['currency_id'] !== $this->default->id,
'native_currency_id' => (string) $this->default->id, 'native_currency_id' => (string)$this->default->id,
'native_currency_code' => $this->default->code, 'native_currency_code' => $this->default->code,
'native_currency_name' => $this->default->name, 'native_currency_name' => $this->default->name,
'native_currency_symbol' => $this->default->symbol, 'native_currency_symbol' => $this->default->symbol,
'native_currency_decimal_places' => (int) $this->default->decimal_places, 'native_currency_decimal_places' => (int)$this->default->decimal_places,
'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null),
'foreign_currency_code' => $transaction['foreign_currency_code'], 'foreign_currency_code' => $transaction['foreign_currency_code'],
@@ -141,11 +174,11 @@ class TransactionGroupTransformer extends AbstractTransformer
'foreign_amount' => $foreignAmount, 'foreign_amount' => $foreignAmount,
'native_foreign_amount' => $nativeForeignAmount, 'native_foreign_amount' => $nativeForeignAmount,
'description' => $transaction['description'], 'description' => $transaction['description'],
'source_id' => (string) $transaction['source_account_id'], 'source_id' => (string)$transaction['source_account_id'],
'source_name' => $transaction['source_account_name'], 'source_name' => $transaction['source_account_name'],
'source_iban' => $transaction['source_account_iban'], 'source_iban' => $transaction['source_account_iban'],
'source_type' => $transaction['source_account_type'], 'source_type' => $transaction['source_account_type'],
'destination_id' => (string) $transaction['destination_account_id'], 'destination_id' => (string)$transaction['destination_account_id'],
'destination_name' => $transaction['destination_account_name'], 'destination_name' => $transaction['destination_account_name'],
'destination_iban' => $transaction['destination_account_iban'], 'destination_iban' => $transaction['destination_account_iban'],
'destination_type' => $transaction['destination_account_type'], 'destination_type' => $transaction['destination_account_type'],
@@ -209,7 +242,7 @@ class TransactionGroupTransformer extends AbstractTransformer
return null; return null;
} }
if (null !== $array[$key]) { if (null !== $array[$key]) {
return (string) $array[$key]; return (string)$array[$key];
} }
if (null !== $default) { if (null !== $default) {
@@ -219,41 +252,6 @@ class TransactionGroupTransformer extends AbstractTransformer
return null; return null;
} }
/**
* @inheritDoc
*/
public function collectMetaData(Collection $objects): void
{
// start with currencies:
$currencies = [];
$journals = [];
/** @var array $object */
foreach ($objects as $object) {
foreach ($object['sums'] as $sum) {
$id = $sum['currency_id'];
if (!array_key_exists($id, $currencies)) {
$currencyObject = TransactionCurrency::find($sum['currency_id']);
$currencies[$id] = $currencyObject;
}
}
/** @var array $transaction */
foreach ($object['transactions'] as $transaction) {
$id = $transaction['transaction_journal_id'];
$journals[$id] = [];
}
}
$this->currencies = $currencies;
$this->default = app('amount')->getDefaultCurrency();
// grab meta for all journals:
$meta = TransactionJournalMeta::whereIn('transaction_journal_id', array_keys($journals))->get();
/** @var TransactionJournalMeta $entry */
foreach ($meta as $entry) {
$id = (int) $entry->transaction_journal_id;
$this->meta[$id][$entry->name] = $entry->data;
}
}
/** /**
* @param string|null $string * @param string|null $string
* @return Carbon|null * @return Carbon|null

View File

@@ -40,11 +40,11 @@ class WebhookAttemptTransformer extends AbstractTransformer
public function transform(WebhookAttempt $attempt): array public function transform(WebhookAttempt $attempt): array
{ {
return [ return [
'id' => (string) $attempt->id, 'id' => (string)$attempt->id,
'created_at' => $attempt->created_at->toAtomString(), 'created_at' => $attempt->created_at->toAtomString(),
'updated_at' => $attempt->updated_at->toAtomString(), 'updated_at' => $attempt->updated_at->toAtomString(),
'webhook_message_id' => (string) $attempt->webhook_message_id, 'webhook_message_id' => (string)$attempt->webhook_message_id,
'status_code' => (int) $attempt->status_code, 'status_code' => (int)$attempt->status_code,
'logs' => $attempt->logs, 'logs' => $attempt->logs,
'response' => $attempt->response, 'response' => $attempt->response,
]; ];

View File

@@ -49,12 +49,12 @@ class WebhookMessageTransformer extends AbstractTransformer
} }
return [ return [
'id' => (string) $message->id, 'id' => (string)$message->id,
'created_at' => $message->created_at->toAtomString(), 'created_at' => $message->created_at->toAtomString(),
'updated_at' => $message->updated_at->toAtomString(), 'updated_at' => $message->updated_at->toAtomString(),
'sent' => $message->sent, 'sent' => $message->sent,
'errored' => $message->errored, 'errored' => $message->errored,
'webhook_id' => (string) $message->webhook_id, 'webhook_id' => (string)$message->webhook_id,
'uuid' => $message->uuid, 'uuid' => $message->uuid,
'message' => $json, 'message' => $json,
]; ];

View File

@@ -53,7 +53,7 @@ class WebhookTransformer extends AbstractTransformer
public function transform(Webhook $webhook): array public function transform(Webhook $webhook): array
{ {
return [ return [
'id' => (int) $webhook->id, 'id' => (int)$webhook->id,
'created_at' => $webhook->created_at->toAtomString(), 'created_at' => $webhook->created_at->toAtomString(),
'updated_at' => $webhook->updated_at->toAtomString(), 'updated_at' => $webhook->updated_at->toAtomString(),
'active' => $webhook->active, 'active' => $webhook->active,

View File

@@ -32,21 +32,6 @@ use Log;
*/ */
trait DepositValidation trait DepositValidation
{ {
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param array $validTypes
* @param array $data
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
/** /**
* @param array $array * @param array $array
* *
@@ -65,7 +50,7 @@ trait DepositValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the destination of a deposit can't be created. // 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.'); Log::error('Both values are NULL, cant create deposit destination.');
$result = false; $result = false;
} }
@@ -80,7 +65,7 @@ trait DepositValidation
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
Log::debug('findExistingAccount() returned NULL, so the result is false.'); 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; $result = false;
} }
if (null !== $search) { if (null !== $search) {
@@ -95,6 +80,21 @@ trait DepositValidation
return $result; return $result;
} }
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/**
* @param array $validTypes
* @param array $data
*
* @return Account|null
*/
abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
/** /**
* @param array $array * @param array $array
* *
@@ -114,7 +114,7 @@ trait DepositValidation
// if both values are NULL return false, // if both values are NULL return false,
// because the source of a deposit can't be created. // because the source of a deposit can't be created.
// (this never happens). // (this never happens).
$this->sourceError = (string) trans('validation.deposit_source_need_data'); $this->sourceError = (string)trans('validation.deposit_source_need_data');
$result = false; $result = false;
} }

View File

@@ -33,13 +33,6 @@ use Log;
*/ */
trait OBValidation trait OBValidation
{ {
/**
* @param array $accountTypes
*
* @return bool
*/
abstract protected function canCreateTypes(array $accountTypes): bool;
/** /**
* @param array $array * @param array $array
* *
@@ -57,7 +50,7 @@ trait OBValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the destination of a deposit can't be created. // 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.'); Log::error('Both values are NULL, cant create OB destination.');
$result = false; $result = false;
} }
@@ -72,7 +65,7 @@ trait OBValidation
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes); 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; $result = false;
} }
if (null !== $search) { if (null !== $search) {
@@ -87,6 +80,13 @@ trait OBValidation
return $result; 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 * Source of an opening balance can either be an asset account
* or an "initial balance account". The latter can be created. * or an "initial balance account". The latter can be created.
@@ -108,7 +108,7 @@ trait OBValidation
// if both values are NULL return false, // if both values are NULL return false,
// because the source of a deposit can't be created. // because the source of a deposit can't be created.
// (this never happens). // (this never happens).
$this->sourceError = (string) trans('validation.ob_source_need_data'); $this->sourceError = (string)trans('validation.ob_source_need_data');
$result = false; $result = false;
} }

View File

@@ -25,7 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Validation\Account; namespace FireflyIII\Validation\Account;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use Log; use Log;
/** /**
@@ -60,7 +59,7 @@ trait ReconciliationValidation
$validTypes = array_keys($this->combinations[$this->transactionType]); $validTypes = array_keys($this->combinations[$this->transactionType]);
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
$this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->sourceError = (string)trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
app('log')->warning('Not a valid source. Cant find it.', $validTypes); app('log')->warning('Not a valid source. Cant find it.', $validTypes);
return false; return false;
@@ -97,7 +96,7 @@ trait ReconciliationValidation
$validTypes = array_keys($this->combinations[$this->transactionType]); $validTypes = array_keys($this->combinations[$this->transactionType]);
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { if (null === $search) {
$this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); $this->sourceError = (string)trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
app('log')->warning('Not a valid source. Cant find it.', $validTypes); app('log')->warning('Not a valid source. Cant find it.', $validTypes);
return false; return false;

View File

@@ -31,6 +31,47 @@ use Log;
*/ */
trait TransferValidation trait TransferValidation
{ {
/**
* @param array $array
*
* @return bool
*/
protected function validateTransferDestination(array $array): bool
{
$accountId = array_key_exists('id', $array) ? $array['id'] : null;
$accountName = array_key_exists('name', $array) ? $array['name'] : null;
Log::debug('Now in validateTransferDestination', $array);
// source can be any of the following types.
$validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? [];
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');
Log::error('Both values are NULL, cant create transfer destination.');
return false;
}
// or try to find the account:
$search = $this->findExistingAccount($validTypes, $array);
if (null === $search) {
$this->destError = (string)trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
return false;
}
$this->destination = $search;
// must not be the same as the source account
if (null !== $this->source && $this->source->id === $this->destination->id) {
$this->sourceError = 'Source and destination are the same.';
$this->destError = 'Source and destination are the same.';
return false;
}
return true;
}
/** /**
* @param array $accountTypes * @param array $accountTypes
* *
@@ -46,47 +87,6 @@ trait TransferValidation
*/ */
abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
/**
* @param array $array
*
* @return bool
*/
protected function validateTransferDestination(array $array): bool
{
$accountId = array_key_exists('id', $array) ? $array['id'] : null;
$accountName = array_key_exists('name', $array) ? $array['name'] : null;
Log::debug('Now in validateTransferDestination', $array);
// source can be any of the following types.
$validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? [];
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');
Log::error('Both values are NULL, cant create transfer destination.');
return false;
}
// or try to find the account:
$search = $this->findExistingAccount($validTypes, $array);
if (null === $search) {
$this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]);
return false;
}
$this->destination = $search;
// must not be the same as the source account
if (null !== $this->source && $this->source->id === $this->destination->id) {
$this->sourceError = 'Source and destination are the same.';
$this->destError = 'Source and destination are the same.';
return false;
}
return true;
}
/** /**
* @param array $array * @param array $array
* *
@@ -102,7 +102,7 @@ trait TransferValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the source of a withdrawal can't be created. // 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');
app('log')->warning('Not a valid source, need more data.'); app('log')->warning('Not a valid source, need more data.');
return false; return false;
@@ -111,7 +111,7 @@ trait TransferValidation
// otherwise try to find the account: // otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { 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]);
app('log')->warning('Not a valid source, cant find it.', $validTypes); app('log')->warning('Not a valid source, cant find it.', $validTypes);
return false; return false;

View File

@@ -32,6 +32,41 @@ use Log;
*/ */
trait WithdrawalValidation trait WithdrawalValidation
{ {
/**
* @param array $array
*
* @return bool
*/
protected function validateGenericSource(array $array): bool
{
$accountId = array_key_exists('id', $array) ? $array['id'] : null;
$accountName = array_key_exists('name', $array) ? $array['name'] : null;
Log::debug('Now in validateGenericSource', $array);
// 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');
app('log')->warning('[a] Not a valid source. Need more data.');
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array);
if (null === $search) {
$this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
app('log')->warning('Not a valid source. Cant find it.', $validTypes);
return false;
}
$this->source = $search;
Log::debug('Valid source account!');
return true;
}
/** /**
* @param array $accountTypes * @param array $accountTypes
* *
@@ -47,41 +82,6 @@ trait WithdrawalValidation
*/ */
abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
/**
* @param array $array
*
* @return bool
*/
protected function validateGenericSource(array $array): bool
{
$accountId = array_key_exists('id', $array) ? $array['id'] : null;
$accountName = array_key_exists('name', $array) ? $array['name'] : null;
Log::debug('Now in validateGenericSource', $array);
// 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');
app('log')->warning('[a] Not a valid source. Need more data.');
return false;
}
// otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array);
if (null === $search) {
$this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]);
app('log')->warning('Not a valid source. Cant find it.', $validTypes);
return false;
}
$this->source = $search;
Log::debug('Valid source account!');
return true;
}
/** /**
* @param array $array * @param array $array
* *
@@ -97,7 +97,7 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL return false, // if both values are NULL return false,
// because the destination of a withdrawal can never be created automatically. // 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; return false;
} }
@@ -110,7 +110,7 @@ trait WithdrawalValidation
if (in_array($type, $validTypes, true)) { if (in_array($type, $validTypes, true)) {
return 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; return false;
} }
@@ -136,7 +136,7 @@ trait WithdrawalValidation
if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) {
// if both values are NULL we return false, // if both values are NULL we return false,
// because the source of a withdrawal can't be created. // 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');
app('log')->warning('[b] Not a valid source. Need more data.'); app('log')->warning('[b] Not a valid source. Need more data.');
return false; return false;
@@ -145,7 +145,7 @@ trait WithdrawalValidation
// otherwise try to find the account: // otherwise try to find the account:
$search = $this->findExistingAccount($validTypes, $array); $search = $this->findExistingAccount($validTypes, $array);
if (null === $search) { 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]);
app('log')->warning('Not a valid source. Cant find it.', $validTypes); app('log')->warning('Not a valid source. Cant find it.', $validTypes);
return false; return false;

View File

@@ -242,7 +242,7 @@ class AccountValidator
} }
// find by iban // find by iban
if (null !== $accountIban && '' !== (string) $accountIban) { if (null !== $accountIban && '' !== (string)$accountIban) {
$first = $this->accountRepository->findByIbanNull($accountIban, $validTypes); $first = $this->accountRepository->findByIbanNull($accountIban, $validTypes);
if ((null !== $first) && in_array($first->accountType->type, $validTypes, true)) { if ((null !== $first) && in_array($first->accountType->type, $validTypes, true)) {
return $first; return $first;
@@ -250,7 +250,7 @@ class AccountValidator
} }
// find by number // find by number
if (null !== $accountNumber && '' !== (string) $accountNumber) { if (null !== $accountNumber && '' !== (string)$accountNumber) {
$first = $this->accountRepository->findByAccountNumber($accountNumber, $validTypes); $first = $this->accountRepository->findByAccountNumber($accountNumber, $validTypes);
if ((null !== $first) && in_array($first->accountType->type, $validTypes, true)) { if ((null !== $first) && in_array($first->accountType->type, $validTypes, true)) {
return $first; return $first;
@@ -258,7 +258,7 @@ class AccountValidator
} }
// find by name: // find by name:
if ('' !== (string) $accountName) { if ('' !== (string)$accountName) {
return $this->accountRepository->findByName($accountName, $validTypes); return $this->accountRepository->findByName($accountName, $validTypes);
} }

View File

@@ -50,26 +50,26 @@ trait ValidatesBulkTransactionQuery
// find both accounts, must be same type. // find both accounts, must be same type.
// already validated: belongs to this user. // already validated: belongs to this user.
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$source = $repository->find((int) $json['where']['account_id']); $source = $repository->find((int)$json['where']['account_id']);
$dest = $repository->find((int) $json['update']['account_id']); $dest = $repository->find((int)$json['update']['account_id']);
if (null === $source) { if (null === $source) {
$validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'where', 'account_id')); $validator->errors()->add('query', sprintf((string)trans('validation.invalid_query_data'), 'where', 'account_id'));
return; return;
} }
if (null === $dest) { if (null === $dest) {
$validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'update', 'account_id')); $validator->errors()->add('query', sprintf((string)trans('validation.invalid_query_data'), 'update', 'account_id'));
return; return;
} }
if ($source->accountType->type !== $dest->accountType->type) { if ($source->accountType->type !== $dest->accountType->type) {
$validator->errors()->add('query', (string) trans('validation.invalid_query_account_type')); $validator->errors()->add('query', (string)trans('validation.invalid_query_account_type'));
return; return;
} }
// must have same currency: // must have same currency:
if ($repository->getAccountCurrency($source)->id !== $repository->getAccountCurrency($dest)->id) { if ($repository->getAccountCurrency($source)->id !== $repository->getAccountCurrency($dest)->id) {
$validator->errors()->add('query', (string) trans('validation.invalid_query_currency')); $validator->errors()->add('query', (string)trans('validation.invalid_query_currency'));
} }
} }
} }

View File

@@ -39,36 +39,36 @@ trait ValidatesAutoBudgetRequest
$type = $data['auto_budget_type'] ?? ''; $type = $data['auto_budget_type'] ?? '';
$amount = array_key_exists('auto_budget_amount', $data) ? $data['auto_budget_amount'] : null; $amount = array_key_exists('auto_budget_amount', $data) ? $data['auto_budget_amount'] : null;
$period = array_key_exists('auto_budget_period', $data) ? $data['auto_budget_period'] : null; $period = array_key_exists('auto_budget_period', $data) ? $data['auto_budget_period'] : null;
$currencyId = array_key_exists('auto_budget_currency_id', $data) ? (int) $data['auto_budget_currency_id'] : null; $currencyId = array_key_exists('auto_budget_currency_id', $data) ? (int)$data['auto_budget_currency_id'] : null;
$currencyCode = array_key_exists('auto_budget_currency_code', $data) ? $data['auto_budget_currency_code'] : null; $currencyCode = array_key_exists('auto_budget_currency_code', $data) ? $data['auto_budget_currency_code'] : null;
if (is_numeric($type)) { if (is_numeric($type)) {
$type = (int) $type; $type = (int)$type;
} }
if ('' === $type || 0 === $type) { if ('' === $type || 0 === $type) {
return; return;
} }
// basic float check: // basic float check:
if (!is_numeric($amount)) { if (!is_numeric($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'));
return; return;
} }
if ('' === $amount) { 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')) { if (1 !== bccomp((string)$amount, '0')) {
$validator->errors()->add('auto_budget_amount', (string) trans('validation.auto_budget_amount_positive')); $validator->errors()->add('auto_budget_amount', (string)trans('validation.auto_budget_amount_positive'));
} }
if ('' === $period) { 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 (null !== $currencyId && null !== $currencyCode && '' === $currencyCode && 0 === $currencyId) { if (null !== $currencyId && null !== $currencyCode && '' === $currencyCode && 0 === $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'));
} }
// too big amount // too big amount
if ((int)$amount > 268435456) { if ((int)$amount > 268435456) {
$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'));
return; return;
} }
} }

View File

@@ -55,8 +55,8 @@ trait CurrencyValidation
&& 0 !== bccomp('0', $transaction['foreign_amount']) && 0 !== bccomp('0', $transaction['foreign_amount'])
) { ) {
$validator->errors()->add( $validator->errors()->add(
'transactions.' . $index . '.foreign_amount', '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 the currency is present, then the amount must be present as well.
@@ -66,8 +66,8 @@ trait CurrencyValidation
$transaction $transaction
)) { )) {
$validator->errors()->add( $validator->errors()->add(
'transactions.' . $index . '.foreign_amount', 'transactions.'.$index.'.foreign_amount',
(string) trans('validation.require_currency_amount') (string)trans('validation.require_currency_amount')
); );
} }
} }

View File

@@ -1,4 +1,5 @@
<?php <?php
/** /**
* FireflyValidator.php * FireflyValidator.php
* Copyright (c) 2019 james@firefly-iii.org * Copyright (c) 2019 james@firefly-iii.org
@@ -91,7 +92,7 @@ class FireflyValidator extends Validator
{ {
$field = $parameters[1] ?? 'id'; $field = $parameters[1] ?? 'id';
if (0 === (int) $value) { if (0 === (int)$value) {
return true; return true;
} }
$count = DB::table($parameters[0])->where('user_id', auth()->user()->id)->where($field, $value)->count(); $count = DB::table($parameters[0])->where('user_id', auth()->user()->id)->where($field, $value)->count();
@@ -188,13 +189,40 @@ class FireflyValidator extends Validator
// replace characters outside of ASCI range. // replace characters outside of ASCI range.
$value = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value); $value = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
$search = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; $search = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
$replace = ['', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', $replace = [
'32', '33', '34', '35',]; '',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'23',
'24',
'25',
'26',
'27',
'28',
'29',
'30',
'31',
'32',
'33',
'34',
'35',
];
// take // take
$first = substr($value, 0, 4); $first = substr($value, 0, 4);
$last = substr($value, 4); $last = substr($value, 4);
$iban = $last . $first; $iban = $last.$first;
$iban = trim(str_replace($search, $replace, $iban)); $iban = trim(str_replace($search, $replace, $iban));
if (0 === strlen($iban)) { if (0 === strlen($iban)) {
return false; return false;
@@ -209,7 +237,7 @@ class FireflyValidator extends Validator
return false; return false;
} }
return 1 === (int) $checksum; return 1 === (int)$checksum;
} }
/** /**
@@ -224,7 +252,7 @@ class FireflyValidator extends Validator
/** @var mixed $compare */ /** @var mixed $compare */
$compare = $parameters[0] ?? '0'; $compare = $parameters[0] ?? '0';
return bccomp((string) $value, (string) $compare) < 0; return bccomp((string)$value, (string)$compare) < 0;
} }
/** /**
@@ -239,7 +267,7 @@ class FireflyValidator extends Validator
/** @var mixed $compare */ /** @var mixed $compare */
$compare = $parameters[0] ?? '0'; $compare = $parameters[0] ?? '0';
return bccomp((string) $value, (string) $compare) > 0; return bccomp((string)$value, (string)$compare) > 0;
} }
/** /**
@@ -253,7 +281,7 @@ class FireflyValidator extends Validator
{ {
$field = $parameters[1] ?? 'id'; $field = $parameters[1] ?? 'id';
if (0 === (int) $value) { if (0 === (int)$value) {
return true; return true;
} }
$count = DB::table($parameters[0])->where($field, $value)->count(); $count = DB::table($parameters[0])->where($field, $value)->count();
@@ -273,7 +301,7 @@ class FireflyValidator extends Validator
// first, get the index from this string: // first, get the index from this string:
$value = $value ?? ''; $value = $value ?? '';
$parts = explode('.', $attribute); $parts = explode('.', $attribute);
$index = (int) ($parts[1] ?? '0'); $index = (int)($parts[1] ?? '0');
// get the name of the trigger from the data array: // get the name of the trigger from the data array:
$actionType = $this->data['actions'][$index]['type'] ?? 'invalid'; $actionType = $this->data['actions'][$index]['type'] ?? 'invalid';
@@ -306,8 +334,14 @@ class FireflyValidator extends Validator
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$account = $repository->findByName( $account = $repository->findByName(
$value, $value,
[AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, [
AccountType::CREDITCARD] AccountType::DEFAULT,
AccountType::ASSET,
AccountType::LOAN,
AccountType::DEBT,
AccountType::MORTGAGE,
AccountType::CREDITCARD,
]
); );
return null !== $account; return null !== $account;
@@ -337,7 +371,7 @@ class FireflyValidator extends Validator
{ {
// first, get the index from this string: // first, get the index from this string:
$parts = explode('.', $attribute); $parts = explode('.', $attribute);
$index = (int) ($parts[1] ?? '0'); $index = (int)($parts[1] ?? '0');
// get the name of the trigger from the data array: // get the name of the trigger from the data array:
$triggerType = $this->data['triggers'][$index]['type'] ?? 'invalid'; $triggerType = $this->data['triggers'][$index]['type'] ?? 'invalid';
@@ -354,18 +388,35 @@ class FireflyValidator extends Validator
} }
// these trigger types need a simple strlen check: // these trigger types need a simple strlen check:
$length = ['source_account_starts', 'source_account_ends', 'source_account_is', 'source_account_contains', 'destination_account_starts', $length = [
'source_account_starts',
'source_account_ends',
'source_account_is',
'source_account_contains',
'destination_account_starts',
'destination_account_ends', 'destination_account_ends',
'destination_account_is', 'destination_account_contains', 'description_starts', 'description_ends', 'description_contains', 'description_is', 'destination_account_is',
'destination_account_contains',
'description_starts',
'description_ends',
'description_contains',
'description_is',
'category_is', 'category_is',
'budget_is', 'tag_is', 'currency_is', 'notes_contain', 'notes_start', 'notes_end', 'notes_are',]; 'budget_is',
'tag_is',
'currency_is',
'notes_contain',
'notes_start',
'notes_end',
'notes_are',
];
if (in_array($triggerType, $length, true)) { if (in_array($triggerType, $length, true)) {
return '' !== $value; return '' !== $value;
} }
// check if it's an existing account. // check if it's an existing account.
if (in_array($triggerType, ['destination_account_id', 'source_account_id'], true)) { if (in_array($triggerType, ['destination_account_id', 'source_account_id'], true)) {
return is_numeric($value) && (int) $value > 0; return is_numeric($value) && (int)$value > 0;
} }
// check transaction type. // check transaction type.
@@ -401,7 +452,7 @@ class FireflyValidator extends Validator
{ {
$verify = false; $verify = false;
if (array_key_exists('verify_password', $this->data)) { if (array_key_exists('verify_password', $this->data)) {
$verify = 1 === (int) $this->data['verify_password']; $verify = 1 === (int)$this->data['verify_password'];
} }
if ($verify) { if ($verify) {
/** @var Verifier $service */ /** @var Verifier $service */
@@ -430,14 +481,14 @@ class FireflyValidator extends Validator
return $this->validateByAccountTypeString($value, $parameters, $this->data['objectType']); return $this->validateByAccountTypeString($value, $parameters, $this->data['objectType']);
} }
if (array_key_exists('type', $this->data)) { if (array_key_exists('type', $this->data)) {
return $this->validateByAccountTypeString($value, $parameters, (string) $this->data['type']); return $this->validateByAccountTypeString($value, $parameters, (string)$this->data['type']);
} }
if (array_key_exists('account_type_id', $this->data)) { if (array_key_exists('account_type_id', $this->data)) {
return $this->validateByAccountTypeId($value, $parameters); return $this->validateByAccountTypeId($value, $parameters);
} }
$parameterId = $parameters[0] ?? null; $parameterId = $parameters[0] ?? null;
if (null !== $parameterId) { if (null !== $parameterId) {
return $this->validateByParameterId((int) $parameterId, $value); return $this->validateByParameterId((int)$parameterId, $value);
} }
if (array_key_exists('id', $this->data)) { if (array_key_exists('id', $this->data)) {
return $this->validateByAccountId($value); return $this->validateByAccountId($value);
@@ -480,14 +531,14 @@ class FireflyValidator extends Validator
private function validateByAccountTypeString(string $value, array $parameters, string $type): bool private function validateByAccountTypeString(string $value, array $parameters, string $type): bool
{ {
/** @var array|null $search */ /** @var array|null $search */
$search = Config::get('firefly.accountTypeByIdentifier.' . $type); $search = Config::get('firefly.accountTypeByIdentifier.'.$type);
if (null === $search) { if (null === $search) {
return false; return false;
} }
$accountTypes = AccountType::whereIn('type', $search)->get(); $accountTypes = AccountType::whereIn('type', $search)->get();
$ignore = (int) ($parameters[0] ?? 0.0); $ignore = (int)($parameters[0] ?? 0.0);
$accountTypeIds = $accountTypes->pluck('id')->toArray(); $accountTypeIds = $accountTypes->pluck('id')->toArray();
/** @var Collection $set */ /** @var Collection $set */
$set = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->get(); $set = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->get();
@@ -509,7 +560,7 @@ class FireflyValidator extends Validator
private function validateByAccountTypeId($value, $parameters): bool private function validateByAccountTypeId($value, $parameters): bool
{ {
$type = AccountType::find($this->data['account_type_id'])->first(); $type = AccountType::find($this->data['account_type_id'])->first();
$ignore = (int) ($parameters[0] ?? 0.0); $ignore = (int)($parameters[0] ?? 0.0);
/** @var Collection $set */ /** @var Collection $set */
$set = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->get(); $set = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->get();
@@ -583,9 +634,9 @@ class FireflyValidator extends Validator
*/ */
public function validateUniqueAccountNumberForUser($attribute, $value, $parameters): bool public function validateUniqueAccountNumberForUser($attribute, $value, $parameters): bool
{ {
$accountId = (int) ($this->data['id'] ?? 0.0); $accountId = (int)($this->data['id'] ?? 0.0);
if (0 === $accountId) { if (0 === $accountId) {
$accountId = (int) ($parameters[0] ?? 0.0); $accountId = (int)($parameters[0] ?? 0.0);
} }
$query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
@@ -617,7 +668,7 @@ class FireflyValidator extends Validator
/** @var AccountMeta $entry */ /** @var AccountMeta $entry */
foreach ($set as $entry) { foreach ($set as $entry) {
$otherAccount = $entry->account; $otherAccount = $entry->account;
$otherType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $otherAccount->accountType->type)); $otherType = (string)config(sprintf('firefly.shortNamesByFullName.%s', $otherAccount->accountType->type));
if (('expense' === $otherType || 'revenue' === $otherType) && $otherType !== $type) { if (('expense' === $otherType || 'revenue' === $otherType) && $otherType !== $type) {
Log::debug(sprintf('The other account with this account number is a "%s" so return true.', $otherType)); Log::debug(sprintf('The other account with this account number is a "%s" so return true.', $otherType));
return true; return true;
@@ -634,17 +685,7 @@ class FireflyValidator extends Validator
*/ */
public function validateUniqueCurrencyCode($attribute, $value): bool public function validateUniqueCurrencyCode($attribute, $value): bool
{ {
return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value); return $this->validateUniqueCurrency('code', (string)$attribute, (string)$value);
}
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencyName($attribute, $value): bool
{
return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value);
} }
/** /**
@@ -658,6 +699,16 @@ class FireflyValidator extends Validator
return 0 === DB::table('transaction_currencies')->where($field, $value)->whereNull('deleted_at')->count(); return 0 === DB::table('transaction_currencies')->where($field, $value)->whereNull('deleted_at')->count();
} }
/**
* @param $attribute
* @param $value
* @return bool
*/
public function validateUniqueCurrencyName($attribute, $value): bool
{
return $this->validateUniqueCurrency('name', (string)$attribute, (string)$value);
}
/** /**
* @param $attribute * @param $attribute
* @param $value * @param $value
@@ -665,7 +716,7 @@ class FireflyValidator extends Validator
*/ */
public function validateUniqueCurrencySymbol($attribute, $value): bool public function validateUniqueCurrencySymbol($attribute, $value): bool
{ {
return $this->validateUniqueCurrency('symbol', (string) $attribute, (string) $value); return $this->validateUniqueCurrency('symbol', (string)$attribute, (string)$value);
} }
/** /**
@@ -677,7 +728,7 @@ class FireflyValidator extends Validator
*/ */
public function validateUniqueExistingWebhook($value, $parameters, $something): bool public function validateUniqueExistingWebhook($value, $parameters, $something): bool
{ {
$existingId = (int) ($something[0] ?? 0); $existingId = (int)($something[0] ?? 0);
$trigger = 0; $trigger = 0;
$response = 0; $response = 0;
$delivery = 0; $delivery = 0;
@@ -733,15 +784,15 @@ class FireflyValidator extends Validator
public function validateUniqueObjectForUser($attribute, $value, $parameters): bool public function validateUniqueObjectForUser($attribute, $value, $parameters): bool
{ {
[$table, $field] = $parameters; [$table, $field] = $parameters;
$exclude = (int) ($parameters[2] ?? 0.0); $exclude = (int)($parameters[2] ?? 0.0);
/* /*
* If other data (in $this->getData()) contains * If other data (in $this->getData()) contains
* ID field, set that field to be the $exclude. * ID field, set that field to be the $exclude.
*/ */
$data = $this->getData(); $data = $this->getData();
if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int) $data['id'] > 0) { if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int)$data['id'] > 0) {
$exclude = (int) $data['id']; $exclude = (int)$data['id'];
} }
// get entries from table // get entries from table
$set = DB::table($table)->where('user_id', auth()->user()->id)->whereNull('deleted_at') $set = DB::table($table)->where('user_id', auth()->user()->id)->whereNull('deleted_at')
@@ -773,7 +824,7 @@ class FireflyValidator extends Validator
->where('object_groups.user_id', auth()->user()->id) ->where('object_groups.user_id', auth()->user()->id)
->where('object_groups.title', $value); ->where('object_groups.title', $value);
if (null !== $exclude) { if (null !== $exclude) {
$query->where('object_groups.id', '!=', (int) $exclude); $query->where('object_groups.id', '!=', (int)$exclude);
} }
return 0 === $query->count(); return 0 === $query->count();
@@ -792,7 +843,7 @@ class FireflyValidator extends Validator
$query = DB::table('piggy_banks')->whereNull('piggy_banks.deleted_at') $query = DB::table('piggy_banks')->whereNull('piggy_banks.deleted_at')
->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', auth()->user()->id); ->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', auth()->user()->id);
if (null !== $exclude) { if (null !== $exclude) {
$query->where('piggy_banks.id', '!=', (int) $exclude); $query->where('piggy_banks.id', '!=', (int)$exclude);
} }
$query->where('piggy_banks.name', $value); $query->where('piggy_banks.name', $value);

View File

@@ -35,26 +35,28 @@ use Log;
*/ */
trait GroupValidation trait GroupValidation
{ {
/**
* @param Validator $validator
*
* @return array
*/
abstract protected function getTransactionsArray(Validator $validator): array;
/** /**
* @param Validator $validator * @param Validator $validator
*/ */
protected function preventNoAccountInfo(Validator $validator): void protected function preventNoAccountInfo(Validator $validator): void
{ {
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
$keys = ['source_id', 'destination_id', 'source_name', 'destination_name', 'source_iban', 'destination_iban', 'source_number', 'destination_number']; $keys = [
'source_id',
'destination_id',
'source_name',
'destination_name',
'source_iban',
'destination_iban',
'source_number',
'destination_number',
];
/** @var array $transaction */ /** @var array $transaction */
foreach ($transactions as $index => $transaction) { foreach ($transactions as $index => $transaction) {
$hasAccountInfo = false; $hasAccountInfo = false;
$hasJournalId = array_key_exists('transaction_journal_id', $transaction); $hasJournalId = array_key_exists('transaction_journal_id', $transaction);
foreach ($keys as $key) { foreach ($keys as $key) {
if (array_key_exists($key, $transaction) && '' !== (string) $transaction[$key]) { if (array_key_exists($key, $transaction) && '' !== (string)$transaction[$key]) {
$hasAccountInfo = true; $hasAccountInfo = true;
} }
} }
@@ -62,18 +64,24 @@ trait GroupValidation
if (false === $hasAccountInfo && !$hasJournalId) { if (false === $hasAccountInfo && !$hasJournalId) {
$validator->errors()->add( $validator->errors()->add(
sprintf('transactions.%d.source_id', $index), sprintf('transactions.%d.source_id', $index),
(string) trans('validation.generic_no_source') (string)trans('validation.generic_no_source')
); );
$validator->errors()->add( $validator->errors()->add(
sprintf('transactions.%d.destination_id', $index), sprintf('transactions.%d.destination_id', $index),
(string) trans('validation.generic_no_destination') (string)trans('validation.generic_no_destination')
); );
} }
} }
// only an issue if there is no transaction_journal_id // only an issue if there is no transaction_journal_id
} }
/**
* @param Validator $validator
*
* @return array
*/
abstract protected function getTransactionsArray(Validator $validator): array;
/** /**
* Adds an error to the "description" field when the user has submitted no descriptions and no * Adds an error to the "description" field when the user has submitted no descriptions and no
* journal description. * journal description.
@@ -86,7 +94,7 @@ trait GroupValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
$validDescriptions = 0; $validDescriptions = 0;
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
if ('' !== (string) ($transaction['description'] ?? null)) { if ('' !== (string)($transaction['description'] ?? null)) {
$validDescriptions++; $validDescriptions++;
} }
} }
@@ -95,7 +103,7 @@ trait GroupValidation
if (0 === $validDescriptions) { if (0 === $validDescriptions) {
$validator->errors()->add( $validator->errors()->add(
'transactions.0.description', 'transactions.0.description',
(string) trans('validation.filled', ['attribute' => (string) trans('validation.attributes.description')]) (string)trans('validation.filled', ['attribute' => (string)trans('validation.attributes.description')])
); );
} }
} }
@@ -111,7 +119,7 @@ trait GroupValidation
$groupTitle = $data['group_title'] ?? ''; $groupTitle = $data['group_title'] ?? '';
if ('' === $groupTitle && count($transactions) > 1) { if ('' === $groupTitle && count($transactions) > 1) {
$validator->errors()->add('group_title', (string) trans('validation.group_title_mandatory')); $validator->errors()->add('group_title', (string)trans('validation.group_title_mandatory'));
} }
} }
@@ -169,7 +177,7 @@ trait GroupValidation
if (null === $journalId || 0 === $count) { if (null === $journalId || 0 === $count) {
app('log')->warning(sprintf('Transaction group #%d has %d journals with ID %d', $transactionGroup->id, $count, $journalId)); app('log')->warning(sprintf('Transaction group #%d has %d journals with ID %d', $transactionGroup->id, $count, $journalId));
app('log')->warning('Invalid submission: Each split must have transaction_journal_id (either valid ID or 0).'); app('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')); $validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string)trans('validation.need_id_in_edit'));
} }
} }
} }

View File

@@ -91,7 +91,7 @@ trait RecurrenceValidation
continue; continue;
} }
// validate source account. // validate source account.
$sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; $sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null;
$sourceName = $transaction['source_name'] ?? null; $sourceName = $transaction['source_name'] ?? null;
$validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
@@ -103,7 +103,7 @@ trait RecurrenceValidation
return; return;
} }
// validate destination account // validate destination account
$destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null; $destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null;
$destinationName = $transaction['destination_name'] ?? null; $destinationName = $transaction['destination_name'] ?? null;
$validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName,]); $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName,]);
// do something with result: // do something with result:
@@ -127,7 +127,7 @@ trait RecurrenceValidation
$repetitions = $data['repetitions'] ?? []; $repetitions = $data['repetitions'] ?? [];
// need at least one transaction // need at least one transaction
if (!is_countable($repetitions) || 0 === count($repetitions)) { if (!is_countable($repetitions) || 0 === count($repetitions)) {
$validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition')); $validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition'));
} }
} }
@@ -145,7 +145,7 @@ trait RecurrenceValidation
} }
// need at least one transaction // need at least one transaction
if (0 === count($repetitions)) { if (0 === count($repetitions)) {
$validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition')); $validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition'));
} }
} }
@@ -162,15 +162,15 @@ trait RecurrenceValidation
$repeatUntil = $data['repeat_until'] ?? null; $repeatUntil = $data['repeat_until'] ?? null;
if (null !== $repetitions && null !== $repeatUntil) { if (null !== $repetitions && null !== $repeatUntil) {
// expect a date OR count: // expect a date OR count:
$validator->errors()->add('repeat_until', (string) trans('validation.require_repeat_until')); $validator->errors()->add('repeat_until', (string)trans('validation.require_repeat_until'));
$validator->errors()->add('nr_of_repetitions', (string) trans('validation.require_repeat_until')); $validator->errors()->add('nr_of_repetitions', (string)trans('validation.require_repeat_until'));
} }
} }
public function validateRecurringConfig(Validator $validator) public function validateRecurringConfig(Validator $validator)
{ {
$data = $validator->getData(); $data = $validator->getData();
$reps = array_key_exists('nr_of_repetitions', $data) ? (int) $data['nr_of_repetitions'] : null; $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; $repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null;
if (null === $reps && null === $repeatUntil) { if (null === $reps && null === $repeatUntil) {
@@ -193,7 +193,7 @@ trait RecurrenceValidation
$data = $validator->getData(); $data = $validator->getData();
$repetitions = $data['repetitions'] ?? []; $repetitions = $data['repetitions'] ?? [];
if (!is_array($repetitions)) { if (!is_array($repetitions)) {
$validator->errors()->add(sprintf('repetitions.%d.type', 0), (string) trans('validation.valid_recurrence_rep_type')); $validator->errors()->add(sprintf('repetitions.%d.type', 0), (string)trans('validation.valid_recurrence_rep_type'));
return; return;
} }
@@ -211,23 +211,23 @@ trait RecurrenceValidation
$repetition['moment'] = $repetition['moment'] ?? 'invalid'; $repetition['moment'] = $repetition['moment'] ?? 'invalid';
switch ($repetition['type'] ?? 'empty') { switch ($repetition['type'] ?? 'empty') {
default: default:
$validator->errors()->add(sprintf('repetitions.%d.type', $index), (string) trans('validation.valid_recurrence_rep_type')); $validator->errors()->add(sprintf('repetitions.%d.type', $index), (string)trans('validation.valid_recurrence_rep_type'));
return; return;
case 'daily': case 'daily':
$this->validateDaily($validator, $index, (string) $repetition['moment']); $this->validateDaily($validator, $index, (string)$repetition['moment']);
break; break;
case 'monthly': case 'monthly':
$this->validateMonthly($validator, $index, (int) $repetition['moment']); $this->validateMonthly($validator, $index, (int)$repetition['moment']);
break; break;
case 'ndom': case 'ndom':
$this->validateNdom($validator, $index, (string) $repetition['moment']); $this->validateNdom($validator, $index, (string)$repetition['moment']);
break; break;
case 'weekly': case 'weekly':
$this->validateWeekly($validator, $index, (int) $repetition['moment']); $this->validateWeekly($validator, $index, (int)$repetition['moment']);
break; break;
case 'yearly': case 'yearly':
$this->validateYearly($validator, $index, (string) $repetition['moment']); $this->validateYearly($validator, $index, (string)$repetition['moment']);
break; break;
} }
} }
@@ -243,7 +243,7 @@ trait RecurrenceValidation
protected function validateDaily(Validator $validator, int $index, string $moment): void protected function validateDaily(Validator $validator, int $index, string $moment): void
{ {
if ('' !== $moment) { if ('' !== $moment) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -257,7 +257,7 @@ trait RecurrenceValidation
protected function validateMonthly(Validator $validator, int $index, int $dayOfMonth): void protected function validateMonthly(Validator $validator, int $index, int $dayOfMonth): void
{ {
if ($dayOfMonth < 1 || $dayOfMonth > 31) { if ($dayOfMonth < 1 || $dayOfMonth > 31) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -273,19 +273,19 @@ trait RecurrenceValidation
{ {
$parameters = explode(',', $moment); $parameters = explode(',', $moment);
if (2 !== count($parameters)) { if (2 !== count($parameters)) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
return; return;
} }
$nthDay = (int) ($parameters[0] ?? 0.0); $nthDay = (int)($parameters[0] ?? 0.0);
$dayOfWeek = (int) ($parameters[1] ?? 0.0); $dayOfWeek = (int)($parameters[1] ?? 0.0);
if ($nthDay < 1 || $nthDay > 5) { if ($nthDay < 1 || $nthDay > 5) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
return; return;
} }
if ($dayOfWeek < 1 || $dayOfWeek > 7) { if ($dayOfWeek < 1 || $dayOfWeek > 7) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -299,7 +299,7 @@ trait RecurrenceValidation
protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void
{ {
if ($dayOfWeek < 1 || $dayOfWeek > 7) { if ($dayOfWeek < 1 || $dayOfWeek > 7) {
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
} }
} }
@@ -316,7 +316,7 @@ trait RecurrenceValidation
Carbon::createFromFormat('Y-m-d', $moment); Carbon::createFromFormat('Y-m-d', $moment);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
Log::debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage())); Log::debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage()));
$validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment'));
} }
} }
} }

View File

@@ -101,10 +101,10 @@ trait TransactionValidation
$accountValidator->setTransactionType($transactionType); $accountValidator->setTransactionType($transactionType);
// validate source account. // validate source account.
$sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; $sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null;
$sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null; $sourceName = array_key_exists('source_name', $transaction) ? (string)$transaction['source_name'] : null;
$sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null; $sourceIban = array_key_exists('source_iban', $transaction) ? (string)$transaction['source_iban'] : null;
$sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null; $sourceNumber = array_key_exists('source_number', $transaction) ? (string)$transaction['source_number'] : null;
$source = [ $source = [
'id' => $sourceId, 'id' => $sourceId,
'name' => $sourceName, 'name' => $sourceName,
@@ -121,10 +121,10 @@ trait TransactionValidation
return; return;
} }
// validate destination account // validate destination account
$destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null; $destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null;
$destinationName = array_key_exists('destination_name', $transaction) ? (string) $transaction['destination_name'] : null; $destinationName = array_key_exists('destination_name', $transaction) ? (string)$transaction['destination_name'] : null;
$destinationIban = array_key_exists('destination_iban', $transaction) ? (string) $transaction['destination_iban'] : null; $destinationIban = array_key_exists('destination_iban', $transaction) ? (string)$transaction['destination_iban'] : null;
$destinationNumber = array_key_exists('destination_number', $transaction) ? (string) $transaction['destination_number'] : null; $destinationNumber = array_key_exists('destination_number', $transaction) ? (string)$transaction['destination_number'] : null;
$destination = [ $destination = [
'id' => $destinationId, 'id' => $destinationId,
'name' => $destinationName, 'name' => $destinationName,
@@ -224,7 +224,7 @@ trait TransactionValidation
// validate if the submitted source and / or name are valid // validate if the submitted source and / or name are valid
if (array_key_exists('source_id', $transaction) || array_key_exists('source_name', $transaction)) { if (array_key_exists('source_id', $transaction) || array_key_exists('source_name', $transaction)) {
Log::debug('Will try to validate source account information.'); Log::debug('Will try to validate source account information.');
$sourceId = (int) ($transaction['source_id'] ?? 0); $sourceId = (int)($transaction['source_id'] ?? 0);
$sourceName = $transaction['source_name'] ?? null; $sourceName = $transaction['source_name'] ?? null;
$validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
@@ -252,7 +252,7 @@ trait TransactionValidation
$accountValidator->source = $source; $accountValidator->source = $source;
} }
} }
$destinationId = (int) ($transaction['destination_id'] ?? 0); $destinationId = (int)($transaction['destination_id'] ?? 0);
$destinationName = $transaction['destination_name'] ?? null; $destinationName = $transaction['destination_name'] ?? null;
$array = ['id' => $destinationId, 'name' => $destinationName,]; $array = ['id' => $destinationId, 'name' => $destinationName,];
$validDestination = $accountValidator->validateDestination($array); $validDestination = $accountValidator->validateDestination($array);
@@ -293,7 +293,7 @@ trait TransactionValidation
} }
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($transactionGroup->transactionJournals as $journal) { foreach ($transactionGroup->transactionJournals as $journal) {
if ((int) $journal->id === (int) $transaction['transaction_journal_id']) { if ((int)$journal->id === (int)$transaction['transaction_journal_id']) {
return $journal->transactions()->where('amount', '<', 0)->first()->account; return $journal->transactions()->where('amount', '<', 0)->first()->account;
} }
} }
@@ -313,7 +313,7 @@ trait TransactionValidation
// need at least one transaction // need at least one transaction
if (0 === count($transactions)) { if (0 === count($transactions)) {
$validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction'));
} }
} }
@@ -328,7 +328,7 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
// need at least one transaction // need at least one transaction
if (0 === count($transactions)) { if (0 === count($transactions)) {
$validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction'));
Log::debug('Added error: at_least_one_transaction.'); Log::debug('Added error: at_least_one_transaction.');
return; return;
@@ -344,7 +344,7 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
foreach ($transactions as $key => $value) { foreach ($transactions as $key => $value) {
if (!is_int($key)) { if (!is_int($key)) {
$validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction')); $validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction'));
Log::debug('Added error: at_least_one_transaction.'); Log::debug('Added error: at_least_one_transaction.');
return; return;
@@ -368,13 +368,13 @@ trait TransactionValidation
} }
$unique = array_unique($types); $unique = array_unique($types);
if (count($unique) > 1) { if (count($unique) > 1) {
$validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); $validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal'));
return; return;
} }
$first = $unique[0] ?? 'invalid'; $first = $unique[0] ?? 'invalid';
if ('invalid' === $first) { if ('invalid' === $first) {
$validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type')); $validator->errors()->add('transactions.0.type', (string)trans('validation.invalid_transaction_type'));
} }
} }
@@ -389,14 +389,14 @@ trait TransactionValidation
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);
$types = []; $types = [];
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
$originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0)); $originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0));
// if type is not set, fall back to the type of the journal, if one is given. // if type is not set, fall back to the type of the journal, if one is given.
$types[] = $transaction['type'] ?? $originalType; $types[] = $transaction['type'] ?? $originalType;
} }
$unique = array_unique($types); $unique = array_unique($types);
if (count($unique) > 1) { if (count($unique) > 1) {
app('log')->warning('Add error for mismatch transaction types.'); app('log')->warning('Add error for mismatch transaction types.');
$validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); $validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal'));
return; return;
} }
@@ -447,18 +447,18 @@ trait TransactionValidation
default: default:
case 'withdrawal': case 'withdrawal':
if (count($sources) > 1) { if (count($sources) > 1) {
$validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
} }
break; break;
case 'deposit': case 'deposit':
if (count($dests) > 1) { if (count($dests) > 1) {
$validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
} }
break; break;
case'transfer': case'transfer':
if (count($sources) > 1 || count($dests) > 1) { if (count($sources) > 1 || count($dests) > 1) {
$validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
$validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
} }
break; break;
} }
@@ -489,14 +489,14 @@ trait TransactionValidation
$result = $this->compareAccountData($type, $comparison); $result = $this->compareAccountData($type, $comparison);
if (false === $result) { if (false === $result) {
if ('withdrawal' === $type) { if ('withdrawal' === $type) {
$validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
} }
if ('deposit' === $type) { if ('deposit' === $type) {
$validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
} }
if ('transfer' === $type) { if ('transfer' === $type) {
$validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal'));
$validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal'));
} }
app('log')->warning('Add error about equal accounts.'); app('log')->warning('Add error about equal accounts.');
@@ -519,7 +519,7 @@ trait TransactionValidation
/** @var array $transaction */ /** @var array $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
// source or destination may be omitted. If this is the case, use the original source / destination name + ID. // 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)); $originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0));
// get field. // get field.
$comparison[$field][] = $transaction[$field] ?? $originalData[$field]; $comparison[$field][] = $transaction[$field] ?? $originalData[$field];