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 |
||
| 11 | class RequestTransformerTest extends \PHPUnit_Framework_TestCase |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * @return RequestTransformer |
||
| 15 | */ |
||
| 16 | public function getSubject() |
||
| 17 | { |
||
| 18 | $serializer = m::mock('MediaMonks\RestApi\Serializer\SerializerInterface'); |
||
| 19 | $serializer->shouldReceive('getSupportedFormats')->andReturn(['json', 'xml']); |
||
| 20 | $serializer->shouldReceive('getDefaultFormat')->andReturn('json'); |
||
| 21 | |||
| 22 | return new RequestTransformer($serializer); |
||
| 23 | } |
||
| 24 | |||
| 25 | public function testTransformChangesRequestParameters() |
||
| 26 | { |
||
| 27 | $subject = $this->getSubject(); |
||
| 28 | $content = ['Hello', 'World!']; |
||
| 29 | $request = $this->getRequest($content); |
||
| 30 | |||
| 31 | $subject->transform($request); |
||
| 32 | |||
| 33 | $this->assertEquals($content, iterator_to_array($request->request->getIterator())); |
||
| 34 | } |
||
| 35 | |||
| 36 | public function testTransformChangesRequestFormatDefault() |
||
| 37 | { |
||
| 38 | $subject = $this->getSubject(); |
||
| 39 | $request = $this->getRequest([]); |
||
| 40 | |||
| 41 | $subject->transform($request); |
||
| 42 | |||
| 43 | $this->assertEquals('json', $request->getRequestFormat()); |
||
| 44 | } |
||
| 45 | |||
| 46 | public function testTransformChangesRequestFormatGiven() |
||
| 47 | { |
||
| 48 | $subject = $this->getSubject(); |
||
| 49 | $request = $this->getRequest([]); |
||
| 50 | $request->initialize(['_format' => 'xml']); |
||
| 51 | |||
| 52 | $subject->transform($request); |
||
| 53 | |||
| 54 | $this->assertEquals('xml', $request->getRequestFormat()); |
||
| 55 | } |
||
| 56 | |||
| 57 | public function testTransformChangesRequestFormatUnknown() |
||
| 58 | { |
||
| 59 | $subject = $this->getSubject(); |
||
| 60 | $request = $this->getRequest([]); |
||
| 61 | $request->initialize(['_format' => 'csv']); |
||
| 62 | |||
| 63 | $subject->transform($request); |
||
| 64 | |||
| 65 | $this->assertEquals(Format::getDefault(), $request->getRequestFormat()); |
||
| 66 | } |
||
| 67 | |||
| 68 | protected function getRequest($content) |
||
| 69 | { |
||
| 70 | $request = Request::create('/'); |
||
| 71 | $request->initialize([], [], [], [], [], [], json_encode($content)); |
||
| 72 | $request->headers->add(['Content-type' => 'application/json']); |
||
| 73 | return $request; |
||
| 74 | } |
||
| 75 | } |
||
| 76 |