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 |
||
23 | class FlashMessagesSpec extends ObjectBehavior |
||
24 | { |
||
25 | function let(SessionDriverInterface $sessionDriver) |
||
26 | { |
||
27 | $sessionDriver->get('_messages_', [])->shouldBeCalled()->willReturn([]); |
||
28 | $sessionDriver->set(Argument::type('string'), Argument::any())->willReturn($sessionDriver); |
||
29 | $sessionDriver->erase(Argument::type('string'))->willReturn($sessionDriver); |
||
30 | |||
31 | $this->beConstructedWith($sessionDriver); |
||
32 | |||
33 | } |
||
34 | |||
35 | function it_is_initializable() |
||
36 | { |
||
37 | $this->shouldHaveType(FlashMessages::class); |
||
38 | } |
||
39 | |||
40 | function it_can_set_messages_of_a_given_type(SessionDriverInterface $sessionDriver) |
||
41 | { |
||
42 | |||
43 | $this->set(FlashMessages::TYPE_INFO, 'Info messages') |
||
44 | ->shouldBe($this->getWrappedObject()); |
||
45 | $sessionDriver->set('_messages_', [FlashMessages::TYPE_INFO => ['Info messages']]) |
||
46 | ->shouldHaveBeenCalled(); |
||
47 | } |
||
48 | |||
49 | function it_cast_to_info_a_message_set_with_an_unknown_type(SessionDriverInterface $sessionDriver) |
||
50 | { |
||
51 | $this->flush(); |
||
52 | $this->set('Some Type', 'Info messages') |
||
53 | ->shouldBe($this->getWrappedObject()); |
||
54 | $sessionDriver->set('_messages_', [FlashMessages::TYPE_INFO => ['Info messages']]) |
||
55 | ->shouldHaveBeenCalled(); |
||
56 | } |
||
57 | |||
58 | function it_can_retrieve_all_messages() |
||
59 | { |
||
60 | $this->set(FlashMessages::TYPE_INFO, 'Info messages'); |
||
61 | $this->messages() |
||
62 | ->shouldHaveKey(FlashMessages::TYPE_INFO); |
||
63 | } |
||
64 | |||
65 | function it_flushes_all_messages_when_retrieving_them() |
||
66 | { |
||
67 | $this->messages()->shouldBeEmpty(); |
||
68 | } |
||
69 | |||
70 | function it_can_flush_all_messages(SessionDriverInterface $sessionDriver) |
||
71 | { |
||
72 | $this->set(FlashMessages::TYPE_ERROR, 'Error message'); |
||
73 | $this->flush(); |
||
74 | $this->messages()->shouldBeEmpty(); |
||
75 | $sessionDriver->erase('_messages_')->shouldHaveBeenCalled(); |
||
76 | } |
||
77 | |||
78 | public function getMatchers() |
||
79 | { |
||
80 | return [ |
||
81 | 'beEmpty' => function(array $subject) { |
||
82 | if (! empty($subject)) { |
||
83 | $count = count($subject); |
||
84 | throw new FailureException("Expecting and empty array, but got one with $count elements"); |
||
85 | } |
||
86 | return true; |
||
87 | } |
||
88 | ]; |
||
89 | } |
||
90 | } |