Test Failed
Pull Request — master (#186)
by
unknown
11:43
created

FormModel::getAttributeRawValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
362
                    $class->$attribute->setAttribute(implode('.', $nested), $value);
363 9
                } elseif (is_array($value)) {
364
                    $class->$attribute->load($value, '');
365
                } else {
366 9
                    throw new RuntimeException('$value must be array for using as nested attribute');
367
                }
368 9
            } else {
369 1
                $class->$attribute = $value;
370
            }
371
        };
372 8
373 1
        $closure = Closure::bind($setter, null, $this);
374
375
        /** @var Closure $closure */
376 7
        $closure($this, $attribute, $value, $nested);
377
    }
378
379 417
    /**
380
     * @return string[]
381 417
     *
382
     * @psalm-return array{0: string, 1: null|string[]}
383 417
     */
384
    private function getNestedAttribute(string $attribute, string ...$nested): array
385 417
    {
386
        if (!$nested) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $nested of type array<integer,string> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
387 3
            if (strpos($attribute, '.') === false) {
388
                return [$attribute, null];
389 3
            }
390
391
            $nested = explode('.', $attribute);
392 417
            $attribute = array_shift($nested);
393
        }
394
395 5
        /** @var string */
396
        $attributeNested = $this->attributes[$attribute] ?? '';
397 5
398
        if (!is_subclass_of($attributeNested, self::class)) {
399
            throw new InvalidArgumentException("Attribute \"$attribute\" is not a nested attribute.");
400
        }
401
402
        if (!property_exists($attributeNested, $nested[0])) {
403
            throw new InvalidArgumentException("Undefined property: \"$attributeNested::$nested[0]\".");
404
        }
405
406
        return [$attribute, $nested];
407
    }
408
409
    /**
410
     * @return iterable|object|scalar|Stringable|null
411
     */
412
    private function getNestedAttributeValue(string $method, string $attribute, string ...$nested)
413
    {
414
        $result = '';
415
416
        [$attribute, $nested] = $this->getNestedAttribute($attribute, ...$nested);
417
418
        if ($nested !== null) {
419
            /** @var FormModelInterface $attributeNestedValue */
420
            $attributeNestedValue = $this->getAttributeCastValue($attribute);
421
            /** @var string */
422
            $result = $attributeNestedValue->$method(...$nested);
423
        }
424
425
        return $result;
426
    }
427
428
    public function isValidated(): bool
429
    {
430
        return $this->validated;
431
    }
432
}
433