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 |
||
| 16 | class ConfigBuilder implements ConfigBuilderContract |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * @var ConfigFactory |
||
| 20 | */ |
||
| 21 | private $configFactory; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * Items holder array. |
||
| 25 | * |
||
| 26 | * @var array |
||
| 27 | */ |
||
| 28 | private $items = []; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @var ConfigFileParser[]|ConfigParser[] |
||
| 32 | */ |
||
| 33 | private $parsers = []; |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Construct function. |
||
| 37 | * |
||
| 38 | * @param null|ConfigFactoryContract $configFactory |
||
| 39 | */ |
||
| 40 | public function __construct(ConfigFactoryContract $configFactory = null) |
||
| 44 | |||
| 45 | /** |
||
| 46 | * @inheritDoc |
||
| 47 | */ |
||
| 48 | public function addFileParser(ConfigFileParser $parser) |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @inheritDoc |
||
| 55 | */ |
||
| 56 | public function build(): Config |
||
| 60 | |||
| 61 | /** |
||
| 62 | * Merges configuration data. |
||
| 63 | * |
||
| 64 | * @param array $config |
||
| 65 | * @return void |
||
| 66 | */ |
||
| 67 | public function merge(array $config) |
||
| 71 | |||
| 72 | /** |
||
| 73 | * Merges configuration data form file. |
||
| 74 | * |
||
| 75 | * @param string $filename |
||
| 76 | * @return void |
||
| 77 | */ |
||
| 78 | public function mergeFile(string $filename) |
||
| 90 | |||
| 91 | /** |
||
| 92 | * Appends a value to a config array. |
||
| 93 | * |
||
| 94 | * @param string $path |
||
| 95 | * @param mixed $value |
||
| 96 | * @return void |
||
| 97 | */ |
||
| 98 | View Code Duplication | public function push(string $path, $value) |
|
| 115 | |||
| 116 | /** |
||
| 117 | * Sets value to the configuration data. |
||
| 118 | * |
||
| 119 | * @param string $path |
||
| 120 | * @param $value |
||
| 121 | * @return void |
||
| 122 | */ |
||
| 123 | View Code Duplication | public function set(string $path, $value) |
|
| 140 | } |
||
| 141 |
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare 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.phpHowever, as
OtherDir/Foo.phpdoes 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: