Passed
Push — ft/pagefield ( db2ad6...f2722b )
by Ben
10:27
created

DynamicAttributes   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 12
c 1
b 0
f 0
dl 0
loc 44
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A all() 0 3 1
A fromRawValue() 0 9 4
A set() 0 3 1
A get() 0 3 1
A has() 0 3 1
A toJson() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Thinktomorrow\Chief\DynamicAttributes;
6
7
class DynamicAttributes
8
{
9
    /** @var array */
10
    private $values;
11
12
    public function __construct(array $values)
13
    {
14
        $this->values = $values;
15
    }
16
17
    public static function fromRawValue($value): self
18
    {
19
        if ($value instanceof self) {
20
            return $value;
21
        }
22
23
        $value = is_null($value) ? [] : (is_array($value) ? $value : json_decode($value, true));
24
25
        return new static((array) $value);
26
    }
27
28
    public function has(string $key): bool
29
    {
30
        return ($this->get($key, '__NOTFOUND__') !== '__NOTFOUND__');
31
    }
32
33
    public function get(string $key, $default = null)
34
    {
35
        return data_get($this->values, $key, $default);
36
    }
37
38
    public function set(string $key, $value)
39
    {
40
        data_set($this->values, $key, $value);
41
    }
42
43
    public function all()
44
    {
45
        return $this->values;
46
    }
47
48
    public function toJson(): string
49
    {
50
        return json_encode($this->all());
51
    }
52
}
53