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 GH6402Test extends OrmFunctionalTestCase |
||
| 17 | { |
||
| 18 | protected function setUp() |
||
| 19 | { |
||
| 20 | $this->useModelSet('quote'); |
||
| 21 | |||
| 22 | parent::setUp(); |
||
| 23 | } |
||
| 24 | |||
| 25 | public function testFind() |
||
| 26 | { |
||
| 27 | $id = $this->createAddress(); |
||
| 28 | |||
| 29 | $address = $this->_em->find(Address::class, $id); |
||
| 30 | self::assertNotNull($address->user); |
||
| 31 | } |
||
| 32 | |||
| 33 | View Code Duplication | public function testQuery() |
|
| 34 | { |
||
| 35 | $id = $this->createAddress(); |
||
| 36 | |||
| 37 | $addresses = $this->_em->createQuery('SELECT a FROM ' . Address::class . ' a WHERE a.id = :id') |
||
| 38 | ->setParameter('id', $id) |
||
| 39 | ->getResult(); |
||
| 40 | |||
| 41 | self::assertCount(1, $addresses); |
||
| 42 | self::assertNotNull($addresses[0]->user); |
||
| 43 | } |
||
| 44 | |||
| 45 | public function testFindWithSubClass() |
||
| 52 | |||
| 53 | View Code Duplication | public function testQueryWithSubClass() |
|
| 54 | { |
||
| 55 | $id = $this->createFullAddress(); |
||
| 56 | |||
| 57 | $addresses = $this->_em->createQuery('SELECT a FROM ' . FullAddress::class . ' a WHERE a.id = :id') |
||
| 58 | ->setParameter('id', $id) |
||
| 59 | ->getResult(); |
||
| 60 | |||
| 61 | self::assertCount(1, $addresses); |
||
| 62 | self::assertNotNull($addresses[0]->user); |
||
| 63 | } |
||
| 64 | |||
| 65 | private function createAddress() |
||
| 66 | { |
||
| 67 | $address = new Address(); |
||
| 68 | $address->zip = 'bar'; |
||
| 69 | |||
| 70 | $this->persistAddress($address); |
||
| 71 | |||
| 72 | return $address->id; |
||
| 73 | } |
||
| 74 | |||
| 75 | private function createFullAddress() |
||
| 85 | |||
| 86 | private function persistAddress(Address $address) |
||
| 96 | } |
||
| 97 |
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: