Completed
Pull Request — 1.x (#5)
by Dorian
01:32
created

MaxLengthValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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