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 |
||
| 14 | class OrXBuilderTest extends \PHPUnit_Framework_TestCase |
||
| 15 | { |
||
| 16 | public function testConstruct() |
||
| 17 | { |
||
| 18 | $builder = new OrXBuilder(new Registry()); |
||
| 19 | |||
| 20 | $this->assertInstanceOf(OrXBuilder::class, $builder); |
||
| 21 | } |
||
| 22 | |||
| 23 | public function testBuildReturnsOrxExpression() |
||
| 24 | { |
||
| 25 | $orx = $this->createOrX(); |
||
| 26 | $registry = $this->createRegistry($orx); |
||
| 27 | |||
| 28 | $builder = new OrXBuilder($registry); |
||
| 29 | |||
| 30 | $query = $builder->build($orx, new QueryBuilder()); |
||
| 31 | |||
| 32 | $this->assertInstanceOf(BoolQuery::class, $query); |
||
| 33 | |||
| 34 | $this->assertArrayHasKey('bool', $query->toArray()); |
||
| 35 | $this->assertArrayHasKey('should', $query->toArray()['bool']); |
||
| 36 | $this->assertCount(2, $query->toArray()['bool']['should']); |
||
| 37 | } |
||
| 38 | |||
| 39 | /** |
||
| 40 | * @return OrX |
||
| 41 | */ |
||
| 42 | private function createOrX() |
||
| 43 | { |
||
| 44 | return new OrX( |
||
| 45 | $this->createMock(Specification::class), |
||
| 46 | $this->createMock(Specification::class) |
||
| 47 | ); |
||
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * @param OrX $orx |
||
| 52 | * |
||
| 53 | * @return Registry |
||
| 54 | */ |
||
| 55 | private function createRegistry($orx) |
||
| 56 | { |
||
| 57 | $builder = $this->createMock(Builder::class); |
||
| 58 | $builder |
||
| 59 | ->expects($this->any()) |
||
| 60 | ->method('build') |
||
| 61 | ->willReturn($this->createMock(AbstractQuery::class)) |
||
| 62 | ; |
||
| 63 | |||
| 64 | $registry = new Registry(); |
||
| 65 | |||
| 66 | $registry->register(get_class($orx->getFirstPart()), $builder); |
||
| 67 | $registry->register(get_class($orx->getSecondPart()), $builder); |
||
| 68 | |||
| 69 | return $registry; |
||
| 70 | } |
||
| 71 | |||
| 72 | |||
| 73 | View Code Duplication | public function testBuildThrowExceptionIfNotOrXSpecification() |
|
| 83 | } |
||
| 84 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.