Length   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 92
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 28
c 2
b 0
f 0
dl 0
loc 92
rs 10
wmc 17

2 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 20 8
B isValid() 0 31 9
1
<?php
2
3
namespace Kontrolio\Rules\Core;
4
5
use InvalidArgumentException;
6
use LogicException;
7
use Kontrolio\Rules\AbstractRule;
8
9
/**
10
 * Length validation rule.
11
 *
12
 * @package Kontrolio\Rules\Core
13
 */
14
class Length extends AbstractRule
15
{
16
    /**
17
     * Minimum length.
18
     *
19
     * @var int
20
     */
21
    private $min;
22
23
    /**
24
     * Maximum length.
25
     *
26
     * @var int
27
     */
28
    private $max;
29
30
    /**
31
     * Charset.
32
     *
33
     * @var string
34
     */
35
    private $charset;
36
37
    /**
38
     * Length validation rule constructor.
39
     *
40
     * @param int $min
41
     * @param int $max
42
     * @param string $charset
43
     * @throws InvalidArgumentException
44
     * @throws LogicException
45
     */
46
    public function __construct(
47
        $min = null,
48
        $max = null,
49
        $charset = 'UTF-8'
50
    ) {
51
        if ($min === null && $max === null) {
52
            throw new InvalidArgumentException('Either option "min" or "max" must be given.');
53
        }
54
55
        if ($min !== null && $max !== null && $min > $max) {
56
            throw new LogicException('"Min" option cannot be greater that "max".');
57
        }
58
59
        if ($max !== null && $max < $min) {
60
            throw new LogicException('"Max" option cannot be less that "min".');
61
        }
62
63
        $this->min = $min;
64
        $this->max = $max;
65
        $this->charset = $charset;
66
    }
67
68
    /**
69
     * Validates input.
70
     *
71
     * @param mixed $input
72
     *
73
     * @return bool
74
     */
75
    public function isValid($input = null)
76
    {
77
        if ($input === null || $input === '') {
78
            return false;
79
        }
80
81
        $input = (string) $input;
82
83
        if (!$invalidCharset = !@mb_check_encoding($input, $this->charset)) {
84
            $length = mb_strlen($input, $this->charset);
85
        }
86
87
        if ($invalidCharset) {
88
            $this->violations[] = 'charset';
89
90
            return false;
91
        }
92
93
        if ($this->max !== null && $length > $this->max) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $length does not seem to be defined for all execution paths leading up to this point.
Loading history...
94
            $this->violations[] = 'max';
95
96
            return false;
97
        }
98
99
        if ($this->min !== null && $length < $this->min) {
100
            $this->violations[] = 'min';
101
102
            return false;
103
        }
104
105
        return true;
106
    }
107
}
108