Completed
Push — master ( 813757...d8be45 )
by Ítalo
03:56 queued 02:00
created

GuardTrait::count()

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
    /**
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)
44
    {
45 5
        return $element >= 0 && $element < $this->count();
46
    }
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)
54
    {
55 22
        if (filter_var($element, FILTER_VALIDATE_INT) === false) {
56 4
            throw new TypeException('Only integer keys may be used with ' . (get_class($this)));
57
        }
58 19
    }
59
}
60