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 |
||
22 | class A extends OpenElement implements FlowContent, InteractiveContent, PhrasingContent, InlineElement, TransparentElement |
||
23 | { |
||
24 | 5 | protected function getAllowedAttributes() |
|
25 | { |
||
26 | $aAllowedAttributes = array( |
||
27 | 5 | '/^href$/i' => Element::ATTR_URI, |
|
28 | 5 | '/^target$/i' => Element::ATTR_CS_STRING, |
|
29 | 5 | '/^download$/i' => Element::ATTR_CS_STRING, |
|
30 | 5 | '/^ping$/i' => Element::ATTR_URI, |
|
31 | 5 | '/^rel$/i' => Element::ATTR_CS_STRING, |
|
32 | 5 | '/^hreflang$/i' => Element::ATTR_CS_STRING, |
|
33 | 5 | '/^type$/i' => Element::ATTR_CS_STRING, |
|
34 | '/^referrerpolicy$/i' => Element::ATTR_CS_STRING |
||
35 | 5 | ); |
|
36 | |||
37 | 5 | return array_merge( |
|
38 | 5 | $aAllowedAttributes, |
|
39 | 5 | parent::getAllowedAttributes() |
|
40 | 5 | ); |
|
41 | } |
||
42 | |||
43 | 5 | View Code Duplication | protected function fixSelf(LoggerInterface $logger) |
|
|||
44 | { |
||
45 | // If the "itemprop" attribute is specified on an "a" element, then |
||
46 | // the "href" attribute must also be specified. |
||
47 | 5 | if ($this->hasAttribute('itemprop') && !$this->hasAttribute('href')) { |
|
48 | 1 | $logger->debug($this . ' with "itemprop" attribute requires the "href" attribute also. Adding empty "href" attribute.'); |
|
49 | 1 | $this->addAttribute('href', ''); |
|
50 | 1 | } |
|
51 | 5 | } |
|
52 | |||
53 | 5 | protected function removeInvalidChildren(LoggerInterface $logger) |
|
54 | { |
||
55 | // There must be no interactive content or "a" element descendants. |
||
56 | 5 | foreach ($this->children as $child) { |
|
57 | 5 | if ($child instanceof NonParticipating) { |
|
58 | 1 | continue; |
|
59 | } |
||
60 | |||
61 | 5 | if ($child instanceof self && |
|
62 | 5 | ($child instanceof InteractiveContent && $child->isInteractiveContent())) { |
|
63 | 1 | $logger->debug('Removing ' . $child . '. Element "a" cannot contain "a" or interactive content elements.'); |
|
64 | 1 | $this->removeChild($child); |
|
65 | 1 | } |
|
66 | 5 | } |
|
67 | 5 | } |
|
68 | |||
69 | 5 | protected function removeInvalidSelf(LoggerInterface $logger) |
|
96 | |||
97 | 1 | public function isInteractiveContent() |
|
98 | { |
||
99 | 1 | return $this->hasAttribute('href'); |
|
100 | } |
||
101 | |||
102 | public function isTransparentElement() |
||
106 | } |
||
107 |
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.