Type::validate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * This file is part of php-simple-request.
4
 *
5
 * php-simple-request is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * php-simple-request is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with php-simple-request.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
namespace Mcustiel\SimpleRequest\Validator;
19
20
use Mcustiel\SimpleRequest\Interfaces\ValidatorInterface;
21
use Mcustiel\SimpleRequest\Exception\UnspecifiedValidatorException;
22
23
/**
24
 * Checks if a value is of the specified type.
25
 *
26
 * @author mcustiel
27
 */
28
class Type implements ValidatorInterface
29
{
30
    /**
31
     *
32
     * @var string
33
     */
34
    private $type;
35
    /**
36
     *
37
     * @var array
38
     */
39
    private $validTypes = [
40
        'array'   => ['array'],
41
        'object'  => ['object'],
42
        'integer' => ['integer'],
43
        'number'  => ['integer', 'double'],
44
        'string'  => ['string'],
45
        'boolean' => ['boolean'],
46
        'null'    => ['NULL'],
47
    ];
48
49
    /**
50
     * {@inheritdoc}
51
     *
52
     * @see \Mcustiel\SimpleRequest\Interfaces\Specificable::setSpecification()
53
     */
54 115
    public function setSpecification($specification = null)
55
    {
56 115
        if (!isset($this->validTypes[$specification])) {
57 2
            throw new UnspecifiedValidatorException(
58
                'The validator Type is being initialized without a valid type name'
59 2
            );
60
        }
61 113
        $this->type = $specification;
62 113
    }
63
64
    /**
65
     * {@inheritdoc}
66
     *
67
     * @see \Mcustiel\SimpleRequest\Interfaces\ValidatorInterface::validate()
68
     */
69 114
    public function validate($value)
70
    {
71 114
        return in_array(gettype($value), $this->validTypes[$this->type]);
72
    }
73
}
74