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 |
||
| 10 | class ServiceProviderTest extends \PHPUnit_Framework_TestCase |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * @var \PHPUnit_Framework_MockObject_MockObject|\League\Container\ContainerInterface |
||
| 14 | */ |
||
| 15 | private $container; |
||
| 16 | /** |
||
| 17 | * @var ServiceProvider |
||
| 18 | */ |
||
| 19 | private $obj; |
||
| 20 | |||
| 21 | protected function setUp() |
||
| 22 | { |
||
| 23 | $this->container = $this->getMockBuilder('\League\Container\ContainerInterface') |
||
| 24 | ->setMethods(['get']) |
||
| 25 | ->getMockForAbstractClass(); |
||
| 26 | |||
| 27 | $this->obj = new ServiceProvider(); |
||
| 28 | |||
| 29 | $this->obj->setContainer($this->container); |
||
| 30 | } |
||
| 31 | |||
| 32 | public function testAdd() |
||
| 33 | { |
||
| 34 | $s = $this->obj; |
||
| 35 | |||
| 36 | /** @var \League\Container\ServiceProvider\ServiceProviderInterface | \PHPUnit_Framework_MockObject_MockObject $resolved */ |
||
| 37 | $resolved = $this->getMockBuilder('\League\Container\ServiceProvider\ServiceProviderInterface') |
||
| 38 | ->setMethods(['provides']) |
||
| 39 | ->getMockForAbstractClass(); |
||
| 40 | |||
| 41 | $resolved->expects($this->once()) |
||
| 42 | ->method('provides') |
||
| 43 | ->willReturn(['service']); |
||
| 44 | |||
| 45 | $this->container->expects($this->once()) |
||
| 46 | ->method('get') |
||
| 47 | ->with('test') |
||
| 48 | ->willReturn($resolved); |
||
| 49 | |||
| 50 | $this->assertFalse($s->provides('service')); |
||
| 51 | |||
| 52 | $s->add('test'); |
||
| 53 | |||
| 54 | $this->assertTrue($s->provides('service')); |
||
| 55 | } |
||
| 56 | } |
||
| 57 |