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 Collection accountMeta
* @property bool encrypted
* @property int account_type_id
* @property Collection piggyBanks
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/

View File

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

View File

@@ -32,7 +32,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property User $user
* @property string $key
* @property int $user_id
* @property mixed status
* @property string status
* @property int id
*/
class ExportJob extends Model
{
@@ -53,7 +54,7 @@ class ExportJob extends Model
public static function routeBinder(string $value): ExportJob
{
if (auth()->check()) {
$key = trim($value);
$key = trim($value);
/** @var User $user */
$user = auth()->user();
/** @var ExportJob $exportJob */

View File

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

View File

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

View File

@@ -36,6 +36,12 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @property string $tag
* @property int $id
* @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
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -82,18 +82,6 @@ class AccountRepository implements AccountRepositoryInterface
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.
*
@@ -113,16 +101,6 @@ class AccountRepository implements AccountRepositoryInterface
return null;
}
/**
* @param Account $account
*
* @return Note|null
*/
public function getNote(Account $account): ?Note
{
return $account->notes()->first();
}
/**
* Get note text or null.
*
@@ -185,29 +163,6 @@ class AccountRepository implements AccountRepositoryInterface
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.
*
@@ -253,7 +208,7 @@ class AccountRepository implements AccountRepositoryInterface
/**
* @param User $user
*/
public function setUser(User $user)
public function setUser(User $user): void
{
$this->user = $user;
}
@@ -262,6 +217,7 @@ class AccountRepository implements AccountRepositoryInterface
* @param array $data
*
* @return Account
* @throws \FireflyIII\Exceptions\FireflyException
*/
public function store(array $data): Account
{
@@ -286,20 +242,4 @@ class AccountRepository implements AccountRepositoryInterface
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;
/**
* @param int $accountId
* Find by account number. Is used.
*
* @deprecated
* @return Account
*/
public function find(int $accountId): Account;
/**
* @param string $number
* @param array $types
*
@@ -70,15 +64,6 @@ interface AccountRepositoryInterface
*/
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 array $types
@@ -102,15 +87,6 @@ interface AccountRepositoryInterface
*/
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
*
@@ -147,13 +123,6 @@ interface AccountRepositoryInterface
*/
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.
*
@@ -191,15 +160,6 @@ interface AccountRepositoryInterface
*/
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.
*
@@ -237,12 +197,4 @@ interface AccountRepositoryInterface
* @return 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
*
* @return array
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array
{
@@ -182,7 +183,7 @@ class AccountTasker implements AccountTaskerInterface
/**
* @param User $user
*/
public function setUser(User $user)
public function setUser(User $user): void
{
$this->user = $user;
}
@@ -191,6 +192,7 @@ class AccountTasker implements AccountTaskerInterface
* @param Collection $transactions
*
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function groupByOpposing(Collection $transactions): array
{

View File

@@ -38,22 +38,6 @@ use Log;
*/
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
@@ -82,33 +66,6 @@ trait FindAccountsTrait
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 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));
return $account;
} else {
}
if ($account->name !== $name) {
Log::debug(sprintf('"%s" does not equal "%s"', $account->name, $name));
}
}
@@ -244,9 +202,11 @@ trait FindAccountsTrait
/**
* @return Account
*
* @throws FireflyException
*/
public function getCashAccount(): Account
{
/** @var AccountType $type */
$type = AccountType::where('type', AccountType::CASH)->first();
/** @var AccountFactory $factory */
$factory = app(AccountFactory::class);
@@ -267,7 +227,8 @@ trait FindAccountsTrait
if (AccountType::ASSET !== $account->accountType->type) {
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();
$accounts = $this->user->accounts()->where('account_type_id', $type->id)->get();
/** @var Account $current */

View File

@@ -37,6 +37,7 @@ use Storage;
/**
* Class AttachmentRepository.
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AttachmentRepository implements AttachmentRepositoryInterface
{
@@ -58,7 +59,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface
try {
unlink($file);
} 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();
@@ -78,21 +79,6 @@ class AttachmentRepository implements AttachmentRepositoryInterface
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
*
@@ -100,6 +86,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface
*/
public function findWithoutUser(int $id): Attachment
{
$attachment = Attachment::find($id);
if (null === $attachment) {
return new Attachment;

View File

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

View File

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

View File

@@ -89,7 +89,11 @@ class BudgetRepository implements BudgetRepositoryInterface
public function cleanupBudgets(): bool
{
// delete limits with amount 0:
BudgetLimit::where('amount', 0)->delete();
try {
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.
$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');
if (isset($count[$key])) {
// delete it!
BudgetLimit::find($budgetLimit->id)->delete();
try {
BudgetLimit::find($budgetLimit->id)->delete();
} catch (Exception $e) {
Log::debug(sprintf('Could not delete budget limit: %s', $e->getMessage()));
}
}
$count[$key] = true;
}
@@ -115,7 +123,6 @@ class BudgetRepository implements BudgetRepositoryInterface
* @param Carbon $end
*
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function collectBudgetInformation(Collection $budgets, Carbon $start, Carbon $end): array
{
@@ -249,6 +256,7 @@ class BudgetRepository implements BudgetRepositoryInterface
* @param int $budgetId
*
* @return Budget
* @deprecated
*/
public function find(int $budgetId): Budget
{
@@ -467,9 +475,8 @@ class BudgetRepository implements BudgetRepositoryInterface
$total = bcadd($availableBudget->amount, $total);
$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;
}
/** @noinspection MoreThanThreeArgumentsInspection */
/**
* 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.
@@ -658,6 +666,7 @@ class BudgetRepository implements BudgetRepositoryInterface
return $result;
}
/** @noinspection MoreThanThreeArgumentsInspection */
/**
* @param TransactionCurrency $currency
* @param Carbon $start
@@ -688,11 +697,12 @@ class BudgetRepository implements BudgetRepositoryInterface
/**
* @param User $user
*/
public function setUser(User $user)
public function setUser(User $user): void
{
$this->user = $user;
}
/** @noinspection MoreThanThreeArgumentsInspection */
/**
* @param Collection $budgets
* @param Collection $accounts
@@ -842,17 +852,17 @@ class BudgetRepository implements BudgetRepositoryInterface
// find any rule actions related to budgets, with this budget name, and update them accordingly.
$types = [
$types = [
'set_budget',
];
$actions = RuleAction::leftJoin('rules', 'rules.id', '=', 'rule_actions.rule_id')
->where('rules.user_id', $this->user->id)
->whereIn('rule_actions.action_type', $types)
->where('rule_actions.action_value', $oldName)
->get(['rule_actions.*']);
->where('rules.user_id', $this->user->id)
->whereIn('rule_actions.action_type', $types)
->where('rule_actions.action_value', $oldName)
->get(['rule_actions.*']);
Log::debug(sprintf('Found %d actions to update.', $actions->count()));
/** @var RuleAction $action */
foreach($actions as $action) {
foreach ($actions as $action) {
$action->action_value = $data['name'];
$action->save();
Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value));
@@ -915,6 +925,7 @@ class BudgetRepository implements BudgetRepositoryInterface
return $budgetLimit;
}
/** @noinspection MoreThanThreeArgumentsInspection */
/**
* @param Budget $budget
* @param Carbon $start

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -95,8 +95,9 @@ class ImportJobRepository implements ImportJobRepositoryInterface
*
* @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['done'] += $steps;
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
*/
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);
$total = (int)($extended['steps'] ?? 0);
$total += $steps;
@@ -136,7 +138,7 @@ class ImportJobRepository implements ImportJobRepositoryInterface
->where('name', 'importHash')
->count();
return (int)$count;
return $count;
}
/**
@@ -309,12 +311,12 @@ class ImportJobRepository implements ImportJobRepositoryInterface
// verify content:
$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()));
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)));
return false;
@@ -472,7 +474,7 @@ class ImportJobRepository implements ImportJobRepositoryInterface
/**
* @param User $user
*/
public function setUser(User $user)
public function setUser(User $user): void
{
$this->user = $user;
}
@@ -480,12 +482,11 @@ class ImportJobRepository implements ImportJobRepositoryInterface
/**
* Handle upload for job.
*
* @param ImportJob $job
* @param string $name
* @param UploadedFile $file
* @param ImportJob $job
* @param string $name
* @param string $fileName
*
* @return MessageBag
* @throws FireflyException
*/
public function storeCLIUpload(ImportJob $job, string $name, string $fileName): MessageBag
{
@@ -538,7 +539,6 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* @param UploadedFile $file
*
* @return MessageBag
* @throws FireflyException
*/
public function storeFileUpload(ImportJob $job, string $name, UploadedFile $file): MessageBag
{
@@ -607,7 +607,6 @@ class ImportJobRepository implements ImportJobRepositoryInterface
* @param ImportJob $job
*
* @return string
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function uploadFileContents(ImportJob $job): string
{

View File

@@ -60,7 +60,7 @@ interface ImportJobRepositoryInterface
*
* @return ImportJob
*/
public function addStepsDone(ImportJob $job, int $steps = 1): ImportJob;
public function addStepsDone(ImportJob $job, int $steps = null): ImportJob;
/**
* @param ImportJob $job
@@ -68,7 +68,7 @@ interface ImportJobRepositoryInterface
*
* @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.
@@ -125,7 +125,7 @@ interface ImportJobRepositoryInterface
*
* @return string
*/
public function getStatus(ImportJob $job);
public function getStatus(ImportJob $job): string;
/**
* @param ImportJob $job

View File

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

View File

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

View File

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

View File

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

View File

@@ -107,12 +107,12 @@ class RecurringRepository implements RecurringRepositoryInterface
$return = 0;
/** @var RecurrenceTransactionMeta $meta */
foreach ($recurrenceTransaction->recurrenceTransactionMeta as $meta) {
if ($meta->name === 'budget_id') {
if ('budget_id' === $meta->name) {
$return = (int)$meta->value;
}
}
return $return === 0 ? null : $return;
return 0 === $return ? null : $return;
}
/**
@@ -127,12 +127,12 @@ class RecurringRepository implements RecurringRepositoryInterface
$return = '';
/** @var RecurrenceTransactionMeta $meta */
foreach ($recurrenceTransaction->recurrenceTransactionMeta as $meta) {
if ($meta->name === 'category_name') {
if ('category_name' === $meta->name) {
$return = (string)$meta->value;
}
}
return $return === '' ? null : $return;
return '' === $return ? null : $return;
}
/**
@@ -158,9 +158,8 @@ class RecurringRepository implements RecurringRepositoryInterface
if (null !== $end) {
$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.');
while ($mutator <= $end) {
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')));
$return[] = clone $mutator;
}
@@ -236,7 +235,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$mutator->addDays($dayDifference);
Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d')));
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.');
$return[] = clone $mutator;
}
@@ -263,10 +262,10 @@ class RecurringRepository implements RecurringRepositoryInterface
Log::debug(sprintf('DoM corrected is %d', $domCorrected));
$mutator->day = $domCorrected;
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('$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')));
$return[] = clone $mutator;
}
@@ -324,7 +323,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$tags = [];
/** @var RecurrenceMeta $meta */
foreach ($recurrence->recurrenceMeta as $meta) {
if ($meta->name === 'tags' && '' !== $meta->value) {
if ('tags' === $meta->name && '' !== $meta->value) {
$tags = explode(',', $meta->value);
}
}
@@ -417,7 +416,7 @@ class RecurringRepository implements RecurringRepositoryInterface
case 'daily':
while ($total < $count) {
$mutator->addDay();
if ($attempts % $skipMod === 0) {
if (0 === $attempts % $skipMod) {
$return[] = clone $mutator;
$total++;
}
@@ -439,7 +438,7 @@ class RecurringRepository implements RecurringRepositoryInterface
$mutator->addDays($dayDifference);
while ($total < $count) {
if ($attempts % $skipMod === 0) {
if (0 === $attempts % $skipMod) {
$return[] = clone $mutator;
$total++;
}
@@ -458,7 +457,7 @@ class RecurringRepository implements RecurringRepositoryInterface
while ($total < $count) {
$domCorrected = min($dayOfMonth, $mutator->daysInMonth);
$mutator->day = $domCorrected;
if ($attempts % $skipMod === 0) {
if (0 === $attempts % $skipMod) {
$return[] = clone $mutator;
$total++;
}
@@ -477,7 +476,7 @@ class RecurringRepository implements RecurringRepositoryInterface
while ($total < $count) {
$string = sprintf('%s %s of %s %s', $counters[$parts[0]], $daysOfWeek[$parts[1]], $mutator->format('F'), $mutator->format('Y'));
$newCarbon = new Carbon($string);
if ($attempts % $skipMod === 0) {
if (0 === $attempts % $skipMod) {
$return[] = clone $newCarbon;
$total++;
}
@@ -493,7 +492,7 @@ class RecurringRepository implements RecurringRepositoryInterface
}
$obj = clone $date;
while ($total < $count) {
if ($attempts % $skipMod === 0) {
if (0 === $attempts % $skipMod) {
$return[] = clone $obj;
$total++;
}

View File

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

View File

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

View File

@@ -223,7 +223,7 @@ class TagRepository implements TagRepositoryInterface
/**
* @param User $user
*/
public function setUser(User $user)
public function setUser(User $user): void
{
$this->user = $user;
}
@@ -290,7 +290,7 @@ class TagRepository implements TagRepositoryInterface
$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 */
foreach ($result as $tag) {
$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) {
$min = $amount;
}
@@ -396,17 +396,16 @@ class TagRepository implements TagRepositoryInterface
Log::debug(sprintf('The range is: %s', $range));
// 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));
$return = [];
$size = 12;
foreach ($result as $tag) {
if ($step === 0) {
if (0 === $step) {
// easy: size is 12:
$size = 12;
}
if ($step !== 0) {
if (0 !== $step) {
$amount = bcsub((string)$tag->amount_sum, $min);
Log::debug(sprintf('Work with amount %s for tag %s', $amount, $tag->tag));
$size = ((int)(float)$amount * $step) + 12;
@@ -442,35 +441,4 @@ class TagRepository implements TagRepositoryInterface
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\Role;
use FireflyIII\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Log;
@@ -49,9 +50,17 @@ class UserRepository implements UserRepositoryInterface
*/
public function attachRole(User $user, string $role): bool
{
$admin = Role::where('name', 'owner')->first();
$user->attachRole($admin);
$user->save();
$roleObject = Role::where('name', $role)->first();
if (null === $roleObject) {
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;
}
@@ -76,8 +85,8 @@ class UserRepository implements UserRepositoryInterface
app('preferences')->setForUser($user, 'previous_email_' . date('Y-m-d-H-i-s'), $oldEmail);
// set undo and confirm token:
app('preferences')->setForUser($user, 'email_change_undo_token', (string)bin2hex(random_bytes(16)));
app('preferences')->setForUser($user, 'email_change_confirm_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', bin2hex(random_bytes(16)));
// update user
$user->email = $newEmail;
@@ -228,7 +237,7 @@ class UserRepository implements UserRepositoryInterface
$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_code'] = $user->blocked_code;
$return['accounts'] = $user->accounts()->count();
@@ -263,7 +272,14 @@ class UserRepository implements UserRepositoryInterface
*/
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,23 +46,25 @@ use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Laravel\Passport\HasApiTokens;
use Log;
use Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Class User.
*
* @property int $id
* @property string $email
* @property bool $isAdmin used in admin user controller.
* @property bool $has2FA used in admin user controller.
* @property array $prefs used in admin user controller.
* @property mixed password
* @property int $id
* @property string $email
* @property bool $isAdmin used in admin user controller.
* @property bool $has2FA used in admin user controller.
* @property array $prefs used in admin user controller.
* @property mixed password
* @property Collection roles
* @property string blocked_code
* @property bool blocked
*/
class User extends Authenticatable
{
@@ -127,30 +129,6 @@ class User extends Authenticatable
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
* Link to attachments