-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpresentablecollection.php
104 lines (87 loc) · 2.13 KB
/
presentablecollection.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
<?php
/**
* Presentable class
*
* This class is heavily based off of Machuga's Presenter bundle. https://github.com/machuga/laravel-presenter
*
* @author Shawn McCool <shawn@heybigname.com>
* @author Matthew Machuga
* @version 1.0
* @license MIT
*/
class PresentableCollection implements ArrayAccess, Iterator, Countable, Serializable
{
protected $_position = 0;
protected $container = array();
public static function to_array($presenter, $collection)
{
$instance = new static($presenter, $collection);
return (array) $instance->container;
}
public static function make($presenter, $collection)
{
return static::to_array($presenter, $collection);
}
public function __construct($presenter, $collection)
{
$this->container = array_map(function($item) use ($presenter)
{
return new $presenter($item);
}, $collection);
}
public function rewind()
{
$this->_position = 0;
}
public function current()
{
return $this->container[$this->_position];
}
public function key()
{
return $this->_position;
}
public function next()
{
++$this->_position;
}
public function valid()
{
return isset($this->container[$this->_position]);
}
public function count()
{
return count($this->container);
}
public function offsetSet($offset, $value)
{
if(is_null($offset))
{
$this->container[] = $value;
}
else
{
$this->container[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function serialize()
{
return serialize($this->container);
}
public function unserialize($collection)
{
$this->container = unserialize($collection);
}
}