1
0

earray.class.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 {
  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 each(callable $fn){
  37. foreach($this->data as $offset => $model){
  38. $fn($model, $offset);
  39. }
  40. return $this;
  41. }
  42. public function to_array(){
  43. return $this->data;
  44. }
  45. public function rewind(){
  46. $this->index = 0;
  47. }
  48. public function current(){
  49. return $this[$this->keys()[$this->index]];
  50. }
  51. public function key(){
  52. return $this->keys()[$this->index];
  53. }
  54. public function next(){
  55. $keys = $this->keys();
  56. return isset($keys[++$this->index]) ? $this->list[$keys[$this->index]] : false;
  57. }
  58. public function valid(){
  59. return isset($this->keys()[$this->index]);
  60. }
  61. public function keys(){
  62. return array_keys($this->data);
  63. }
  64. }
  65. ?>