Length   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 70
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 12 3
A getMessageParameters() 0 6 1
1
<?php
2
/**
3
 * Particle.
4
 *
5
 * @link      http://github.com/particle-php for the canonical source repository
6
 * @copyright Copyright (c) 2005-2016 Particle (http://particle-php.com)
7
 * @license   https://github.com/particle-php/validator/blob/master/LICENSE New BSD License
8
 */
9
namespace Particle\Validator\Rule;
10
11
use Particle\Validator\Rule;
12
13
/**
14
 * This rule is for validating the exact length of a string.
15
 *
16
 * @package Particle\Validator\Rule
17
 */
18
class Length extends Rule
19
{
20
    /**
21
     * A constant that will be used for the error message when the value is too short.
22
     */
23
    const TOO_SHORT = 'Length::TOO_SHORT';
24
25
    /**
26
     * A constant that will be used for the error message when the value is too long.
27
     */
28
    const TOO_LONG = 'Length::TOO_LONG';
29
30
    /**
31
     * The message templates which can be returned by this validator.
32
     *
33
     * @var array
34
     */
35
    protected $messageTemplates = [
36
        self::TOO_SHORT => '{{ name }} is too short and must be {{ length }} characters long',
37
        self::TOO_LONG => '{{ name }} is too long and must be {{ length }} characters long',
38
    ];
39
40
    /**
41
     * The length the value should have.
42
     *
43
     * @var int
44
     */
45
    protected $length;
46
47
    /**
48
     * Construct the Length validator.
49
     *
50
     * @param int $length
51
     */
52 13
    public function __construct($length)
53
    {
54 13
        $this->length = $length;
55 13
    }
56
57
    /**
58
     * Attempts to see if the length of the value is exactly the number expected and returns the result as a bool.
59
     *
60
     * @param mixed $value
61
     * @return bool
62
     */
63 10
    public function validate($value)
64
    {
65 10
        $actualLength = strlen($value);
66
67 10
        if ($actualLength > $this->length) {
68 1
            return $this->error(self::TOO_LONG);
69
        }
70 9
        if ($actualLength < $this->length) {
71 6
            return $this->error(self::TOO_SHORT);
72
        }
73 3
        return true;
74
    }
75
76
    /**
77
     * Returns the parameters that may be used in a validation message.
78
     *
79
     * @return array
80
     */
81 7
    protected function getMessageParameters()
82
    {
83 7
        return array_merge(parent::getMessageParameters(), [
84 7
            'length' => $this->length
85 7
        ]);
86
    }
87
}
88