|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Linna Array. |
| 5 | + * |
| 6 | + * @author Sebastian Rapetti <[email protected]> |
| 7 | + * @copyright (c) 2017, Sebastian Rapetti |
| 8 | + * @license http://opensource.org/licenses/MIT MIT License |
| 9 | + */ |
| 10 | +declare(strict_types=1); |
| 11 | + |
| 12 | +namespace Linna; |
| 13 | + |
| 14 | +use ArrayObject; |
| 15 | +use InvalidArgumentException; |
| 16 | + |
| 17 | +/** |
| 18 | + * Create an array of typed elements. |
| 19 | + */ |
| 20 | +class TypedObjectArray extends ArrayObject |
| 21 | +{ |
| 22 | + /** |
| 23 | + * @var string Current type for array |
| 24 | + */ |
| 25 | + protected $type = ''; |
| 26 | + |
| 27 | + /** |
| 28 | + * Contructor. |
| 29 | + * |
| 30 | + * @param string $type |
| 31 | + * @param array $array |
| 32 | + * |
| 33 | + * @throws InvalidArgumentException If elements of passed with $array |
| 34 | + * are not of the configured type |
| 35 | + */ |
| 36 | + public function __construct(string $type, array $array = []) |
| 37 | + { |
| 38 | + //check elements of passed array |
| 39 | + //I will find another method |
| 40 | + foreach ($array as $element) { |
| 41 | + if ($element instanceof $type) { |
| 42 | + continue; |
| 43 | + } |
| 44 | + throw new InvalidArgumentException('Elements passed to '.__CLASS__.' must be of the type '.$type); |
| 45 | + } |
| 46 | + |
| 47 | + //call parent constructor |
| 48 | + parent::__construct($array, 0, 'ArrayIterator'); |
| 49 | + //store array type |
| 50 | + $this->type = $type; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Array style value assignment. |
| 55 | + * |
| 56 | + * @param mixed $index |
| 57 | + * @param mixed $newval |
| 58 | + * |
| 59 | + * @throws InvalidArgumentException If value passed with $newval are not of the configured type |
| 60 | + * |
| 61 | + * @return void |
| 62 | + */ |
| 63 | + public function offsetSet($index, $newval) |
| 64 | + { |
| 65 | + if ($newval instanceof $this->type) { |
| 66 | + parent::offsetSet($index, $newval); |
| 67 | + return; |
| 68 | + } |
| 69 | + throw new InvalidArgumentException('Elements passed to '.__CLASS__.' must be of the type '.$this->type); |
| 70 | + } |
| 71 | +} |
0 commit comments