1 | <?php |
||
2 | |||
3 | namespace Silk\Meta; |
||
4 | |||
5 | use Silk\Support\Collection; |
||
6 | |||
7 | /** |
||
8 | * @property-read string $type |
||
9 | * @property-read int $id |
||
10 | */ |
||
11 | class ObjectMeta |
||
12 | { |
||
13 | /** |
||
14 | * Object type |
||
15 | * @var string |
||
16 | */ |
||
17 | protected $type; |
||
18 | |||
19 | /** |
||
20 | * Object ID |
||
21 | * @var int |
||
22 | */ |
||
23 | protected $id; |
||
24 | |||
25 | /** |
||
26 | * ObjectMeta constructor. |
||
27 | * |
||
28 | * @param string $type Object type |
||
29 | * @param int $id Object ID |
||
30 | */ |
||
31 | public function __construct($type, $id) |
||
32 | { |
||
33 | $this->type = $type; |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
34 | $this->id = (int) $id; |
||
0 ignored issues
–
show
|
|||
35 | } |
||
36 | |||
37 | /** |
||
38 | * Get meta object for the key. |
||
39 | * |
||
40 | * @param string $key meta key |
||
41 | * |
||
42 | * @return Meta |
||
43 | */ |
||
44 | public function get($key) |
||
45 | { |
||
46 | return new Meta($this->type, $this->id, $key); |
||
47 | } |
||
48 | |||
49 | /** |
||
50 | * Set the value for the given key. |
||
51 | * |
||
52 | * @param string $key Meta key |
||
53 | * @param mixed $value New meta value |
||
54 | * |
||
55 | * @return $this |
||
56 | */ |
||
57 | public function set($key, $value) |
||
58 | { |
||
59 | $this->get($key)->set($value); |
||
60 | |||
61 | return $this; |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * Get all meta for the object as a Collection. |
||
66 | * |
||
67 | * @return Collection |
||
68 | */ |
||
69 | public function collect() |
||
70 | { |
||
71 | return Collection::make($this->toArray())->map(function ($value, $key) { |
||
72 | return new Meta($this->type, $this->id, $key); |
||
73 | }); |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Get the representation of the instance as an array. |
||
78 | * |
||
79 | * @return array |
||
80 | */ |
||
81 | public function toArray() |
||
82 | { |
||
83 | return (array) get_metadata($this->type, $this->id, '', false); |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * Magic Getter. |
||
88 | * |
||
89 | * @param string $property Accessed property |
||
90 | * |
||
91 | * @return mixed |
||
92 | */ |
||
93 | public function __get($property) |
||
94 | { |
||
95 | return isset($this->$property) ? $this->$property : null; |
||
96 | } |
||
97 | } |
||
98 |