Code optimisations.

This commit is contained in:
James Cole
2018-07-22 18:50:27 +02:00
parent ea2c48bca5
commit ca096852a5
56 changed files with 221 additions and 427 deletions

View File

@@ -52,6 +52,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property Carbon lastActivityDate * @property Carbon lastActivityDate
* @property Collection accountMeta * @property Collection accountMeta
* @property bool encrypted * @property bool encrypted
* @property int account_type_id
* @property Collection piggyBanks
* *
* @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */

View File

@@ -27,6 +27,7 @@ use FireflyIII\User;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
@@ -38,6 +39,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property int $user_id * @property int $user_id
* @property-read string $email * @property-read string $email
* @property bool encrypted * @property bool encrypted
* @property Collection budgetlimits
*/ */
class Budget extends Model class Budget extends Model
{ {

View File

@@ -32,7 +32,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property User $user * @property User $user
* @property string $key * @property string $key
* @property int $user_id * @property int $user_id
* @property mixed status * @property string status
* @property int id
*/ */
class ExportJob extends Model class ExportJob extends Model
{ {

View File

@@ -41,6 +41,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property int $tag_id * @property int $tag_id
* @property Tag $tag * @property Tag $tag
* @property array $errors * @property array $errors
* @property array extended_status
* @property int id
*/ */
class ImportJob extends Model class ImportJob extends Model
{ {

View File

@@ -41,6 +41,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property int $id * @property int $id
* @property int $order * @property int $order
* @property Collection $rules * @property Collection $rules
* @property string description
*/ */
class RuleGroup extends Model class RuleGroup extends Model
{ {

View File

@@ -36,6 +36,12 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property string $tag * @property string $tag
* @property int $id * @property int $id
* @property \Carbon\Carbon $date * @property \Carbon\Carbon $date
* @property int zoomLevel
* @property float longitude
* @property float latitude
* @property string description
* @property string amount_sum
* @property string tagMode
*/ */
class Tag extends Model class Tag extends Model
{ {

View File

@@ -89,6 +89,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property string $after // used in audit reports. * @property string $after // used in audit reports.
* @property int $opposing_id // ID of the opposing transaction, used in collector * @property int $opposing_id // ID of the opposing transaction, used in collector
* @property bool $encrypted // is the journal encrypted * @property bool $encrypted // is the journal encrypted
* @property bool reconciled
* @SuppressWarnings(PHPMD.TooManyPublicMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/ */
class Transaction extends Model class Transaction extends Model

View File

@@ -53,6 +53,9 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property Carbon book_date * @property Carbon book_date
* @property Carbon process_date * @property Carbon process_date
* @property bool encrypted * @property bool encrypted
* @property int order
* @property int budget_id
* @property string period_marker
* *
* @SuppressWarnings(PHPMD.TooManyPublicMethods) * @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.CouplingBetweenObjects)

View File

@@ -38,14 +38,14 @@ class AccountServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->registerRepository(); $this->registerRepository();
$this->registerTasker(); $this->registerTasker();
@@ -54,7 +54,7 @@ class AccountServiceProvider extends ServiceProvider
/** /**
* Register account repository * Register account repository
*/ */
private function registerRepository() private function registerRepository(): void
{ {
$this->app->bind( $this->app->bind(
AccountRepositoryInterface::class, AccountRepositoryInterface::class,
@@ -74,7 +74,7 @@ class AccountServiceProvider extends ServiceProvider
/** /**
* Register the tasker. * Register the tasker.
*/ */
private function registerTasker() private function registerTasker(): void
{ {
$this->app->bind( $this->app->bind(
AccountTaskerInterface::class, AccountTaskerInterface::class,

View File

@@ -36,14 +36,14 @@ class AdminServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->linkType(); $this->linkType();
} }
@@ -51,7 +51,7 @@ class AdminServiceProvider extends ServiceProvider
/** /**
* Register link type repository * Register link type repository
*/ */
private function linkType() private function linkType(): void
{ {
$this->app->bind( $this->app->bind(
LinkTypeRepositoryInterface::class, LinkTypeRepositoryInterface::class,

View File

@@ -35,7 +35,7 @@ class AppServiceProvider extends ServiceProvider
/** /**
* Bootstrap any application services. * Bootstrap any application services.
*/ */
public function boot() public function boot(): void
{ {
Schema::defaultStringLength(191); Schema::defaultStringLength(191);
} }
@@ -43,7 +43,7 @@ class AppServiceProvider extends ServiceProvider
/** /**
* Register any application services. * Register any application services.
*/ */
public function register() public function register(): void
{ {
Passport::ignoreMigrations(); Passport::ignoreMigrations();
} }

View File

@@ -36,14 +36,14 @@ class AttachmentServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
AttachmentRepositoryInterface::class, AttachmentRepositoryInterface::class,

View File

@@ -44,7 +44,7 @@ class AuthServiceProvider extends ServiceProvider
/** /**
* Register any authentication / authorization services. * Register any authentication / authorization services.
*/ */
public function boot() public function boot(): void
{ {
$this->registerPolicies(); $this->registerPolicies();
Passport::routes(); Passport::routes();

View File

@@ -36,14 +36,14 @@ class BillServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
BillRepositoryInterface::class, BillRepositoryInterface::class,

View File

@@ -34,7 +34,7 @@ class BroadcastServiceProvider extends ServiceProvider
/** /**
* Bootstrap any application services. * Bootstrap any application services.
*/ */
public function boot() public function boot(): void
{ {
Broadcast::routes(); Broadcast::routes();

View File

@@ -36,14 +36,14 @@ class BudgetServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
BudgetRepositoryInterface::class, BudgetRepositoryInterface::class,

View File

@@ -36,14 +36,14 @@ class CategoryServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
CategoryRepositoryInterface::class, CategoryRepositoryInterface::class,

View File

@@ -36,14 +36,14 @@ class CurrencyServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
CurrencyRepositoryInterface::class, CurrencyRepositoryInterface::class,

View File

@@ -113,7 +113,7 @@ class EventServiceProvider extends ServiceProvider
} }
/** /**
* * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
protected function registerCreateEvents(): void protected function registerCreateEvents(): void
{ {

View File

@@ -38,14 +38,14 @@ class ExportJobServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->exportJob(); $this->exportJob();
$this->importJob(); $this->importJob();
@@ -54,7 +54,7 @@ class ExportJobServiceProvider extends ServiceProvider
/** /**
* Register export job. * Register export job.
*/ */
private function exportJob() private function exportJob(): void
{ {
$this->app->bind( $this->app->bind(
ExportJobRepositoryInterface::class, ExportJobRepositoryInterface::class,
@@ -73,7 +73,7 @@ class ExportJobServiceProvider extends ServiceProvider
/** /**
* Register import job. * Register import job.
*/ */
private function importJob() private function importJob(): void
{ {
$this->app->bind( $this->app->bind(
ImportJobRepositoryInterface::class, ImportJobRepositoryInterface::class,

View File

@@ -75,17 +75,21 @@ use TwigBridge\Extension\Loader\Functions;
use Validator; use Validator;
/** /**
* @codeCoverageIgnore *
* Class FireflyServiceProvider. * Class FireflyServiceProvider.
*
* @codeCoverageIgnore
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class FireflyServiceProvider extends ServiceProvider class FireflyServiceProvider extends ServiceProvider
{ {
/** /**
* Start provider. * Start provider.
*/ */
public function boot() public function boot(): void
{ {
Validator::resolver( Validator::resolver(
/** @noinspection MoreThanThreeArgumentsInspection */
function ($translator, $data, $rules, $messages) { function ($translator, $data, $rules, $messages) {
return new FireflyValidator($translator, $data, $rules, $messages); return new FireflyValidator($translator, $data, $rules, $messages);
} }
@@ -105,8 +109,10 @@ class FireflyServiceProvider extends ServiceProvider
/** /**
* Register stuff. * Register stuff.
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
'preferences', 'preferences',

View File

@@ -35,7 +35,7 @@ class FireflySessionProvider extends ServiceProvider
/** /**
* Register the service provider. * Register the service provider.
*/ */
public function register() public function register(): void
{ {
$this->registerSessionManager(); $this->registerSessionManager();
@@ -47,7 +47,7 @@ class FireflySessionProvider extends ServiceProvider
/** /**
* Register the session driver instance. * Register the session driver instance.
*/ */
protected function registerSessionDriver() protected function registerSessionDriver(): void
{ {
$this->app->singleton( $this->app->singleton(
'session.store', 'session.store',
@@ -63,7 +63,7 @@ class FireflySessionProvider extends ServiceProvider
/** /**
* Register the session manager instance. * Register the session manager instance.
*/ */
protected function registerSessionManager() protected function registerSessionManager(): void
{ {
$this->app->singleton( $this->app->singleton(
'session', 'session',

View File

@@ -38,14 +38,14 @@ class JournalServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->registerRepository(); $this->registerRepository();
$this->registerCollector(); $this->registerCollector();
@@ -54,7 +54,7 @@ class JournalServiceProvider extends ServiceProvider
/** /**
* Register the collector. * Register the collector.
*/ */
private function registerCollector() private function registerCollector(): void
{ {
$this->app->bind( $this->app->bind(
JournalCollectorInterface::class, JournalCollectorInterface::class,
@@ -73,7 +73,7 @@ class JournalServiceProvider extends ServiceProvider
/** /**
* Register repository. * Register repository.
*/ */
private function registerRepository() private function registerRepository(): void
{ {
$this->app->bind( $this->app->bind(
JournalRepositoryInterface::class, JournalRepositoryInterface::class,

View File

@@ -1,60 +0,0 @@
<?php
/**
* LogServiceProvider.php
* Copyright (c) 2017 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/>.
*/
declare(strict_types=1);
namespace FireflyIII\Providers;
use Illuminate\Log\LogServiceProvider as LaravelLogServiceProvider;
use Illuminate\Log\Writer;
/**
* @codeCoverageIgnore
* Class LogServiceProvider.
*/
class LogServiceProvider extends LaravelLogServiceProvider
{
/**
* Configure the Monolog handlers for the application.
*
* @param \Illuminate\Log\Writer $log
*/
protected function configureDailyHandler(Writer $log)
{
$log->useDailyFiles(
$this->app->storagePath() . '/logs/firefly-iii.log',
$this->maxFiles(),
$this->logLevel()
);
}
/**
* Configure the Monolog handlers for the application.
*
* @param \Illuminate\Log\Writer $log
*/
protected function configureSingleHandler(Writer $log)
{
$log->useFiles(
$this->app->storagePath() . '/logs/firefly-iii.log',
$this->logLevel()
);
}
}

View File

@@ -36,14 +36,14 @@ class PiggyBankServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
PiggyBankRepositoryInterface::class, PiggyBankRepositoryInterface::class,

View File

@@ -43,7 +43,7 @@ class RouteServiceProvider extends ServiceProvider
/** /**
* Define the routes for the application. * Define the routes for the application.
*/ */
public function map() public function map(): void
{ {
$this->mapApiRoutes(); $this->mapApiRoutes();
@@ -55,7 +55,7 @@ class RouteServiceProvider extends ServiceProvider
* *
* These routes are typically stateless. * These routes are typically stateless.
*/ */
protected function mapApiRoutes() protected function mapApiRoutes(): void
{ {
Route::prefix('api/v1') Route::prefix('api/v1')
->middleware('auth:api') ->middleware('auth:api')
@@ -68,7 +68,7 @@ class RouteServiceProvider extends ServiceProvider
* *
* These routes all receive session state, CSRF protection, etc. * These routes all receive session state, CSRF protection, etc.
*/ */
protected function mapWebRoutes() protected function mapWebRoutes(): void
{ {
Route::middleware('web') Route::middleware('web')
->namespace($this->namespace) ->namespace($this->namespace)

View File

@@ -36,14 +36,14 @@ class RuleGroupServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
RuleGroupRepositoryInterface::class, RuleGroupRepositoryInterface::class,

View File

@@ -36,14 +36,14 @@ class RuleServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
RuleRepositoryInterface::class, RuleRepositoryInterface::class,

View File

@@ -36,14 +36,14 @@ class SearchServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
SearchInterface::class, SearchInterface::class,

View File

@@ -36,14 +36,14 @@ class TagServiceProvider extends ServiceProvider
/** /**
* Bootstrap the application services. * Bootstrap the application services.
*/ */
public function boot() public function boot(): void
{ {
} }
/** /**
* Register the application services. * Register the application services.
*/ */
public function register() public function register(): void
{ {
$this->app->bind( $this->app->bind(
TagRepositoryInterface::class, TagRepositoryInterface::class,

View File

@@ -82,18 +82,6 @@ class AccountRepository implements AccountRepositoryInterface
return $this->user->accounts()->find($accountId); return $this->user->accounts()->find($accountId);
} }
/**
* Return account type by string.
*
* @param string $type
*
* @return AccountType|null
*/
public function getAccountType(string $type): ?AccountType
{
return AccountType::whereType($type)->first();
}
/** /**
* Return meta value for account. Null if not found. * Return meta value for account. Null if not found.
* *
@@ -113,16 +101,6 @@ class AccountRepository implements AccountRepositoryInterface
return null; return null;
} }
/**
* @param Account $account
*
* @return Note|null
*/
public function getNote(Account $account): ?Note
{
return $account->notes()->first();
}
/** /**
* Get note text or null. * Get note text or null.
* *
@@ -185,29 +163,6 @@ class AccountRepository implements AccountRepositoryInterface
return $journal->date->format('Y-m-d'); return $journal->date->format('Y-m-d');
} }
/**
* Returns the date of the very last transaction in this account.
*
* @param Account $account
*
* @return Carbon
*/
public function newestJournalDate(Account $account): Carbon
{
$last = new Carbon;
$date = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->first(['transaction_journals.date']);
if (null !== $date) {
$last = new Carbon($date->date);
}
return $last;
}
/** /**
* Returns the date of the very first transaction in this account. * Returns the date of the very first transaction in this account.
* *
@@ -253,7 +208,7 @@ class AccountRepository implements AccountRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
@@ -262,6 +217,7 @@ class AccountRepository implements AccountRepositoryInterface
* @param array $data * @param array $data
* *
* @return Account * @return Account
* @throws \FireflyIII\Exceptions\FireflyException
*/ */
public function store(array $data): Account public function store(array $data): Account
{ {
@@ -286,20 +242,4 @@ class AccountRepository implements AccountRepositoryInterface
return $account; return $account;
} }
/**
* @param TransactionJournal $journal
* @param array $data
*
* @return TransactionJournal
*/
public function updateReconciliation(TransactionJournal $journal, array $data): TransactionJournal
{
/** @var JournalUpdateService $service */
$service = app(JournalUpdateService::class);
$journal = $service->update($journal, $data);
return $journal;
}
} }

View File

@@ -55,14 +55,8 @@ interface AccountRepositoryInterface
public function destroy(Account $account, ?Account $moveTo): bool; public function destroy(Account $account, ?Account $moveTo): bool;
/** /**
* @param int $accountId * Find by account number. Is used.
* *
* @deprecated
* @return Account
*/
public function find(int $accountId): Account;
/**
* @param string $number * @param string $number
* @param array $types * @param array $types
* *
@@ -70,15 +64,6 @@ interface AccountRepositoryInterface
*/ */
public function findByAccountNumber(string $number, array $types): ?Account; public function findByAccountNumber(string $number, array $types): ?Account;
/**
* @param string $iban
* @param array $types
*
* @deprecated
* @return Account
*/
public function findByIban(string $iban, array $types): Account;
/** /**
* @param string $iban * @param string $iban
* @param array $types * @param array $types
@@ -102,15 +87,6 @@ interface AccountRepositoryInterface
*/ */
public function findNull(int $accountId): ?Account; public function findNull(int $accountId): ?Account;
/**
* Return account type by string.
*
* @param string $type
*
* @return AccountType|null
*/
public function getAccountType(string $type): ?AccountType;
/** /**
* @param array $accountIds * @param array $accountIds
* *
@@ -147,13 +123,6 @@ interface AccountRepositoryInterface
*/ */
public function getMetaValue(Account $account, string $field): ?string; public function getMetaValue(Account $account, string $field): ?string;
/**
* @param Account $account
*
* @return Note|null
*/
public function getNote(Account $account): ?Note;
/** /**
* Get note text or null. * Get note text or null.
* *
@@ -191,15 +160,6 @@ interface AccountRepositoryInterface
*/ */
public function getReconciliation(Account $account): ?Account; public function getReconciliation(Account $account): ?Account;
/**
* Returns the date of the very last transaction in this account.
*
* @param Account $account
*
* @return Carbon
*/
public function newestJournalDate(Account $account): Carbon;
/** /**
* Returns the date of the very first transaction in this account. * Returns the date of the very first transaction in this account.
* *
@@ -237,12 +197,4 @@ interface AccountRepositoryInterface
* @return Account * @return Account
*/ */
public function update(Account $account, array $data): Account; public function update(Account $account, array $data): Account;
/**
* @param TransactionJournal $journal
* @param array $data
*
* @return TransactionJournal
*/
public function updateReconciliation(TransactionJournal $journal, array $data): TransactionJournal;
} }

View File

@@ -44,6 +44,7 @@ class AccountTasker implements AccountTaskerInterface
* @param Carbon $end * @param Carbon $end
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/ */
public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array
{ {
@@ -182,7 +183,7 @@ class AccountTasker implements AccountTaskerInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
@@ -191,6 +192,7 @@ class AccountTasker implements AccountTaskerInterface
* @param Collection $transactions * @param Collection $transactions
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
private function groupByOpposing(Collection $transactions): array private function groupByOpposing(Collection $transactions): array
{ {

View File

@@ -38,22 +38,6 @@ use Log;
*/ */
trait FindAccountsTrait trait FindAccountsTrait
{ {
/**
* @param $accountId
*
* @deprecated
* @return Account
*/
public function find(int $accountId): Account
{
/** @var Account $account */
$account = $this->user->accounts()->find($accountId);
if (null === $account) {
return new Account;
}
return $account;
}
/** /**
* @param string $number * @param string $number
@@ -82,33 +66,6 @@ trait FindAccountsTrait
return null; return null;
} }
/**
* @param string $iban
* @param array $types
*
* @deprecated
* @return Account
*/
public function findByIban(string $iban, array $types): Account
{
$query = $this->user->accounts()->where('iban', '!=', '')->whereNotNull('iban');
if (\count($types) > 0) {
$query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id');
$query->whereIn('account_types.type', $types);
}
$accounts = $query->get(['accounts.*']);
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->iban === $iban) {
return $account;
}
}
return new Account;
}
/** /**
* @param string $iban * @param string $iban
* @param array $types * @param array $types
@@ -158,7 +115,8 @@ trait FindAccountsTrait
Log::debug(sprintf('Found #%d (%s) with type id %d', $account->id, $account->name, $account->account_type_id)); Log::debug(sprintf('Found #%d (%s) with type id %d', $account->id, $account->name, $account->account_type_id));
return $account; return $account;
} else { }
if ($account->name !== $name) {
Log::debug(sprintf('"%s" does not equal "%s"', $account->name, $name)); Log::debug(sprintf('"%s" does not equal "%s"', $account->name, $name));
} }
} }
@@ -244,9 +202,11 @@ trait FindAccountsTrait
/** /**
* @return Account * @return Account
* *
* @throws FireflyException
*/ */
public function getCashAccount(): Account public function getCashAccount(): Account
{ {
/** @var AccountType $type */
$type = AccountType::where('type', AccountType::CASH)->first(); $type = AccountType::where('type', AccountType::CASH)->first();
/** @var AccountFactory $factory */ /** @var AccountFactory $factory */
$factory = app(AccountFactory::class); $factory = app(AccountFactory::class);
@@ -268,6 +228,7 @@ trait FindAccountsTrait
throw new FireflyException(sprintf('%s is not an asset account.', $account->name)); throw new FireflyException(sprintf('%s is not an asset account.', $account->name));
} }
$name = $account->name . ' reconciliation'; $name = $account->name . ' reconciliation';
/** @var AccountType $type */
$type = AccountType::where('type', AccountType::RECONCILIATION)->first(); $type = AccountType::where('type', AccountType::RECONCILIATION)->first();
$accounts = $this->user->accounts()->where('account_type_id', $type->id)->get(); $accounts = $this->user->accounts()->where('account_type_id', $type->id)->get();
/** @var Account $current */ /** @var Account $current */

View File

@@ -37,6 +37,7 @@ use Storage;
/** /**
* Class AttachmentRepository. * Class AttachmentRepository.
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class AttachmentRepository implements AttachmentRepositoryInterface class AttachmentRepository implements AttachmentRepositoryInterface
{ {
@@ -58,7 +59,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface
try { try {
unlink($file); unlink($file);
} catch (Exception $e) { } catch (Exception $e) {
Log::error(sprintf('Could not delete file for attachment %d.', $attachment->id)); Log::error(sprintf('Could not delete file for attachment %d: %s', $attachment->id, $e->getMessage()));
} }
$attachment->delete(); $attachment->delete();
@@ -78,21 +79,6 @@ class AttachmentRepository implements AttachmentRepositoryInterface
return $disk->exists($attachment->fileName()); return $disk->exists($attachment->fileName());
} }
/**
* @param int $id
*
* @return Attachment
*/
public function find(int $id): Attachment
{
$attachment = $this->user->attachments()->find($id);
if (null === $attachment) {
return new Attachment;
}
return $attachment;
}
/** /**
* @param int $id * @param int $id
* *
@@ -100,6 +86,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface
*/ */
public function findWithoutUser(int $id): Attachment public function findWithoutUser(int $id): Attachment
{ {
$attachment = Attachment::find($id); $attachment = Attachment::find($id);
if (null === $attachment) { if (null === $attachment) {
return new Attachment; return new Attachment;

View File

@@ -48,13 +48,6 @@ interface AttachmentRepositoryInterface
*/ */
public function exists(Attachment $attachment): bool; public function exists(Attachment $attachment): bool;
/**
* @param int $id
*
* @return Attachment
*/
public function find(int $id): Attachment;
/** /**
* @param int $id * @param int $id
* *

View File

@@ -553,7 +553,7 @@ class BillRepository implements BillRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }

View File

@@ -89,7 +89,11 @@ class BudgetRepository implements BudgetRepositoryInterface
public function cleanupBudgets(): bool public function cleanupBudgets(): bool
{ {
// delete limits with amount 0: // delete limits with amount 0:
try {
BudgetLimit::where('amount', 0)->delete(); BudgetLimit::where('amount', 0)->delete();
} catch (Exception $e) {
Log::debug(sprintf('Could not delete budget limit: %s', $e->getMessage()));
}
// do the clean up by hand because Sqlite can be tricky with this. // do the clean up by hand because Sqlite can be tricky with this.
$budgetLimits = BudgetLimit::orderBy('created_at', 'DESC')->get(['id', 'budget_id', 'start_date', 'end_date']); $budgetLimits = BudgetLimit::orderBy('created_at', 'DESC')->get(['id', 'budget_id', 'start_date', 'end_date']);
@@ -99,7 +103,11 @@ class BudgetRepository implements BudgetRepositoryInterface
$key = $budgetLimit->budget_id . '-' . $budgetLimit->start_date->format('Y-m-d') . $budgetLimit->end_date->format('Y-m-d'); $key = $budgetLimit->budget_id . '-' . $budgetLimit->start_date->format('Y-m-d') . $budgetLimit->end_date->format('Y-m-d');
if (isset($count[$key])) { if (isset($count[$key])) {
// delete it! // delete it!
try {
BudgetLimit::find($budgetLimit->id)->delete(); BudgetLimit::find($budgetLimit->id)->delete();
} catch (Exception $e) {
Log::debug(sprintf('Could not delete budget limit: %s', $e->getMessage()));
}
} }
$count[$key] = true; $count[$key] = true;
} }
@@ -115,7 +123,6 @@ class BudgetRepository implements BudgetRepositoryInterface
* @param Carbon $end * @param Carbon $end
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function collectBudgetInformation(Collection $budgets, Carbon $start, Carbon $end): array public function collectBudgetInformation(Collection $budgets, Carbon $start, Carbon $end): array
{ {
@@ -249,6 +256,7 @@ class BudgetRepository implements BudgetRepositoryInterface
* @param int $budgetId * @param int $budgetId
* *
* @return Budget * @return Budget
* @deprecated
*/ */
public function find(int $budgetId): Budget public function find(int $budgetId): Budget
{ {
@@ -467,9 +475,8 @@ class BudgetRepository implements BudgetRepositoryInterface
$total = bcadd($availableBudget->amount, $total); $total = bcadd($availableBudget->amount, $total);
$days += $availableBudget->start_date->diffInDays($availableBudget->end_date); $days += $availableBudget->start_date->diffInDays($availableBudget->end_date);
} }
$avg = bcdiv($total, (string)$days);
return $avg; return bcdiv($total, (string)$days);
} }
/** /**
@@ -535,6 +542,7 @@ class BudgetRepository implements BudgetRepositoryInterface
return $set; return $set;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* This method is being used to generate the budget overview in the year/multi-year report. Its used * This method is being used to generate the budget overview in the year/multi-year report. Its used
* in both the year/multi-year budget overview AND in the accompanying chart. * in both the year/multi-year budget overview AND in the accompanying chart.
@@ -658,6 +666,7 @@ class BudgetRepository implements BudgetRepositoryInterface
return $result; return $result;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param TransactionCurrency $currency * @param TransactionCurrency $currency
* @param Carbon $start * @param Carbon $start
@@ -688,11 +697,12 @@ class BudgetRepository implements BudgetRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $budgets * @param Collection $budgets
* @param Collection $accounts * @param Collection $accounts
@@ -915,6 +925,7 @@ class BudgetRepository implements BudgetRepositoryInterface
return $budgetLimit; return $budgetLimit;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Budget $budget * @param Budget $budget
* @param Carbon $start * @param Carbon $start

View File

@@ -59,7 +59,6 @@ interface BudgetRepositoryInterface
* @param Carbon $end * @param Carbon $end
* *
* @return array * @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/ */
public function collectBudgetInformation(Collection $budgets, Carbon $start, Carbon $end): array; public function collectBudgetInformation(Collection $budgets, Carbon $start, Carbon $end): array;
@@ -186,6 +185,7 @@ interface BudgetRepositoryInterface
*/ */
public function getBudgetLimits(Budget $budget, Carbon $start = null, Carbon $end = null): Collection; public function getBudgetLimits(Budget $budget, Carbon $start = null, Carbon $end = null): Collection;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $budgets * @param Collection $budgets
* @param Collection $accounts * @param Collection $accounts
@@ -224,6 +224,7 @@ interface BudgetRepositoryInterface
*/ */
public function getNoBudgetPeriodReport(Collection $accounts, Carbon $start, Carbon $end): array; public function getNoBudgetPeriodReport(Collection $accounts, Carbon $start, Carbon $end): array;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param TransactionCurrency $currency * @param TransactionCurrency $currency
* @param Carbon $start * @param Carbon $start
@@ -239,6 +240,7 @@ interface BudgetRepositoryInterface
*/ */
public function setUser(User $user); public function setUser(User $user);
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $budgets * @param Collection $budgets
* @param Collection $accounts * @param Collection $accounts
@@ -296,6 +298,7 @@ interface BudgetRepositoryInterface
*/ */
public function updateBudgetLimit(BudgetLimit $budgetLimit, array $data): BudgetLimit; public function updateBudgetLimit(BudgetLimit $budgetLimit, array $data): BudgetLimit;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Budget $budget * @param Budget $budget
* @param Carbon $start * @param Carbon $start

View File

@@ -59,6 +59,7 @@ class CategoryRepository implements CategoryRepositoryInterface
return true; return true;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts
@@ -84,6 +85,7 @@ class CategoryRepository implements CategoryRepositoryInterface
* @param int $categoryId * @param int $categoryId
* *
* @return Category * @return Category
* @deprecated
*/ */
public function find(int $categoryId): Category public function find(int $categoryId): Category
{ {
@@ -211,6 +213,7 @@ class CategoryRepository implements CategoryRepositoryInterface
return $lastJournalDate; return $lastJournalDate;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts
@@ -294,6 +297,7 @@ class CategoryRepository implements CategoryRepositoryInterface
return $result; return $result;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts
@@ -383,11 +387,12 @@ class CategoryRepository implements CategoryRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts

View File

@@ -40,6 +40,7 @@ interface CategoryRepositoryInterface
*/ */
public function destroy(Category $category): bool; public function destroy(Category $category): bool;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts
@@ -111,6 +112,7 @@ interface CategoryRepositoryInterface
*/ */
public function lastUseDate(Category $category, Collection $accounts): ?Carbon; public function lastUseDate(Category $category, Collection $accounts): ?Carbon;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts
@@ -130,6 +132,7 @@ interface CategoryRepositoryInterface
*/ */
public function periodExpensesNoCategory(Collection $accounts, Carbon $start, Carbon $end): array; public function periodExpensesNoCategory(Collection $accounts, Carbon $start, Carbon $end): array;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts
@@ -154,6 +157,7 @@ interface CategoryRepositoryInterface
*/ */
public function setUser(User $user); public function setUser(User $user);
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param Collection $categories * @param Collection $categories
* @param Collection $accounts * @param Collection $accounts

View File

@@ -27,6 +27,7 @@ use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\CurrencyExchangeRate; use FireflyIII\Models\CurrencyExchangeRate;
use FireflyIII\Models\Preference; use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Services\Internal\Destroy\CurrencyDestroyService; use FireflyIII\Services\Internal\Destroy\CurrencyDestroyService;
use FireflyIII\Services\Internal\Update\CurrencyUpdateService; use FireflyIII\Services\Internal\Update\CurrencyUpdateService;
use FireflyIII\User; use FireflyIII\User;
@@ -93,7 +94,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface
*/ */
public function destroy(TransactionCurrency $currency): bool public function destroy(TransactionCurrency $currency): bool
{ {
if ($this->user->hasRole('owner')) { /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
if ($repository->hasRole($this->user, 'owner')) {
/** @var CurrencyDestroyService $service */ /** @var CurrencyDestroyService $service */
$service = app(CurrencyDestroyService::class); $service = app(CurrencyDestroyService::class);
$service->destroy($currency); $service->destroy($currency);
@@ -298,7 +303,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }

View File

@@ -66,11 +66,10 @@ class ExportJobRepository implements ExportJobRepositoryInterface
/** @var ExportJob $entry */ /** @var ExportJob $entry */
foreach ($set as $entry) { foreach ($set as $entry) {
$key = $entry->key; $key = $entry->key;
$len = \strlen($key);
$files = scandir(storage_path('export'), SCANDIR_SORT_NONE); $files = scandir(storage_path('export'), SCANDIR_SORT_NONE);
/** @var string $file */ /** @var string $file */
foreach ($files as $file) { foreach ($files as $file) {
if (substr($file, 0, $len) === $key) { if (0 === strpos($file, $key)) {
unlink(storage_path('export') . DIRECTORY_SEPARATOR . $file); unlink(storage_path('export') . DIRECTORY_SEPARATOR . $file);
} }
} }
@@ -121,11 +120,12 @@ class ExportJobRepository implements ExportJobRepositoryInterface
/** /**
* @param string $key * @param string $key
* * @deprecated
* @return ExportJob * @return ExportJob
*/ */
public function findByKey(string $key): ExportJob public function findByKey(string $key): ExportJob
{ {
/** @var ExportJob $result */
$result = $this->user->exportJobs()->where('key', $key)->first(['export_jobs.*']); $result = $this->user->exportJobs()->where('key', $key)->first(['export_jobs.*']);
if (null === $result) { if (null === $result) {
return new ExportJob; return new ExportJob;
@@ -152,7 +152,7 @@ class ExportJobRepository implements ExportJobRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }

View File

@@ -57,7 +57,7 @@ interface ExportJobRepositoryInterface
/** /**
* @param string $key * @param string $key
* * @deprecated
* @return ExportJob * @return ExportJob
*/ */
public function findByKey(string $key): ExportJob; public function findByKey(string $key): ExportJob;

View File

@@ -95,8 +95,9 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* *
* @return ImportJob * @return ImportJob
*/ */
public function addStepsDone(ImportJob $job, int $steps = 1): ImportJob public function addStepsDone(ImportJob $job, int $steps = null): ImportJob
{ {
$steps = $steps ?? 1;
$status = $this->getExtendedStatus($job); $status = $this->getExtendedStatus($job);
$status['done'] += $steps; $status['done'] += $steps;
Log::debug(sprintf('Add %d to steps done for job "%s" making steps done %d', $steps, $job->key, $status['done'])); Log::debug(sprintf('Add %d to steps done for job "%s" making steps done %d', $steps, $job->key, $status['done']));
@@ -110,8 +111,9 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* *
* @return ImportJob * @return ImportJob
*/ */
public function addTotalSteps(ImportJob $job, int $steps = 1): ImportJob public function addTotalSteps(ImportJob $job, int $steps = null): ImportJob
{ {
$steps = $steps ?? 1;
$extended = $this->getExtendedStatus($job); $extended = $this->getExtendedStatus($job);
$total = (int)($extended['steps'] ?? 0); $total = (int)($extended['steps'] ?? 0);
$total += $steps; $total += $steps;
@@ -136,7 +138,7 @@ class ImportJobRepository implements ImportJobRepositoryInterface
->where('name', 'importHash') ->where('name', 'importHash')
->count(); ->count();
return (int)$count; return $count;
} }
/** /**
@@ -309,12 +311,12 @@ class ImportJobRepository implements ImportJobRepositoryInterface
// verify content: // verify content:
$result = mb_detect_encoding($content, 'UTF-8', true); $result = mb_detect_encoding($content, 'UTF-8', true);
if ($result === false) { if (false === $result) {
Log::error(sprintf('Cannot detect encoding for uploaded import file "%s".', $file->getClientOriginalName())); Log::error(sprintf('Cannot detect encoding for uploaded import file "%s".', $file->getClientOriginalName()));
return false; return false;
} }
if ($result !== 'ASCII' && $result !== 'UTF-8') { if ('ASCII' !== $result && 'UTF-8' !== $result) {
Log::error(sprintf('Uploaded import file is %s instead of UTF8!', var_export($result, true))); Log::error(sprintf('Uploaded import file is %s instead of UTF8!', var_export($result, true)));
return false; return false;
@@ -472,7 +474,7 @@ class ImportJobRepository implements ImportJobRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
@@ -482,10 +484,9 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* *
* @param ImportJob $job * @param ImportJob $job
* @param string $name * @param string $name
* @param UploadedFile $file * @param string $fileName
* *
* @return MessageBag * @return MessageBag
* @throws FireflyException
*/ */
public function storeCLIUpload(ImportJob $job, string $name, string $fileName): MessageBag public function storeCLIUpload(ImportJob $job, string $name, string $fileName): MessageBag
{ {
@@ -538,7 +539,6 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* @param UploadedFile $file * @param UploadedFile $file
* *
* @return MessageBag * @return MessageBag
* @throws FireflyException
*/ */
public function storeFileUpload(ImportJob $job, string $name, UploadedFile $file): MessageBag public function storeFileUpload(ImportJob $job, string $name, UploadedFile $file): MessageBag
{ {
@@ -607,7 +607,6 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* @param ImportJob $job * @param ImportJob $job
* *
* @return string * @return string
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/ */
public function uploadFileContents(ImportJob $job): string public function uploadFileContents(ImportJob $job): string
{ {

View File

@@ -60,7 +60,7 @@ interface ImportJobRepositoryInterface
* *
* @return ImportJob * @return ImportJob
*/ */
public function addStepsDone(ImportJob $job, int $steps = 1): ImportJob; public function addStepsDone(ImportJob $job, int $steps = null): ImportJob;
/** /**
* @param ImportJob $job * @param ImportJob $job
@@ -68,7 +68,7 @@ interface ImportJobRepositoryInterface
* *
* @return ImportJob * @return ImportJob
*/ */
public function addTotalSteps(ImportJob $job, int $steps = 1): ImportJob; public function addTotalSteps(ImportJob $job, int $steps = null): ImportJob;
/** /**
* Return number of imported rows with this hash value. * Return number of imported rows with this hash value.
@@ -125,7 +125,7 @@ interface ImportJobRepositoryInterface
* *
* @return string * @return string
*/ */
public function getStatus(ImportJob $job); public function getStatus(ImportJob $job): string;
/** /**
* @param ImportJob $job * @param ImportJob $job

View File

@@ -51,6 +51,7 @@ class JournalRepository implements JournalRepositoryInterface
/** @var User */ /** @var User */
private $user; private $user;
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param TransactionJournal $journal * @param TransactionJournal $journal
* @param TransactionType $type * @param TransactionType $type
@@ -141,6 +142,7 @@ class JournalRepository implements JournalRepositoryInterface
* @param int $journalId * @param int $journalId
* *
* @return TransactionJournal * @return TransactionJournal
* @deprecated
*/ */
public function find(int $journalId): TransactionJournal public function find(int $journalId): TransactionJournal
{ {
@@ -300,6 +302,7 @@ class JournalRepository implements JournalRepositoryInterface
if (null !== $budget) { if (null !== $budget) {
return $budget->id; return $budget->id;
} }
/** @noinspection NullPointerExceptionInspection */
$budget = $journal->transactions()->first()->budgets()->first(); $budget = $journal->transactions()->first()->budgets()->first();
if (null !== $budget) { if (null !== $budget) {
return $budget->id; return $budget->id;
@@ -321,6 +324,7 @@ class JournalRepository implements JournalRepositoryInterface
if (null !== $category) { if (null !== $category) {
return $category->name; return $category->name;
} }
/** @noinspection NullPointerExceptionInspection */
$category = $journal->transactions()->first()->categories()->first(); $category = $journal->transactions()->first()->categories()->first();
if (null !== $category) { if (null !== $category) {
return $category->name; return $category->name;
@@ -343,6 +347,7 @@ class JournalRepository implements JournalRepositoryInterface
if (null === $field) { if (null === $field) {
return $journal->date->format('Y-m-d'); return $journal->date->format('Y-m-d');
} }
/** @noinspection NotOptimalIfConditionsInspection */
if (null !== $journal->$field && $journal->$field instanceof Carbon) { if (null !== $journal->$field && $journal->$field instanceof Carbon) {
// make field NULL // make field NULL
$carbon = clone $journal->$field; $carbon = clone $journal->$field;
@@ -731,7 +736,7 @@ class JournalRepository implements JournalRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }

View File

@@ -39,6 +39,7 @@ use Illuminate\Support\MessageBag;
*/ */
interface JournalRepositoryInterface interface JournalRepositoryInterface
{ {
/** @noinspection MoreThanThreeArgumentsInspection */
/** /**
* @param TransactionJournal $journal * @param TransactionJournal $journal
* @param TransactionType $type * @param TransactionType $type

View File

@@ -84,6 +84,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface
* @param int $id * @param int $id
* *
* @return LinkType * @return LinkType
* @deprecated
*/ */
public function find(int $id): LinkType public function find(int $id): LinkType
{ {

View File

@@ -530,7 +530,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
*/ */
private function updateNote(PiggyBank $piggyBank, string $note): bool private function updateNote(PiggyBank $piggyBank, string $note): bool
{ {
if (0 === \strlen($note)) { if ('' === $note) {
$dbNote = $piggyBank->notes()->first(); $dbNote = $piggyBank->notes()->first();
if (null !== $dbNote) { if (null !== $dbNote) {
$dbNote->delete(); $dbNote->delete();

View File

@@ -107,12 +107,12 @@ class RecurringRepository implements RecurringRepositoryInterface
$return = 0; $return = 0;
/** @var RecurrenceTransactionMeta $meta */ /** @var RecurrenceTransactionMeta $meta */
foreach ($recurrenceTransaction->recurrenceTransactionMeta as $meta) { foreach ($recurrenceTransaction->recurrenceTransactionMeta as $meta) {
if ($meta->name === 'budget_id') { if ('budget_id' === $meta->name) {
$return = (int)$meta->value; $return = (int)$meta->value;
} }
} }
return $return === 0 ? null : $return; return 0 === $return ? null : $return;
} }
/** /**
@@ -127,12 +127,12 @@ class RecurringRepository implements RecurringRepositoryInterface
$return = ''; $return = '';
/** @var RecurrenceTransactionMeta $meta */ /** @var RecurrenceTransactionMeta $meta */
foreach ($recurrenceTransaction->recurrenceTransactionMeta as $meta) { foreach ($recurrenceTransaction->recurrenceTransactionMeta as $meta) {
if ($meta->name === 'category_name') { if ('category_name' === $meta->name) {
$return = (string)$meta->value; $return = (string)$meta->value;
} }
} }
return $return === '' ? null : $return; return '' === $return ? null : $return;
} }
/** /**
@@ -158,9 +158,8 @@ class RecurringRepository implements RecurringRepositoryInterface
if (null !== $end) { if (null !== $end) {
$query->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00')); $query->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00'));
} }
$result = $query->get(['transaction_journals.*']);
return $result; return $query->get(['transaction_journals.*']);
} }
/** /**
@@ -210,7 +209,7 @@ class RecurringRepository implements RecurringRepositoryInterface
Log::debug('Rep is daily. Start of loop.'); Log::debug('Rep is daily. Start of loop.');
while ($mutator <= $end) { while ($mutator <= $end) {
Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d')));
if ($attempts % $skipMod === 0) { if (0 === $attempts % $skipMod) {
Log::debug(sprintf('Attempts modulo skipmod is zero, include %s', $mutator->format('Y-m-d'))); Log::debug(sprintf('Attempts modulo skipmod is zero, include %s', $mutator->format('Y-m-d')));
$return[] = clone $mutator; $return[] = clone $mutator;
} }
@@ -236,7 +235,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$mutator->addDays($dayDifference); $mutator->addDays($dayDifference);
Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d')));
while ($mutator <= $end) { while ($mutator <= $end) {
if ($attempts % $skipMod === 0 && $start->lte($mutator) && $end->gte($mutator)) { if (0 === $attempts % $skipMod && $start->lte($mutator) && $end->gte($mutator)) {
Log::debug('Date is in range of start+end, add to set.'); Log::debug('Date is in range of start+end, add to set.');
$return[] = clone $mutator; $return[] = clone $mutator;
} }
@@ -263,10 +262,10 @@ class RecurringRepository implements RecurringRepositoryInterface
Log::debug(sprintf('DoM corrected is %d', $domCorrected)); Log::debug(sprintf('DoM corrected is %d', $domCorrected));
$mutator->day = $domCorrected; $mutator->day = $domCorrected;
Log::debug(sprintf('Mutator is now %s.', $mutator->format('Y-m-d'))); Log::debug(sprintf('Mutator is now %s.', $mutator->format('Y-m-d')));
Log::debug(sprintf('$attempts %% $skipMod === 0 is %s', var_export($attempts % $skipMod === 0, true))); Log::debug(sprintf('$attempts %% $skipMod === 0 is %s', var_export(0 === $attempts % $skipMod, true)));
Log::debug(sprintf('$start->lte($mutator) is %s', var_export($start->lte($mutator), true))); Log::debug(sprintf('$start->lte($mutator) is %s', var_export($start->lte($mutator), true)));
Log::debug(sprintf('$end->gte($mutator) is %s', var_export($end->gte($mutator), true))); Log::debug(sprintf('$end->gte($mutator) is %s', var_export($end->gte($mutator), true)));
if ($attempts % $skipMod === 0 && $start->lte($mutator) && $end->gte($mutator)) { if (0 === $attempts % $skipMod && $start->lte($mutator) && $end->gte($mutator)) {
Log::debug(sprintf('ADD %s to return!', $mutator->format('Y-m-d'))); Log::debug(sprintf('ADD %s to return!', $mutator->format('Y-m-d')));
$return[] = clone $mutator; $return[] = clone $mutator;
} }
@@ -324,7 +323,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$tags = []; $tags = [];
/** @var RecurrenceMeta $meta */ /** @var RecurrenceMeta $meta */
foreach ($recurrence->recurrenceMeta as $meta) { foreach ($recurrence->recurrenceMeta as $meta) {
if ($meta->name === 'tags' && '' !== $meta->value) { if ('tags' === $meta->name && '' !== $meta->value) {
$tags = explode(',', $meta->value); $tags = explode(',', $meta->value);
} }
} }
@@ -417,7 +416,7 @@ class RecurringRepository implements RecurringRepositoryInterface
case 'daily': case 'daily':
while ($total < $count) { while ($total < $count) {
$mutator->addDay(); $mutator->addDay();
if ($attempts % $skipMod === 0) { if (0 === $attempts % $skipMod) {
$return[] = clone $mutator; $return[] = clone $mutator;
$total++; $total++;
} }
@@ -439,7 +438,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$mutator->addDays($dayDifference); $mutator->addDays($dayDifference);
while ($total < $count) { while ($total < $count) {
if ($attempts % $skipMod === 0) { if (0 === $attempts % $skipMod) {
$return[] = clone $mutator; $return[] = clone $mutator;
$total++; $total++;
} }
@@ -458,7 +457,7 @@ class RecurringRepository implements RecurringRepositoryInterface
while ($total < $count) { while ($total < $count) {
$domCorrected = min($dayOfMonth, $mutator->daysInMonth); $domCorrected = min($dayOfMonth, $mutator->daysInMonth);
$mutator->day = $domCorrected; $mutator->day = $domCorrected;
if ($attempts % $skipMod === 0) { if (0 === $attempts % $skipMod) {
$return[] = clone $mutator; $return[] = clone $mutator;
$total++; $total++;
} }
@@ -477,7 +476,7 @@ class RecurringRepository implements RecurringRepositoryInterface
while ($total < $count) { while ($total < $count) {
$string = sprintf('%s %s of %s %s', $counters[$parts[0]], $daysOfWeek[$parts[1]], $mutator->format('F'), $mutator->format('Y')); $string = sprintf('%s %s of %s %s', $counters[$parts[0]], $daysOfWeek[$parts[1]], $mutator->format('F'), $mutator->format('Y'));
$newCarbon = new Carbon($string); $newCarbon = new Carbon($string);
if ($attempts % $skipMod === 0) { if (0 === $attempts % $skipMod) {
$return[] = clone $newCarbon; $return[] = clone $newCarbon;
$total++; $total++;
} }
@@ -493,7 +492,7 @@ class RecurringRepository implements RecurringRepositoryInterface
} }
$obj = clone $date; $obj = clone $date;
while ($total < $count) { while ($total < $count) {
if ($attempts % $skipMod === 0) { if (0 === $attempts % $skipMod) {
$return[] = clone $obj; $return[] = clone $obj;
$total++; $total++;
} }

View File

@@ -264,7 +264,7 @@ class RuleRepository implements RuleRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }

View File

@@ -265,7 +265,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }

View File

@@ -223,7 +223,7 @@ class TagRepository implements TagRepositoryInterface
/** /**
* @param User $user * @param User $user
*/ */
public function setUser(User $user) public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
@@ -290,7 +290,7 @@ class TagRepository implements TagRepositoryInterface
$sum = bcadd($sum, app('steam')->positive((string)$journal->transaction_amount)); $sum = bcadd($sum, app('steam')->positive((string)$journal->transaction_amount));
} }
return (string)$sum; return $sum;
} }
/** /**
@@ -373,7 +373,7 @@ class TagRepository implements TagRepositoryInterface
/** @var Tag $tag */ /** @var Tag $tag */
foreach ($result as $tag) { foreach ($result as $tag) {
$tagsWithAmounts[$tag->id] = (string)$tag->amount_sum; $tagsWithAmounts[$tag->id] = (string)$tag->amount_sum;
$amount = \strlen($tagsWithAmounts[$tag->id]) ? $tagsWithAmounts[$tag->id] : '0'; $amount = '' !== $tagsWithAmounts[$tag->id] ? $tagsWithAmounts[$tag->id] : '0';
if (null === $min) { if (null === $min) {
$min = $amount; $min = $amount;
} }
@@ -396,17 +396,16 @@ class TagRepository implements TagRepositoryInterface
Log::debug(sprintf('The range is: %s', $range)); Log::debug(sprintf('The range is: %s', $range));
// each euro difference is this step in the scale: // each euro difference is this step in the scale:
$step = (float)$range !== 0.0 ? 8 / (float)$range : 0; $step = 0.0 !== (float)$range ? 8 / (float)$range : 0;
Log::debug(sprintf('The step is: %f', $step)); Log::debug(sprintf('The step is: %f', $step));
$return = []; $size = 12;
foreach ($result as $tag) { foreach ($result as $tag) {
if ($step === 0) { if (0 === $step) {
// easy: size is 12: // easy: size is 12:
$size = 12; $size = 12;
} }
if ($step !== 0) { if (0 !== $step) {
$amount = bcsub((string)$tag->amount_sum, $min); $amount = bcsub((string)$tag->amount_sum, $min);
Log::debug(sprintf('Work with amount %s for tag %s', $amount, $tag->tag)); Log::debug(sprintf('Work with amount %s for tag %s', $amount, $tag->tag));
$size = ((int)(float)$amount * $step) + 12; $size = ((int)(float)$amount * $step) + 12;
@@ -442,35 +441,4 @@ class TagRepository implements TagRepositoryInterface
return $tag; return $tag;
} }
/**
* @param array $range
* @param float $amount
* @param float $min
* @param float $max
*
* @return int
*/
private function cloudScale(array $range, float $amount, float $min, float $max): int
{
$amountDiff = $max - $min;
// no difference? Every tag same range:
if (0.0 === $amountDiff) {
return $range[0];
}
$diff = $range[1] - $range[0];
$step = 1;
if (0.0 !== $diff) {
$step = $amountDiff / $diff;
}
if (0.0 === $step) {
$step = 1;
}
$extra = $step / $amount;
return (int)($range[0] + $extra);
}
} }

View File

@@ -25,6 +25,7 @@ namespace FireflyIII\Repositories\User;
use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\Role; use FireflyIII\Models\Role;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Log; use Log;
@@ -49,9 +50,17 @@ class UserRepository implements UserRepositoryInterface
*/ */
public function attachRole(User $user, string $role): bool public function attachRole(User $user, string $role): bool
{ {
$admin = Role::where('name', 'owner')->first(); $roleObject = Role::where('name', $role)->first();
$user->attachRole($admin); if (null === $roleObject) {
$user->save(); return false;
}
try {
$user->roles()->attach($role);
} catch (QueryException $e) {
// don't care
Log::info(sprintf('Query exception when giving user a role: %s', $e->getMessage()));
}
return true; return true;
} }
@@ -76,8 +85,8 @@ class UserRepository implements UserRepositoryInterface
app('preferences')->setForUser($user, 'previous_email_' . date('Y-m-d-H-i-s'), $oldEmail); app('preferences')->setForUser($user, 'previous_email_' . date('Y-m-d-H-i-s'), $oldEmail);
// set undo and confirm token: // set undo and confirm token:
app('preferences')->setForUser($user, 'email_change_undo_token', (string)bin2hex(random_bytes(16))); app('preferences')->setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16)));
app('preferences')->setForUser($user, 'email_change_confirm_token', (string)bin2hex(random_bytes(16))); app('preferences')->setForUser($user, 'email_change_confirm_token', bin2hex(random_bytes(16)));
// update user // update user
$user->email = $newEmail; $user->email = $newEmail;
@@ -228,7 +237,7 @@ class UserRepository implements UserRepositoryInterface
$return['has_2fa'] = true; $return['has_2fa'] = true;
} }
$return['is_admin'] = $user->hasRole('owner'); $return['is_admin'] = $this->hasRole($user, 'owner');
$return['blocked'] = 1 === (int)$user->blocked; $return['blocked'] = 1 === (int)$user->blocked;
$return['blocked_code'] = $user->blocked_code; $return['blocked_code'] = $user->blocked_code;
$return['accounts'] = $user->accounts()->count(); $return['accounts'] = $user->accounts()->count();
@@ -263,7 +272,14 @@ class UserRepository implements UserRepositoryInterface
*/ */
public function hasRole(User $user, string $role): bool public function hasRole(User $user, string $role): bool
{ {
return $user->hasRole($role); /** @var Role $userRole */
foreach ($user->roles as $userRole) {
if ($userRole->name === $role) {
return true;
}
}
return false;
} }
/** /**

View File

@@ -46,11 +46,10 @@ use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough; use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Laravel\Passport\HasApiTokens; use Laravel\Passport\HasApiTokens;
use Log;
use Request; use Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -63,6 +62,9 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property bool $has2FA used in admin user controller. * @property bool $has2FA used in admin user controller.
* @property array $prefs used in admin user controller. * @property array $prefs used in admin user controller.
* @property mixed password * @property mixed password
* @property Collection roles
* @property string blocked_code
* @property bool blocked
*/ */
class User extends Authenticatable class User extends Authenticatable
{ {
@@ -127,30 +129,6 @@ class User extends Authenticatable
return $this->hasMany(Account::class); return $this->hasMany(Account::class);
} }
/**
* Alias to eloquent many-to-many relation's attach() method.
*
* Full credit goes to: https://github.com/Zizaco/entrust
*
* @param mixed $role
*/
public function attachRole($role)
{
if (\is_object($role)) {
$role = $role->getKey();
}
if (\is_array($role)) {
$role = $role['id'];
}
try {
$this->roles()->attach($role);
} catch (QueryException $e) {
// don't care
Log::info(sprintf('Query exception when giving user a role: %s', $e->getMessage()));
}
}
/** /**
* @codeCoverageIgnore * @codeCoverageIgnore
* Link to attachments * Link to attachments