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

DynamicAttributes::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 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