GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

OperationsRepository::setUser()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * OperationsRepository.php
4
 * Copyright (c) 2019 [email protected]
5
 *
6
 * This file is part of Firefly III (https://github.com/firefly-iii).
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License as
10
 * published by the Free Software Foundation, either version 3 of the
11
 * License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License
19
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
declare(strict_types=1);
23
24
namespace FireflyIII\Repositories\Category;
25
26
27
use Carbon\Carbon;
28
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
29
use FireflyIII\Models\TransactionType;
30
use FireflyIII\User;
31
use Illuminate\Support\Collection;
32
use Log;
33
34
/**
35
 *
36
 * Class OperationsRepository
37
 */
38
class OperationsRepository implements OperationsRepositoryInterface
39
{
40
    /** @var User */
41
    private $user;
42
43
    /**
44
     * Constructor.
45
     */
46
    public function __construct()
47
    {
48
        if ('testing' === config('app.env')) {
49
            Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
50
            die(__METHOD__);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
51
        }
52
    }
53
54
    /**
55
     * This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
56
     * which have the specified category set to them. It's grouped per currency, with as few details in the array
57
     * as possible. Amounts are always negative.
58
     *
59
     * First currency, then categories.
60
     *
61
     * @param Carbon          $start
62
     * @param Carbon          $end
63
     * @param Collection|null $accounts
64
     * @param Collection|null $categories
65
     *
66
     * @return array
67
     */
68
    public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
69
    {
70
        /** @var GroupCollectorInterface $collector */
71
        $collector = app(GroupCollectorInterface::class);
72
        $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL]);
73
        if (null !== $accounts && $accounts->count() > 0) {
74
            $collector->setAccounts($accounts);
75
        }
76
        if (null !== $categories && $categories->count() > 0) {
77
            $collector->setCategories($categories);
78
        }
79
        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
80
            $collector->setCategories($this->getCategories());
81
        }
82
        $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
83
        $journals = $collector->getExtractedJournals();
84
        $array    = [];
85
86
        foreach ($journals as $journal) {
87
            $currencyId   = (int)$journal['currency_id'];
88
            $categoryId   = (int)$journal['category_id'];
89
            $categoryName = (string)$journal['category_name'];
90
91
            // catch "no category" entries.
92
            if (0 === $categoryId) {
93
                continue;
94
            }
95
96
            // info about the currency:
97
            $array[$currencyId] = $array[$currencyId] ?? [
98
                    'categories'              => [],
99
                    'currency_id'             => $currencyId,
100
                    'currency_name'           => $journal['currency_name'],
101
                    'currency_symbol'         => $journal['currency_symbol'],
102
                    'currency_code'           => $journal['currency_code'],
103
                    'currency_decimal_places' => $journal['currency_decimal_places'],
104
                ];
105
106
            // info about the categories:
107
            $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [
108
                    'id'                   => $categoryId,
109
                    'name'                 => $categoryName,
110
                    'transaction_journals' => [],
111
                ];
112
113
            // add journal to array:
114
            // only a subset of the fields.
115
            $journalId = (int)$journal['transaction_journal_id'];
116
117
118
            $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [
119
                'amount'                   => app('steam')->negative($journal['amount']),
120
                'date'                     => $journal['date'],
121
                'source_account_id'        => $journal['source_account_id'],
122
                'budget_name'              => $journal['budget_name'],
123
                'source_account_name'      => $journal['source_account_name'],
124
                'destination_account_id' => $journal['destination_account_id'],
125
                'destination_account_name' => $journal['destination_account_name'],
126
                'description'              => $journal['description'],
127
                'transaction_group_id'     => $journal['transaction_group_id'],
128
            ];
129
130
        }
131
132
        return $array;
133
    }
134
135
    /**
136
     * This method returns a list of all the deposit transaction journals (as arrays) set in that period
137
     * which have the specified category set to them. It's grouped per currency, with as few details in the array
138
     * as possible. Amounts are always positive.
139
     *
140
     * @param Carbon          $start
141
     * @param Carbon          $end
142
     * @param Collection|null $accounts
143
     * @param Collection|null $categories
144
     *
145
     * @return array
146
     */
147
    public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
148
    {
149
        /** @var GroupCollectorInterface $collector */
150
        $collector = app(GroupCollectorInterface::class);
151
        $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::DEPOSIT]);
152
        if (null !== $accounts && $accounts->count() > 0) {
153
            $collector->setAccounts($accounts);
154
        }
155
        if (null !== $categories && $categories->count() > 0) {
156
            $collector->setCategories($categories);
157
        }
158
        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
159
            $collector->setCategories($this->getCategories());
160
        }
161
        $collector->withCategoryInformation()->withAccountInformation();
162
        $journals = $collector->getExtractedJournals();
163
        $array    = [];
164
165
        foreach ($journals as $journal) {
166
            $currencyId   = (int)$journal['currency_id'];
167
            $categoryId   = (int)$journal['category_id'];
168
            $categoryName = (string)$journal['category_name'];
169
170
            // catch "no category" entries.
171
            if (0 === $categoryId) {
172
                $categoryName = (string)trans('firefly.no_category');
173
            }
174
175
            // info about the currency:
176
            $array[$currencyId] = $array[$currencyId] ?? [
177
                    'categories'              => [],
178
                    'currency_id'             => $currencyId,
179
                    'currency_name'           => $journal['currency_name'],
180
                    'currency_symbol'         => $journal['currency_symbol'],
181
                    'currency_code'           => $journal['currency_code'],
182
                    'currency_decimal_places' => $journal['currency_decimal_places'],
183
                ];
184
185
            // info about the categories:
186
            $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [
187
                    'id'                   => $categoryId,
188
                    'name'                 => $categoryName,
189
                    'transaction_journals' => [],
190
                ];
191
192
            // add journal to array:
193
            // only a subset of the fields.
194
            $journalId = (int)$journal['transaction_journal_id'];
195
196
197
            $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [
198
                'amount'                   => app('steam')->positive($journal['amount']),
199
                'date'                     => $journal['date'],
200
                'source_account_id'        => $journal['source_account_id'],
201
                'destination_account_id'   => $journal['destination_account_id'],
202
                'source_account_name'      => $journal['source_account_name'],
203
                'destination_account_name' => $journal['destination_account_name'],
204
                'description'              => $journal['description'],
205
                'transaction_group_id'     => $journal['transaction_group_id'],
206
            ];
207
208
        }
209
210
        return $array;
211
    }
212
213
    /**
214
     * @param User $user
215
     */
216
    public function setUser(User $user): void
217
    {
218
        $this->user = $user;
219
    }
220
221
    /**
222
     * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative.
223
     *
224
     * @param Carbon          $start
225
     * @param Carbon          $end
226
     * @param Collection|null $accounts
227
     * @param Collection|null $categories
228
     *
229
     * @return array
230
     */
231
    public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
232
    {
233
        /** @var GroupCollectorInterface $collector */
234
        $collector = app(GroupCollectorInterface::class);
235
        $collector->setUser($this->user)->setRange($start, $end)
236
                  ->setTypes([TransactionType::WITHDRAWAL]);
237
238
        if (null !== $accounts && $accounts->count() > 0) {
239
            $collector->setAccounts($accounts);
240
        }
241
        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
242
            $categories = $this->getCategories();
243
        }
244
        $collector->setCategories($categories);
245
        $collector->withCategoryInformation();
246
        $journals = $collector->getExtractedJournals();
247
        $array    = [];
248
249
        foreach ($journals as $journal) {
250
            $currencyId                = (int)$journal['currency_id'];
251
            $array[$currencyId]        = $array[$currencyId] ?? [
252
                    'sum'                     => '0',
253
                    'currency_id'             => $currencyId,
254
                    'currency_name'           => $journal['currency_name'],
255
                    'currency_symbol'         => $journal['currency_symbol'],
256
                    'currency_code'           => $journal['currency_code'],
257
                    'currency_decimal_places' => (int)$journal['currency_decimal_places'],
258
                ];
259
            $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount']));
260
        }
261
262
        return $array;
263
    }
264
265
    /**
266
     * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive.
267
     *
268
     * @param Carbon          $start
269
     * @param Carbon          $end
270
     * @param Collection|null $accounts
271
     * @param Collection|null $categories
272
     *
273
     * @return array
274
     */
275
    public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
276
    {
277
        /** @var GroupCollectorInterface $collector */
278
        $collector = app(GroupCollectorInterface::class);
279
        $collector->setUser($this->user)->setRange($start, $end)
280
                  ->setTypes([TransactionType::DEPOSIT]);
281
282
        if (null !== $accounts && $accounts->count() > 0) {
283
            $collector->setAccounts($accounts);
284
        }
285
        if (null === $categories || (null !== $categories && 0 === $categories->count())) {
286
            $categories = $this->getCategories();
287
        }
288
        $collector->setCategories($categories);
289
        $journals = $collector->getExtractedJournals();
290
        $array    = [];
291
292
        foreach ($journals as $journal) {
293
            $currencyId                = (int)$journal['currency_id'];
294
            $array[$currencyId]        = $array[$currencyId] ?? [
295
                    'sum'                     => '0',
296
                    'currency_id'             => $currencyId,
297
                    'currency_name'           => $journal['currency_name'],
298
                    'currency_symbol'         => $journal['currency_symbol'],
299
                    'currency_code'           => $journal['currency_code'],
300
                    'currency_decimal_places' => $journal['currency_decimal_places'],
301
                ];
302
            $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($journal['amount']));
303
        }
304
305
        return $array;
306
    }
307
308
    /**
309
     * Returns a list of all the categories belonging to a user.
310
     *
311
     * @return Collection
312
     */
313
    private function getCategories(): Collection
314
    {
315
        /** @var Collection $set */
316
        $set = $this->user->categories()->get();
317
318
        return $set;
319
    }
320
}