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 |
||
8 | class MetaCompiler |
||
9 | { |
||
10 | /** |
||
11 | * @var callable[] |
||
12 | */ |
||
13 | private $compilers = []; |
||
14 | private $metaConfig; |
||
15 | |||
16 | public function __construct(array $metaConfig = []) { |
||
17 | $this->metaConfig = $metaConfig; |
||
18 | |||
19 | $this->addCompiler('title', [$this, 'compileTitle']); |
||
20 | $this->addCompiler('description', [$this, 'compileDescription']); |
||
21 | $this->addCompiler('image', [$this, 'compileImage']); |
||
22 | $this->addCompiler('pagination', [$this, 'compilePagination']); |
||
23 | $this->addCompiler('meta', [$this, 'compileMeta']); |
||
24 | $this->addCompiler('_name', [$this, 'compileNamedMeta']); |
||
25 | } |
||
26 | |||
27 | public function setDefaultMeta(Meta &$meta) { |
||
28 | foreach ($this->metaConfig as $name => $value) { |
||
29 | $meta->name($name, $value); |
||
30 | } |
||
31 | } |
||
32 | |||
33 | public function addCompiler(string $name, callable $callback) : MetaCompiler { |
||
38 | |||
39 | public function compilePage(Page $page) { |
||
40 | $variables = $page->getVariables(); |
||
50 | |||
51 | public function compilePageVariable(Page $page, string $name, $data, bool $force = false) { |
||
64 | |||
65 | private function compileTitle(Page $page, string $data) { |
||
68 | |||
69 | private function compileDescription(Page $page, string $data) { |
||
72 | |||
73 | private function compileImage(Page $page, $data) { |
||
80 | |||
81 | private function compilePagination(Page $page, array $pagination) { |
||
90 | |||
91 | private function compileMeta(Page $page, array $data) { |
||
96 | |||
97 | private function compileNamedMeta(Page $page, $data, string $name) { |
||
100 | } |
||
101 |
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.