firefly-iii/app/Factory/AccountFactory.php

254 lines
8.2 KiB
PHP
Raw Normal View History

<?php
2018-05-11 03:08:34 -05:00
/**
* AccountFactory.php
* Copyright (c) 2018 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
/** @noinspection PhpDynamicAsStaticMethodCallInspection */
/** @noinspection PhpUndefinedMethodInspection */
2018-05-11 03:08:34 -05:00
declare(strict_types=1);
namespace FireflyIII\Factory;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
2018-12-21 09:38:10 -06:00
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Services\Internal\Support\AccountServiceTrait;
use FireflyIII\User;
2018-08-04 10:30:47 -05:00
use Log;
/**
2018-02-19 12:44:46 -06:00
* Factory to create or return accounts.
*
* Class AccountFactory
*/
class AccountFactory
{
2018-09-26 23:26:03 -05:00
/** @var User */
private $user;
use AccountServiceTrait;
/**
2018-12-21 09:38:10 -06:00
* AccountFactory constructor.
2019-02-13 10:38:41 -06:00
*
2018-12-21 09:38:10 -06:00
* @codeCoverageIgnore
*/
public function __construct()
{
if ('testing' === config('app.env')) {
2019-06-07 11:20:15 -05:00
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
}
}
/**
* @param array $data
*
* @return Account
* @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function create(array $data): Account
{
$type = $this->getAccountType($data['account_type_id'], $data['accountType']);
if (null === $type) {
throw new FireflyException(
sprintf('AccountFactory::create() was unable to find account type #%d ("%s").', $data['account_type_id'], $data['accountType'])
);
}
$data['iban'] = $this->filterIban($data['iban']);
// account may exist already:
Log::debug('Data array is as follows', $data);
$return = $this->find($data['name'], $type->type);
if (null === $return) {
// create it:
$databaseData
= [
'user_id' => $this->user->id,
'account_type_id' => $type->id,
'name' => $data['name'],
'virtual_balance' => $data['virtualBalance'] ?? '0',
'active' => true === $data['active'],
'iban' => $data['iban'],
];
2018-12-21 09:38:10 -06:00
// find currency, or use default currency instead.
/** @var TransactionCurrencyFactory $factory */
$factory = app(TransactionCurrencyFactory::class);
/** @var TransactionCurrency $currency */
$currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null));
if (null === $currency) {
// use default currency:
$currency = app('amount')->getDefaultCurrencyByUser($this->user);
}
2019-02-13 10:38:41 -06:00
$currency->enabled = true;
2018-12-21 09:38:10 -06:00
$currency->save();
unset($data['currency_code']);
$data['currency_id'] = $currency->id;
2018-08-04 10:30:47 -05:00
// remove virtual balance when not an asset account or a liability
$canHaveVirtual = [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD];
2019-06-07 23:19:21 -05:00
if (!in_array($type->type, $canHaveVirtual, true)) {
$databaseData['virtual_balance'] = '0';
}
// fix virtual balance when it's empty
if ('' === $databaseData['virtual_balance']) {
$databaseData['virtual_balance'] = '0';
}
2018-04-03 12:15:06 -05:00
$return = Account::create($databaseData);
$this->updateMetaData($return, $data);
2019-06-07 23:19:21 -05:00
if (in_array($type->type, $canHaveVirtual, true)) {
if ($this->validIBData($data)) {
$this->updateIB($return, $data);
}
if (!$this->validIBData($data)) {
$this->deleteIB($return);
}
}
$this->updateNote($return, $data['notes'] ?? '');
}
return $return;
}
/**
* @param string $accountName
* @param string $accountType
*
* @return Account|null
*/
public function find(string $accountName, string $accountType): ?Account
{
$type = AccountType::whereType($accountType)->first();
$accounts = $this->user->accounts()->where('account_type_id', $type->id)->get(['accounts.*']);
$return = null;
/** @var Account $object */
foreach ($accounts as $object) {
if ($object->name === $accountName) {
$return = $object;
break;
}
}
return $return;
}
/**
2018-08-24 00:18:33 -05:00
*
* @param string $accountName
* @param string $accountType
*
* @return Account
* @throws FireflyException
*/
public function findOrCreate(string $accountName, string $accountType): Account
{
2018-09-26 23:26:03 -05:00
Log::debug(sprintf('Searching for "%s" of type "%s"', $accountName, $accountType));
$type = AccountType::whereType($accountType)->first();
$accounts = $this->user->accounts()->where('account_type_id', $type->id)->get(['accounts.*']);
$return = null;
2018-09-26 23:26:03 -05:00
Log::debug(sprintf('Account type is #%d', $type->id));
/** @var Account $object */
foreach ($accounts as $object) {
if ($object->name === $accountName) {
2018-09-26 23:26:03 -05:00
Log::debug(sprintf('Found account #%d "%s".', $object->id, $object->name));
$return = $object;
break;
}
}
if (null === $return) {
2018-09-26 23:26:03 -05:00
Log::debug('Found nothing. Will create a new one.');
$return = $this->create(
[
'user_id' => $this->user->id,
'name' => $accountName,
'account_type_id' => $type->id,
'accountType' => null,
'virtualBalance' => '0',
'iban' => null,
'active' => true,
]
);
}
return $return;
}
/**
* @param User $user
*/
public function setUser(User $user): void
{
$this->user = $user;
}
/**
* @param int|null $accountTypeId
* @param null|string $accountType
*
* @return AccountType|null
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function getAccountType(?int $accountTypeId, ?string $accountType): ?AccountType
{
2018-04-02 07:42:07 -05:00
$accountTypeId = (int)$accountTypeId;
$result = null;
if ($accountTypeId > 0) {
$result = AccountType::find($accountTypeId);
}
if (null === $result) {
2018-08-04 10:30:47 -05:00
Log::debug(sprintf('No account type found by ID, continue search for "%s".', $accountType));
/** @var array $types */
$types = config('firefly.accountTypeByIdentifier.' . $accountType) ?? [];
if (count($types) > 0) {
Log::debug(sprintf('%d accounts in list from config', count($types)), $types);
2018-08-05 13:42:45 -05:00
$result = AccountType::whereIn('type', $types)->first();
2018-08-04 10:30:47 -05:00
}
if (null === $result && null !== $accountType) {
// try as full name:
$result = AccountType::whereType($accountType)->first();
}
2018-03-24 12:55:02 -05:00
}
if (null === $result) {
Log::warning(sprintf('Found NO account type based on %d and "%s"', $accountTypeId, $accountType));
}
if (null !== $result) {
Log::debug(sprintf('Found account type based on %d and "%s": "%s"', $accountTypeId, $accountType, $result->type));
}
2018-03-24 12:55:02 -05:00
return $result;
}
2018-03-05 12:35:58 -06:00
}