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 |
||
| 19 | trait CommonDriverMethods |
||
| 20 | { |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var array |
||
| 24 | */ |
||
| 25 | protected $data = []; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * Checks if provided file exists |
||
| 29 | * |
||
| 30 | * @param string $file |
||
| 31 | * |
||
| 32 | * @throws FileNotFoundException if provided file does not exists |
||
| 33 | */ |
||
| 34 | protected function checkFile($file) |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Returns the value store with provided key or the default value. |
||
| 45 | * |
||
| 46 | * @param string $key The key used to store the value in configuration |
||
| 47 | * @param mixed $default The default value if no value was stored. |
||
| 48 | * |
||
| 49 | * @return mixed The stored value or the default value if key |
||
| 50 | * was not found. |
||
| 51 | */ |
||
| 52 | public function get($key, $default = null) |
||
| 56 | |||
| 57 | /** |
||
| 58 | * Set/Store the provided value with a given key. |
||
| 59 | * |
||
| 60 | * @param string $key The key used to store the value in configuration. |
||
| 61 | * @param mixed $value The value to store under the provided key. |
||
| 62 | * |
||
| 63 | * @return CommonDriverMethods|self Self instance for method call chains. |
||
|
|
|||
| 64 | */ |
||
| 65 | public function set($key, $value) |
||
| 70 | |||
| 71 | /** |
||
| 72 | * Recursive method to parse dot notation keys and retrieve the value |
||
| 73 | * |
||
| 74 | * @param string $key The key/index to search |
||
| 75 | * @param mixed $default The value if key doesn't exists |
||
| 76 | * @param array $data The data to search |
||
| 77 | * |
||
| 78 | * @return mixed The stored value or the default value if key |
||
| 79 | * or index was not found. |
||
| 80 | */ |
||
| 81 | View Code Duplication | public static function getValue($key, $default, $data) |
|
| 94 | /** |
||
| 95 | * Recursive method to parse dot notation keys and set the value |
||
| 96 | * |
||
| 97 | * @param string $key The key used to store the value in configuration. |
||
| 98 | * @param mixed $value The value to store under the provided key. |
||
| 99 | * @param array $data The data to search |
||
| 100 | */ |
||
| 101 | View Code Duplication | public static function setValue($key, $value, &$data) |
|
| 115 | } |
||
| 116 |
In PHP traits cannot be used for type-hinting as they do not define a well-defined structure. This is because any class that uses a trait can rename that trait’s methods.
If you would like to return an object that has a guaranteed set of methods, you could create a companion interface that lists these methods explicitly.