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 |
||
| 8 | class EventTest extends TestCase |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * @var EmitterInterface |
||
| 12 | */ |
||
| 13 | private $emitter; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @var Event |
||
| 17 | */ |
||
| 18 | private $event; |
||
| 19 | |||
| 20 | protected function setUp() |
||
| 21 | { |
||
| 22 | $this->emitter = $this->createMock(EmitterInterface::class); |
||
| 23 | $this->event = new Event($this->emitter); |
||
| 24 | } |
||
| 25 | |||
| 26 | public function testAcknowledge() |
||
| 27 | { |
||
| 28 | $message = new Message( |
||
| 29 | 'queue', |
||
| 30 | 'handler', |
||
| 31 | ['foo' => 'bar'] |
||
| 32 | ); |
||
| 33 | |||
| 34 | $this->emitter |
||
| 35 | ->expects($this->exactly(2)) |
||
| 36 | ->method('emit') |
||
| 37 | ->withConsecutive( |
||
| 38 | [Event::MESSAGE_ACKNOWLEDGE, $message], |
||
| 39 | [sprintf('%s.%s', Event::MESSAGE_ACKNOWLEDGE, $message->handler()), $message] |
||
| 40 | ); |
||
| 41 | |||
| 42 | $this->event->acknowledge($message); |
||
| 43 | } |
||
| 44 | |||
| 45 | public function testFinish() |
||
| 46 | { |
||
| 47 | $message = new Message( |
||
| 48 | 'queue', |
||
| 49 | 'handler', |
||
| 50 | ['foo' => 'bar'] |
||
| 51 | ); |
||
| 52 | |||
| 53 | $this->emitter |
||
| 54 | ->expects($this->exactly(2)) |
||
| 55 | ->method('emit') |
||
| 56 | ->withConsecutive( |
||
| 57 | [Event::MESSAGE_FINISH, $message], |
||
| 58 | [sprintf('%s.%s', Event::MESSAGE_FINISH, $message->handler()), $message] |
||
| 59 | ); |
||
| 60 | |||
| 61 | $this->event->finish($message); |
||
| 62 | } |
||
| 63 | |||
| 64 | public function testReject() |
||
| 65 | { |
||
| 66 | $message = new Message( |
||
| 67 | 'queue', |
||
| 68 | 'handler', |
||
| 69 | ['foo' => 'bar'] |
||
| 70 | ); |
||
| 71 | |||
| 72 | $exception = new Exception; |
||
| 73 | |||
| 74 | $this->emitter |
||
| 75 | ->expects($this->exactly(2)) |
||
| 76 | ->method('emit') |
||
| 77 | ->withConsecutive( |
||
| 78 | [Event::MESSAGE_REJECT, $message, $exception], |
||
| 79 | [sprintf('%s.%s', Event::MESSAGE_REJECT, $message->handler()), $message, $exception] |
||
| 80 | ); |
||
| 81 | |||
| 82 | $this->event->reject($message, $exception); |
||
| 83 | } |
||
| 84 | } |
||
| 85 |