UniqueItemsConstraint::supports()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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\InvalidTypeException;
15
use JVal\Types;
16
use JVal\Utils;
17
use JVal\Walker;
18
use stdClass;
19
20
/**
21
 * Constraint for the "uniqueItems" keyword.
22
 */
23
class UniqueItemsConstraint implements Constraint
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28 373
    public function keywords()
29
    {
30 373
        return ['uniqueItems'];
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 357
    public function supports($type)
37
    {
38 357
        return $type === Types::TYPE_ARRAY;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 28
    public function normalize(stdClass $schema, Context $context, Walker $walker)
45
    {
46 28
        if (!is_bool($schema->uniqueItems)) {
47 1
            $context->enterNode('uniqueItems');
48
49 1
            throw new InvalidTypeException($context, Types::TYPE_BOOLEAN);
50
        }
51 27
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 21
    public function apply($instance, stdClass $schema, Context $context, Walker $walker)
57
    {
58 21
        if ($schema->uniqueItems === true) {
59 18
            foreach ($instance as $i => $aItem) {
60 18
                foreach ($instance as $j => $bItem) {
61 18
                    if ($i !== $j && Utils::areEqual($aItem, $bItem)) {
62 8
                        $context->addViolation('elements must be unique');
63 8
                        break 2;
64
                    }
65 18
                }
66 18
            }
67 18
        }
68 21
    }
69
}
70