Test Failed
Pull Request — master (#160)
by Wilmer
02:22
created

FormModel::writeProperty()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 16
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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