Code cleanup that (hopefully) matches style CI

This commit is contained in:
James Cole
2020-03-17 15:02:57 +01:00
parent 2b6c3fd743
commit 24129ab69c
21 changed files with 266 additions and 257 deletions

View File

@@ -29,6 +29,7 @@ use FireflyIII\Exceptions\FireflyException;
use Illuminate\Auth\AuthenticationException; use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
/** /**
* Class Authenticate * Class Authenticate
@@ -38,14 +39,14 @@ class Authenticate
/** /**
* The authentication factory instance. * The authentication factory instance.
* *
* @var \Illuminate\Contracts\Auth\Factory * @var Auth
*/ */
protected $auth; protected $auth;
/** /**
* Create a new middleware instance. * Create a new middleware instance.
* *
* @param \Illuminate\Contracts\Auth\Factory $auth * @param Auth $auth
* *
* @return void * @return void
*/ */
@@ -57,14 +58,14 @@ class Authenticate
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* @param string[] ...$guards * @param string[] ...$guards
*
* @return mixed
* *
* @throws AuthenticationException * @throws AuthenticationException
* @throws FireflyException * @throws FireflyException
* @return mixed
*
*/ */
public function handle($request, Closure $next, ...$guards) public function handle($request, Closure $next, ...$guards)
{ {
@@ -78,11 +79,11 @@ class Authenticate
* Determine if the user is logged in to any of the given guards. * Determine if the user is logged in to any of the given guards.
* *
* @param $request * @param $request
* @param array $guards * @param array $guards
* *
* @return mixed
* @throws AuthenticationException * @throws AuthenticationException
* @throws FireflyException * @throws FireflyException
* @return mixed
*/ */
protected function authenticate($request, array $guards) protected function authenticate($request, array $guards)
{ {
@@ -96,10 +97,10 @@ class Authenticate
// do an extra check on user object. // do an extra check on user object.
/** @noinspection PhpUndefinedMethodInspection */ /** @noinspection PhpUndefinedMethodInspection */
$user = $this->auth->authenticate(); $user = $this->auth->authenticate();
if (1 === (int)$user->blocked) { if (1 === (int) $user->blocked) {
$message = (string)trans('firefly.block_account_logout'); $message = (string) trans('firefly.block_account_logout');
if ('email_changed' === $user->blocked_code) { if ('email_changed' === $user->blocked_code) {
$message = (string)trans('firefly.email_changed_logout'); $message = (string) trans('firefly.email_changed_logout');
} }
app('session')->flash('logoutMessage', $message); app('session')->flash('logoutMessage', $message);
/** @noinspection PhpUndefinedMethodInspection */ /** @noinspection PhpUndefinedMethodInspection */

View File

@@ -25,6 +25,7 @@ namespace FireflyIII\Http\Middleware;
use Closure; use Closure;
use FireflyIII\Support\Domain; use FireflyIII\Support\Domain;
use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
/** /**
@@ -35,7 +36,7 @@ class Binder
/** /**
* The authentication factory instance. * The authentication factory instance.
* *
* @var \Illuminate\Contracts\Auth\Factory * @var Auth
*/ */
protected $auth; protected $auth;
/** /**
@@ -48,7 +49,7 @@ class Binder
/** /**
* Binder constructor. * Binder constructor.
* *
* @param \Illuminate\Contracts\Auth\Factory $auth * @param Auth $auth
*/ */
public function __construct(Auth $auth) public function __construct(Auth $auth)
{ {
@@ -60,8 +61,8 @@ class Binder
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* *
* @return mixed * @return mixed
* *

View File

@@ -41,21 +41,21 @@ class InstallationId
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param Closure $next * @param Closure $next
* *
* @return mixed
*
* @throws FireflyException * @throws FireflyException
* *
* @return mixed
*
*/ */
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
$config = app('fireflyconfig')->get('installation_id', null); $config = app('fireflyconfig')->get('installation_id', null);
if (null === $config) { if (null === $config) {
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_URL, 'firefly-iii.org'); $uuid5 = Uuid::uuid5(Uuid::NAMESPACE_URL, 'firefly-iii.org');
$uniqueId = (string)$uuid5; $uniqueId = (string) $uuid5;
Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId)); Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId));
app('fireflyconfig')->set('installation_id', $uniqueId); app('fireflyconfig')->set('installation_id', $uniqueId);
} }
return $next($request); return $next($request);
} }
} }

View File

@@ -29,6 +29,7 @@ use DB;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Support\System\OAuthKeys; use FireflyIII\Support\System\OAuthKeys;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Log; use Log;
/** /**
@@ -42,13 +43,13 @@ class Installer
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
*
* @return mixed
* *
* @throws FireflyException * @throws FireflyException
* *
* @return mixed
*
*/ */
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
@@ -107,8 +108,8 @@ class Installer
/** /**
* Check if the tables are created and accounted for. * Check if the tables are created and accounted for.
* *
* @return bool
* @throws FireflyException * @throws FireflyException
* @return bool
*/ */
private function hasNoTables(): bool private function hasNoTables(): bool
{ {
@@ -127,14 +128,12 @@ class Installer
Log::warning('There are no Firefly III tables present. Redirect to migrate routine.'); Log::warning('There are no Firefly III tables present. Redirect to migrate routine.');
return true; return true;
} }
throw new FireflyException(sprintf('Could not access the database: %s', $message)); throw new FireflyException(sprintf('Could not access the database: %s', $message));
} }
Log::debug('Everything seems OK with the tables.'); Log::debug('Everything seems OK with the tables.');
return false; return false;
} }
/** /**
@@ -145,12 +144,14 @@ class Installer
private function oldDBVersion(): bool private function oldDBVersion(): bool
{ {
// older version in config than database? // older version in config than database?
$configVersion = (int)config('firefly.db_version'); $configVersion = (int) config('firefly.db_version');
$dbVersion = (int)app('fireflyconfig')->getFresh('db_version', 1)->data; $dbVersion = (int) app('fireflyconfig')->getFresh('db_version', 1)->data;
if ($configVersion > $dbVersion) { if ($configVersion > $dbVersion) {
Log::warning( Log::warning(
sprintf( sprintf(
'The current configured version (%d) is older than the required version (%d). Redirect to migrate routine.', $dbVersion, $configVersion 'The current configured version (%d) is older than the required version (%d). Redirect to migrate routine.',
$dbVersion,
$configVersion
) )
); );
@@ -169,12 +170,14 @@ class Installer
private function oldVersion(): bool private function oldVersion(): bool
{ {
// version compare thing. // version compare thing.
$configVersion = (string)config('firefly.version'); $configVersion = (string) config('firefly.version');
$dbVersion = (string)app('fireflyconfig')->getFresh('ff3_version', '1.0')->data; $dbVersion = (string) app('fireflyconfig')->getFresh('ff3_version', '1.0')->data;
if (1 === version_compare($configVersion, $dbVersion)) { if (1 === version_compare($configVersion, $dbVersion)) {
Log::warning( Log::warning(
sprintf( sprintf(
'The current configured Firefly III version (%s) is older than the required version (%s). Redirect to migrate routine.', $dbVersion, $configVersion 'The current configured Firefly III version (%s) is older than the required version (%s). Redirect to migrate routine.',
$dbVersion,
$configVersion
) )
); );
@@ -184,5 +187,4 @@ class Installer
return false; return false;
} }
} }

View File

@@ -38,8 +38,8 @@ class InterestingMessage
/** /**
* Flashes the user an interesting message if the URL parameters warrant it. * Flashes the user an interesting message if the URL parameters warrant it.
* *
* @param Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* *
* @return mixed * @return mixed
* *
@@ -85,7 +85,7 @@ class InterestingMessage
// send message about newly created transaction group. // send message about newly created transaction group.
/** @var TransactionGroup $group */ /** @var TransactionGroup $group */
$group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int)$transactionGroupId); $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int) $transactionGroupId);
if (null === $group) { if (null === $group) {
return; return;
@@ -101,12 +101,12 @@ class InterestingMessage
$title = $count > 1 ? $group->title : $journal->description; $title = $count > 1 ? $group->title : $journal->description;
if ('created' === $message) { if ('created' === $message) {
session()->flash('success_uri', route('transactions.show', [$transactionGroupId])); session()->flash('success_uri', route('transactions.show', [$transactionGroupId]));
session()->flash('success', (string)trans('firefly.stored_journal', ['description' => $title])); session()->flash('success', (string) trans('firefly.stored_journal', ['description' => $title]));
} }
if ('updated' === $message) { if ('updated' === $message) {
$type = strtolower($journal->transactionType->type); $type = strtolower($journal->transactionType->type);
session()->flash('success_uri', route('transactions.show', [$transactionGroupId])); session()->flash('success_uri', route('transactions.show', [$transactionGroupId]));
session()->flash('success', (string)trans(sprintf('firefly.updated_%s', $type), ['description' => $title])); session()->flash('success', (string) trans(sprintf('firefly.updated_%s', $type), ['description' => $title]));
} }
} }

View File

@@ -36,9 +36,9 @@ class IsAdmin
/** /**
* Handle an incoming request. Must be admin. * Handle an incoming request. Must be admin.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* @param string|null $guard * @param string|null $guard
* *
* @return mixed * @return mixed
*/ */

View File

@@ -36,8 +36,8 @@ class IsDemoUser
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* *
* @return mixed * @return mixed
*/ */
@@ -53,7 +53,7 @@ class IsDemoUser
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
if ($repository->hasRole($user, 'demo')) { if ($repository->hasRole($user, 'demo')) {
Log::info('User is a demo user.'); Log::info('User is a demo user.');
$request->session()->flash('info', (string)trans('firefly.not_available_demo_user')); $request->session()->flash('info', (string) trans('firefly.not_available_demo_user'));
$current = $request->url(); $current = $request->url();
$previous = $request->session()->previousUrl(); $previous = $request->session()->previousUrl();
if ($current !== $previous) { if ($current !== $previous) {

View File

@@ -35,9 +35,9 @@ class IsSandStormUser
/** /**
* Handle an incoming request. May not be a limited user (ie. Sandstorm env. or demo user). * Handle an incoming request. May not be a limited user (ie. Sandstorm env. or demo user).
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* @param string|null $guard * @param string|null $guard
* *
* @return mixed * @return mixed
*/ */
@@ -48,8 +48,8 @@ class IsSandStormUser
return $next($request); return $next($request);
} }
if (1 === (int)getenv('SANDSTORM')) { if (1 === (int) getenv('SANDSTORM')) {
app('session')->flash('warning', (string)trans('firefly.sandstorm_not_available')); app('session')->flash('warning', (string) trans('firefly.sandstorm_not_available'));
return response()->redirectTo(route('index')); return response()->redirectTo(route('index'));
} }

View File

@@ -36,8 +36,8 @@ class Range
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param Closure $next * @param Closure $next
* *
* @return mixed * @return mixed
*/ */
@@ -77,7 +77,7 @@ class Range
$lang = $pref->data; $lang = $pref->data;
App::setLocale($lang); App::setLocale($lang);
Carbon::setLocale(substr($lang, 0, 2)); Carbon::setLocale(substr($lang, 0, 2));
$locale = explode(',', (string)trans('config.locale')); $locale = explode(',', (string) trans('config.locale'));
$locale = array_map('trim', $locale); $locale = array_map('trim', $locale);
setlocale(LC_TIME, $locale); setlocale(LC_TIME, $locale);
@@ -89,12 +89,12 @@ class Range
} }
// save some formats: // save some formats:
$monthAndDayFormat = (string)trans('config.month_and_day'); $monthAndDayFormat = (string) trans('config.month_and_day');
$dateTimeFormat = (string)trans('config.date_time'); $dateTimeFormat = (string) trans('config.date_time');
$defaultCurrency = app('amount')->getDefaultCurrency(); $defaultCurrency = app('amount')->getDefaultCurrency();
// also format for moment JS: // also format for moment JS:
$madMomentJS = (string)trans('config.month_and_day_moment_js'); $madMomentJS = (string) trans('config.month_and_day_moment_js');
app('view')->share('madMomentJS', $madMomentJS); app('view')->share('madMomentJS', $madMomentJS);
app('view')->share('monthAndDayFormat', $monthAndDayFormat); app('view')->share('monthAndDayFormat', $monthAndDayFormat);

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;
use Closure; use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
/** /**
@@ -35,9 +36,9 @@ class RedirectIfAuthenticated
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* @param string|null $guard * @param string|null $guard
* *
* @return mixed * @return mixed
*/ */

View File

@@ -39,16 +39,16 @@ class Sandstorm
* Detects if is using Sandstorm, and responds by logging the user * Detects if is using Sandstorm, and responds by logging the user
* in and/or creating an account. * in and/or creating an account.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* @param string|null $guard * @param string|null $guard
* *
* @return mixed * @return mixed
*/ */
public function handle(Request $request, Closure $next, $guard = null) public function handle(Request $request, Closure $next, $guard = null)
{ {
// is in Sandstorm environment? // is in Sandstorm environment?
$sandstorm = 1 === (int)getenv('SANDSTORM'); $sandstorm = 1 === (int) getenv('SANDSTORM');
app('view')->share('SANDSTORM', $sandstorm); app('view')->share('SANDSTORM', $sandstorm);
if (!$sandstorm) { if (!$sandstorm) {
return $next($request); return $next($request);
@@ -58,7 +58,7 @@ class Sandstorm
if (Auth::guard($guard)->guest()) { if (Auth::guard($guard)->guest()) {
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
$userId = (string)$request->header('X-Sandstorm-User-Id'); $userId = (string) $request->header('X-Sandstorm-User-Id');
// catch anonymous: // catch anonymous:
$userId = '' === $userId ? 'anonymous' : $userId; $userId = '' === $userId ? 'anonymous' : $userId;

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;
use Closure; use Closure;
use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
/** /**
@@ -35,11 +36,11 @@ class SecureHeaders
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Closure $next * @param Closure $next
* *
* @throws Exception
* @return mixed * @return mixed
* @throws \Exception
*/ */
public function handle(Request $request, Closure $next) public function handle(Request $request, Closure $next)
{ {
@@ -105,8 +106,8 @@ class SecureHeaders
*/ */
private function getTrackingScriptSource(): string private function getTrackingScriptSource(): string
{ {
if ('' !== (string)config('firefly.tracker_site_id') && '' !== (string)config('firefly.tracker_url')) { if ('' !== (string) config('firefly.tracker_site_id') && '' !== (string) config('firefly.tracker_url')) {
return (string)config('firefly.tracker_url'); return (string) config('firefly.tracker_url');
} }
return ''; return '';

View File

@@ -22,6 +22,7 @@ declare(strict_types=1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession; use Illuminate\Session\Middleware\StartSession;
use Log; use Log;
@@ -36,8 +37,8 @@ class StartFireflySession extends StartSession
/** /**
* Store the current URL for the request if necessary. * Store the current URL for the request if necessary.
* *
* @param \Illuminate\Http\Request $request * @param Request $request
* @param \Illuminate\Contracts\Session\Session $session * @param Session $session
*/ */
protected function storeCurrentUrl(Request $request, $session): void protected function storeCurrentUrl(Request $request, $session): void
{ {
@@ -45,12 +46,13 @@ class StartFireflySession extends StartSession
$isScriptPage = strpos($uri, 'jscript'); $isScriptPage = strpos($uri, 'jscript');
$isDeletePage = strpos($uri, 'delete'); $isDeletePage = strpos($uri, 'delete');
$isLoginPage = strpos($uri, '/login'); $isLoginPage = strpos($uri, '/login');
$isJsonPage = strpos($uri, '/json'); $isJsonPage = strpos($uri, '/json');
// also stop remembering "delete" URL's. // also stop remembering "delete" URL's.
if (false === $isScriptPage && false === $isDeletePage if (false === $isScriptPage && false === $isDeletePage
&& false === $isLoginPage && false === $isJsonPage && false === $isLoginPage
&& false === $isJsonPage
&& 'GET' === $request->method() && 'GET' === $request->method()
&& !$request->ajax()) { && !$request->ajax()) {
$session->setPreviousUrl($uri); $session->setPreviousUrl($uri);

View File

@@ -43,7 +43,7 @@ class TrustProxies extends Middleware
*/ */
public function __construct(Repository $config) public function __construct(Repository $config)
{ {
$trustedProxies = (string)config('firefly.trusted_proxies'); $trustedProxies = (string) config('firefly.trusted_proxies');
$this->proxies = explode(',', $trustedProxies); $this->proxies = explode(',', $trustedProxies);
if ('**' === $trustedProxies) { if ('**' === $trustedProxies) {
$this->proxies = '**'; $this->proxies = '**';

View File

@@ -112,10 +112,10 @@ class AccountFormRequest extends Request
'what' => 'in:' . $types, 'what' => 'in:' . $types,
'interest_period' => 'in:daily,monthly,yearly', 'interest_period' => 'in:daily,monthly,yearly',
]; ];
$rules = Location::requestRules($rules); $rules = Location::requestRules($rules);
if ('liabilities' === $this->get('objectType')) { if ('liabilities' === $this->get('objectType')) {
$rules['opening_balance'] = ['numeric', 'required','max:1000000000']; $rules['opening_balance'] = ['numeric', 'required', 'max:1000000000'];
$rules['opening_balance_date'] = 'date|required'; $rules['opening_balance_date'] = 'date|required';
} }

View File

@@ -51,7 +51,7 @@ class JournalLinkRequest extends Request
$return = []; $return = [];
$linkType = $this->get('link_type'); $linkType = $this->get('link_type');
$parts = explode('_', $linkType); $parts = explode('_', $linkType);
$return['link_type_id'] = (int)$parts[0]; $return['link_type_id'] = (int) $parts[0];
$return['transaction_journal_id'] = $this->integer('opposing'); $return['transaction_journal_id'] = $this->integer('opposing');
$return['notes'] = $this->string('notes'); $return['notes'] = $this->string('notes');
$return['direction'] = $parts[1]; $return['direction'] = $parts[1];

View File

@@ -53,9 +53,9 @@ class RecurrenceFormRequest extends Request
/** /**
* Get the data required by the controller. * Get the data required by the controller.
* *
* @return array
* @throws FireflyException * @throws FireflyException
* *
* @return array
*/ */
public function getAll(): array public function getAll(): array
{ {
@@ -136,9 +136,9 @@ class RecurrenceFormRequest extends Request
/** /**
* The rules for this request. * The rules for this request.
* *
* @return array
* @throws FireflyException * @throws FireflyException
* *
* @return array
*/ */
public function rules(): array public function rules(): array
{ {
@@ -250,16 +250,16 @@ class RecurrenceFormRequest extends Request
default: default:
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore
case 'withdrawal': case 'withdrawal':
$sourceId = (int)$data['source_id']; $sourceId = (int) $data['source_id'];
$destinationId = (int)$data['withdrawal_destination_id']; $destinationId = (int) $data['withdrawal_destination_id'];
break; break;
case 'deposit': case 'deposit':
$sourceId = (int)$data['deposit_source_id']; $sourceId = (int) $data['deposit_source_id'];
$destinationId = (int)$data['destination_id']; $destinationId = (int) $data['destination_id'];
break; break;
case 'transfer': case 'transfer':
$sourceId = (int)$data['source_id']; $sourceId = (int) $data['source_id'];
$destinationId = (int)$data['destination_id']; $destinationId = (int) $data['destination_id'];
break; break;
} }
@@ -269,7 +269,7 @@ class RecurrenceFormRequest extends Request
// do something with result: // do something with result:
if (false === $validSource) { if (false === $validSource) {
$message = (string)trans('validation.generic_invalid_source'); $message = (string) trans('validation.generic_invalid_source');
$validator->errors()->add('source_id', $message); $validator->errors()->add('source_id', $message);
$validator->errors()->add('deposit_source_id', $message); $validator->errors()->add('deposit_source_id', $message);
@@ -280,7 +280,7 @@ class RecurrenceFormRequest extends Request
$validDestination = $accountValidator->validateDestination($destinationId, null); $validDestination = $accountValidator->validateDestination($destinationId, null);
// do something with result: // do something with result:
if (false === $validDestination) { if (false === $validDestination) {
$message = (string)trans('validation.generic_invalid_destination'); $message = (string) trans('validation.generic_invalid_destination');
$validator->errors()->add('destination_id', $message); $validator->errors()->add('destination_id', $message);
$validator->errors()->add('withdrawal_destination_id', $message); $validator->errors()->add('withdrawal_destination_id', $message);

View File

@@ -62,7 +62,7 @@ class ReportFormRequest extends Request
$collection = new Collection; $collection = new Collection;
if (is_array($set)) { if (is_array($set)) {
foreach ($set as $accountId) { foreach ($set as $accountId) {
$account = $repository->findNull((int)$accountId); $account = $repository->findNull((int) $accountId);
if (null !== $account) { if (null !== $account) {
$collection->push($account); $collection->push($account);
} }
@@ -85,7 +85,7 @@ class ReportFormRequest extends Request
$collection = new Collection; $collection = new Collection;
if (is_array($set)) { if (is_array($set)) {
foreach ($set as $budgetId) { foreach ($set as $budgetId) {
$budget = $repository->findNull((int)$budgetId); $budget = $repository->findNull((int) $budgetId);
if (null !== $budget) { if (null !== $budget) {
$collection->push($budget); $collection->push($budget);
} }
@@ -108,7 +108,7 @@ class ReportFormRequest extends Request
$collection = new Collection; $collection = new Collection;
if (is_array($set)) { if (is_array($set)) {
foreach ($set as $categoryId) { foreach ($set as $categoryId) {
$category = $repository->findNull((int)$categoryId); $category = $repository->findNull((int) $categoryId);
if (null !== $category) { if (null !== $category) {
$collection->push($category); $collection->push($category);
} }
@@ -118,18 +118,41 @@ class ReportFormRequest extends Request
return $collection; return $collection;
} }
/**
* Validate list of accounts which exist twice in system.
*
* @return Collection
*/
public function getDoubleList(): Collection
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$set = $this->get('double');
$collection = new Collection;
if (is_array($set)) {
foreach ($set as $accountId) {
$account = $repository->findNull((int) $accountId);
if (null !== $account) {
$collection->push($account);
}
}
}
return $collection;
}
/** /**
* Validate end date. * Validate end date.
* *
* @throws FireflyException
* @return Carbon * @return Carbon
* *
* @throws FireflyException
*/ */
public function getEndDate(): Carbon public function getEndDate(): Carbon
{ {
$date = new Carbon; $date = new Carbon;
$range = $this->get('daterange'); $range = $this->get('daterange');
$parts = explode(' - ', (string)$range); $parts = explode(' - ', (string) $range);
if (2 === count($parts)) { if (2 === count($parts)) {
try { try {
$date = new Carbon($parts[1]); $date = new Carbon($parts[1]);
@@ -146,41 +169,18 @@ class ReportFormRequest extends Request
return $date; return $date;
} }
/**
* Validate list of accounts which exist twice in system.
*
* @return Collection
*/
public function getDoubleList(): Collection
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$set = $this->get('double');
$collection = new Collection;
if (is_array($set)) {
foreach ($set as $accountId) {
$account = $repository->findNull((int)$accountId);
if (null !== $account) {
$collection->push($account);
}
}
}
return $collection;
}
/** /**
* Validate start date. * Validate start date.
* *
* @throws FireflyException
* @return Carbon * @return Carbon
* *
* @throws FireflyException
*/ */
public function getStartDate(): Carbon public function getStartDate(): Carbon
{ {
$date = new Carbon; $date = new Carbon;
$range = $this->get('daterange'); $range = $this->get('daterange');
$parts = explode(' - ', (string)$range); $parts = explode(' - ', (string) $range);
if (2 === count($parts)) { if (2 === count($parts)) {
try { try {
$date = new Carbon($parts[0]); $date = new Carbon($parts[0]);
@@ -216,7 +216,7 @@ class ReportFormRequest extends Request
$collection->push($tag); $collection->push($tag);
continue; continue;
} }
$tag = $repository->findNull((int)$tagTag); $tag = $repository->findNull((int) $tagTag);
if (null !== $tag) { if (null !== $tag) {
$collection->push($tag); $collection->push($tag);
continue; continue;

View File

@@ -124,7 +124,7 @@ class Request extends FormRequest
return null; return null;
} }
return (float)$res; return (float) $res;
} }
/** /**
@@ -136,7 +136,7 @@ class Request extends FormRequest
*/ */
public function integer(string $field): int public function integer(string $field): int
{ {
return (int)$this->get($field); return (int) $this->get($field);
} }
/** /**
@@ -155,60 +155,7 @@ class Request extends FormRequest
return null; return null;
} }
return (int)$string; return (int) $string;
}
/**
* Return integer value, or NULL when it's not set.
*
* @param string $field
*
* @return int|null
*/
public function nullableInteger(string $field): ?int
{
if (!$this->has($field)) {
return null;
}
$value = (string)$this->get($field);
if ('' === $value) {
return null;
}
return (int)$value;
}
/**
* Return string value, or NULL if empty.
*
* @param string $field
*
* @return string|null
*/
public function nullableString(string $field): ?string
{
if (!$this->has($field)) {
return null;
}
$res = trim(app('steam')->cleanString((string)($this->get($field) ?? '')));
if ('' === $res) {
return null;
}
return $res;
}
/**
* Return string value.
*
* @param string $field
*
* @return string
*/
public function string(string $field): string
{
return app('steam')->cleanString((string)($this->get($field) ?? ''));
} }
/** /**
@@ -220,41 +167,7 @@ class Request extends FormRequest
*/ */
public function nlString(string $field): string public function nlString(string $field): string
{ {
return app('steam')->nlCleanString((string)($this->get($field) ?? '')); return app('steam')->nlCleanString((string) ($this->get($field) ?? ''));
}
/**
* Return string value, but keep newlines, or NULL if empty.
*
* @param string $field
*
* @return string
*/
public function nullableNlString(string $field): ?string
{
if (!$this->has($field)) {
return null;
}
return app('steam')->nlCleanString((string)($this->get($field) ?? ''));
}
/**
* Parse and clean a string.
*
* @param string|null $string
*
* @return string|null
*/
public function stringFromValue(?string $string): ?string
{
if (null === $string) {
return null;
}
$result = app('steam')->cleanString($string);
return '' === $result ? null : $result;
} }
/** /**
@@ -276,59 +189,90 @@ class Request extends FormRequest
} }
/** /**
* Return date or NULL. * Return integer value, or NULL when it's not set.
* *
* @param string $field * @param string $field
* *
* @return Carbon|null * @return int|null
*/ */
protected function date(string $field): ?Carbon public function nullableInteger(string $field): ?int
{ {
$result = null; if (!$this->has($field)) {
try { return null;
$result = $this->get($field) ? new Carbon($this->get($field)) : null;
} catch (Exception $e) {
Log::debug(sprintf('Exception when parsing date. Not interesting: %s', $e->getMessage()));
} }
return $result; $value = (string) $this->get($field);
if ('' === $value) {
return null;
}
return (int) $value;
} }
/** /**
* Return date time or NULL. * Return string value, but keep newlines, or NULL if empty.
* *
* @param string $field * @param string $field
* *
* @return Carbon|null * @return string
*/ */
protected function dateTime(string $field): ?Carbon public function nullableNlString(string $field): ?string
{ {
if (null === $this->get($field)) { if (!$this->has($field)) {
return null;
}
$value = (string)$this->get($field);
if (10 === strlen($value)) {
// probably a date format.
try {
$result = Carbon::createFromFormat('Y-m-d', $value);
} catch (InvalidDateException $e) {
Log::error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage()));
return null;
}
return $result;
}
// is an atom string, I hope?
try {
$result = Carbon::parse($value);
} catch (InvalidDateException $e) {
Log::error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage()));
return null; return null;
} }
return $result; return app('steam')->nlCleanString((string) ($this->get($field) ?? ''));
}
/**
* Return string value, or NULL if empty.
*
* @param string $field
*
* @return string|null
*/
public function nullableString(string $field): ?string
{
if (!$this->has($field)) {
return null;
}
$res = trim(app('steam')->cleanString((string) ($this->get($field) ?? '')));
if ('' === $res) {
return null;
}
return $res;
}
/**
* Return string value.
*
* @param string $field
*
* @return string
*/
public function string(string $field): string
{
return app('steam')->cleanString((string) ($this->get($field) ?? ''));
}
/**
* Parse and clean a string.
*
* @param string|null $string
*
* @return string|null
*/
public function stringFromValue(?string $string): ?string
{
if (null === $string) {
return null;
}
$result = app('steam')->cleanString($string);
return '' === $result ? null : $result;
} }
/** /**
@@ -374,9 +318,9 @@ class Request extends FormRequest
) { ) {
Log::debug('Method is PUT and all fields present.'); Log::debug('Method is PUT and all fields present.');
$data['update_location'] = true; $data['update_location'] = true;
$data['longitude'] = $this->nullableString($longitudeKey); $data['longitude'] = $this->nullableString($longitudeKey);
$data['latitude'] = $this->nullableString($latitudeKey); $data['latitude'] = $this->nullableString($latitudeKey);
$data['zoom_level'] = $this->nullableString($zoomLevelKey); $data['zoom_level'] = $this->nullableString($zoomLevelKey);
} }
if (null === $data['longitude'] || null === $data['latitude'] || null === $data['zoom_level']) { if (null === $data['longitude'] || null === $data['latitude'] || null === $data['zoom_level']) {
Log::debug('One of the fields is NULL, wont save.'); Log::debug('One of the fields is NULL, wont save.');
@@ -389,6 +333,61 @@ class Request extends FormRequest
return $data; return $data;
} }
/**
* Return date or NULL.
*
* @param string $field
*
* @return Carbon|null
*/
protected function date(string $field): ?Carbon
{
$result = null;
try {
$result = $this->get($field) ? new Carbon($this->get($field)) : null;
} catch (Exception $e) {
Log::debug(sprintf('Exception when parsing date. Not interesting: %s', $e->getMessage()));
}
return $result;
}
/**
* Return date time or NULL.
*
* @param string $field
*
* @return Carbon|null
*/
protected function dateTime(string $field): ?Carbon
{
if (null === $this->get($field)) {
return null;
}
$value = (string) $this->get($field);
if (10 === strlen($value)) {
// probably a date format.
try {
$result = Carbon::createFromFormat('Y-m-d', $value);
} catch (InvalidDateException $e) {
Log::error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage()));
return null;
}
return $result;
}
// is an atom string, I hope?
try {
$result = Carbon::parse($value);
} catch (InvalidDateException $e) {
Log::error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage()));
return null;
}
return $result;
}
/** /**
* @param Validator $validator * @param Validator $validator
@@ -398,27 +397,27 @@ class Request extends FormRequest
$data = $validator->getData(); $data = $validator->getData();
$type = $data['auto_budget_type'] ?? ''; $type = $data['auto_budget_type'] ?? '';
$amount = $data['auto_budget_amount'] ?? ''; $amount = $data['auto_budget_amount'] ?? '';
$period = (string)($data['auto_budget_period'] ?? ''); $period = (string) ($data['auto_budget_period'] ?? '');
$currencyId = $data['auto_budget_currency_id'] ?? ''; $currencyId = $data['auto_budget_currency_id'] ?? '';
$currencyCode = $data['auto_budget_currency_code'] ?? ''; $currencyCode = $data['auto_budget_currency_code'] ?? '';
if (is_numeric($type)) { if (is_numeric($type)) {
$type = (int)$type; $type = (int) $type;
} }
if (0 === $type || 'none' === $type || '' === $type) { if (0 === $type || 'none' === $type || '' === $type) {
return; return;
} }
// basic float check: // basic float check:
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 ('' === $currencyCode && '' === $currencyId) { if ('' === $currencyCode && '' === $currencyId) {
$validator->errors()->add('auto_budget_amount', (string)trans('validation.require_currency_info')); $validator->errors()->add('auto_budget_amount', (string) trans('validation.require_currency_info'));
} }
} }

View File

@@ -116,7 +116,7 @@ class RuleFormRequest extends Request
$return[] = [ $return[] = [
'type' => $action['type'] ?? 'invalid', 'type' => $action['type'] ?? 'invalid',
'value' => $action['value'] ?? '', 'value' => $action['value'] ?? '',
'stop_processing' => 1 === (int)$stopProcessing, 'stop_processing' => 1 === (int) $stopProcessing,
]; ];
} }
} }
@@ -137,7 +137,7 @@ class RuleFormRequest extends Request
$return[] = [ $return[] = [
'type' => $trigger['type'] ?? 'invalid', 'type' => $trigger['type'] ?? 'invalid',
'value' => $trigger['value'] ?? '', 'value' => $trigger['value'] ?? '',
'stop_processing' => 1 === (int)$stopProcessing, 'stop_processing' => 1 === (int) $stopProcessing,
]; ];
} }
} }

View File

@@ -53,6 +53,7 @@ class TagFormRequest extends Request
'date' => $this->date('date'), 'date' => $this->date('date'),
'description' => $this->string('description'), 'description' => $this->string('description'),
]; ];
return $this->appendLocationData($data, 'location'); return $this->appendLocationData($data, 'location');
} }
@@ -74,12 +75,13 @@ class TagFormRequest extends Request
$tagRule = 'required|min:1|uniqueObjectForUser:tags,tag,' . $tag->id; $tagRule = 'required|min:1|uniqueObjectForUser:tags,tag,' . $tag->id;
} }
$rules= [ $rules = [
'tag' => $tagRule, 'tag' => $tagRule,
'id' => $idRule, 'id' => $idRule,
'description' => 'min:1|nullable', 'description' => 'min:1|nullable',
'date' => 'date|nullable', 'date' => 'date|nullable',
]; ];
return Location::requestRules($rules); return Location::requestRules($rules);
} }
} }