HelpsLoopFunctions::checksPropertyExists()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\LoopFunctions\Traits;
6
7
trait HelpsLoopFunctions
8
{
9
    /**
10
     * Assign the value to the property or rescue.
11
     *
12
     * @param  int|string  $key
13
     * @param  mixed  $value
14
     * @param  mixed|null  $rescue
15
     * @return void
16
     *
17
     * @throws \ReflectionException
18
     */
19 18
    private function assignValue(int|string $key, mixed $value, mixed $rescue = null): void
20
    {
21 18
        if ($this->canAssignValue($key)) {
22 17
            rescue(
23 17
                fn () => $this->{$key} = $value,
24 17
                $rescue,
25 17
                config('loop-functions.log') ?? false
26 17
            );
27
        }
28
    }
29
30
    /**
31
     * @param  int|string  $key
32
     * @return bool
33
     *
34
     * @throws \ReflectionException
35
     */
36 18
    private function canAssignValue(int|string $key): bool
37
    {
38 18
        return is_string($key)
39 18
            && $this->checksPropertyExists($key)
40 18
            && (empty($this->{$key}) || $this->hasDefaultValue($key));
41
    }
42
43
    /**
44
     * @param  int|string  $key
45
     * @return bool
46
     */
47 18
    private function checksPropertyExists(int|string $key): bool
48
    {
49 18
        if ($this->allowsDynamicProperties()) {
50 17
            return true;
51
        }
52
53 1
        return property_exists($this, $key);
54
    }
55
56
    /**
57
     * @param  int|string  $key
58
     * @return bool
59
     *
60
     * @throws \ReflectionException
61
     */
62 3
    private function hasDefaultValue(int|string $key): bool
63
    {
64 3
        $default = (new \ReflectionProperty($this, $key))
65 3
            ->getDefaultValue();
66
67 3
        return ! empty($default);
68
    }
69
70
    /**
71
     * @param  mixed  $value
72
     * @return bool
73
     */
74 9
    private function canWalkRecursively(mixed $value): bool
75
    {
76 9
        return is_iterable($value);
77
    }
78
79
    /**
80
     * @return bool
81
     */
82 18
    private function allowsDynamicProperties(): bool
83
    {
84 18
        return config('loop-functions.dynamic_properties', true);
85
    }
86
87
    /**
88
     * @return array
89
     */
90 18
    private function ignoredPropertyNames(): array
91
    {
92 18
        return config('loop-functions.ignore_keys', ['id', 'password']);
93
    }
94
}
95