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 declare(strict_types=1); |
||
5 | class Origin |
||
6 | { |
||
7 | private array $configuration; |
||
|
|||
8 | |||
9 | 4 | public function __construct(array $configuration) |
|
10 | { |
||
11 | 4 | $this->configuration = $configuration; |
|
12 | } |
||
13 | |||
14 | 4 | public function get(): string |
|
15 | { |
||
16 | 4 | if (isset($this->configuration['ssl'])) { |
|
17 | 2 | return $this->getHttpsOrigin(); |
|
18 | } |
||
19 | |||
20 | 2 | return $this->getHttpOrigin(); |
|
21 | } |
||
22 | |||
23 | 2 | private function getHttpsOrigin(): string |
|
24 | { |
||
25 | 2 | $origin = 'https://' . $this->configuration['hostname']; |
|
26 | |||
27 | 2 | if ($this->configuration['ssl']['port'] !== 443) { |
|
28 | 1 | $origin .= ':' . $this->configuration['ssl']['port']; |
|
29 | } |
||
30 | |||
31 | 2 | return $origin; |
|
32 | } |
||
33 | |||
34 | 2 | private function getHttpOrigin(): string |
|
35 | { |
||
36 | 2 | $origin = 'http://' . $this->configuration['hostname']; |
|
37 | |||
38 | 2 | if ($this->configuration['expose']['port'] !== 80) { |
|
39 | 1 | $origin .= ':' . $this->configuration['expose']['port']; |
|
40 | } |
||
41 | |||
42 | 2 | return $origin; |
|
43 | } |
||
44 | } |
||
45 |