Completed
Push — master ( 801ae3...f2d109 )
by Ítalo
04:18
created

GuardTrait::validateTraversable()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 3
nc 2
nop 1
crap 12
1
<?php
2
3
namespace Collections\Traits;
4
5
use Collections\Exception\EmptyException;
6
use Collections\Exception\InvalidArgumentException;
7
use Collections\Exception\TypeException;
8
9
trait GuardTrait
10
{
11
    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...
12
13
    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...
14
15
    /**
16
     * Ensures that we throw the correct exception when an empty collection is found
17
     * @param $method
18
     * @throws EmptyException
19
     */
20
    protected function emptyGuard($method)
21
    {
22
        if ($this->isEmpty()) {
23
            throw new EmptyException(
24
                "{$method} cannot be called when the structure is empty"
25
            );
26
        }
27
    }
28
29
    /**
30
     * Validates if a key is withing bounds (usually only useful with vectors)
31
     * @param $key
32 5
     */
33
    protected function validateKeyBounds($key)
34 5
    {
35 2
        if (!$this->isBoundedKey($key)) {
36
            throw new \OutOfBoundsException("Integer key $key is out of bounds");
37 3
        }
38
    }
39
40
    /**
41
     * @param int $element
42
     * @return bool
43 5
     */
44
    protected function isBoundedKey($element)
45 5
    {
46
        return $element >= 0 && $element < $this->count();
47
    }
48
49
    /**
50
     * Validate if an element respects the correct type (usually only useful with vectors)
51
     * @param $element
52
     * @throws TypeException
53 22
     */
54
    protected function validateKeyType($element)
55 22
    {
56 4
        if (filter_var($element, FILTER_VALIDATE_INT) === false) {
57
            throw new TypeException('Only integer keys may be used with ' . (get_class($this)));
58 19
        }
59
    }
60
61
    protected function validateTraversable($traversable)
62
    {
63
        if (!is_array($traversable) && !$traversable instanceof \Traversable) {
64
            throw InvalidArgumentException::invalidTraversable();
65
        }
66
    }
67
}
68