Completed
Pull Request — master (#4)
by Mariano
04:20
created

Properties::getPropertiesConfigFor()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of php-simple-request.
4
 *
5
 * php-simple-request is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * php-simple-request is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with php-simple-request.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
namespace Mcustiel\SimpleRequest\Annotation\Validator;
19
20
use Mcustiel\SimpleRequest\Annotation\ValidatorAnnotation;
21
use Mcustiel\SimpleRequest\Validator\Properties as PropertiesValidator;
22
use Mcustiel\SimpleRequest\Exception\InvalidAnnotationException;
23
24
/**
25
 * @Annotation
26
 * @Target({ "PROPERTY", "ANNOTATION" })
27
 *
28
 * @author mcustiel
29
 */
30
class Properties extends ValidatorAnnotation
31
{
32
    public $properties = [];
33
    public $patternProperties = [];
34
    public $additionalProperties;
35
36 80
    public function __construct()
37
    {
38 80
        parent::__construct(PropertiesValidator::class);
39 80
    }
40
41 80
    public function getValue()
42
    {
43
        return [
44 80
            'properties'           => $this->getPropertiesConfigFor($this->properties),
45 79
            'patternProperties'    => $this->getPropertiesConfigFor($this->patternProperties),
46 79
            'additionalProperties' => $this->additionalProperties,
47 79
        ];
48
    }
49
50 80
    private function getPropertiesConfigFor(array $data)
51
    {
52 80
        $count = count($data);
53 80
        $this->validatePropertiesCountOrThrowException($count);
54 79
        $properties = array();
55 79
        for ($i = 0; $i < $count; $i += 2) {
56 79
            $properties[$data[$i]] = $data[$i + 1];
57 79
        }
58 79
        return $properties;
59
    }
60
61 80
    private function validatePropertiesCountOrThrowException($count)
62
    {
63 80
        if ($count % 2 != 0) {
64 1
            throw new InvalidAnnotationException(
65
                'Properties field must specify a set of (name, validator) pairs'
66 1
            );
67
        }
68 79
    }
69
}
70