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 |
||
13 | class Pages { |
||
14 | |||
15 | /** |
||
16 | * @var Page[] |
||
17 | */ |
||
18 | private $pages; |
||
19 | |||
20 | /** |
||
21 | * @param Page[] $pages |
||
22 | 4 | */ |
|
23 | 4 | public function __construct( $pages = [] ) { |
|
24 | 4 | $this->pages = []; |
|
25 | 4 | $this->addPages( $pages ); |
|
26 | } |
||
27 | |||
28 | /** |
||
29 | * @param Page[]|Pages $pages |
||
30 | * |
||
31 | * @throws InvalidArgumentException |
||
32 | 4 | */ |
|
33 | 4 | View Code Duplication | public function addPages( $pages ) { |
|
|||
34 | if ( !is_array( $pages ) && !$pages instanceof Pages ) { |
||
35 | throw new InvalidArgumentException( '$pages needs to either be an array or a Pages object' ); |
||
36 | 4 | } |
|
37 | 1 | if ( $pages instanceof Pages ) { |
|
38 | 1 | $pages = $pages->toArray(); |
|
39 | 4 | } |
|
40 | 4 | foreach ( $pages as $page ) { |
|
41 | 4 | $this->addPage( $page ); |
|
42 | 4 | } |
|
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param Page $page |
||
47 | 4 | */ |
|
48 | 4 | public function addPage( Page $page ) { |
|
49 | 4 | $this->pages[$page->getId()] = $page; |
|
50 | } |
||
51 | |||
52 | /** |
||
53 | * @param int $id |
||
54 | * |
||
55 | * @return bool |
||
56 | */ |
||
57 | public function hasPageWithId( $id ) { |
||
58 | return array_key_exists( $id, $this->pages ); |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * @param Page $page |
||
63 | * |
||
64 | * @return bool |
||
65 | */ |
||
66 | public function hasPage( Page $page ) { |
||
67 | return array_key_exists( $page->getId(), $this->pages ); |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * @return Page|null Page or null if there is no page |
||
72 | */ |
||
73 | public function getLatest() { |
||
74 | if ( empty( $this->pages ) ) { |
||
75 | return null; |
||
76 | } |
||
77 | return $this->pages[ max( array_keys( $this->pages ) ) ]; |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * @param int $pageid |
||
82 | * |
||
83 | * @throws RuntimeException |
||
84 | * @return Page |
||
85 | */ |
||
86 | public function get( $pageid ) { |
||
92 | |||
93 | /** |
||
94 | * @return Page[] |
||
95 | */ |
||
96 | 4 | public function toArray() { |
|
99 | } |
||
100 |
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.