Completed
Push — master ( 0e2954...632183 )
by Ítalo
04:23
created

GuardTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 62.5%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 0
cbo 2
dl 0
loc 38
ccs 10
cts 16
cp 0.625
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
isEmpty() 0 1 ?
count() 0 1 ?
A emptyGuard() 0 8 2
A validateKeyBounds() 0 6 2
A isBoundedKey() 0 4 2
A validateKeyType() 0 6 2
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