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 |
||
| 29 | class ManagerFactory |
||
| 30 | { |
||
| 31 | /** |
||
| 32 | * @var MetadataCollector |
||
| 33 | */ |
||
| 34 | private $metadataCollector; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @var Converter |
||
| 38 | */ |
||
| 39 | private $converter; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @var LoggerInterface |
||
| 43 | */ |
||
| 44 | private $logger; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @var LoggerInterface |
||
| 48 | */ |
||
| 49 | private $tracer; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @var EventDispatcherInterface |
||
| 53 | */ |
||
| 54 | private $eventDispatcher; |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @var Stopwatch |
||
| 58 | */ |
||
| 59 | private $stopwatch; |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @param MetadataCollector $metadataCollector Metadata collector service. |
||
| 63 | * @param Converter $converter Converter service to transform arrays to objects and visa versa. |
||
| 64 | * @param LoggerInterface $tracer |
||
| 65 | * @param LoggerInterface $logger |
||
| 66 | */ |
||
| 67 | public function __construct($metadataCollector, $converter, $tracer = null, $logger = null) |
||
| 74 | |||
| 75 | /** |
||
| 76 | * @param EventDispatcherInterface $eventDispatcher |
||
| 77 | */ |
||
| 78 | public function setEventDispatcher(EventDispatcherInterface $eventDispatcher) |
||
| 82 | |||
| 83 | /** |
||
| 84 | * @param Stopwatch $stopwatch |
||
| 85 | */ |
||
| 86 | public function setStopwatch(Stopwatch $stopwatch) |
||
| 90 | |||
| 91 | /** |
||
| 92 | * Factory function to create a manager instance. |
||
| 93 | * |
||
| 94 | * @param string $managerName Manager name. |
||
| 95 | * @param array $connection Connection configuration. |
||
| 96 | * @param array $analysis Analyzers, filters and tokenizers config. |
||
| 97 | * @param array $managerConfig Manager configuration. |
||
| 98 | * |
||
| 99 | * @return Manager |
||
| 100 | */ |
||
| 101 | public function createManager($managerName, $connection, $analysis, $managerConfig) |
||
| 171 | |||
| 172 | View Code Duplication | private function dispatch($eventName, $event) |
|
| 180 | } |
||
| 181 |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: