| 1 | <?php |
||
| 7 | abstract class TypeCollection extends ArrayCollection |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * {@inheritdoc} |
||
| 11 | * |
||
| 12 | * @throws UnexpectedValueException |
||
| 13 | */ |
||
| 14 | 61 | public function __construct(array $elements = []) |
|
| 15 | { |
||
| 16 | 61 | parent::__construct(); |
|
| 17 | |||
| 18 | 61 | foreach ($elements as $element) { |
|
| 19 | 17 | $this->add($element); |
|
| 20 | 61 | } |
|
| 21 | 61 | } |
|
| 22 | |||
| 23 | /** |
||
| 24 | * {@inheritdoc} |
||
| 25 | * |
||
| 26 | * @throws UnexpectedValueException |
||
| 27 | */ |
||
| 28 | 31 | public function add($value) |
|
| 29 | { |
||
| 30 | 31 | if (!$this->acceptsType($value)) { |
|
| 31 | 2 | throw $this->doUnexpectedValueError($value); |
|
| 32 | } |
||
| 33 | |||
| 34 | 30 | return parent::add($value); |
|
| 35 | } |
||
| 36 | |||
| 37 | /** |
||
| 38 | * {@inheritdoc} |
||
| 39 | * |
||
| 40 | * @throws UnexpectedValueException |
||
| 41 | */ |
||
| 42 | 2 | public function set($key, $value) |
|
| 43 | { |
||
| 44 | 2 | if (!$this->acceptsType($value)) { |
|
| 45 | 1 | throw $this->doUnexpectedValueError($value); |
|
| 46 | } |
||
| 47 | |||
| 48 | 1 | parent::set($key, $value); |
|
| 49 | 1 | } |
|
| 50 | |||
| 51 | /** |
||
| 52 | * @param $element |
||
| 53 | * |
||
| 54 | * @return UnexpectedValueException |
||
| 55 | */ |
||
| 56 | 3 | private function doUnexpectedValueError($element) |
|
| 57 | { |
||
| 58 | 3 | return new UnexpectedValueException(sprintf( |
|
| 59 | 3 | '"%s" does not match the expected type.', |
|
| 60 | 3 | is_object($element) ? get_class($element) : gettype($element) |
|
| 61 | 3 | )); |
|
| 62 | } |
||
| 63 | |||
| 64 | /** |
||
| 65 | * @param $value |
||
| 66 | * |
||
| 67 | * @return bool |
||
| 68 | */ |
||
| 69 | abstract public function acceptsType($value); |
||
| 70 | } |
||
| 71 |