Last code optimization before release.

This commit is contained in:
James Cole 2018-07-28 10:45:16 +02:00
parent d35470a79e
commit 0c7b652a70
No known key found for this signature in database
GPG Key ID: C16961E655E74B5E
42 changed files with 217 additions and 301 deletions

View File

@ -26,6 +26,7 @@ namespace FireflyIII\Rules;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use Illuminate\Contracts\Validation\Rule; use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Collection;
use Log; use Log;
/** /**
@ -116,6 +117,7 @@ class UniqueIban implements Rule
if (null !== $this->account) { if (null !== $this->account) {
$query->where('accounts.id', '!=', $this->account->id); $query->where('accounts.id', '!=', $this->account->id);
} }
/** @var Collection $result */
$result = $query->get(['accounts.*']); $result = $query->get(['accounts.*']);
foreach ($result as $account) { foreach ($result as $account) {
if ($account->iban === $iban) { if ($account->iban === $iban) {

View File

@ -29,6 +29,7 @@ use FireflyIII\Services\Github\Object\Release;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Log; use Log;
use RuntimeException;
use SimpleXMLElement; use SimpleXMLElement;
/** /**
@ -55,10 +56,14 @@ class UpdateRequest implements GithubRequest
} }
if (200 !== $res->getStatusCode()) { if (200 !== $res->getStatusCode()) {
throw new FireflyException(sprintf('Returned code %d, error: %s', $res->getStatusCode(), $res->getBody()->getContents())); throw new FireflyException(sprintf('Returned code %d.', $res->getStatusCode()));
}
try {
$releaseXml = new SimpleXMLElement($res->getBody()->getContents(), LIBXML_NOCDATA);
} catch (RunTimeException $e) {
Log::error(sprintf('Could not get body from github updat result: %s', $e->getMessage()));
$releaseXml = new SimpleXMLElement('');
} }
$releaseXml = new SimpleXMLElement($res->getBody()->getContents(), LIBXML_NOCDATA);
//fetch the products for each category //fetch the products for each category
if (isset($releaseXml->entry)) { if (isset($releaseXml->entry)) {

View File

@ -27,6 +27,7 @@ use Exception;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Log; use Log;
use RunTimeException;
/** /**
* Class IpifyOrg * Class IpifyOrg
@ -51,11 +52,17 @@ class IpifyOrg implements IPRetrievalInterface
return null; return null;
} }
if (200 !== $res->getStatusCode()) { if (200 !== $res->getStatusCode()) {
Log::warning(sprintf('Could not retrieve external IP: %d %s', $res->getStatusCode(), $res->getBody()->getContents())); Log::warning(sprintf('Could not retrieve external IP: %d', $res->getStatusCode()));
return null; return null;
} }
try {
$body = (string)$res->getBody()->getContents();
} catch (RunTimeException $e) {
Log::error(sprintf('Could not get body from ipify.org result: %s', $e->getMessage()));
$body = null;
}
return (string)$res->getBody()->getContents(); return $body;
} }
} }

View File

@ -25,6 +25,8 @@ namespace FireflyIII\Services\Internal\File;
use Crypt; use Crypt;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use Illuminate\Contracts\Encryption\EncryptException;
use Log;
/** /**
* Class EncryptService * Class EncryptService
@ -43,7 +45,13 @@ class EncryptService
throw new FireflyException(sprintf('File "%s" does not seem to exist.', $file)); throw new FireflyException(sprintf('File "%s" does not seem to exist.', $file));
} }
$content = file_get_contents($file); $content = file_get_contents($file);
$content = Crypt::encrypt($content); try {
$content = Crypt::encrypt($content);
} catch (EncryptException $e) {
$message = sprintf('Could not encrypt file: %s', $e->getMessage());
Log::error($message);
throw new FireflyException($message);
}
$newName = sprintf('%s.upload', $key); $newName = sprintf('%s.upload', $key);
$path = storage_path('upload') . '/' . $newName; $path = storage_path('upload') . '/' . $newName;

View File

@ -228,7 +228,7 @@ trait RecurringTransactionTrait
/** /**
* @param Recurrence $recurrence * @param Recurrence $recurrence
* @param array $tagst * @param array $tags
*/ */
protected function updateTags(Recurrence $recurrence, array $tags): void protected function updateTags(Recurrence $recurrence, array $tags): void
{ {

View File

@ -26,6 +26,7 @@ use Exception;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Log; use Log;
use RuntimeException;
/** /**
* Class PwndVerifierV2. * Class PwndVerifierV2.
@ -64,7 +65,12 @@ class PwndVerifierV2 implements Verifier
if (404 === $res->getStatusCode()) { if (404 === $res->getStatusCode()) {
return true; return true;
} }
$strpos = stripos($res->getBody()->getContents(), $rest); try {
$strpos = stripos($res->getBody()->getContents(), $rest);
} catch (RunTimeException $e) {
Log::error(sprintf('Could not get body from Pwnd result: %s', $e->getMessage()));
$strpos = false;
}
if (false === $strpos) { if (false === $strpos) {
Log::debug(sprintf('%s was not found in result body. Return true.', $rest)); Log::debug(sprintf('%s was not found in result body. Return true.', $rest));

View File

@ -28,6 +28,7 @@ use FireflyIII\User;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use Log; use Log;
use RuntimeException;
/** /**
* Class SpectreRequest * Class SpectreRequest
@ -208,7 +209,12 @@ abstract class SpectreRequest
throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage())); throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage()));
} }
$statusCode = $res->getStatusCode(); $statusCode = $res->getStatusCode();
$returnBody = $res->getBody()->getContents(); try {
$returnBody = $res->getBody()->getContents();
} catch (RunTimeException $e) {
Log::error(sprintf('Could not get body from SpectreRequest::GET result: %s', $e->getMessage()));
$returnBody = '';
}
$this->detectError($returnBody, $statusCode); $this->detectError($returnBody, $statusCode);
$array = json_decode($returnBody, true); $array = json_decode($returnBody, true);
@ -252,7 +258,14 @@ abstract class SpectreRequest
} catch (GuzzleException|Exception $e) { } catch (GuzzleException|Exception $e) {
throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage())); throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage()));
} }
$body = $res->getBody()->getContents();
try {
$body = $res->getBody()->getContents();
} catch (RunTimeException $e) {
Log::error(sprintf('Could not get body from SpectreRequest::POST result: %s', $e->getMessage()));
$body = '';
}
$statusCode = $res->getStatusCode(); $statusCode = $res->getStatusCode();
$this->detectError($body, $statusCode); $this->detectError($body, $statusCode);

View File

@ -46,6 +46,9 @@ class Amount
* @param bool $csPrecedes * @param bool $csPrecedes
* *
* @return string * @return string
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public static function getAmountJsConfig(bool $sepBySpace, int $signPosn, string $sign, bool $csPrecedes): string public static function getAmountJsConfig(bool $sepBySpace, int $signPosn, string $sign, bool $csPrecedes): string
{ {
@ -53,7 +56,7 @@ class Amount
$space = ' '; $space = ' ';
// require space between symbol and amount? // require space between symbol and amount?
if (!$sepBySpace) { if ($sepBySpace === false) {
$space = ''; // no $space = ''; // no
} }
@ -116,6 +119,7 @@ class Amount
* @param bool $coloured * @param bool $coloured
* *
* @return string * @return string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function formatAnything(TransactionCurrency $format, string $amount, bool $coloured = null): string public function formatAnything(TransactionCurrency $format, string $amount, bool $coloured = null): string
{ {
@ -130,12 +134,8 @@ class Amount
// some complicated switches to format the amount correctly: // some complicated switches to format the amount correctly:
$precedes = $amount < 0 ? $info['n_cs_precedes'] : $info['p_cs_precedes']; $precedes = $amount < 0 ? $info['n_cs_precedes'] : $info['p_cs_precedes'];
$separated = $amount < 0 ? $info['n_sep_by_space'] : $info['p_sep_by_space']; $separated = $amount < 0 ? $info['n_sep_by_space'] : $info['p_sep_by_space'];
$space = $separated ? ' ' : ''; $space = $separated === true ? ' ' : '';
$result = $format->symbol . $space . $formatted; $result = $precedes === true ? $format->symbol . $space . $formatted : $formatted . $space . $format->symbol;
if (!$precedes) {
$result = $formatted . $space . $format->symbol;
}
if (true === $coloured) { if (true === $coloured) {
if ($amount > 0) { if ($amount > 0) {

View File

@ -41,11 +41,11 @@ class AccountList implements BinderInterface
* *
* @return Collection * @return Collection
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public static function routeBinder(string $value, Route $route): Collection public static function routeBinder(string $value, Route $route): Collection
{ {
if (auth()->check()) { if (auth()->check()) {
$collection = new Collection; $collection = new Collection;
if ('allAssetAccounts' === $value) { if ('allAssetAccounts' === $value) {
/** @var \Illuminate\Support\Collection $collection */ /** @var \Illuminate\Support\Collection $collection */
@ -55,18 +55,8 @@ class AccountList implements BinderInterface
->get(['accounts.*']); ->get(['accounts.*']);
} }
if ('allAssetAccounts' !== $value) { if ('allAssetAccounts' !== $value) {
$incoming = array_map('\intval', explode(',', $value));
$list = []; $list = array_merge(array_unique($incoming), [0]);
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = (int)$entry;
}
$list = array_unique($list);
if (0 === \count($list)) {
Log::error('Account list is empty.');
throw new NotFoundHttpException; // @codeCoverageIgnore
}
/** @var \Illuminate\Support\Collection $collection */ /** @var \Illuminate\Support\Collection $collection */
$collection = auth()->user()->accounts() $collection = auth()->user()->accounts()
->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')

View File

@ -38,16 +38,12 @@ class BudgetList implements BinderInterface
* *
* @return Collection * @return Collection
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public static function routeBinder(string $value, Route $route): Collection public static function routeBinder(string $value, Route $route): Collection
{ {
if (auth()->check()) { if (auth()->check()) {
$list = []; $list = array_unique(array_map('\intval', explode(',', $value)));
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = (int)$entry;
}
$list = array_unique($list);
if (0 === \count($list)) { if (0 === \count($list)) {
throw new NotFoundHttpException; // @codeCoverageIgnore throw new NotFoundHttpException; // @codeCoverageIgnore
} }

View File

@ -38,16 +38,12 @@ class CategoryList implements BinderInterface
* *
* @return Collection * @return Collection
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public static function routeBinder(string $value, Route $route): Collection public static function routeBinder(string $value, Route $route): Collection
{ {
if (auth()->check()) { if (auth()->check()) {
$list = []; $list = array_unique(array_map('\intval', explode(',', $value)));
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = (int)$entry;
}
$list = array_unique($list);
if (0 === \count($list)) { if (0 === \count($list)) {
throw new NotFoundHttpException; // @codeCoverageIgnore throw new NotFoundHttpException; // @codeCoverageIgnore
} }

View File

@ -46,28 +46,25 @@ class Date implements BinderInterface
/** @var FiscalHelperInterface $fiscalHelper */ /** @var FiscalHelperInterface $fiscalHelper */
$fiscalHelper = app(FiscalHelperInterface::class); $fiscalHelper = app(FiscalHelperInterface::class);
switch ($value) { $magicWords = [
default: 'currentMonthStart' => Carbon::now()->startOfMonth(),
try { 'currentMonthEnd' => Carbon::now()->endOfMonth(),
$date = new Carbon($value); 'currentYearStart' => Carbon::now()->startOfYear(),
} catch (Exception $e) { 'currentYearEnd' => Carbon::now()->endOfYear(),
Log::error(sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage())); 'currentFiscalYearStart' => $fiscalHelper->startOfFiscalYear(Carbon::now()),
throw new NotFoundHttpException; 'currentFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(Carbon::now()),
} ];
if (isset($magicWords[$value])) {
return $date; return $magicWords[$value];
case 'currentMonthStart':
return Carbon::now()->startOfMonth();
case 'currentMonthEnd':
return Carbon::now()->endOfMonth();
case 'currentYearStart':
return Carbon::now()->startOfYear();
case 'currentYearEnd':
return Carbon::now()->endOfYear();
case 'currentFiscalYearStart':
return $fiscalHelper->startOfFiscalYear(Carbon::now());
case 'currentFiscalYearEnd':
return $fiscalHelper->endOfFiscalYear(Carbon::now());
} }
try {
$result = new Carbon($value);
} catch (Exception $e) {
Log::error(sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage()));
throw new NotFoundHttpException;
}
return $result;
} }
} }

View File

@ -37,6 +37,8 @@ class ImportProvider implements BinderInterface
{ {
/** /**
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public static function getProviders(): array public static function getProviders(): array
{ {

View File

@ -41,12 +41,7 @@ class JournalList implements BinderInterface
public static function routeBinder(string $value, Route $route): Collection public static function routeBinder(string $value, Route $route): Collection
{ {
if (auth()->check()) { if (auth()->check()) {
$list = []; $list = array_unique(array_map('\intval', explode(',', $value)));
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = (int)$entry;
}
$list = array_unique($list);
if (0 === \count($list)) { if (0 === \count($list)) {
throw new NotFoundHttpException; // @codeCoverageIgnore throw new NotFoundHttpException; // @codeCoverageIgnore
} }

View File

@ -41,16 +41,14 @@ class SimpleJournalList implements BinderInterface
* *
* @return mixed * @return mixed
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/ */
public static function routeBinder(string $value, Route $route): Collection public static function routeBinder(string $value, Route $route): Collection
{ {
if (auth()->check()) { if (auth()->check()) {
$list = []; $list = array_unique(array_map('\intval', explode(',', $value)));
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = (int)$entry;
}
$list = array_unique($list);
if (0 === \count($list)) { if (0 === \count($list)) {
throw new NotFoundHttpException; // @codeCoverageIgnore throw new NotFoundHttpException; // @codeCoverageIgnore
} }
@ -97,7 +95,6 @@ class SimpleJournalList implements BinderInterface
} }
if ($final->count() > 0) { if ($final->count() > 0) {
if (\count($messages) > 0) { if (\count($messages) > 0) {
session()->flash('info', $messages); session()->flash('info', $messages);
} }

View File

@ -44,12 +44,7 @@ class TagList implements BinderInterface
public static function routeBinder(string $value, Route $route): Collection public static function routeBinder(string $value, Route $route): Collection
{ {
if (auth()->check()) { if (auth()->check()) {
$list = []; $list = array_unique(array_map('\strtolower', explode(',', $value)));
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = strtolower(trim($entry));
}
$list = array_unique($list);
if (0 === \count($list)) { if (0 === \count($list)) {
Log::error('Tag list is empty.'); Log::error('Tag list is empty.');
throw new NotFoundHttpException; // @codeCoverageIgnore throw new NotFoundHttpException; // @codeCoverageIgnore

View File

@ -25,6 +25,7 @@ namespace FireflyIII\Support;
use Amount as Amt; use Amount as Amt;
use Carbon\Carbon; use Carbon\Carbon;
use Eloquent; use Eloquent;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
@ -46,6 +47,8 @@ use Throwable;
/** /**
* Class ExpandedForm. * Class ExpandedForm.
* *
* @SuppressWarnings(PHPMD.TooManyMethods)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/ */
class ExpandedForm class ExpandedForm
{ {
@ -94,6 +97,7 @@ class ExpandedForm
* @param array $options * @param array $options
* *
* @return string * @return string
* @throws FireflyException
*/ */
public function amount(string $name, $value = null, array $options = null): string public function amount(string $name, $value = null, array $options = null): string
{ {
@ -132,19 +136,6 @@ class ExpandedForm
return $html; return $html;
} }
/**
* @param string $name
* @param mixed $value
* @param array $options
*
* @return string
* @throws \FireflyIII\Exceptions\FireflyException
*/
public function amountSmall(string $name, $value = null, array $options = null): string
{
return $this->currencyField($name, 'amount-small', $value, $options);
}
/** /**
* @param string $name * @param string $name
* @param array $options * @param array $options
@ -232,6 +223,7 @@ class ExpandedForm
* @param array $options * @param array $options
* *
* @return string * @return string
* @throws FireflyException
*/ */
public function balance(string $name, $value = null, array $options = null): string public function balance(string $name, $value = null, array $options = null): string
{ {
@ -428,6 +420,7 @@ class ExpandedForm
* @param \Illuminate\Support\Collection $set * @param \Illuminate\Support\Collection $set
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function makeSelectList(Collection $set): array public function makeSelectList(Collection $set): array
{ {
@ -453,6 +446,7 @@ class ExpandedForm
* @param \Illuminate\Support\Collection $set * @param \Illuminate\Support\Collection $set
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function makeSelectListWithEmpty(Collection $set): array public function makeSelectListWithEmpty(Collection $set): array
{ {
@ -475,36 +469,6 @@ class ExpandedForm
return $selectList; return $selectList;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/**
* @param string $name
* @param array $list
* @param mixed $selected
* @param array $options
*
* @return string
*
*/
public function multiRadio(string $name, array $list = null, $selected = null, array $options = null): string
{
$list = $list ?? [];
$label = $this->label($name, $options);
$options = $this->expandOptionArray($name, $label, $options);
$classes = $this->getHolderClasses($name);
$selected = $this->fillFieldValue($name, $selected);
unset($options['class']);
try {
$html = view('form.multiRadio', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render();
} catch (Throwable $e) {
Log::debug(sprintf('Could not render multiRadio(): %s', $e->getMessage()));
$html = 'Could not render multiRadio.';
}
return $html;
}
/** /**
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
@ -538,40 +502,6 @@ class ExpandedForm
return $html; return $html;
} }
/**
* @param string $name
* @param mixed $value
* @param array $options
*
* @return string
* @throws \FireflyIII\Exceptions\FireflyException
*
*/
public function nonSelectableBalance(string $name, $value = null, array $options = null): string
{
$label = $this->label($name, $options);
$options = $this->expandOptionArray($name, $label, $options);
$classes = $this->getHolderClasses($name);
$value = $this->fillFieldValue($name, $value);
$options['step'] = 'any';
$selectedCurrency = $options['currency'] ?? Amt::getDefaultCurrency();
unset($options['currency'], $options['placeholder']);
// make sure value is formatted nicely:
if (null !== $value && '' !== $value) {
$decimals = $selectedCurrency->decimal_places ?? 2;
$value = round($value, $decimals);
}
try {
$html = view('form.non-selectable-amount', compact('selectedCurrency', 'classes', 'name', 'label', 'value', 'options'))->render();
} catch (Throwable $e) {
Log::debug(sprintf('Could not render nonSelectableBalance(): %s', $e->getMessage()));
$html = 'Could not render nonSelectableBalance.';
}
return $html;
}
/** /**
* @param string $name * @param string $name
* @param mixed $value * @param mixed $value
@ -841,6 +771,59 @@ class ExpandedForm
return $html; return $html;
} }
/**
* @param string $name
* @param string $view
* @param mixed $value
* @param array $options
*
* @return string
* @throws FireflyException
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function currencyField(string $name, string $view, $value = null, array $options = null): string
{
$label = $this->label($name, $options);
$options = $this->expandOptionArray($name, $label, $options);
$classes = $this->getHolderClasses($name);
$value = $this->fillFieldValue($name, $value);
$options['step'] = 'any';
$defaultCurrency = $options['currency'] ?? Amt::getDefaultCurrency();
/** @var Collection $currencies */
$currencies = app('amount')->getAllCurrencies();
unset($options['currency'], $options['placeholder']);
// perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount)
$preFilled = session('preFilled');
$key = 'amount_currency_id_' . $name;
$sentCurrencyId = isset($preFilled[$key]) ? (int)$preFilled[$key] : $defaultCurrency->id;
Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId));
// find this currency in set of currencies:
foreach ($currencies as $currency) {
if ($currency->id === $sentCurrencyId) {
$defaultCurrency = $currency;
Log::debug(sprintf('default currency is now %s', $defaultCurrency->code));
break;
}
}
// make sure value is formatted nicely:
if (null !== $value && '' !== $value) {
$value = round($value, $defaultCurrency->decimal_places);
}
try {
$html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render();
} catch (Throwable $e) {
Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage()));
$html = 'Could not render currencyField.';
}
return $html;
}
/** /**
* @param $name * @param $name
* @param $label * @param $label
@ -865,6 +848,7 @@ class ExpandedForm
* @param $value * @param $value
* *
* @return mixed * @return mixed
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
protected function fillFieldValue(string $name, $value) protected function fillFieldValue(string $name, $value)
{ {
@ -906,6 +890,8 @@ class ExpandedForm
return $classes; return $classes;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param $name * @param $name
* @param $options * @param $options
@ -922,56 +908,4 @@ class ExpandedForm
return (string)trans('form.' . $name); return (string)trans('form.' . $name);
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/**
* @param string $name
* @param string $view
* @param mixed $value
* @param array $options
*
* @return string
* @throws \FireflyIII\Exceptions\FireflyException
* @throws \FireflyIII\Exceptions\FireflyException
*/
private function currencyField(string $name, string $view, $value = null, array $options = null): string
{
$label = $this->label($name, $options);
$options = $this->expandOptionArray($name, $label, $options);
$classes = $this->getHolderClasses($name);
$value = $this->fillFieldValue($name, $value);
$options['step'] = 'any';
$defaultCurrency = $options['currency'] ?? Amt::getDefaultCurrency();
$currencies = app('amount')->getAllCurrencies();
unset($options['currency'], $options['placeholder']);
// perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount)
$preFilled = session('preFilled');
$key = 'amount_currency_id_' . $name;
$sentCurrencyId = isset($preFilled[$key]) ? (int)$preFilled[$key] : $defaultCurrency->id;
Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId));
// find this currency in set of currencies:
foreach ($currencies as $currency) {
if ($currency->id === $sentCurrencyId) {
$defaultCurrency = $currency;
Log::debug(sprintf('default currency is now %s', $defaultCurrency->code));
break;
}
}
// make sure value is formatted nicely:
if (null !== $value && '' !== $value) {
$value = round($value, $defaultCurrency->decimal_places);
}
try {
$html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render();
} catch (Throwable $e) {
Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage()));
$html = 'Could not render currencyField.';
}
return $html;
}
} }

View File

@ -271,6 +271,7 @@ class ConfigureMappingHandler implements FileConfigurationInterface
* *
* @return array * @return array
* @throws FireflyException * @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function getValuesForMapping(Reader $reader, array $config, array $columnConfig): array public function getValuesForMapping(Reader $reader, array $config, array $columnConfig): array
{ {

View File

@ -58,6 +58,7 @@ class ConfigureRolesHandler implements FileConfigurationInterface
* @param array $config * @param array $config
* *
* @return MessageBag * @return MessageBag
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function configurationComplete(array $config): MessageBag public function configurationComplete(array $config): MessageBag
{ {

View File

@ -110,6 +110,7 @@ class ChooseAccountsHandler implements SpectreJobConfigurationInterface
* *
* @return array * @return array
* @throws FireflyException * @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function getNextData(): array public function getNextData(): array
{ {

View File

@ -128,6 +128,7 @@ class ImportTransaction
* @param ColumnValue $columnValue * @param ColumnValue $columnValue
* *
* @throws FireflyException * @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function addColumnValue(ColumnValue $columnValue): void public function addColumnValue(ColumnValue $columnValue): void
{ {

View File

@ -48,6 +48,7 @@ class AssetAccountMapper
* @param array $data * @param array $data
* *
* @return Account * @return Account
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function map(?int $accountId, array $data): Account public function map(?int $accountId, array $data): Account
{ {

View File

@ -81,6 +81,7 @@ class MappedValuesValidator
* *
* @return array * @return array
* @throws FireflyException * @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function validate(array $mappings): array public function validate(array $mappings): array
{ {

View File

@ -135,44 +135,32 @@ class MappingConverger
return $role; return $role;
} }
switch ($role) { $roleMapping = [
default: 'account-id' => 'account-id',
throw new FireflyException(sprintf('Cannot indicate new role for mapped role "%s"', $role)); // @codeCoverageIgnore 'account-name' => 'account-id',
case 'account-id': 'account-iban' => 'account-id',
case 'account-name': 'account-number' => 'account-id',
case 'account-iban': 'bill-id' => 'bill-id',
case 'account-number': 'bill-name' => 'bill-id',
$newRole = 'account-id'; 'budget-id' => 'budget-id',
break; 'budget-name' => 'budget-id',
case 'bill-id': 'currency-id' => 'currency-id',
case 'bill-name': 'currency-name' => 'currency-id',
$newRole = 'bill-id'; 'currency-code' => 'currency-id',
break; 'currency-symbol' => 'currency-id',
case 'budget-id': 'category-id' => 'category-id',
case 'budget-name': 'category-name' => 'category-id',
$newRole = 'budget-id'; 'foreign-currency-id' => 'foreign-currency-id',
break; 'foreign-currency-code' => 'foreign-currency-id',
case 'currency-id': 'opposing-id' => 'opposing-id',
case 'currency-name': 'opposing-name' => 'opposing-id',
case 'currency-code': 'opposing-iban' => 'opposing-id',
case 'currency-symbol': 'opposing-number' => 'opposing-id',
$newRole = 'currency-id'; ];
break; if (!isset($roleMapping[$role])) {
case 'category-id': throw new FireflyException(sprintf('Cannot indicate new role for mapped role "%s"', $role)); // @codeCoverageIgnore
case 'category-name':
$newRole = 'category-id';
break;
case 'foreign-currency-id':
case 'foreign-currency-code':
$newRole = 'foreign-currency-id';
break;
case 'opposing-id':
case 'opposing-name':
case 'opposing-iban':
case 'opposing-number':
$newRole = 'opposing-id';
break;
} }
$newRole = $roleMapping[$role];
Log::debug(sprintf('Role was "%s", but because of mapping (mapped to #%d), role becomes "%s"', $role, $mapped, $newRole)); Log::debug(sprintf('Role was "%s", but because of mapping (mapped to #%d), role becomes "%s"', $role, $mapped, $newRole));
// also store the $mapped values in a "mappedValues" array. // also store the $mapped values in a "mappedValues" array.

View File

@ -45,6 +45,7 @@ class OpposingAccountMapper
* @param array $data * @param array $data
* *
* @return Account * @return Account
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function map(?int $accountId, string $amount, array $data): Account public function map(?int $accountId, string $amount, array $data): Account
{ {

View File

@ -107,6 +107,7 @@ class StageImportDataHandler
* @param LocalAccount $originalSource * @param LocalAccount $originalSource
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
private function convertToArray(array $transactions, SpectreAccount $spectreAccount, LocalAccount $originalSource): array private function convertToArray(array $transactions, SpectreAccount $spectreAccount, LocalAccount $originalSource): array
{ {

View File

@ -87,6 +87,7 @@ class Navigation
* *
* @return array * @return array
* @throws \FireflyIII\Exceptions\FireflyException * @throws \FireflyIII\Exceptions\FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function blockPeriods(\Carbon\Carbon $start, \Carbon\Carbon $end, string $range): array public function blockPeriods(\Carbon\Carbon $start, \Carbon\Carbon $end, string $range): array
{ {

View File

@ -188,6 +188,7 @@ class Search implements SearchInterface
* @param JournalCollectorInterface $collector * @param JournalCollectorInterface $collector
* *
* @return JournalCollectorInterface * @return JournalCollectorInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
private function applyModifiers(JournalCollectorInterface $collector): JournalCollectorInterface private function applyModifiers(JournalCollectorInterface $collector): JournalCollectorInterface
{ {

View File

@ -46,11 +46,11 @@ class Transaction extends Twig_Extension
*/ */
public function amount(TransactionModel $transaction): string public function amount(TransactionModel $transaction): string
{ {
// at this point amount is always negative.
$amount = bcmul(app('steam')->positive((string)$transaction->transaction_amount), '-1'); $amount = bcmul(app('steam')->positive((string)$transaction->transaction_amount), '-1');
$format = '%s'; $format = '%s';
$coloured = true; $coloured = true;
// at this point amount is always negative.
if (TransactionType::RECONCILIATION === $transaction->transaction_type_type && 1 === bccomp((string)$transaction->transaction_amount, '0')) { if (TransactionType::RECONCILIATION === $transaction->transaction_type_type && 1 === bccomp((string)$transaction->transaction_amount, '0')) {
$amount = bcmul($amount, '-1'); $amount = bcmul($amount, '-1');
} }

View File

@ -32,9 +32,6 @@ use Log;
*/ */
class ClearBudget implements ActionInterface class ClearBudget implements ActionInterface
{ {
/** @var RuleAction The rule action */
private $action;
/** /**
* TriggerInterface constructor. * TriggerInterface constructor.
* *
@ -42,7 +39,6 @@ class ClearBudget implements ActionInterface
*/ */
public function __construct(RuleAction $action) public function __construct(RuleAction $action)
{ {
$this->action = $action;
} }
/** /**

View File

@ -32,9 +32,6 @@ use Log;
*/ */
class ClearCategory implements ActionInterface class ClearCategory implements ActionInterface
{ {
/** @var RuleAction The rule action */
private $action;
/** /**
* TriggerInterface constructor. * TriggerInterface constructor.
* *
@ -42,7 +39,6 @@ class ClearCategory implements ActionInterface
*/ */
public function __construct(RuleAction $action) public function __construct(RuleAction $action)
{ {
$this->action = $action;
} }
/** /**

View File

@ -32,9 +32,6 @@ use Log;
*/ */
class ClearNotes implements ActionInterface class ClearNotes implements ActionInterface
{ {
/** @var RuleAction The rule action */
private $action;
/** /**
* TriggerInterface constructor. * TriggerInterface constructor.
* *
@ -42,7 +39,6 @@ class ClearNotes implements ActionInterface
*/ */
public function __construct(RuleAction $action) public function __construct(RuleAction $action)
{ {
$this->action = $action;
} }
/** /**

View File

@ -31,9 +31,6 @@ use Log;
*/ */
class RemoveAllTags implements ActionInterface class RemoveAllTags implements ActionInterface
{ {
/** @var RuleAction The rule action */
private $action;
/** /**
* TriggerInterface constructor. * TriggerInterface constructor.
* *
@ -41,7 +38,6 @@ class RemoveAllTags implements ActionInterface
*/ */
public function __construct(RuleAction $action) public function __construct(RuleAction $action)
{ {
$this->action = $action;
} }
/** /**

View File

@ -61,7 +61,11 @@ class SetCategory implements ActionInterface
$factory = app(CategoryFactory::class); $factory = app(CategoryFactory::class);
$factory->setUser($journal->user); $factory->setUser($journal->user);
$category = $factory->findOrCreate(null, $name); $category = $factory->findOrCreate(null, $name);
if (null === $category) {
Log::error(sprintf('Action SetCategory did not fire because "%s" did not result in a valid category.', $name));
return true;
}
$journal->categories()->detach(); $journal->categories()->detach();
// set category on transactions: // set category on transactions:
/** @var Transaction $transaction */ /** @var Transaction $transaction */

View File

@ -100,7 +100,12 @@ class SetSourceAccount implements ActionInterface
// update source transaction with new source account: // update source transaction with new source account:
// get source transaction: // get source transaction:
$transaction = $journal->transactions()->where('amount', '<', 0)->first(); $transaction = $journal->transactions()->where('amount', '<', 0)->first();
if (null === $transaction) {
Log::error(sprintf('Cannot change source account of journal #%d because no source transaction exists.', $journal->id));
return false;
}
$transaction->account_id = $this->newSourceAccount->id; $transaction->account_id = $this->newSourceAccount->id;
$transaction->save(); $transaction->save();
$journal->touch(); $journal->touch();
@ -130,7 +135,7 @@ class SetSourceAccount implements ActionInterface
/** /**
* *
*/ */
private function findRevenueAccount() private function findRevenueAccount(): void
{ {
$account = $this->repository->findByName($this->action->action_value, [AccountType::REVENUE]); $account = $this->repository->findByName($this->action->action_value, [AccountType::REVENUE]);
if (null === $account) { if (null === $account) {

View File

@ -52,7 +52,7 @@ class TriggerFactory
* *
* @throws FireflyException * @throws FireflyException
*/ */
public static function getTrigger(RuleTrigger $trigger) public static function getTrigger(RuleTrigger $trigger): AbstractTrigger
{ {
$triggerType = $trigger->trigger_type; $triggerType = $trigger->trigger_type;
@ -84,7 +84,7 @@ class TriggerFactory
* *
* @throws FireflyException * @throws FireflyException
*/ */
public static function makeTriggerFromStrings(string $triggerType, string $triggerValue, bool $stopProcessing) public static function makeTriggerFromStrings(string $triggerType, string $triggerValue, bool $stopProcessing): AbstractTrigger
{ {
/** @var AbstractTrigger $class */ /** @var AbstractTrigger $class */
$class = self::getTriggerClass($triggerType); $class = self::getTriggerClass($triggerType);

View File

@ -72,8 +72,9 @@ final class Processor
* @return Processor * @return Processor
* @throws \FireflyIII\Exceptions\FireflyException * @throws \FireflyIII\Exceptions\FireflyException
*/ */
public static function make(Rule $rule, $includeActions = true) public static function make(Rule $rule, bool $includeActions = null): Processor
{ {
$includeActions = $includeActions ?? true;
Log::debug(sprintf('Making new rule from Rule %d', $rule->id)); Log::debug(sprintf('Making new rule from Rule %d', $rule->id));
Log::debug(sprintf('Rule is strict: %s', var_export($rule->strict, true))); Log::debug(sprintf('Rule is strict: %s', var_export($rule->strict, true)));
$self = new self; $self = new self;
@ -85,7 +86,7 @@ final class Processor
Log::debug(sprintf('Push trigger %d', $trigger->id)); Log::debug(sprintf('Push trigger %d', $trigger->id));
$self->triggers->push(TriggerFactory::getTrigger($trigger)); $self->triggers->push(TriggerFactory::getTrigger($trigger));
} }
if ($includeActions) { if ($includeActions === true) {
$self->actions = $rule->ruleActions()->orderBy('order', 'ASC')->get(); $self->actions = $rule->ruleActions()->orderBy('order', 'ASC')->get();
} }
@ -104,7 +105,7 @@ final class Processor
* *
* @throws \FireflyIII\Exceptions\FireflyException * @throws \FireflyIII\Exceptions\FireflyException
*/ */
public static function makeFromString(string $triggerName, string $triggerValue) public static function makeFromString(string $triggerName, string $triggerValue): Processor
{ {
Log::debug(sprintf('Processor::makeFromString("%s", "%s")', $triggerName, $triggerValue)); Log::debug(sprintf('Processor::makeFromString("%s", "%s")', $triggerName, $triggerValue));
$self = new self; $self = new self;
@ -129,7 +130,7 @@ final class Processor
* *
* @throws \FireflyIII\Exceptions\FireflyException * @throws \FireflyIII\Exceptions\FireflyException
*/ */
public static function makeFromStringArray(array $triggers) public static function makeFromStringArray(array $triggers): Processor
{ {
$self = new self; $self = new self;
foreach ($triggers as $entry) { foreach ($triggers as $entry) {
@ -156,7 +157,7 @@ final class Processor
* *
* @param int $foundTriggers * @param int $foundTriggers
*/ */
public function setFoundTriggers(int $foundTriggers) public function setFoundTriggers(int $foundTriggers): void
{ {
$this->foundTriggers = $foundTriggers; $this->foundTriggers = $foundTriggers;
} }
@ -236,10 +237,10 @@ final class Processor
/** /**
* Run the actions * Run the actions
* *
* @return bool * @return void
* @throws \FireflyIII\Exceptions\FireflyException * @throws \FireflyIII\Exceptions\FireflyException
*/ */
private function actions() private function actions(): void
{ {
/** /**
* @var int * @var int
@ -255,8 +256,6 @@ final class Processor
break; break;
} }
} }
return true;
} }
/** /**

View File

@ -72,7 +72,7 @@ class AbstractTrigger
* *
* @return AbstractTrigger * @return AbstractTrigger
*/ */
public static function makeFromTrigger(RuleTrigger $trigger) public static function makeFromTrigger(RuleTrigger $trigger): AbstractTrigger
{ {
$self = new static; $self = new static;
$self->trigger = $trigger; $self->trigger = $trigger;
@ -91,7 +91,7 @@ class AbstractTrigger
* *
* @return AbstractTrigger * @return AbstractTrigger
*/ */
public static function makeFromTriggerValue(string $triggerValue) public static function makeFromTriggerValue(string $triggerValue): AbstractTrigger
{ {
$self = new static; $self = new static;
$self->triggerValue = $triggerValue; $self->triggerValue = $triggerValue;

View File

@ -74,7 +74,7 @@ final class NotesContain extends AbstractTrigger implements TriggerInterface
{ {
$search = strtolower(trim($this->triggerValue)); $search = strtolower(trim($this->triggerValue));
if (0 === \strlen($search)) { if ('' === $search) {
Log::debug(sprintf('RuleTrigger NotesContain for journal #%d: "%s" is empty, return false.', $journal->id, $search)); Log::debug(sprintf('RuleTrigger NotesContain for journal #%d: "%s" is empty, return false.', $journal->id, $search));
return false; return false;

View File

@ -68,7 +68,7 @@ final class NotesEmpty extends AbstractTrigger implements TriggerInterface
$text = $note->text; $text = $note->text;
} }
if (0 === \strlen($text)) { if ('' === $text) {
Log::debug(sprintf('RuleTrigger NotesEmpty for journal #%d: strlen is 0, return true.', $journal->id)); Log::debug(sprintf('RuleTrigger NotesEmpty for journal #%d: strlen is 0, return true.', $journal->id));
return true; return true;

View File

@ -187,7 +187,7 @@ return [
'ExpandedForm' => [ 'ExpandedForm' => [
'is_safe' => [ 'is_safe' => [
'date', 'text', 'select', 'balance', 'optionsList', 'checkbox', 'amount', 'tags', 'integer', 'textarea', 'location', 'date', 'text', 'select', 'balance', 'optionsList', 'checkbox', 'amount', 'tags', 'integer', 'textarea', 'location',
'multiRadio', 'file', 'multiCheckbox', 'staticText', 'amountSmall', 'password', 'nonSelectableBalance', 'nonSelectableAmount', 'file', 'staticText', 'password', 'nonSelectableAmount',
'number', 'assetAccountList','amountNoCurrency','currencyList','ruleGroupList','assetAccountCheckList','ruleGroupListWithEmpty', 'number', 'assetAccountList','amountNoCurrency','currencyList','ruleGroupList','assetAccountCheckList','ruleGroupListWithEmpty',
'piggyBankList','currencyListEmpty','activeAssetAccountList' 'piggyBankList','currencyListEmpty','activeAssetAccountList'
], ],

View File

@ -1,17 +0,0 @@
<div class="{{ classes }}" id="{{ name }}_holder">
<label for="{{ options.id }}" class="col-sm-4 control-label">{{ label }}</label>
<div class="col-sm-8">
{% for value,description in list %}
<div class="radio">
<label>
{{ Form.radio(name, value, (selected == value), options) }}
{{ description }}
</label>
</div>
{% endfor %}
{% include 'form/help' %}
{% include 'form/feedback' %}
</div>
</div>