-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Sheet.php
106 lines (83 loc) · 2.29 KB
/
Sheet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace Spatie\Sheets;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Support\Str;
use JsonSerializable;
class Sheet implements ArrayAccess, Arrayable, Jsonable, JsonSerializable
{
/** @var array */
protected $attributes;
public function __construct(array $attributes = [])
{
$this->attributes = $attributes;
}
public function __get(string $key)
{
return $this->getAttribute($key);
}
public function __set(string $key, $value)
{
$this->attributes[$key] = $value;
}
public function __isset(string $key)
{
return isset($this->attributes[$key]);
}
public function __unset(string $key)
{
unset($this->attributes[$key]);
}
public function __toString(): string
{
return $this->toJson();
}
public function offsetExists($key)
{
return ! is_null($this->getAttribute($key));
}
public function offsetGet($key)
{
return $this->getAttribute($key);
}
public function offsetSet($key, $value)
{
$this->$key = $value;
}
public function offsetUnset($key)
{
unset($this->attributes[$key]);
}
public function toArray(): array
{
$keys = array_keys($this->attributes);
return array_map(function (string $key) {
return $this->getAttribute($key);
}, array_combine($keys, $keys));
}
public function jsonSerialize(): array
{
return $this->toArray();
}
public function toJson($options = 0): string
{
$json = json_encode($this->jsonSerialize(), $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new JsonEncodingException(
'Error encoding sheet ['.get_class($this).'] to JSON: '.$message
);
}
return $json;
}
protected function getAttribute(string $key)
{
$value = $this->attributes[$key] ?? null;
$accessorFunctionName = 'get'.Str::studly($key).'Attribute';
if (method_exists($this, $accessorFunctionName)) {
return $this->$accessorFunctionName($value);
}
return $value;
}
}