Passed
Push — master ( 6df7c9...74bc2a )
by y
02:15
created

AttributesTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 9
c 0
b 0
f 0
dl 0
loc 57
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A offsetUnset() 0 2 1
A offsetSet() 0 2 1
A offsetExists() 0 2 2
A offsetGet() 0 2 1
A setAttributes() 0 3 1
A getAttributes() 0 2 2
1
<?php
2
3
namespace Helix\DB;
4
5
/**
6
 * Forwards `ArrayAccess` to an EAV array property named `$attributes`.
7
 *
8
 * `ArrayAccess` must be implemented by the class using this trait.
9
 * The `$attributes` property must also be defined in the class,
10
 * and annotated with `@eav TABLE`.
11
 *
12
 * The instance must have its attributes loaded before use as an array,
13
 * otherwise existing EAV data may be lost when the instance is saved.
14
 * Attribute loading is done automatically by {@link Record}.
15
 *
16
 * @see Record::load()
17
 */
18
trait AttributesTrait {
19
20
    /**
21
     * Override this property with your own annotation.
22
     *
23
     * The property must remain `null` when not in use.
24
     *
25
     * @eav EAV_TABLE
26
     * @var array
27
     */
28
    protected $attributes;
29
30
    /**
31
     * @return array
32
     */
33
    public function getAttributes (): array {
34
        return $this->attributes ?: [];
35
    }
36
37
    /**
38
     * @param mixed $attr
39
     * @return bool
40
     */
41
    public function offsetExists ($attr): bool {
42
        return $this->attributes and array_key_exists($attr, $this->attributes);
43
    }
44
45
    /**
46
     * @param mixed $attr
47
     * @return null|mixed
48
     */
49
    public function offsetGet ($attr) {
50
        return $this->attributes[$attr] ?? null;
51
    }
52
53
    /**
54
     * @param mixed $attr
55
     * @param mixed $value
56
     */
57
    public function offsetSet ($attr, $value): void {
58
        $this->attributes[$attr] = $value;
59
    }
60
61
    /**
62
     * @param mixed $attr
63
     */
64
    public function offsetUnset ($attr): void {
65
        unset($this->attributes[$attr]);
66
    }
67
68
    /**
69
     * @param array $attributes
70
     * @return $this
71
     */
72
    public function setAttributes (array $attributes) {
73
        $this->attributes = $attributes;
74
        return $this;
75
    }
76
}