Completed
Push — master ( e86954...7cbcb1 )
by Ítalo
02:48
created

GuardTrait::isEmpty()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
3
namespace Collections\Traits;
4
5
use Collections\Exception\EmptyException;
6
use Collections\Exception\TypeException;
7
8
trait GuardTrait
9
{
10
    abstract function isEmpty();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
11
12
    abstract function count();
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
13
14
    protected function emptyGuard($method)
15
    {
16
        if ($this->isEmpty()) {
17
            throw new EmptyException(
18
                "{$method} cannot be called when the structure is empty"
19
            );
20
        }
21
    }
22
23 5
    protected function validateKeyBounds($k)
24
    {
25 5
        if (!$this->isBoundedKey($k)) {
26 2
            throw new \OutOfBoundsException("Integer key $k is out of bounds");
27
        }
28 3
    }
29
30
    /**
31
     * @param int $element
32
     * @return mixed
33
     */
34 5
    protected function isBoundedKey($element)
35
    {
36 5
        return $element >= 0 && $element < $this->count();
37
    }
38
39 22
    protected function validateKeyType($element)
40
    {
41 22
        if (filter_var($element, FILTER_VALIDATE_INT) === false) {
42 4
            throw new TypeException('Only integer keys may be used with ' . (get_class($this)));
43
        }
44 19
    }
45
}
46