forked from kriskbx/gitlab-time-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayAccessForGetterMethods.php
More file actions
96 lines (85 loc) · 2.21 KB
/
ArrayAccessForGetterMethods.php
File metadata and controls
96 lines (85 loc) · 2.21 KB
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
<?php
namespace kriskbx\gtt\Helper;
trait ArrayAccessForGetterMethods
{
/**
* @return array
*/
protected function methodExceptions()
{
return @$this->methodExceptions ?: [];
}
/**
* @param string $offset
*
* @return string
*/
protected function getOffsetFunctionName($offset)
{
return "get" . ucfirst($offset);
}
/**
* @param string $offset
*
* @return void
*
* @throws \Exception
*/
public function offsetExists($offset)
{
if (in_array($offset, $this->methodExceptions()) || ! method_exists($this,
$this->getOffsetFunctionName($offset))
) {
throw new \Exception("Offset '{$offset}' doesn't exist.");
}
}
/**
* @param string $offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return call_user_func([$this, $this->getOffsetFunctionName($offset)]);
}
/**
* @param string $offset
* @param mixed $value
*
* @return mixed
*/
public function offsetSet($offset, $value)
{
return call_user_func_array([$this, $this->getOffsetFunctionName($offset)], [$value]);
}
/**
* @param string $offset
*
* @return mixed
*/
public function offsetUnset($offset)
{
return call_user_func_array([$this, $this->getOffsetFunctionName($offset)], [null]);
}
/**
* @return array
*/
public function toArray()
{
$reflection = new \ReflectionObject($this);
$methods = collect($reflection->getMethods(\ReflectionMethod::IS_PUBLIC));
return $methods
->filter(function ($method) {
return substr($method->name, 0, 3) == "get"
&& ! in_array(snake_case(str_replace('get', '', $method->name)), $this->methodExceptions());
})
->map(function ($method) {
return [
'key' => snake_case(str_replace('get', '', $method->name)),
'value' => call_user_func([$this, $method->name])
];
})
->pluck('value', 'key')
->firstLevelToArray();
}
}