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 |
||
17 | class YamlHandlerTest extends PHPUnit_Framework_TestCase |
||
18 | { |
||
19 | /** |
||
20 | * tests serialize() method. |
||
21 | * |
||
22 | * @dataProvider serializationSuccessCaseProvider |
||
23 | */ |
||
24 | public function testSerialize($normalizedData, $output) |
||
25 | { |
||
26 | $object = $this->prophesize('StdClass'); |
||
27 | $object->willImplement(NormalizableInterface::class); |
||
28 | $object = $object->reveal(); |
||
29 | |||
30 | $scope = 'test'; |
||
31 | |||
32 | $normalizer = $this->prophesize(MajoraNormalizer::class); |
||
33 | $normalizer->normalize($object, $scope) |
||
34 | ->willReturn($normalizedData) |
||
35 | ->shouldBeCalled() |
||
36 | ; |
||
37 | |||
38 | $collectionHandler = new YamlHandler( |
||
39 | new Yaml(), |
||
40 | $normalizer->reveal() |
||
41 | ); |
||
42 | |||
43 | $this->assertEquals( |
||
44 | $output, |
||
45 | $collectionHandler->serialize($object, $scope) |
||
46 | ); |
||
47 | } |
||
48 | |||
49 | public function serializationSuccessCaseProvider() |
||
50 | { |
||
51 | return array( |
||
52 | 'string_as_array' => array(array('string'), "- string\n"), |
||
53 | 'int_as_array' => array(array(42), "- 42\n"), |
||
54 | 'array_as_array' => array( |
||
55 | array('hello', 'foo' => 'bar', 42), |
||
56 | "0: hello\nfoo: bar\n1: 42\n", |
||
57 | ), |
||
58 | ); |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * tests deserialize() method. |
||
63 | * |
||
64 | * @dataProvider deserializationSuccessCaseProvider |
||
65 | */ |
||
66 | public function testDeserialize($json, $normalizedData) |
||
67 | { |
||
68 | $normalizer = $this->prophesize(MajoraNormalizer::class); |
||
69 | $normalizer->denormalize($normalizedData, \StdClass::class) |
||
70 | ->shouldBeCalled() |
||
71 | ; |
||
72 | |||
73 | $collectionHandler = new YamlHandler( |
||
74 | new Yaml(), |
||
75 | $normalizer->reveal() |
||
76 | ); |
||
77 | $collectionHandler->deserialize($json, \StdClass::class); |
||
78 | } |
||
79 | |||
80 | public function deserializationSuccessCaseProvider() |
||
81 | { |
||
82 | return array( |
||
83 | 'string_as_array' => array("- string\n", array('string')), |
||
84 | 'int_as_array' => array("- 42\n", array(42)), |
||
85 | 'array_as_array' => array( |
||
86 | "0: hello\nfoo: bar\n1: 42\n", |
||
87 | array('hello', 'foo' => 'bar', 42), |
||
88 | ) |
||
89 | ); |
||
90 | } |
||
91 | } |
||
92 |