|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Linna Array. |
| 5 | + * |
| 6 | + * @author Sebastian Rapetti <sebastian.rapetti@alice.it> |
| 7 | + * @copyright (c) 2018, Sebastian Rapetti |
| 8 | + * @license http://opensource.org/licenses/MIT MIT License |
| 9 | + */ |
| 10 | +declare(strict_types=1); |
| 11 | + |
| 12 | +namespace Linna\TypedArrayObject; |
| 13 | + |
| 14 | +use ArrayObject; |
| 15 | +use InvalidArgumentException; |
| 16 | + |
| 17 | +/** |
| 18 | + * Provide a way to create an array of callable typed elements with php. |
| 19 | + */ |
| 20 | +class CallableArrayObject extends ArrayObject |
| 21 | +{ |
| 22 | + public const EXC_MESSAGE = 'Elements passed must be of the type <callable>.'; |
| 23 | + |
| 24 | + /** |
| 25 | + * Class Contructor. |
| 26 | + * |
| 27 | + * @param array $input |
| 28 | + * @param int $flags |
| 29 | + * @param string $iterator_class |
| 30 | + * |
| 31 | + * @throws InvalidArgumentException If elements in the optional array parameter |
| 32 | + * aren't of the configured type. |
| 33 | + */ |
| 34 | + public function __construct(array $input = [], int $flags = 0, string $iterator_class = "ArrayIterator") |
| 35 | + { |
| 36 | + //to avoid foreach, compare sizes of array |
| 37 | + //before and after apply a filter :) |
| 38 | + if (\count($input) > \count(\array_filter($input, 'is_callable'))) { |
| 39 | + throw new InvalidArgumentException(self::EXC_MESSAGE); |
| 40 | + } |
| 41 | + |
| 42 | + //call parent constructor |
| 43 | + parent::__construct($input, $flags, $iterator_class); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Array style value assignment. |
| 48 | + * |
| 49 | + * @ignore |
| 50 | + * |
| 51 | + * @param mixed $index |
| 52 | + * @param int $newval |
| 53 | + * |
| 54 | + * @throws InvalidArgumentException If value passed with $newval are not of the integer type |
| 55 | + * |
| 56 | + * @return void |
| 57 | + */ |
| 58 | + public function offsetSet($index, $newval): void |
| 59 | + { |
| 60 | + if (\is_callable($newval)) { |
| 61 | + parent::offsetSet($index, $newval); |
| 62 | + |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + throw new InvalidArgumentException(self::EXC_MESSAGE); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Append a value at the end of the array. |
| 71 | + * |
| 72 | + * @param int $value |
| 73 | + * @return void |
| 74 | + * |
| 75 | + * @throws InvalidArgumentException If value passed with $value are not of the integer type |
| 76 | + */ |
| 77 | + public function append($value): void |
| 78 | + { |
| 79 | + if (\is_callable($value)) { |
| 80 | + parent::append($value); |
| 81 | + |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + throw new InvalidArgumentException(self::EXC_MESSAGE); |
| 86 | + } |
| 87 | +} |
0 commit comments