StrictlyTypedCollectionTrait::setStrictType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 4
cts 4
cp 1
rs 10
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php namespace BuildR\Collection\Collection;
2
3
use BuildR\Collection\Exception\CollectionException;
4
5
/**
6
 * Trait for collections that can be strictly typed
7
 *
8
 * BuildR PHP Framework
9
 *
10
 * @author Zoltán Borsos <[email protected]>
11
 * @package Collection
12
 * @subpackage Collection
13
 *
14
 * @copyright    Copyright 2015, Zoltán Borsos.
15
 * @license      https://github.com/Zolli/BuildR/blob/master/LICENSE.md
16
 * @link         https://github.com/Zolli/BuildR
17
 *
18
 */
19
trait StrictlyTypedCollectionTrait {
20
21
    /**
22
     * @type NULL|callable
23
     */
24
    protected $typeChecker;
25
26
    /**
27
     * @type NULL|string
28
     */
29
    protected $typeCheckFailMessage;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 5
    public function setStrictType(callable $typeCheck, $message = NULL) {
35 5
        $this->typeChecker = $typeCheck;
36 5
        $this->typeCheckFailMessage = $message;
37 5
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 83
    public function isStrict() {
43 83
        return is_callable($this->typeChecker);
44
    }
45
46
    /**
47
     * Executes the type check if the collection is strict. Always
48
     * returns true, when the collection is not strictly typed
49
     *
50
     * @param mixed $value
51
     *
52
     * @return bool
53
     *
54
     * @throws \BuildR\Collection\Exception\CollectionException
55
     */
56 82
    protected function doTypeCheck($value) {
57 82
        if($this->isStrict()) {
58 3
            $result = (bool) call_user_func_array($this->typeChecker, [$value]);
59
60 3
            if($result === FALSE) {
61 2
                $message = ($this->typeCheckFailMessage === NULL) ? gettype($value) : $this->typeCheckFailMessage;
62
63 2
                throw CollectionException::typeException($message);
64
            }
65
66 1
            return TRUE;
67
        }
68 79
    }
69
70
}
71