Passed
Pull Request — master (#160)
by Wilmer
10:36
created

FormModel   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 360
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 9
Bugs 0 Features 0
Metric Value
eloc 117
c 9
b 0
f 0
dl 0
loc 360
ccs 140
cts 140
cp 1
rs 6
wmc 55

25 Methods

Rating   Name   Duplication   Size   Complexity  
A getAttributeValue() 0 3 1
A getAttributePlaceholders() 0 3 1
A getAttributeHints() 0 3 1
A getAttributeHint() 0 7 2
A getAttributePlaceholder() 0 7 2
A getAttributeLabel() 0 12 3
A getAttributeLabels() 0 3 1
A writeProperty() 0 16 2
A generateAttributeLabel() 0 4 1
A getInflector() 0 6 2
A getNestedAttributeValue() 0 14 2
A isValidated() 0 3 1
A getFormErrors() 0 3 1
A getFormName() 0 12 3
A hasAttribute() 0 3 1
A __construct() 0 4 1
A getRules() 0 3 1
A processValidationResult() 0 13 3
A addErrors() 0 5 3
A setAttribute() 0 21 6
A collectAttributes() 0 17 4
A createFormErrors() 0 9 2
A readProperty() 0 19 3
A getNestedAttribute() 0 16 3
A load() 0 22 5

How to fix   Complexity   

Complex Class

Complex classes like FormModel often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FormModel, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form;
6
7
use Closure;
8
use InvalidArgumentException;
9
use ReflectionClass;
10
use ReflectionNamedType;
11
use Stringable;
12
use Yiisoft\Strings\Inflector;
13
use Yiisoft\Strings\StringHelper;
14
use Yiisoft\Validator\PostValidationHookInterface;
15
use Yiisoft\Validator\ResultSet;
16
use Yiisoft\Validator\RulesProviderInterface;
17
18
use function array_key_exists;
19
use function explode;
20
use function is_subclass_of;
21
use function strpos;
22
23
/**
24
 * Form model represents an HTML form: its data, validation and presentation.
25
 */
26
abstract class FormModel implements FormModelInterface, PostValidationHookInterface, RulesProviderInterface
27
{
28
    protected string $formErrorsClass = FormErrors::class;
29
    private array $attributes;
30
    /** @psalm-var array<string, array<array-key, string>> */
31
    private array $attributesErrors = [];
32
    private FormErrorsInterface $formErrors;
33
    private ?Inflector $inflector = null;
34
    private bool $validated = false;
35
36 590
    public function __construct()
37
    {
38 590
        $this->attributes = $this->collectAttributes();
39 590
        $this->formErrors = $this->createFormErrors($this->formErrorsClass);
40 589
    }
41
42 174
    public function getAttributeHint(string $attribute): string
43
    {
44 174
        $attributeHints = $this->getAttributeHints();
45 174
        $hint = $attributeHints[$attribute] ?? '';
46 174
        $nestedAttributeHint = $this->getNestedAttributeValue('getAttributeHint', $attribute);
47
48 174
        return $nestedAttributeHint !== '' ? $nestedAttributeHint : $hint;
49
    }
50
51
    /**
52
     * @return string[]
53
     */
54 1
    public function getAttributeHints(): array
55
    {
56 1
        return [];
57
    }
58
59 183
    public function getAttributeLabel(string $attribute): string
60
    {
61 183
        $label = $this->generateAttributeLabel($attribute);
62 183
        $labels = $this->getAttributeLabels();
63
64 183
        if (array_key_exists($attribute, $labels)) {
65 2
            $label = $labels[$attribute];
66
        }
67
68 183
        $nestedAttributeLabel = $this->getNestedAttributeValue('getAttributeLabel', $attribute);
69
70 183
        return $nestedAttributeLabel !== '' ? $nestedAttributeLabel : $label;
71
    }
72
73
    /**
74
     * @return string[]
75
     */
76 181
    public function getAttributeLabels(): array
77
    {
78 181
        return [];
79
    }
80
81 157
    public function getAttributePlaceholder(string $attribute): string
82
    {
83 157
        $attributePlaceHolders = $this->getAttributePlaceholders();
84 157
        $placeholder = $attributePlaceHolders[$attribute] ?? '';
85 157
        $nestedAttributePlaceholder = $this->getNestedAttributeValue('getAttributePlaceholder', $attribute);
86
87 157
        return $nestedAttributePlaceholder !== '' ? $nestedAttributePlaceholder : $placeholder;
88
    }
89
90
    /**
91
     * @return string[]
92
     */
93 24
    public function getAttributePlaceholders(): array
94
    {
95 24
        return [];
96
    }
97
98
    /**
99
     * @return iterable|object|scalar|Stringable|null
100
     */
101 488
    public function getAttributeValue(string $attribute)
102
    {
103 488
        return $this->readProperty($attribute);
104
    }
105
106
    /**
107
     * @return FormErrorsInterface Get FormErrors object.
108
     */
109 194
    public function getFormErrors(): FormErrorsInterface
110
    {
111 194
        return $this->formErrors;
112
    }
113
114
    /**
115
     * @return string Returns classname without a namespace part or empty string when class is anonymous
116
     */
117 472
    public function getFormName(): string
118
    {
119 472
        if (strpos(static::class, '@anonymous') !== false) {
120 6
            return '';
121
        }
122
123 467
        $className = strrchr(static::class, '\\');
124 467
        if ($className === false) {
125 1
            return static::class;
126
        }
127
128 466
        return substr($className, 1);
129
    }
130
131 486
    public function hasAttribute(string $attribute): bool
132
    {
133 486
        return array_key_exists($attribute, $this->attributes);
134
    }
135
136
    /**
137
     * @param array $data
138
     * @param string|null $formName
139
     *
140
     * @return bool
141
     */
142 28
    public function load(array $data, ?string $formName = null): bool
143
    {
144 28
        $scope = $formName ?? $this->getFormName();
145
146
        /**
147
         * @psalm-var array<string, scalar|Stringable|null>
148
         */
149 28
        $values = [];
150
151 28
        if ($scope === '' && !empty($data)) {
152 3
            $values = $data;
153 26
        } elseif (isset($data[$scope])) {
154
            /** @var mixed */
155 25
            $values = $data[$scope];
156
        }
157
158
        /** @var array<string, scalar|Stringable|null> $values */
159 28
        foreach ($values as $name => $value) {
160 28
            $this->setAttribute($name, $value);
161
        }
162
163 28
        return $values !== [];
164
    }
165
166
    /**
167
     * @param iterable|object|scalar|Stringable|null $value
168
     *
169
     * @psalm-suppress PossiblyInvalidCast
170
     */
171 151
    public function setAttribute(string $name, $value): void
172
    {
173 151
        [$realName] = $this->getNestedAttribute($name);
174
175 151
        if (isset($this->attributes[$realName])) {
176 150
            switch ($this->attributes[$realName]) {
177 150
                case 'bool':
178 9
                    $this->writeProperty($name, (bool) $value);
179 9
                    break;
180 150
                case 'float':
181 1
                    $this->writeProperty($name, (float) $value);
182 1
                    break;
183 150
                case 'int':
184 54
                    $this->writeProperty($name, (int) $value);
185 54
                    break;
186 118
                case 'string':
187 95
                    $this->writeProperty($name, (string) $value);
188 95
                    break;
189
                default:
190 27
                    $this->writeProperty($name, $value);
191 27
                    break;
192
            }
193
        }
194 151
    }
195
196 41
    public function processValidationResult(ResultSet $resultSet): void
197
    {
198 41
        $this->validated = false;
199 41
        $this->formErrors->clear();
200
201
        /** @var array<array-key, Resultset> $resultSet */
202 41
        foreach ($resultSet as $attribute => $result) {
203 41
            if ($result->isValid() === false) {
204
                /** @psalm-suppress InvalidArgument */
205 37
                $this->addErrors([$attribute => $result->getErrors()]);
206
            }
207
        }
208 41
        $this->validated = true;
209 41
    }
210
211 164
    public function getRules(): array
212
    {
213 164
        return [];
214
    }
215
216
    /**
217
     * Returns the list of attribute types indexed by attribute names.
218
     *
219
     * By default, this method returns all non-static properties of the class.
220
     *
221
     * @return array list of attribute types indexed by attribute names.
222
     */
223 590
    protected function collectAttributes(): array
224
    {
225 590
        $class = new ReflectionClass($this);
226 590
        $attributes = [];
227
228 590
        foreach ($class->getProperties() as $property) {
229 590
            if ($property->isStatic()) {
230 27
                continue;
231
            }
232
233
            /** @var ReflectionNamedType|null $type */
234 590
            $type = $property->getType();
235
236 590
            $attributes[$property->getName()] = $type !== null ? $type->getName() : '';
237
        }
238
239 590
        return $attributes;
240
    }
241
242
    /**
243
     * @psalm-param array<string, array<array-key, string>> $items
244
     */
245 37
    private function addErrors(array $items): void
246
    {
247 37
        foreach ($items as $attribute => $errors) {
248 37
            foreach ($errors as $error) {
249 37
                $this->formErrors->addError($attribute, $error);
250
            }
251
        }
252 37
    }
253
254 590
    private function createFormErrors(string $formErrorsClass): FormErrorsInterface
255
    {
256 590
        $formErrorsClass = new $formErrorsClass();
257
258 590
        if (!$formErrorsClass instanceof FormErrorsInterface) {
259 1
            throw new InvalidArgumentException('Form errors class must implement ' . FormErrorsInterface::class);
260
        }
261
262 589
        return $formErrorsClass;
263
    }
264
265 183
    private function getInflector(): Inflector
266
    {
267 183
        if ($this->inflector === null) {
268 183
            $this->inflector = new Inflector();
269
        }
270 183
        return $this->inflector;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->inflector could return the type null which is incompatible with the type-hinted return Yiisoft\Strings\Inflector. Consider adding an additional type-check to rule them out.
Loading history...
271
    }
272
273
    /**
274
     * Generates a user friendly attribute label based on the give attribute name.
275
     *
276
     * This is done by replacing underscores, dashes and dots with blanks and changing the first letter of each word to
277
     * upper case.
278
     *
279
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
280
     *
281
     * @param string $name the column name.
282
     *
283
     * @return string the attribute label.
284
     */
285 183
    private function generateAttributeLabel(string $name): string
286
    {
287 183
        return StringHelper::uppercaseFirstCharacterInEachWord(
288 183
            $this->getInflector()->toWords($name)
289
        );
290
    }
291
292
    /**
293
     * @return iterable|scalar|Stringable|null
294
     *
295
     * @psalm-suppress MixedReturnStatement
296
     * @psalm-suppress MixedInferredReturnType
297
     * @psalm-suppress MissingClosureReturnType
298
     */
299 488
    private function readProperty(string $attribute)
300
    {
301 488
        $class = static::class;
302
303 488
        [$attribute, $nested] = $this->getNestedAttribute($attribute);
304
305 487
        if (!property_exists($class, $attribute)) {
306 1
            throw new InvalidArgumentException("Undefined property: \"$class::$attribute\".");
307
        }
308
309
        /** @psalm-suppress MixedMethodCall */
310 486
        $getter = static fn (FormModelInterface $class, string $attribute) => $nested === null
311 486
            ? $class->$attribute
312 486
            : $class->$attribute->getAttributeValue($nested);
313
314 486
        $getter = Closure::bind($getter, null, $this);
315
316
        /** @var Closure $getter */
317 486
        return $getter($this, $attribute);
318
    }
319
320
    /**
321
     * @param string $attribute
322
     * @param iterable|object|scalar|Stringable|null $value
323
     *
324
     * @psalm-suppress MissingClosureReturnType
325
     */
326 150
    private function writeProperty(string $attribute, $value): void
327
    {
328 150
        [$attribute, $nested] = $this->getNestedAttribute($attribute);
329
330
        /**
331
         * @psalm-suppress MissingClosureParamType
332
         * @psalm-suppress MixedMethodCall
333
         */
334 150
        $setter = static fn (FormModelInterface $class, string $attribute, $value) => $nested === null
335 150
            ? $class->$attribute = $value
336 150
            : $class->$attribute->setAttribute($nested, $value);
337
338 150
        $setter = Closure::bind($setter, null, $this);
339
340
        /** @var Closure $setter */
341 150
        $setter($this, $attribute, $value);
342 150
    }
343
344
    /**
345
     * @return string[]
346
     *
347
     * @psalm-return array{0: string, 1: null|string}
348
     */
349 510
    private function getNestedAttribute(string $attribute): array
350
    {
351 510
        if (strpos($attribute, '.') === false) {
352 509
            return [$attribute, null];
353
        }
354
355 6
        [$attribute, $nested] = explode('.', $attribute, 2);
356
357
        /** @var object|string */
358 6
        $attributeNested = $this->attributes[$attribute] ?? null;
359
360 6
        if (!is_subclass_of($attributeNested, self::class)) {
361 1
            throw new InvalidArgumentException("Attribute \"$attribute\" is not a nested attribute.");
362
        }
363
364 5
        return [$attribute, $nested];
365
    }
366
367 213
    private function getNestedAttributeValue(string $method, string $attribute): string
368
    {
369 213
        $result = '';
370
371 213
        [$attribute, $nested] = $this->getNestedAttribute($attribute);
372
373 213
        if ($nested !== null) {
374
            /** @var FormModelInterface $attributeNestedValue */
375 3
            $attributeNestedValue = $this->getAttributeValue($attribute);
376
            /** @var string */
377 3
            $result = $attributeNestedValue->$method($nested);
378
        }
379
380 213
        return $result;
381
    }
382
383 11
    public function isValidated(): bool
384
    {
385 11
        return $this->validated;
386
    }
387
}
388