| 1 | <?php |
||
| 8 | trait GuardTrait |
||
| 9 | { |
||
| 10 | abstract function isEmpty(); |
||
| 11 | |||
| 12 | abstract function count(); |
||
| 13 | |||
| 14 | /** |
||
| 15 | * Ensures that we throw the correct exception when an empty collection is found |
||
| 16 | * @param $method |
||
| 17 | * @throws EmptyException |
||
| 18 | */ |
||
| 19 | protected function emptyGuard($method) |
||
| 20 | { |
||
| 21 | if ($this->isEmpty()) { |
||
| 22 | throw new EmptyException( |
||
| 23 | "{$method} cannot be called when the structure is empty" |
||
| 24 | ); |
||
| 25 | } |
||
| 26 | } |
||
| 27 | |||
| 28 | /** |
||
| 29 | * Validates if a key is withing bounds (usually only useful with vectors) |
||
| 30 | * @param $key |
||
| 31 | */ |
||
| 32 | 5 | protected function validateKeyBounds($key) |
|
| 33 | { |
||
| 34 | 5 | if (!$this->isBoundedKey($key)) { |
|
| 35 | 2 | throw new \OutOfBoundsException("Integer key $key is out of bounds"); |
|
| 36 | } |
||
| 37 | 3 | } |
|
| 38 | |||
| 39 | /** |
||
| 40 | * @param int $element |
||
| 41 | * @return bool |
||
| 42 | */ |
||
| 43 | 5 | protected function isBoundedKey($element) |
|
| 47 | |||
| 48 | /** |
||
| 49 | * Validate if an element respects the correct type (usually only useful with vectors) |
||
| 50 | * @param $element |
||
| 51 | * @throws TypeException |
||
| 52 | */ |
||
| 53 | 22 | protected function validateKeyType($element) |
|
| 59 | } |
||
| 60 |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.