|
| 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 | +use TypeError; |
| 17 | + |
| 18 | +/** |
| 19 | + * Create an array of typed elements. |
| 20 | + */ |
| 21 | +class TypedArray extends ArrayObject |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @var array $allowedTypes Types supported by class |
| 25 | + */ |
| 26 | + protected $allowedTypes = [ |
| 27 | + 'array', |
| 28 | + 'bool', |
| 29 | + 'callable', |
| 30 | + 'float', |
| 31 | + 'int', |
| 32 | + 'object', |
| 33 | + 'string', |
| 34 | + ]; |
| 35 | + |
| 36 | + /** |
| 37 | + * @var string $type Current type for array |
| 38 | + */ |
| 39 | + protected $type = ''; |
| 40 | + |
| 41 | + /** |
| 42 | + * Contructor. |
| 43 | + * |
| 44 | + * @param string $type |
| 45 | + * @param array $array |
| 46 | + * @throws InvalidArgumentException If type is not supported |
| 47 | + * @throws TypeError If elements of passed with $array |
| 48 | + * are not of the configured type |
| 49 | + */ |
| 50 | + public function __construct(string $type, array $array = []) |
| 51 | + { |
| 52 | + //single class, multi type support :) |
| 53 | + //if (!isset($this->allowedTypes[$type])){ |
| 54 | + if (!in_array($type, $this->allowedTypes)){ |
| 55 | + throw new InvalidArgumentException($type.' type passed to '.__CLASS__.' not supported'); |
| 56 | + } |
| 57 | + |
| 58 | + //for not utilize foreach, compare sizes of array |
| 59 | + //before and after apply a filter :) |
| 60 | + if (count($array) > count(array_filter($array, 'is_'.$type))) { |
| 61 | + throw new TypeError('Elements passed to '.__CLASS__.' must be of the type '.$type); |
| 62 | + } |
| 63 | + |
| 64 | + //call parent constructor |
| 65 | + parent::__construct($array, 0, 'ArrayIterator'); |
| 66 | + |
| 67 | + //store array type |
| 68 | + $this->type = $type; |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Array style value assignment. |
| 73 | + * |
| 74 | + * @param mixed $index |
| 75 | + * @param mixed $newval |
| 76 | + * |
| 77 | + * @throws TypeError If value passed with $newval are not of the configured type |
| 78 | + * |
| 79 | + * @return void |
| 80 | + */ |
| 81 | + public function offsetSet($index, $newval) |
| 82 | + { |
| 83 | + $is_ = 'is_'.$this->type; |
| 84 | + |
| 85 | + if ($is_($newval)) { |
| 86 | + parent::offsetSet($index, $newval); |
| 87 | + return; |
| 88 | + } |
| 89 | + throw new TypeError('Elements passed to '.__CLASS__.' must be of the type '.$this->type); |
| 90 | + } |
| 91 | +} |
0 commit comments