earray.class.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Juju\Data;
  3. require_once(realpath(dirname(__DIR__).'/events.trait.php'));
  4. use Juju\Events;
  5. class EArray implements \ArrayAccess, \Countable, \Iterator, \Serializable, \JsonSerializable {
  6. use Events;
  7. protected $data = [];
  8. private $index = 0;
  9. public static function from(array $data){
  10. return new static($data);
  11. }
  12. protected function __construct(array $data){
  13. $this->data = $data;
  14. }
  15. public function offsetExists($offset){
  16. $this->fire('exists', $offset);
  17. return isset($this->data[$offset]);
  18. }
  19. public function offsetGet($offset){
  20. $this->fire('get', $offset);
  21. return $this->data[$offset];
  22. }
  23. public function offsetSet($offset, $value){
  24. $this->fire('set', $offset, $value);
  25. $this->data[$offset] = $value;
  26. }
  27. public function offsetUnset($offset){
  28. if($this->offsetExists($offset)){
  29. $this->fire('unset', $offset, $this[$offset]);
  30. unset($this->data[$offset]);
  31. }
  32. }
  33. public function count(){
  34. return count($this->data);
  35. }
  36. public function serialize(){
  37. return serialize($this->data);
  38. }
  39. public function unserialize($data){
  40. $this->data = unserialize($data);
  41. }
  42. public function JsonSerialize(){
  43. return $this->data;
  44. }
  45. public function each(callable $fn){
  46. foreach($this->data as $offset => $model){
  47. $fn($model, $offset);
  48. }
  49. return $this;
  50. }
  51. public function to_array(){
  52. return $this->data;
  53. }
  54. public function rewind(){
  55. $this->index = 0;
  56. }
  57. public function current(){
  58. return $this[$this->keys()[$this->index]];
  59. }
  60. public function key(){
  61. return $this->keys()[$this->index];
  62. }
  63. public function next(){
  64. $keys = $this->keys();
  65. return isset($keys[++$this->index]) ? $this->list[$keys[$this->index]] : false;
  66. }
  67. public function valid(){
  68. return isset($this->keys()[$this->index]);
  69. }
  70. public function keys(){
  71. return array_keys($this->data);
  72. }
  73. }
  74. ?>