Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
Boolean
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
3 / 3
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 validate
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 getInverseError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace Verja\Validator;
4
5use Verja\Error;
6use Verja\Validator;
7
8class Boolean extends Validator
9{
10    /** @var string[] */
11    protected $stringTrue = ['1', 'true', 't', 'yes', 'y'];
12
13    /** @var string[] */
14    protected $stringFalse = ['0', 'false', 'f', 'no', 'n'];
15
16    /**
17     * Boolean constructor.
18     *
19     * @param string[] $stringTrue
20     * @param string[] $stringFalse
21     * @param bool     $overwrite   Overwrite the arrays instead of merging
22     */
23    public function __construct(array $stringTrue = [], array $stringFalse = [], $overwrite = false)
24    {
25        if ($overwrite) {
26            $this->stringTrue = $stringTrue;
27            $this->stringFalse = $stringFalse;
28        } else {
29            $this->stringTrue  = array_merge($this->stringTrue, $stringTrue);
30            $this->stringFalse = array_merge($this->stringFalse, $stringFalse);
31        }
32    }
33
34    /**
35     * Validate $value
36     *
37     * @param mixed $value
38     * @param array $context
39     * @return bool
40     */
41    public function validate($value, array $context = []): bool
42    {
43        if (!is_bool($value) && !is_int($value) &&
44            (!is_string($value) || !in_array($value, $this->stringTrue) && !in_array($value, $this->stringFalse))
45        ) {
46            $this->error = new Error('NOT_BOOLEAN', $value, 'value should be a boolean');
47            return false;
48        }
49
50        return true;
51    }
52
53    public function getInverseError($value)
54    {
55        return new Error('IS_BOOLEAN', $value, 'value should not be a boolean');
56    }
57}