Test Setup Failed
Push — develop ( 17b215...d74e9d )
by Freddie
13:13
created

HeaderSyntaxValidation   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
c 2
b 0
f 0
dl 0
loc 56
ccs 18
cts 18
cp 1
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A validateAllowedHeaders() 0 8 2
A validateRequiredHeaders() 0 9 2
A __construct() 0 3 1
A validate() 0 5 1
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of FlexPHP.
4
 *
5
 * (c) Freddie Gar <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace FlexPHP\Generator\Domain\Validations;
11
12
use FlexPHP\Generator\Domain\Exceptions\HeaderSyntaxValidationException;
13
use FlexPHP\Schema\Constants\Keyword;
14
15
final class HeaderSyntaxValidation implements ValidationInterface
16
{
17
    /**
18
     * @var array
19
     */
20
    private $headers;
21
22
    /**
23
     * @var array
24
     */
25
    private $allowedHeaders = [
26
        Keyword::NAME,
27
        Keyword::DATATYPE,
28
        Keyword::CONSTRAINTS,
29
    ];
30
31
    /**
32 4
     * @var array
33
     */
34 4
    private $requiredHeaders = [
35 4
        Keyword::NAME,
36
        Keyword::DATATYPE,
37 4
    ];
38
39 4
    public function __construct(array $headers)
40 4
    {
41
        $this->headers = $headers;
42 4
    }
43 4
44 4
    public function validate(): void
45
    {
46
        $this->validateAllowedHeaders();
47
48 4
        $this->validateRequiredHeaders();
49 1
    }
50
51
    private function validateAllowedHeaders(): void
52 3
    {
53 3
        $notAllowedHeaders = \array_filter($this->headers, function ($header) {
54 3
            return !\in_array($header, $this->allowedHeaders);
55
        });
56
57
        if (!empty($notAllowedHeaders)) {
58 3
            throw new HeaderSyntaxValidationException('Unknow headers: ' . \implode(', ', $notAllowedHeaders));
59 1
        }
60 1
    }
61
62
    private function validateRequiredHeaders(): void
63 2
    {
64
        $requiredHeaders = \array_filter($this->requiredHeaders, function ($required) {
65
            return !\in_array($required, $this->headers);
66
        });
67
68
        if (!empty($requiredHeaders)) {
69
            throw new HeaderSyntaxValidationException(
70
                'Required headers not present: ' . \implode(', ', $requiredHeaders)
71
            );
72
        }
73
    }
74
}
75