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 |
||
25 | class CentrifugoChecker |
||
26 | { |
||
27 | private int $channelMaxLength; |
||
|
|||
28 | |||
29 | /** |
||
30 | * @param int $centrifugoChannelMaxLength |
||
31 | */ |
||
32 | public function __construct(int $centrifugoChannelMaxLength) |
||
33 | { |
||
34 | $this->channelMaxLength = $centrifugoChannelMaxLength; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @param string $channelName |
||
39 | * |
||
40 | * @throws InvalidArgumentException |
||
41 | * |
||
42 | * @return bool |
||
43 | */ |
||
44 | public function assertValidChannelName(string $channelName): bool |
||
45 | { |
||
46 | if (false === \mb_detect_encoding($channelName, 'ASCII', true)) { |
||
47 | throw new InvalidArgumentException('Invalid channel name. Only ASCII symbols must be used in channel string.'); |
||
48 | } |
||
49 | |||
50 | if (\strlen($channelName) > $this->channelMaxLength) { |
||
51 | throw new InvalidArgumentException(\sprintf('Invalid channel name length. Maximum allowed length is %d.', $this->channelMaxLength)); |
||
52 | } |
||
53 | |||
54 | return true; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @param ResponseInterface $response |
||
59 | * |
||
60 | * @throws CentrifugoException |
||
61 | */ |
||
62 | public function assertValidResponseStatusCode(ResponseInterface $response): void |
||
63 | { |
||
64 | if (Response::HTTP_OK !== $response->getStatusCode()) { |
||
65 | throw new CentrifugoException('Wrong status code for Centrifugo response'); |
||
66 | } |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * @param ResponseInterface $response |
||
71 | * |
||
72 | * @throws CentrifugoException |
||
73 | */ |
||
74 | public function assertValidResponseHeaders(ResponseInterface $response): void |
||
75 | { |
||
76 | $headers = $response->getHeaders(false); |
||
77 | |||
78 | if (!isset($headers['content-type'])) { |
||
79 | throw new CentrifugoException('Missing "content-type" header in Centrifugo response'); |
||
80 | } |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @param ResponseInterface $response |
||
85 | * |
||
86 | * @throws CentrifugoException |
||
87 | */ |
||
88 | public function assertValidResponseContentType(ResponseInterface $response): void |
||
89 | { |
||
90 | $headers = $response->getHeaders(false); |
||
91 | |||
92 | if (!\in_array('application/json', $headers['content-type'], true)) { |
||
93 | throw new CentrifugoException('Unexpected content type for Centrifugo response'); |
||
94 | } |
||
95 | } |
||
96 | } |
||
97 |