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