Completed
Push — develop ( e8233d...5c8fb2 )
by Neomerx
16:15 queued 11:26
created

ToOneRelationshipTypeCheckerRule::execute()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 12
cts 12
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 3
nop 2
crap 5
1
<?php namespace Limoncello\Flute\Validation\JsonApi\Rules;
2
3
/**
4
 * Copyright 2015-2017 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use Limoncello\Flute\Contracts\Validation\ErrorCodes;
20
use Limoncello\Validation\Contracts\Execution\ContextInterface;
21
use Limoncello\Validation\Rules\ExecuteRule;
22
23
/**
24
 * @package Limoncello\Flute
25
 */
26
final class ToOneRelationshipTypeCheckerRule extends ExecuteRule
27
{
28
    /**
29
     * Property key.
30
     */
31
    const PROPERTY_RESOURCE_TYPE = self::PROPERTY_LAST + 1;
32
33
    /**
34
     * @param string $type
35
     */
36 36
    public function __construct(string $type)
37
    {
38 36
        parent::__construct([
39 36
            static::PROPERTY_RESOURCE_TYPE => $type,
40
        ]);
41
    }
42
43
    /**
44
     * @param mixed            $value
45
     * @param ContextInterface $context
46
     *
47
     * @return array
48
     *
49
     * @SuppressWarnings(PHPMD.StaticAccess)
50
     */
51 6
    public static function execute($value, ContextInterface $context): array
52
    {
53
        // parser guarantees that input will be either null or an [$type => $id] where type and id are scalars
54
55 6
        if ($value === null) {
56 2
            return static::createSuccessReply($value);
57
        }
58
59 4
        assert(is_array($value) === true && count($value) === 1);
60 4
        $index = reset($value);
61 4
        $type  = key($value);
62 4
        assert(is_scalar($index) === true && is_scalar($type) === true);
63 4
        $expectedType = $context->getProperties()->getProperty(static::PROPERTY_RESOURCE_TYPE);
64 4
        $reply        = $type === $expectedType ?
65 4
            static::createSuccessReply($index) :
66 4
            static::createErrorReply($context, $type, ErrorCodes::INVALID_RELATIONSHIP_TYPE);
67
68 4
        return $reply;
69
    }
70
}
71