RequiredConstraint::normalize()   B
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 26
c 0
b 0
f 0
ccs 15
cts 15
cp 1
rs 8.439
cc 6
eloc 13
nc 7
nop 3
crap 6
1
<?php
2
3
/*
4
 * This file is part of the JVal package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace JVal\Constraint;
11
12
use JVal\Constraint;
13
use JVal\Context;
14
use JVal\Exception\Constraint\EmptyArrayException;
15
use JVal\Exception\Constraint\InvalidTypeException;
16
use JVal\Exception\Constraint\NotUniqueException;
17
use JVal\Types;
18
use JVal\Walker;
19
use stdClass;
20
21
/**
22
 * Constraint for the "required" keyword.
23
 */
24
class RequiredConstraint implements Constraint
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29 373
    public function keywords()
30
    {
31 373
        return ['required'];
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 357
    public function supports($type)
38
    {
39 357
        return $type === Types::TYPE_OBJECT;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 26
    public function normalize(stdClass $schema, Context $context, Walker $walker)
46
    {
47 26
        $context->enterNode('required');
48
49 26
        if (!is_array($schema->required)) {
50 1
            throw new InvalidTypeException($context, Types::TYPE_ARRAY);
51
        }
52
53 25
        if (0 === $requiredCount = count($schema->required)) {
54 1
            throw new EmptyArrayException($context);
55
        }
56
57 24
        foreach ($schema->required as $index => $property) {
58 24
            if (!is_string($property)) {
59 1
                $context->enterNode($index);
60
61 1
                throw new InvalidTypeException($context, Types::TYPE_STRING);
62
            }
63 24
        }
64
65 23
        if ($requiredCount !== count(array_unique($schema->required))) {
66 1
            throw new NotUniqueException($context);
67
        }
68
69 22
        $context->leaveNode();
70 22
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75 22
    public function apply($instance, stdClass $schema, Context $context, Walker $walker)
76
    {
77 22
        foreach ($schema->required as $property) {
78 22
            if (!property_exists($instance, $property)) {
79 14
                $context->addViolation('property "%s" is missing', [$property]);
80 14
            }
81 22
        }
82 22
    }
83
}
84