Completed
Push — 1.x ( 2692eb...201d44 )
by Dorian
12s
created

MaxLengthValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 31
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getMaxLength() 0 1 1
A setMaxLength() 0 1 1
A __construct() 0 5 1
A validate() 0 6 3
1
<?php
2
namespace MetaHydrator\Validator;
3
4
use MetaHydrator\Exception\ValidationException;
5
6
/**
7
 * An implementation of ValidatorInterface used to limit size of a string
8
 */
9
class MaxLengthValidator extends AbstractValidator
10
{
11
    /** @var int */
12
    private $maxLength;
13
    public function getMaxLength() { return $this->maxLength; }
14
    public function setMaxLength(int $maxLength) { $this->maxLength = $maxLength; }
15
16
    /**
17
     * MaxLengthValidator constructor.
18
     * @param int $maxLength
19
     * @param string $errorMessage
20
     */
21
    public function __construct(int $maxLength, $errorMessage = "")
22
    {
23
        parent::__construct($errorMessage);
24
        $this->maxLength = $maxLength;
25
    }
26
27
    /**
28
     * @param mixed $value
29
     * @param $contextObject
30
     *
31
     * @throws ValidationException
32
     */
33
    public function validate($value, $contextObject = null)
34
    {
35
        if ($value != null && strlen(strval($value)) > $this->maxLength) {
36
            $this->throw();
37
        }
38
    }
39
}
40