earray.class.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 {
  6. use Events;
  7. protected $data = [];
  8. public static function from(array $data){
  9. return new static($data);
  10. }
  11. protected function __construct(array $data){
  12. $this->data = $data;
  13. }
  14. public function offsetExists($offset){
  15. $this->fire('exists', $offset);
  16. return isset($this->data[$offset]);
  17. }
  18. public function offsetGet($offset){
  19. $this->fire('get', $offset);
  20. return $this->data[$offset];
  21. }
  22. public function offsetSet($offset, $value){
  23. $this->fire('set', $offset, $value);
  24. $this->data[$offset] = $value;
  25. }
  26. public function offsetUnset($offset){
  27. if($this->offsetExists($offset)){
  28. $this->fire('unset', $offset, $this[$offset]);
  29. unset($this->data[$offset]);
  30. }
  31. }
  32. public function count(){
  33. return count($this->data);
  34. }
  35. public function each(callable $fn){
  36. foreach($this->data as $offset => $model){
  37. $fn($model, $offset);
  38. }
  39. return $this;
  40. }
  41. public function to_array(){
  42. return $this->data;
  43. }
  44. }
  45. ?>