HeaderSyntaxValidation::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
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
    private array $headers;
18
19
    private array $allowedHeaders = [
20
        Keyword::NAME,
21
        Keyword::DATATYPE,
22
        Keyword::CONSTRAINTS,
23
    ];
24
25
    private array $requiredHeaders = [
26
        Keyword::NAME,
27
        Keyword::DATATYPE,
28
    ];
29
30
    public function __construct(array $headers)
31
    {
32 4
        $this->headers = $headers;
33
    }
34 4
35 4
    public function validate(): void
36
    {
37 4
        $this->validateAllowedHeaders();
38
39 4
        $this->validateRequiredHeaders();
40 4
    }
41
42 4
    private function validateAllowedHeaders(): void
43 4
    {
44 4
        $notAllowedHeaders = \array_filter($this->headers, fn ($header) => !\in_array($header, $this->allowedHeaders));
45
46
        if (!empty($notAllowedHeaders)) {
47
            throw new HeaderSyntaxValidationException('Unknow headers: ' . \implode(', ', $notAllowedHeaders));
48 4
        }
49 1
    }
50
51
    private function validateRequiredHeaders(): void
52 3
    {
53 3
        $requiredHeaders = \array_filter(
54 3
            $this->requiredHeaders,
55
            fn ($required) => !\in_array($required, $this->headers)
56
        );
57
58 3
        if (!empty($requiredHeaders)) {
59 1
            throw new HeaderSyntaxValidationException(
60 1
                'Required headers not present: ' . \implode(', ', $requiredHeaders)
61
            );
62
        }
63 2
    }
64
}
65