Passed
Pull Request — master (#272)
by Sergei
03:19
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
     *
43
     * @param string $attribute the attribute name.
44
     *
45
     * @return string the attribute hint.
46
     */
47 410
    public function getAttributeHint(string $attribute): string
48
    {
49 410
        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
     *
64
     * @return array attribute hints (name => hint)
65
     *
66
     * @psalm-return array<string,string>
67
     */
68 104
    public function getAttributeHints(): array
69
    {
70 104
        return [];
71
    }
72
73
    /**
74
     * Returns the text label for the specified attribute.
75
     *
76
     * @param string $attribute The attribute name.
77
     *
78
     * @return string The attribute label.
79
     */
80 209
    public function getAttributeLabel(string $attribute): string
81
    {
82 209
        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
     *
99
     * {@see \Yiisoft\Form\FormModel::getAttributeLabel()}
100
     *
101
     * @psalm-return array<string,string>
102
     */
103 8
    public function getAttributeLabels(): array
104
    {
105 8
        return [];
106
    }
107
108
    /**
109
     * Returns the text placeholder for the specified attribute.
110
     *
111
     * @param string $attribute the attribute name.
112
     *
113
     * @return string the attribute placeholder.
114
     */
115 183
    public function getAttributePlaceholder(string $attribute): string
116
    {
117 183
        return $this->readAttributeMetaValue(self::META_PLACEHOLDER, $attribute) ?? '';
118
    }
119
120 386
    public function getAttributeValue(string $attribute): mixed
121
    {
122 386
        return $this->readAttributeValue($attribute);
123
    }
124
125
    /**
126
     * Returns the attribute placeholders.
127
     *
128
     * @return array attribute placeholder (name => placeholder)
129
     *
130
     * @psalm-return array<string,string>
131
     */
132 122
    public function getAttributePlaceholders(): array
133
    {
134 122
        return [];
135
    }
136
137
    /**
138
     * Returns the form name that this model class should use.
139
     *
140
     * The form name is mainly used by {@see \Yiisoft\Form\Helper\HtmlForm} to determine how to name the input
141
     * fields for the attributes in a model.
142
     * If the form name is "A" and an attribute name is "b", then the corresponding input name would be "A[b]".
143
     * If the form name is an empty string, then the input name would be "b".
144
     *
145
     * The purpose of the above naming schema is that for forms which contain multiple different models, the attributes
146
     * of each model are grouped in sub-arrays of the POST-data, and it is easier to differentiate between them.
147
     *
148
     * By default, this method returns the model class name (without the namespace part) as the form name. You may
149
     * override it when the model is used in different forms.
150
     *
151
     * @return string The form name of this model class.
152
     */
153 435
    public function getFormName(): string
154
    {
155 435
        if (str_contains(static::class, '@anonymous')) {
156 7
            return '';
157
        }
158
159 429
        $className = strrchr(static::class, '\\');
160 429
        if ($className === false) {
161 1
            return static::class;
162
        }
163
164 428
        return substr($className, 1);
165
    }
166
167
    /**
168
     * If there is such attribute in the set.
169
     */
170 475
    public function hasAttribute(string $attribute): bool
171
    {
172
        try {
173 475
            $this->readAttributeValue($attribute);
174 4
        } catch (ValueNotFoundException) {
175 4
            return false;
176
        }
177 473
        return true;
178
    }
179
180
    public function isValid(): bool
181
    {
182
        return (bool) $this->getValidationResult()?->isValid();
183
    }
184
185
    /**
186
     * @throws UndefinedArrayElementException
187
     * @throws UndefinedObjectPropertyException
188
     * @throws StaticObjectPropertyException
189
     * @throws PropertyNotSupportNestedValuesException
190
     * @throws ValueNotFoundException
191
     */
192 497
    private function readAttributeValue(string $attribute): mixed
193
    {
194 497
        $path = $this->normalizePath($attribute);
195
196 497
        $value = $this;
197 497
        $keys = [[static::class, $this]];
198 497
        foreach ($path as $key) {
199 497
            $keys[] = [$key, $value];
200
201 497
            if (is_array($value)) {
202 4
                if (array_key_exists($key, $value)) {
203 2
                    $value = $value[$key];
204 2
                    continue;
205
                }
206 2
                throw new UndefinedArrayElementException($this->makePropertyPathString($keys));
207
            }
208
209 497
            if (is_object($value)) {
210 497
                $class = new ReflectionClass($value);
211
                try {
212 497
                    $property = $class->getProperty($key);
213 5
                } catch (ReflectionException) {
214 5
                    throw new UndefinedObjectPropertyException($this->makePropertyPathString($keys));
215
                }
216 495
                if ($property->isStatic()) {
217 1
                    throw new StaticObjectPropertyException($this->makePropertyPathString($keys));
218
                }
219 495
                if (PHP_VERSION_ID < 80100) {
220 495
                    $property->setAccessible(true);
221
                }
222 495
                $value = $property->getValue($value);
223 495
                continue;
224
            }
225
226 2
            array_pop($keys);
227 2
            throw new PropertyNotSupportNestedValuesException($this->makePropertyPathString($keys), $value);
228
        }
229
230 493
        return $value;
231
    }
232
233 445
    private function readAttributeMetaValue(int $metaKey, string $attribute): ?string
234
    {
235 445
        $path = $this->normalizePath($attribute);
236
237 445
        $value = $this;
238 445
        $n = 0;
239 445
        foreach ($path as $key) {
240 445
            if ($value instanceof self) {
241 445
                $nestedAttribute = implode('.', array_slice($path, $n));
242 445
                $data = match ($metaKey) {
243 445
                    self::META_LABEL => $value->getAttributeLabels(),
244 445
                    self::META_HINT => $value->getAttributeHints(),
245 445
                    self::META_PLACEHOLDER => $value->getAttributePlaceholders(),
246 445
                    default => throw new InvalidArgumentException('Invalid meta key.'),
247 445
                };
248 445
                if (array_key_exists($nestedAttribute, $data)) {
249 214
                    return $data[$nestedAttribute];
250
                }
251
            }
252
253 351
            $class = new ReflectionClass($value);
254
            try {
255 351
                $property = $class->getProperty($key);
256 3
            } catch (ReflectionException) {
257 3
                return null;
258
            }
259 348
            if ($property->isStatic()) {
260
                return null;
261
            }
262
263 348
            if (PHP_VERSION_ID < 80100) {
264 348
                $property->setAccessible(true);
265
            }
266
            /** @var mixed $value */
267 348
            $value = $property->getValue($value);
268 348
            if (!is_object($value)) {
269 344
                return null;
270
            }
271
272 4
            $n++;
273
        }
274
275 1
        return null;
276
    }
277
278
    /**
279
     * Generates a user-friendly attribute label based on the give attribute name.
280
     *
281
     * 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
     *
286
     * @param string $attribute The attribute name.
287
     *
288
     * @return string The attribute label.
289
     */
290 28
    private function generateAttributeLabel(string $attribute): string
291
    {
292 28
        if (self::$inflector === null) {
293 1
            self::$inflector = new Inflector();
294
        }
295
296 28
        return StringHelper::uppercaseFirstCharacterInEachWord(
297 28
            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

297
            self::$inflector->/** @scrutinizer ignore-call */ 
298
                              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...
298 28
        );
299
    }
300
301
    /**
302
     * @return string[]
303
     */
304 503
    private function normalizePath(string $attribute): array
305
    {
306 503
        $attribute = str_replace(['][', '['], '.', rtrim($attribute, ']'));
307 503
        return StringHelper::parsePath($attribute);
308
    }
309
310
    /**
311
     * @psalm-param array<array-key, array{0:int|string, 1:mixed}> $keys
312
     */
313 9
    private function makePropertyPathString(array $keys): string
314
    {
315 9
        $path = '';
316 9
        foreach ($keys as $key) {
317 9
            if ($path !== '') {
318 9
                if (is_object($key[1])) {
319 9
                    $path .= '::' . $key[0];
320 2
                } elseif (is_array($key[1])) {
321 9
                    $path .= '[' . $key[0] . ']';
322
                }
323
            } else {
324 9
                $path = (string) $key[0];
325
            }
326
        }
327 9
        return $path;
328
    }
329
}
330