RecurrenceUpdateRequest::getTransactionData()   F
last analyzed

Complexity

Conditions 12
Paths 514

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
c 0
b 0
f 0
dl 0
loc 37
rs 3.475
cc 12
nc 514
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * RecurrenceUpdateRequest.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\Api\V1\Requests;
25
26
use FireflyIII\Models\Recurrence;
27
use FireflyIII\Rules\BelongsUser;
28
use FireflyIII\Rules\IsBoolean;
29
use FireflyIII\Validation\RecurrenceValidation;
30
use FireflyIII\Validation\TransactionValidation;
31
use Illuminate\Validation\Validator;
32
33
/**
34
 * Class RecurrenceUpdateRequest
35
 */
36
class RecurrenceUpdateRequest extends Request
37
{
38
    use RecurrenceValidation, TransactionValidation;
0 ignored issues
show
introduced by James Cole
The trait FireflyIII\Validation\TransactionValidation requires some properties which are not provided by FireflyIII\Api\V1\Requests\RecurrenceUpdateRequest: $name, $sourceError, $destError, $transactionType, $account_id, $account, $type
Loading history...
introduced by James Cole
The trait FireflyIII\Validation\RecurrenceValidation requires some properties which are not provided by FireflyIII\Api\V1\Requests\RecurrenceUpdateRequest: $sourceError, $destError
Loading history...
39
40
    /**
41
     * Authorize logged in users.
42
     *
43
     * @return bool
44
     */
45
    public function authorize(): bool
46
    {
47
        // Only allow authenticated users
48
        return auth()->check();
49
    }
50
51
    /**
52
     * Get all data from the request.
53
     *
54
     * @return array
55
     */
56
    public function getAll(): array
57
    {
58
        $active     = null;
59
        $applyRules = null;
60
        if (null !== $this->get('active')) {
61
            $active = $this->boolean('active');
62
        }
63
        if (null !== $this->get('apply_rules')) {
64
            $applyRules = $this->boolean('apply_rules');
65
        }
66
        $return = [
67
            'recurrence'   => [
68
                'type'              => $this->nullableString('type'),
69
                'title'             => $this->nullableString('title'),
70
                'description'       => $this->nullableString('description'),
71
                'first_date'        => $this->date('first_date'),
72
                'notes'             => $this->nullableNlString('notes'),
73
                'repeat_until'      => $this->date('repeat_until'),
74
                'nr_of_repetitions' => $this->nullableInteger('nr_of_repetitions'),
75
                'apply_rules'       => $applyRules,
76
                'active'            => $active,
77
            ],
78
            'transactions' => $this->getTransactionData(),
79
            'repetitions'  => $this->getRepetitionData(),
80
        ];
81
82
        return $return;
83
    }
84
85
    /**
86
     * The rules that the incoming request must be matched against.
87
     *
88
     * @return array
89
     */
90
    public function rules(): array
91
    {
92
        /** @var Recurrence $recurrence */
93
        $recurrence = $this->route()->parameter('recurrence');
94
95
        return [
96
            'type'                  => 'in:withdrawal,transfer,deposit',
97
            'title'                 => sprintf('between:1,255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id),
98
            'description'           => 'between:1,65000',
99
            'first_date'            => 'date',
100
            'apply_rules'           => [new IsBoolean],
101
            'active'                => [new IsBoolean],
102
            'repeat_until'          => 'date',
103
            'nr_of_repetitions'     => 'numeric|between:1,31',
104
            'repetitions.*.type'    => 'in:daily,weekly,ndom,monthly,yearly',
105
            'repetitions.*.moment'  => 'between:0,10',
106
            'repetitions.*.skip'    => 'required|numeric|between:0,31',
107
            'repetitions.*.weekend' => 'required|numeric|min:1|max:4',
108
109
            'transactions.*.description'           => 'required|between:1,255',
110
            'transactions.*.amount'                => 'required|numeric|more:0',
111
            'transactions.*.foreign_amount'        => 'numeric|more:0',
112
            'transactions.*.currency_id'           => 'numeric|exists:transaction_currencies,id',
113
            'transactions.*.currency_code'         => 'min:3|max:3|exists:transaction_currencies,code',
114
            'transactions.*.foreign_currency_id'   => 'numeric|exists:transaction_currencies,id',
115
            'transactions.*.foreign_currency_code' => 'min:3|max:3|exists:transaction_currencies,code',
116
            'transactions.*.source_id'             => ['numeric', 'nullable', new BelongsUser],
117
            'transactions.*.source_name'           => 'between:1,255|nullable',
118
            'transactions.*.destination_id'        => ['numeric', 'nullable', new BelongsUser],
119
            'transactions.*.destination_name'      => 'between:1,255|nullable',
120
121
            // new and updated fields:
122
            'transactions.*.budget_id'             => ['mustExist:budgets,id', new BelongsUser],
123
            'transactions.*.budget_name'           => ['between:1,255', 'nullable', new BelongsUser],
124
            'transactions.*.category_id'           => ['mustExist:categories,id', new BelongsUser],
125
            'transactions.*.category_name'         => 'between:1,255|nullable',
126
            'transactions.*.piggy_bank_id'         => ['numeric', 'mustExist:piggy_banks,id', new BelongsUser],
127
            'transactions.*.piggy_bank_name'       => ['between:1,255', 'nullable', new BelongsUser],
128
            'transactions.*.tags'                  => 'between:1,64000',
129
130
        ];
131
    }
132
133
    /**
134
     * Configure the validator instance.
135
     *
136
     * @param Validator $validator
137
     *
138
     * @return void
139
     */
140
    public function withValidator(Validator $validator): void
141
    {
142
        $validator->after(
143
            function (Validator $validator) {
144
                $this->validateOneRecurrenceTransactionUpdate($validator);
145
                $this->validateOneRepetitionUpdate($validator);
146
                $this->validateRecurrenceRepetition($validator);
147
                $this->validateRepetitionMoment($validator);
148
                $this->validateForeignCurrencyInformation($validator);
149
                $this->valUpdateAccountInfo($validator);
150
            }
151
        );
152
    }
153
154
    /**
155
     * Returns the repetition data as it is found in the submitted data.
156
     *
157
     * @return array|null
158
     */
159
    private function getRepetitionData(): ?array
160
    {
161
        $return = [];
162
        // repetition data:
163
        /** @var array $repetitions */
164
        $repetitions = $this->get('repetitions');
165
        if (null === $repetitions) {
0 ignored issues
show
introduced by James Cole
The condition null === $repetitions is always false.
Loading history...
166
            return null;
167
        }
168
        /** @var array $repetition */
169
        foreach ($repetitions as $repetition) {
170
            $return[] = [
171
                'type'    => $repetition['type'],
172
                'moment'  => $repetition['moment'],
173
                'skip'    => (int)$repetition['skip'],
174
                'weekend' => (int)$repetition['weekend'],
175
            ];
176
        }
177
178
        return $return;
179
    }
180
181
    /**
182
     * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
183
     * standards but it just has a lot of ??-statements because of the fields that may or may not exist.
184
     *
185
     * @return array|null
186
     */
187
    private function getTransactionData(): ?array
188
    {
189
        $return = [];
190
        // transaction data:
191
        /** @var array $transactions */
192
        $transactions = $this->get('transactions');
193
        if (null === $transactions) {
0 ignored issues
show
introduced by James Cole
The condition null === $transactions is always false.
Loading history...
194
            return null;
195
        }
196
        /** @var array $transaction */
197
        foreach ($transactions as $transaction) {
198
            $return[] = [
199
                'amount'                => $transaction['amount'],
200
                'currency_id'           => isset($transaction['currency_id']) ? (int)$transaction['currency_id'] : null,
201
                'currency_code'         => $transaction['currency_code'] ?? null,
202
                'foreign_amount'        => $transaction['foreign_amount'] ?? null,
203
                'foreign_currency_id'   => isset($transaction['foreign_currency_id']) ? (int)$transaction['foreign_currency_id'] : null,
204
                'foreign_currency_code' => $transaction['foreign_currency_code'] ?? null,
205
                'source_id'             => isset($transaction['source_id']) ? (int)$transaction['source_id'] : null,
206
                'source_name'           => isset($transaction['source_name']) ? (string)$transaction['source_name'] : null,
207
                'destination_id'        => isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null,
208
                'destination_name'      => isset($transaction['destination_name']) ? (string)$transaction['destination_name'] : null,
209
                'description'           => $transaction['description'],
210
                'type'                  => $this->string('type'),
211
212
                // new and updated fields:
213
                'piggy_bank_id'         => isset($transaction['piggy_bank_id']) ? (int)$transaction['piggy_bank_id'] : null,
214
                'piggy_bank_name'       => $transaction['piggy_bank_name'] ?? null,
215
                'tags'                  => $transaction['tags'] ?? [],
216
                'budget_id'             => isset($transaction['budget_id']) ? (int)$transaction['budget_id'] : null,
217
                'budget_name'           => $transaction['budget_name'] ?? null,
218
                'category_id'           => isset($transaction['category_id']) ? (int)$transaction['category_id'] : null,
219
                'category_name'         => $transaction['category_name'] ?? null,
220
            ];
221
        }
222
223
        return $return;
224
    }
225
}
226