Completed
Push — master ( 54d34b...6715bf )
by Artem
02:12
created

JmsPreSerializeListenerTest   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 234
Duplicated Lines 32.05 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 6
Bugs 3 Features 3
Metric Value
wmc 13
c 6
b 3
f 3
lcom 1
cbo 14
dl 75
loc 234
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 20 1
A tearDown() 0 8 1
A testSerializationWithIncludedHost() 15 15 1
A testSerializationWithIncludedHttpHostAndPort() 15 15 1
A testSerializationWithIncludedHttpsHostAndPort() 15 15 1
A testSerializationWithoutIncludedHost() 15 15 1
A testExceptionForIncompatibleAnnotations() 15 15 1
A testSerializationOfTheSameObjectTwice() 0 21 1
B generateRequestContext() 0 32 4
A addEventListener() 0 7 1

How to fix   Duplicated Code   

Duplicated Code

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
2
/*
3
 * This file is part of the FreshVichUploaderSerializationBundle
4
 *
5
 * (c) Artem Genvald <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Fresh\VichUploaderSerializationBundle\Tests\EventListener;
12
13
use Doctrine\Common\Annotations\AnnotationReader;
14
use Doctrine\Common\Annotations\AnnotationRegistry;
15
use Doctrine\Common\Annotations\CachedReader;
16
use Doctrine\Common\Cache\ArrayCache;
17
use Fresh\VichUploaderSerializationBundle\EventListener\JmsPreSerializeListener;
18
use Fresh\VichUploaderSerializationBundle\Tests\Fixtures;
19
use JMS\Serializer\DeserializationContext;
20
use JMS\Serializer\EventDispatcher\ObjectEvent;
21
use JMS\Serializer\EventDispatcher\Events as JmsEvents;
22
use Monolog\Logger;
23
use JMS\Serializer\EventDispatcher\EventDispatcherInterface;
24
use Symfony\Component\Routing\RequestContext;
25
use Vich\UploaderBundle\Storage\StorageInterface;
26
use JMS\Serializer\EventDispatcher\EventDispatcher;
27
28
/**
29
 * JmsPreSerializeListenerTest
30
 *
31
 * @author Artem Genvald <[email protected]>
32
 */
33
class JmsPreSerializeListenerTest extends \PHPUnit_Framework_TestCase
34
{
35
    /**
36
     * @var EventDispatcherInterface $dispatcher Dispatcher
37
     */
38
    private $dispatcher;
39
40
    /**
41
     * @var StorageInterface $storage Vich storage
42
     */
43
    private $storage;
44
45
    /**
46
     * @var RequestContext $requestContext Request context
47
     */
48
    private $requestContext;
49
50
    /**
51
     * @var CachedReader $annotationReader Cached annotation reader
52
     */
53
    private $annotationReader;
54
55
    /**
56
     * @var Logger $logger Logger
57
     */
58
    private $logger;
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    protected function setUp()
64
    {
65
        AnnotationRegistry::registerLoader('class_exists');
66
67
        // Mock storage
68
        $this->storage = $this->getMockBuilder('Vich\UploaderBundle\Storage\FileSystemStorage')
69
                              ->disableOriginalConstructor()
70
                              ->getMock();
71
        $this->storage->expects($this->any())
72
                      ->method('resolveUri')
73
                      ->will($this->onConsecutiveCalls('/uploads/photo.jpg', '/uploads/cover.jpg'));
74
75
        $this->annotationReader = new CachedReader(new AnnotationReader(), new ArrayCache());
76
77
        // Mock logger
78
        $this->logger = $this->getMockBuilder('Monolog\Logger')
79
                             ->disableOriginalConstructor()
80
                             ->setMethods(['debug'])
81
                             ->getMock();
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    protected function tearDown()
88
    {
89
        $this->dispatcher       = null;
90
        $this->storage          = null;
91
        $this->requestContext   = null;
92
        $this->annotationReader = null;
93
        $this->logger           = null;
94
    }
95
96
    /**
97
     * Test serialization with included host in the URI
98
     */
99 View Code Duplication
    public function testSerializationWithIncludedHost()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
    {
101
        $this->generateRequestContext();
102
103
        $user = (new Fixtures\UserA())
104
            ->setPhotoName('photo.jpg')
105
            ->setCoverName('cover.jpg');
106
107
        $context = DeserializationContext::create();
108
        $event = new ObjectEvent($context, $user, []);
109
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserA::class, $context->getFormat(), $event);
110
111
        $this->assertEquals('http://example.com/uploads/photo.jpg', $user->getPhotoName());
112
        $this->assertEquals('http://example.com/uploads/cover.jpg', $user->getCoverName());
113
    }
114
115
    /**
116
     * Test serialization with included http host and port in the URI
117
     */
118 View Code Duplication
    public function testSerializationWithIncludedHttpHostAndPort()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
    {
120
        $this->generateRequestContext(false, true);
121
122
        $user = (new Fixtures\UserA())
123
            ->setPhotoName('photo.jpg')
124
            ->setCoverName('cover.jpg');
125
126
        $context = DeserializationContext::create();
127
        $event = new ObjectEvent($context, $user, []);
128
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserA::class, $context->getFormat(), $event);
129
130
        $this->assertEquals('http://example.com:8000/uploads/photo.jpg', $user->getPhotoName());
131
        $this->assertEquals('http://example.com:8000/uploads/cover.jpg', $user->getCoverName());
132
    }
133
134
    /**
135
     * Test serialization with included https host and port in the URI
136
     */
137 View Code Duplication
    public function testSerializationWithIncludedHttpsHostAndPort()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
138
    {
139
        $this->generateRequestContext(true, true);
140
141
        $user = (new Fixtures\UserA())
142
            ->setPhotoName('photo.jpg')
143
            ->setCoverName('cover.jpg');
144
145
        $context = DeserializationContext::create();
146
        $event = new ObjectEvent($context, $user, []);
147
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserA::class, $context->getFormat(), $event);
148
149
        $this->assertEquals('https://example.com:8800/uploads/photo.jpg', $user->getPhotoName());
150
        $this->assertEquals('https://example.com:8800/uploads/cover.jpg', $user->getCoverName());
151
    }
152
153
    /**
154
     * Test serialization without included host in the URI
155
     */
156 View Code Duplication
    public function testSerializationWithoutIncludedHost()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
    {
158
        $this->generateRequestContext();
159
160
        $user = (new Fixtures\UserB())
161
            ->setPhotoName('photo.jpg')
162
            ->setCoverName('cover.jpg');
163
164
        $context = DeserializationContext::create();
165
        $event = new ObjectEvent($context, $user, []);
166
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserB::class, $context->getFormat(), $event);
167
168
        $this->assertEquals('http://example.com/uploads/photo.jpg', $user->getPhotoName());
169
        $this->assertEquals('/uploads/cover.jpg', $user->getCoverName());
170
    }
171
172
    /**
173
     * Test serialization without included host in the URI
174
     *
175
     * @expectedException \Fresh\VichUploaderSerializationBundle\Exception\IncompatibleUploadableAndSerializableFieldAnnotationException
176
     */
177 View Code Duplication
    public function testExceptionForIncompatibleAnnotations()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
178
    {
179
        $this->generateRequestContext();
180
181
        $user = (new Fixtures\UserC())
182
            ->setPhotoName('photo.jpg')
183
            ->setCoverName('cover.jpg');
184
185
        $context = DeserializationContext::create();
186
        $event = new ObjectEvent($context, $user, []);
187
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserC::class, $context->getFormat(), $event);
188
189
        $this->assertEquals('http://example.com/uploads/photo.jpg', $user->getPhotoName());
190
        $this->assertEquals('/uploads/cover.jpg', $user->getCoverName());
191
    }
192
193
    /**
194
     * Test serialization of the same object twice
195
     */
196
    public function testSerializationOfTheSameObjectTwice()
197
    {
198
        $this->generateRequestContext();
199
200
        $user1 = (new Fixtures\UserA())
201
            ->setPhotoName('photo.jpg')
202
            ->setCoverName('cover.jpg');
203
204
        $context = DeserializationContext::create();
205
        $event = new ObjectEvent($context, $user1, []);
206
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserA::class, $context->getFormat(), $event);
207
208
        $this->assertEquals('http://example.com/uploads/photo.jpg', $user1->getPhotoName());
209
        $this->assertEquals('http://example.com/uploads/cover.jpg', $user1->getCoverName());
210
211
        $event = new ObjectEvent($context, $user1, []);
212
        $this->dispatcher->dispatch(JmsEvents::PRE_SERIALIZE, Fixtures\UserA::class, $context->getFormat(), $event);
213
214
        $this->assertEquals('http://example.com/uploads/photo.jpg', $user1->getPhotoName());
215
        $this->assertEquals('http://example.com/uploads/cover.jpg', $user1->getCoverName());
216
    }
217
218
    /**
219
     *
220
     * @param bool $https
221
     * @param bool $port
222
     */
223
    protected function generateRequestContext($https = false, $port = false)
224
    {
225
226
        // Mock Request contest
227
        $this->requestContext = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')
228
            ->disableOriginalConstructor()
229
            ->getMock();
230
231
        $scheme = ($https) ? 'https':'http';
232
233
        $this->requestContext->expects($this->any())
234
            ->method('getScheme')
235
            ->willReturn($scheme);
236
237
        $this->requestContext->expects($this->any())
238
            ->method('getHost')
239
            ->willReturn('example.com');
240
241
        if ($port) {
242
            if ($https) {
243
                $this->requestContext->expects($this->any())
244
                    ->method('getHttpsPort')
245
                    ->willReturn(8800);
246
            } else {
247
                $this->requestContext->expects($this->any())
248
                    ->method('getHttpPort')
249
                    ->willReturn(8000);
250
            }
251
        }
252
253
        $this->addEventListener();
254
    }
255
256
    /**
257
     * Add pre serialize event listener
258
     */
259
    protected function addEventListener()
260
    {
261
        $this->dispatcher = new EventDispatcher();
262
        $listener = new JmsPreSerializeListener($this->storage, $this->requestContext, $this->annotationReader, $this->logger);
263
264
        $this->dispatcher->addListener(JmsEvents::PRE_SERIALIZE, [$listener, 'onPreSerialize']);
265
    }
266
}
267