Skip to content

Commit 403bd3c

Browse files
authored
Create Arrayable.php
1 parent 89239bd commit 403bd3c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/Traits/Arrayable.php

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
namespace ZhenMu\Support\Traits;
4+
5+
use Illuminate\Support\Arr;
6+
7+
trait Arrayable
8+
{
9+
protected array $attributes = [];
10+
11+
public static function makeAttribute(array $attributes = [])
12+
{
13+
$instance = new static();
14+
15+
$instance->attributes = $attributes;
16+
17+
return $instance;
18+
}
19+
20+
public function offsetExists(mixed $offset): bool
21+
{
22+
return Arr::has($this->attributes, $offset);
23+
}
24+
25+
public function offsetGet(mixed $offset): mixed
26+
{
27+
if ($value = Arr::get($this->attributes, $offset)) {
28+
if (is_array($value)) {
29+
return static::makeAttribute($value);
30+
}
31+
}
32+
33+
return $value ?? null;
34+
}
35+
36+
public function offsetSet(mixed $key, mixed $value): void
37+
{
38+
Arr::set($this->attributes, $key, $value);
39+
}
40+
41+
public function offsetUnset(mixed $offset): void
42+
{
43+
Arr::forget($this->attributes, $offset);
44+
}
45+
46+
public function __set(string $attribute, mixed $value): void
47+
{
48+
$this[$attribute] = $value;
49+
}
50+
51+
public function __get(string $attribute): mixed
52+
{
53+
return $this[$attribute];
54+
}
55+
56+
public function toArray()
57+
{
58+
return $this->attributes;
59+
}
60+
}

0 commit comments

Comments
 (0)