FieldHelper   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 38
ccs 13
cts 13
cp 1
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fieldMatches() 0 5 3
A findField() 0 14 6
1
<?php
2
3
namespace JoshGaber\NovaUnit\Fields;
4
5
use Laravel\Nova\Fields\Field;
6
use Laravel\Nova\Panel;
7
8
class FieldHelper
9
{
10
    /**
11
     * Finds the first field with a name or attribute matching the given name.
12
     *
13
     * @param array $fields The list of fields to search
14
     * @param string $fieldName The name or attribute of the field to match
15
     * @param bool $allowPanels Whether fields inside panels should also be searched
16
     * @return Field|null The first matching field if found, or null if not
17
     */
18 48
    public static function findField(array $fields, string $fieldName, bool $allowPanels = false): ?Field
19
    {
20 48
        foreach ($fields as $field) {
21 48
            if ($allowPanels && $field instanceof Panel) {
22 2
                $panelField = self::findField($field->data, $fieldName, $allowPanels);
23 2
                if ($panelField instanceof Field) {
24 2
                    return $panelField;
25
                }
26 48
            } elseif (self::fieldMatches($field, $fieldName)) {
27 48
                return $field;
28
            }
29
        }
30
31 5
        return null;
32
    }
33
34
    /**
35
     * Determines whether the given field has a name or attribute matching the provided field name.
36
     *
37
     * @param mixed $field The field
38
     * @param string $fieldName the field name or attribute to match
39
     * @return bool
40
     */
41 48
    public static function fieldMatches($field, string $fieldName): bool
42
    {
43 48
        return $field instanceof Field && (
44 48
            $field->attribute === $fieldName ||
45 48
            \mb_strtolower($field->name) === \mb_strtolower($fieldName)
46
        );
47
    }
48
}
49