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 |
||
| 5 | class AliceContext extends Context |
||
| 6 | { |
||
| 7 | /** |
||
| 8 | * @BeforeBackground |
||
| 9 | **/ |
||
| 10 | public function loadAlice($event) |
||
| 34 | |||
| 35 | protected function loadFixtures($loader, $fixtures, $files) |
||
| 36 | { |
||
| 37 | $persistable = $this->getPersistableClasses(); |
||
| 38 | |||
| 39 | foreach ($fixtures as $id => $fixture) { |
||
| 40 | if (in_array($id, $files)) { |
||
| 41 | foreach ($loader->load($fixture) as $object) { |
||
| 42 | if (in_array(get_class($object), $persistable)) { |
||
| 43 | $this->getEntityManager()->persist($object); |
||
| 44 | } |
||
| 45 | } |
||
| 46 | |||
| 47 | $this->getEntityManager()->flush(); |
||
| 48 | } |
||
| 49 | } |
||
| 50 | } |
||
| 51 | |||
| 52 | private function getPersistableClasses() |
||
| 53 | { |
||
| 54 | $persistable = array(); |
||
| 55 | $metadatas = $this->getEntityManager()->getMetadataFactory()->getAllMetadata(); |
||
| 56 | |||
| 57 | foreach ($metadatas as $metadata) { |
||
| 58 | if (isset($metadata->isEmbeddedClass) && $metadata->isEmbeddedClass) { |
||
| 59 | continue; |
||
| 60 | } |
||
| 61 | |||
| 62 | $persistable[] = $metadata->getName(); |
||
| 63 | } |
||
| 64 | |||
| 65 | return $persistable; |
||
| 66 | } |
||
| 67 | |||
| 68 | protected function registerCache($loader) |
||
| 69 | { |
||
| 70 | foreach ($loader->getCache() as $cache) { |
||
| 71 | list($values, $entity) = $cache; |
||
| 72 | $reflection = new \ReflectionClass($entity); |
||
| 73 | View Code Duplication | do { |
|
| 74 | $this |
||
| 75 | ->getRecordBag() |
||
| 76 | ->getCollection($reflection->getName()) |
||
| 77 | ->attach($entity, $values) |
||
| 78 | ; |
||
| 79 | $reflection = $reflection->getParentClass(); |
||
| 80 | } while (false !== $reflection); |
||
| 81 | } |
||
| 82 | $loader->clearCache(); |
||
| 83 | } |
||
| 84 | |||
| 85 | protected function resolveDepsFromArray(array $fixtures) |
||
| 95 | |||
| 96 | protected function resolveDeps($fixture, array &$result = []) |
||
| 111 | } |
||
| 112 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.