|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ahc\Underscore; |
| 4 | + |
| 5 | +class Underscore implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable |
| 6 | +{ |
| 7 | + const VERSION = '0.0.1'; |
| 8 | + |
| 9 | + /** @var array The array manipulated by this object */ |
| 10 | + protected $data; |
| 11 | + |
| 12 | + /** |
| 13 | + * Constructor. |
| 14 | + * |
| 15 | + * @param array|mixed $data. |
| 16 | + */ |
| 17 | + public function __construct($data = []) |
| 18 | + { |
| 19 | + $this->data = is_array($data) ? $data : Helper::asArray($data); |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Get the underlying array data. |
| 24 | + * |
| 25 | + * @param string|int|null $index |
| 26 | + * |
| 27 | + * @return mixed |
| 28 | + */ |
| 29 | + public function get($index = null) |
| 30 | + { |
| 31 | + if (null === $index) { |
| 32 | + return $this->data; |
| 33 | + } |
| 34 | + |
| 35 | + return $this->data[$index]; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * {@inheritdoc} |
| 40 | + */ |
| 41 | + public function offsetExists($index) |
| 42 | + { |
| 43 | + return \array_key_exists($index, $this->data); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * {@inheritdoc} |
| 48 | + */ |
| 49 | + public function offsetGet($index) |
| 50 | + { |
| 51 | + return $this->data[$index]; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * {@inheritdoc} |
| 56 | + */ |
| 57 | + public function offsetSet($index, $value) |
| 58 | + { |
| 59 | + $this->data[$index] = $value; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * {@inheritdoc} |
| 64 | + */ |
| 65 | + public function offsetUnset($index) |
| 66 | + { |
| 67 | + unset($this->data[$index]); |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * {@inheritdoc} |
| 72 | + */ |
| 73 | + public function count() |
| 74 | + { |
| 75 | + return \count($this->data); |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * {@inheritdoc} |
| 80 | + */ |
| 81 | + public function getIterator() |
| 82 | + { |
| 83 | + return new \ArrayIterator($this->data); |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * {@inheritdoc} |
| 88 | + */ |
| 89 | + public function jsonSerialize() |
| 90 | + { |
| 91 | + return $this->data; |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * {@inheritdoc} |
| 96 | + */ |
| 97 | + public function __toString() |
| 98 | + { |
| 99 | + return \json_encode($this->data); |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +\class_alias('Ahc\Underscore\Underscore', 'Ahc\Underscore'); |
0 commit comments