TextMapValidator::validate()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 34
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 23
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 34
ccs 0
cts 18
cp 0
crap 20
rs 9.552
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/validize project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\Validize\Validator;
10
11
use Daikon\Interop\Assert;
12
use Daikon\Interop\Assertion;
13
use Daikon\ValueObject\TextMap;
14
15
final class TextMapValidator extends Validator
16
{
17
    private const MAX_SIZE = 0;
18
    private const MIN_TEXT_LEN = 1;
19
    private const MAX_TEXT_LEN = 80;
20
21
    /** @param mixed $input */
22
    protected function validate($input): TextMap
23
    {
24
        Assertion::isArray($input, 'Must be an array.');
25
26
        $path = $this->getPath();
27
        $settings = $this->getSettings();
28
        $size = $settings['size'] ?? self::MAX_SIZE;
29
        $keys = $settings['keys'] ?? [];
30
        $min = $settings['min'] ?? self::MIN_TEXT_LEN;
31
        $max = $settings['max'] ?? self::MAX_TEXT_LEN;
32
33
        if ($size > 0) {
34
            Assertion::maxCount($input, $size, "Must have at most $size size.");
35
        }
36
37
        $formatAssertion = Assert::lazy();
38
        foreach ($input as $key => $item) {
39
            $formatAssertion
40
                ->that($key, $path)
41
                ->string('Key must be a string.')
42
                ->notBlank('Key must not be blank.');
43
44
            if (!empty($keys)) {
45
                $formatAssertion->inArray($keys, "Key '$key' is not allowed.");
46
            }
47
48
            $formatAssertion
49
                ->that($item, $path)
50
                ->string($path."[$key] must be a string.")
51
                ->betweenLength($min, $max, $path."[$key] must be between $min and $max characters.");
52
        }
53
        $formatAssertion->verifyNow();
54
55
        return TextMap::fromNative($input);
56
    }
57
}
58