Conditions | 11 |
Paths | 7 |
Total Lines | 39 |
Code Lines | 15 |
Lines | 0 |
Ratio | 0 % |
Tests | 1 |
CRAP Score | 11 |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php declare(strict_types=1); |
||
19 | function validate_array(array $data, array $fields, ?string $exception = null): bool |
||
20 | { |
||
21 | $isInt = count(array_filter(array_keys($fields), 'is_int')) === count($fields); |
||
22 | 1 | ||
23 | foreach ($fields as $field => $type) { |
||
24 | if ($isInt) { |
||
25 | $field = $type; |
||
26 | assert(is_string($field)); |
||
27 | } |
||
28 | |||
29 | /** @psalm-suppress PossiblyInvalidArrayOffset */ |
||
30 | if ((! isset($data[$field]) && // This is faster, |
||
31 | // but it will also return false on fields which |
||
32 | // value is null, so calling array_key_exists when that happens. |
||
33 | ! array_key_exists($field, $data)) || |
||
34 | ( |
||
35 | ! $isInt && ( |
||
36 | ( |
||
37 | is_string($type) && gettype($data[$field]) !== $type |
||
38 | ) || |
||
39 | ( |
||
40 | is_array($type) && ! in_array(gettype($data[$field]), $type, true) |
||
41 | ) |
||
42 | ) |
||
43 | ) |
||
44 | ) { |
||
45 | if ($exception === null) { |
||
46 | return false; |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * @psalm-suppress InvalidThrow |
||
51 | * @psalm-suppress InvalidStringClass |
||
52 | */ |
||
53 | throw new $exception($data, $field); |
||
54 | } |
||
55 | } |
||
56 | |||
57 | return true; |
||
58 | } |
||
59 |