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 // phpcs:ignore WordPress.Files.FileName |
||
14 | class Test_Manifest_Reader extends TestCase { |
||
15 | |||
16 | /** |
||
17 | * A mock of the version selector used by the reader. |
||
18 | * |
||
19 | * @var Version_Selector|\PHPUnit\Framework\MockObject\MockObject |
||
20 | */ |
||
21 | private $version_selector; |
||
22 | |||
23 | /** |
||
24 | * The manifest reader we're testing. |
||
25 | * |
||
26 | * @var Manifest_Reader |
||
27 | */ |
||
28 | private $reader; |
||
29 | |||
30 | /** |
||
31 | * Setup runs before each test. |
||
32 | * |
||
33 | * @before |
||
34 | */ |
||
35 | public function set_up() { |
||
36 | $this->version_selector = $this->getMockBuilder( Version_Selector::class ) |
||
37 | ->disableOriginalConstructor() |
||
38 | ->getMock(); |
||
39 | $this->reader = new Manifest_Reader( $this->version_selector ); |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * Tests that nothing is read without any plugins. |
||
44 | */ |
||
45 | public function test_reads_nothing_without_plugins() { |
||
56 | |||
57 | /** |
||
58 | * Tests that nothing is read for plugins that have no manifest. |
||
59 | */ |
||
60 | public function test_reads_nothing_for_plugins_without_manifests() { |
||
71 | |||
72 | /** |
||
73 | * Tests that a single plugin manifest can be read successfully. |
||
74 | */ |
||
75 | public function test_reads_single_plugin_manifest() { |
||
99 | |||
100 | /** |
||
101 | * Tests that the reader only keeps the latest version when processing multiple manifests. |
||
102 | */ |
||
103 | View Code Duplication | public function test_read_overwrites_older_version_in_manifest() { |
|
134 | |||
135 | /** |
||
136 | * Tests that the reader ignores older versions when a newer version is already set. |
||
137 | */ |
||
138 | View Code Duplication | public function test_read_ignores_older_version_when_newer_already_loaded() { |
|
169 | } |
||
170 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: