Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
23 | final class HeadersConstraint extends Constraint |
||
24 | { |
||
25 | private $errors = []; |
||
26 | |||
27 | private $expectedHeadersSchemas; |
||
28 | |||
29 | private $validator; |
||
30 | |||
31 | 11 | public function __construct(array $expectedHeadersSchemas) |
|
32 | { |
||
33 | 11 | $this->expectedHeadersSchemas = array_map([$this, 'normalizeJsonSchema'], $expectedHeadersSchemas); |
|
34 | 11 | $this->validator = new Validator('undefined'); |
|
35 | } |
||
36 | |||
37 | 3 | public function toString(): string |
|
38 | { |
||
39 | 3 | return 'matches an specified headers schemas'; |
|
40 | } |
||
41 | |||
42 | 11 | protected function matches($actualHeaders): bool |
|
43 | { |
||
44 | 11 | if (!is_array($actualHeaders)) { |
|
45 | 1 | throw new UnexpectedValueException('Array expected'); |
|
46 | } |
||
47 | |||
48 | 10 | View Code Duplication | foreach ($this->expectedHeadersSchemas as $name => $expectedSchema) { |
|
|||
49 | 8 | if (isset($actualHeaders[$name])) { |
|
50 | 6 | $errors = $this->validator->validate( |
|
51 | 6 | $this->normalizeHeaderValue($actualHeaders[$name], $expectedSchema->type), |
|
52 | 6 | $expectedSchema, |
|
53 | 6 | new JsonPointer("#/{$name}") |
|
54 | ); |
||
55 | 6 | $this->errors = array_merge($this->errors, $errors); |
|
56 | 4 | } elseif (isset($expectedSchema->required) && $expectedSchema->required) { |
|
57 | 2 | $this->errors[] = [ |
|
58 | 2 | 'property' => $name, |
|
59 | 2 | 'message' => "Missing required header ({$name})", |
|
60 | ]; |
||
61 | } |
||
62 | } |
||
63 | |||
64 | 10 | return empty($this->errors); |
|
65 | } |
||
66 | |||
67 | 3 | protected function failureDescription($other): string |
|
68 | { |
||
69 | 3 | return json_encode($other) . ' ' . $this->toString(); |
|
70 | } |
||
71 | |||
72 | 3 | protected function additionalFailureDescription($other): string |
|
73 | { |
||
74 | 3 | return $this->validator->serializeErrors($this->errors); |
|
75 | } |
||
76 | |||
77 | 9 | private static function normalizeJsonSchema($schema): stdClass |
|
81 | |||
82 | /** |
||
83 | * The PSR-7 says that the header values MUST be an array of strings, |
||
84 | * but OpenAPI allow scalar values. So if scalar value expected, |
||
85 | * we try to cast array to scalar, using first element. |
||
86 | * |
||
87 | * @return mixed |
||
88 | */ |
||
89 | 6 | private static function normalizeHeaderValue(array $value, string $type) |
|
101 | } |
||
102 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.