Passed
Push — master ( 443842...86f0b2 )
by Joshua
05:55 queued 01:59
created

Content::fromArray()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 4
nop 1
dl 0
loc 20
ccs 0
cts 18
cp 0
crap 20
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SeamsCMS\Delivery\Model;
6
7
class Content
8
{
9
    use HydratorTrait {
10
        fromArray as fromArrayTrait;
11
    }
12
13
    /** @var array */
14
    private $content;
15
16
    /**
17
     * @param string $field
18
     * @param string|null $locale
19
     * @param string|null $fallbackLocale
20
     *
21
     * @return scalar|Content|Content[]|null
22
     */
23
    public function get($field, string $locale = null, string $fallbackLocale = null)
24
    {
25
        if ($locale && $this->has($field, $locale)) {
26
            return $this->content[$field]['locales'][$locale];
27
        }
28
29
        if ($fallbackLocale && $this->has($field, $fallbackLocale)) {
30
            return $this->content[$field]['locales'][$fallbackLocale];
31
        } elseif ($this->has($field)) {
32
            return $this->content[$field]['value'];
33
        }
34
35
        return null;
36
    }
37
38
    /**
39
     * @param string $field
40
     * @param string|null $locale
41
     *
42
     * @return bool
43
     */
44
    public function has(string $field, string $locale = null): bool
45
    {
46
        if ($locale) {
47
            return isset($this->content[$field]['locales'][$locale]);
48
        }
49
50
        return isset($this->content[$field]['value']);
51
    }
52
53
    /**
54
     * @param string $field
55
     *
56
     * @return bool True if the field exists and is localized, false otherwise
57
     */
58
    public function isLocalized(string $field): bool
59
    {
60
        return !empty($this->content[$field]['locales']);
61
    }
62
63
    /**
64
     * @param array $data
65
     * @return Content
66
     */
67
    public static function fromArray(array $data)
68
    {
69
        $data['meta'] = ContentMeta::fromArray($data['meta']);
70
71
        foreach ($data['content'] as $key => $item) {
72
            if (is_array($item['value'])) {
73
                if (isset($item['value']['meta'])) {
74
                    $data['content'][$key]['value'] = Content::fromArray($item['value']);
75
                } else {
76
                    $data['content'][$key]['value'] = array_map(
77
                        function ($value) {
78
                            return Content::fromArray($value);
79
                        },
80
                        $item['value']
81
                    );
82
                }
83
            }
84
        }
85
86
        return self::fromArrayTrait($data);
87
    }
88
}
89