Test Failed
Pull Request — master (#272)
by Sergei
03:01
created

FormModel::makePathString()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form;
6
7
use InvalidArgumentException;
8
use ReflectionClass;
9
use ReflectionException;
10
use Yiisoft\Form\Exception\PropertyNotSupportNestedValuesException;
11
use Yiisoft\Form\Exception\StaticObjectPropertyException;
12
use Yiisoft\Form\Exception\UndefinedArrayElementException;
13
use Yiisoft\Form\Exception\UndefinedObjectPropertyException;
14
use Yiisoft\Form\Exception\ValueNotFoundException;
15
use Yiisoft\Hydrator\Validator\ValidatedInputTrait;
16
use Yiisoft\Strings\Inflector;
17
use Yiisoft\Strings\StringHelper;
18
19
use function array_key_exists;
20
use function array_slice;
21
use function is_array;
22
use function is_object;
23
use function str_contains;
24
use function strrchr;
25
use function substr;
26
27
/**
28
 * Form model represents an HTML form: its data, validation and presentation.
29
 */
30
abstract class FormModel implements FormModelInterface
31
{
32
    use ValidatedInputTrait;
33
34
    private const META_LABEL = 1;
35
    private const META_HINT = 2;
36
    private const META_PLACEHOLDER = 3;
37
38
    private static ?Inflector $inflector = null;
39
40
    /**
41
     * Returns the text hint for the specified attribute.
42 407
     *
43
     * @param string $attribute the attribute name.
44 407
     *
45
     * @return string the attribute hint.
46
     */
47
    public function getAttributeHint(string $attribute): string
48
    {
49
        return $this->readAttributeMetaValue(self::META_HINT, $attribute) ?? '';
50
    }
51
52
    /**
53
     * Returns the attribute hints.
54
     *
55
     * Attribute hints are mainly used for display purpose. For example, given an attribute `isPublic`, we can declare
56
     * a hint `Whether the post should be visible for not logged-in users`, which provides user-friendly description of
57
     * the attribute meaning and can be displayed to end users.
58
     *
59
     * Unlike label hint will not be generated, if its explicit declaration is omitted.
60
     *
61
     * Note, in order to inherit hints defined in the parent class, a child class needs to merge the parent hints with
62
     * child hints using functions such as `array_merge()`.
63 101
     *
64
     * @return array attribute hints (name => hint)
65 101
     *
66
     * @psalm-return array<string,string>
67
     */
68
    public function getAttributeHints(): array
69
    {
70
        return [];
71
    }
72
73
    /**
74
     * Returns the text label for the specified attribute.
75 206
     *
76
     * @param string $attribute The attribute name.
77 206
     *
78
     * @return string The attribute label.
79
     */
80
    public function getAttributeLabel(string $attribute): string
81
    {
82
        return $this->readAttributeMetaValue(self::META_LABEL, $attribute) ?? $this->generateAttributeLabel($attribute);
83
    }
84
85
    /**
86
     * Returns the attribute labels.
87
     *
88
     * Attribute labels are mainly used for display purpose. For example, given an attribute `firstName`, we can
89
     * declare a label `First Name` which is more user-friendly and can be displayed to end users.
90
     *
91
     * By default, an attribute label is generated automatically. This method allows you to
92
     * explicitly specify attribute labels.
93
     *
94
     * Note, in order to inherit labels defined in the parent class, a child class needs to merge the parent labels
95
     * with child labels using functions such as `array_merge()`.
96
     *
97
     * @return array attribute labels (name => label)
98 5
     *
99
     * {@see \Yiisoft\Form\FormModel::getAttributeLabel()}
100 5
     *
101
     * @psalm-return array<string,string>
102
     */
103
    public function getAttributeLabels(): array
104
    {
105
        return [];
106
    }
107
108
    /**
109
     * Returns the text placeholder for the specified attribute.
110 183
     *
111
     * @param string $attribute the attribute name.
112 183
     *
113
     * @return string the attribute placeholder.
114
     */
115 383
    public function getAttributePlaceholder(string $attribute): string
116
    {
117 383
        return $this->readAttributeMetaValue(self::META_PLACEHOLDER, $attribute) ?? '';
118
    }
119
120
    public function getAttributeValue(string $attribute): mixed
121
    {
122
        try {
123
            return $this->readAttributeValue($attribute);
124
        } catch (PropertyNotSupportNestedValuesException $exception) {
125
            return $exception->getValue() === null
126
                ? null
127 122
                : throw $exception;
128
        } catch (UndefinedArrayElementException) {
129 122
            return null;
130
        }
131
    }
132
133
    /**
134
     * Returns the attribute placeholders.
135
     *
136
     * @return array attribute placeholder (name => placeholder)
137
     *
138
     * @psalm-return array<string,string>
139
     */
140
    public function getAttributePlaceholders(): array
141
    {
142
        return [];
143
    }
144
145
    /**
146
     * Returns the form name that this model class should use.
147
     *
148 432
     * The form name is mainly used by {@see \Yiisoft\Form\Helper\HtmlForm} to determine how to name the input
149
     * fields for the attributes in a model.
150 432
     * If the form name is "A" and an attribute name is "b", then the corresponding input name would be "A[b]".
151 7
     * If the form name is an empty string, then the input name would be "b".
152
     *
153
     * The purpose of the above naming schema is that for forms which contain multiple different models, the attributes
154 426
     * of each model are grouped in sub-arrays of the POST-data, and it is easier to differentiate between them.
155 426
     *
156 1
     * By default, this method returns the model class name (without the namespace part) as the form name. You may
157
     * override it when the model is used in different forms.
158
     *
159 425
     * @return string The form name of this model class.
160
     */
161
    public function getFormName(): string
162
    {
163
        if (str_contains(static::class, '@anonymous')) {
164
            return '';
165 472
        }
166
167
        $className = strrchr(static::class, '\\');
168 472
        if ($className === false) {
169 4
            return static::class;
170 4
        }
171
172 470
        return substr($className, 1);
173
    }
174
175
    /**
176
     * If there is such attribute in the set.
177
     */
178
    public function hasAttribute(string $attribute): bool
179
    {
180
        try {
181
            $this->readAttributeValue($attribute);
182
        } catch (ValueNotFoundException) {
183 494
            return false;
184
        }
185 494
        return true;
186
    }
187 494
188 494
    public function isValid(): bool
189 494
    {
190 494
        return (bool) $this->getValidationResult()?->isValid();
191
    }
192 494
193 3
    /**
194
     * @throws UndefinedArrayElementException
195 2
     * @throws UndefinedObjectPropertyException
196 2
     * @throws StaticObjectPropertyException
197
     * @throws PropertyNotSupportNestedValuesException
198 1
     * @throws ValueNotFoundException
199
     */
200
    private function readAttributeValue(string $attribute): mixed
201 494
    {
202 494
        $path = $this->normalizePath($attribute);
203
204 494
        $value = $this;
205 5
        $keys = [[static::class, $this]];
206 5
        foreach ($path as $key) {
207
            $keys[] = [$key, $value];
208 492
209 1
            if (is_array($value)) {
210
                if (array_key_exists($key, $value)) {
211 492
                    $value = $value[$key];
212 492
                    continue;
213
                }
214
                throw new UndefinedArrayElementException($this->makePropertyPathString($keys));
215 492
            }
216 492
217
            if (is_object($value)) {
218
                $class = new ReflectionClass($value);
219 1
                try {
220 1
                    $property = $class->getProperty($key);
221 1
                } catch (ReflectionException) {
222 1
                    throw new UndefinedObjectPropertyException($this->makePropertyPathString($keys));
223
                }
224
                if ($property->isStatic()) {
225 489
                    throw new StaticObjectPropertyException($this->makePropertyPathString($keys));
226
                }
227
                if (PHP_VERSION_ID < 80100) {
228 442
                    $property->setAccessible(true);
229
                }
230 442
                $value = $property->getValue($value);
231
                continue;
232 442
            }
233 442
234 442
            array_pop($keys);
235 442
            throw new PropertyNotSupportNestedValuesException($this->makePropertyPathString($keys), $value);
236 442
        }
237 442
238 442
        return $value;
239 442
    }
240 442
241 442
    private function readAttributeMetaValue(int $metaKey, string $attribute): ?string
242 442
    {
243 442
        $path = $this->normalizePath($attribute);
244 214
245
        $value = $this;
246
        $n = 0;
247
        foreach ($path as $key) {
248 348
            if ($value instanceof self) {
249
                $nestedAttribute = implode('.', array_slice($path, $n));
250 348
                $data = match ($metaKey) {
251 3
                    self::META_LABEL => $value->getAttributeLabels(),
252 3
                    self::META_HINT => $value->getAttributeHints(),
253
                    self::META_PLACEHOLDER => $value->getAttributePlaceholders(),
254 345
                    default => throw new InvalidArgumentException('Invalid meta key.'),
255
                };
256
                if (array_key_exists($nestedAttribute, $data)) {
257
                    return $data[$nestedAttribute];
258 345
                }
259 345
            }
260
261
            $class = new ReflectionClass($value);
262 345
            try {
263 345
                $property = $class->getProperty($key);
264 341
            } catch (ReflectionException) {
265
                return null;
266
            }
267 4
            if ($property->isStatic()) {
268
                return null;
269
            }
270 1
271
            if (PHP_VERSION_ID < 80100) {
272
                $property->setAccessible(true);
273
            }
274
            /** @var mixed $value */
275
            $value = $property->getValue($value);
276
            if (!is_object($value)) {
277
                return null;
278
            }
279
280
            $n++;
281
        }
282
283
        return null;
284
    }
285 25
286
    /**
287 25
     * Generates a user-friendly attribute label based on the give attribute name.
288 1
     *
289
     * This is done by replacing underscores, dashes and dots with blanks and changing the first letter of each word to
290
     * upper case.
291 25
     *
292 25
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
293 25
     *
294
     * @param string $attribute The attribute name.
295
     *
296
     * @return string The attribute label.
297
     */
298
    private function generateAttributeLabel(string $attribute): string
299 500
    {
300
        if (self::$inflector === null) {
301 500
            self::$inflector = new Inflector();
302 500
        }
303
304
        return StringHelper::uppercaseFirstCharacterInEachWord(
305
            self::$inflector->toWords($attribute)
0 ignored issues
show
Bug introduced by
The method toWords() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

305
            self::$inflector->/** @scrutinizer ignore-call */ 
306
                              toWords($attribute)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
306
        );
307
    }
308 6
309
    /**
310 6
     * @return string[]
311
     */
312
    private function normalizePath(string $attribute): array
313
    {
314
        $attribute = str_replace(['][', '['], '.', rtrim($attribute, ']'));
315
        return StringHelper::parsePath($attribute);
316 7
    }
317
318 7
    /**
319 7
     * @psalm-param array<array-key, array{0:int|string, 1:mixed}> $keys
320 7
     */
321 7
    private function makePropertyPathString(array $keys): string
322 7
    {
323 1
        $path = '';
324 7
        foreach ($keys as $key) {
325
            if ($path !== '') {
326
                if (is_object($key[1])) {
327 7
                    $path .= '::' . $key[0];
328
                } elseif (is_array($key[1])) {
329
                    $path .= '[' . $key[0] . ']';
330 7
                }
331
            } else {
332
                $path = (string) $key[0];
333
            }
334
        }
335
        return $path;
336
    }
337
}
338