Completed
Push — master ( 44ea8e...1ef346 )
by Bukashk0zzz
12:10
created

testSerializationWithEventSubscriber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 13
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Bukashk0zzzLiipImagineSerializationBundle
5
 *
6
 * (c) Denis Golubovskiy <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Bukashk0zzz\LiipImagineSerializationBundle\Tests\EventListener;
13
14
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Fixtures\UserPhotos;
15
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Fixtures\UserPictures;
16
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Normalizer\FilteredUrlNormalizer;
17
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Normalizer\OriginUrlNormalizer;
18
use Doctrine\Common\Annotations\AnnotationRegistry;
19
use JMS\Serializer\DeserializationContext;
20
use JMS\Serializer\SerializerBuilder;
21
use Symfony\Component\Routing\RequestContext;
22
use JMS\Serializer\EventDispatcher\EventDispatcher;
23
use Vich\UploaderBundle\Storage\StorageInterface;
24
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
25
use Liip\ImagineBundle\Imagine\Cache\Signer;
26
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Fixtures\User;
27
28
/**
29
 * JmsSerializeListenerTest
30
 *
31
 * @author Denis Golubovskiy <[email protected]>
32
 */
33
class JmsSerializeListenerTest extends \PHPUnit_Framework_TestCase
34
{
35
    /**
36
     * @var RequestContext $requestContext Request context
37
     */
38
    private $requestContext;
39
40
    /**
41
     * @var CacheManager $cacheManager LiipImagineBundle Cache Manager
42
     */
43
    private $cacheManager;
44
45
    /**
46
     * @var StorageInterface $storage Vich storage
47
     */
48
    private $vichStorage;
49
50
    /**
51
     * @var JmsSerializeEventsManager $eventManager JMS Serialize test event manager
52
     */
53
    private $eventManager;
54
55
    /**
56
     * @var DeserializationContext $context JMS context
57
     */
58
    private $context;
59
60
    /**
61
     * @var string $filePath Image file path
62
     */
63
    private $filePath;
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    protected function setUp()
69
    {
70
        AnnotationRegistry::registerLoader('class_exists');
71
        $this->filePath = (new User())->getCoverUrl();
72
        $this->generateVichStorage();
73
        $this->context = (new JmsSerializeContextGenerator())->generateContext();
74
        $this->eventManager = new JmsSerializeEventsManager();
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    protected function tearDown()
81
    {
82
        $this->requestContext = null;
83
        $this->eventManager = null;
84
        $this->cacheManager = null;
85
        $this->vichStorage = null;
86
        $this->filePath = null;
87
    }
88
89
    /**
90
     * Test virtualField serialization
91
     */
92
    public function testVirtualFieldSerialization()
93
    {
94
        $user = new User();
95
        $this->generateCacheManager();
96
        $this->generateRequestContext();
97
        $this->eventManager->addEventListeners($this->requestContext, $this->cacheManager, $this->vichStorage);
98
        $serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) {
99
            $this->eventManager->addEvents($dispatcher, $this->requestContext, $this->cacheManager, $this->vichStorage);
100
        })->build();
101
        $result = $serializer->serialize($user, 'json');
102
103
        static::assertJson($result);
104
        $data = json_decode($result, true);
105
        static::assertEquals('http://example.com:8800/a/path/to/an/image3.png', $data['imageThumb']);
106
    }
107
108
    /**
109
     * Test serialization
110
     */
111
    public function testSerialization()
112
    {
113
        $user = new User();
114
        $this->generateCacheManager();
115
        $this->generateRequestContext();
116
        $this->eventManager->addEventListeners($this->requestContext, $this->cacheManager, $this->vichStorage);
117
        $this->eventManager->dispatchEvents($this->context, $user);
118
        static::assertEquals('http://example.com:8800/a/path/to/an/image1.png', $user->getCoverUrl());
119
        static::assertEquals('http://example.com:8800/a/path/to/an/image2.png', $user->getPhotoName());
120
    }
121
122
    /**
123
     * Test serialization of proxy object and field with array of filters
124
     */
125
    public function testProxySerialization()
126
    {
127
        $userPictures = new UserPictures();
128
        $this->generateCacheManager();
129
        $this->generateRequestContext(false, true);
130
        $this->eventManager->addEventListeners($this->requestContext, $this->cacheManager, $this->vichStorage);
131
        $data = $this->serializeObject($userPictures);
132
133
        static::assertEquals('http://example.com:8800/a/path/to/an/image1.png', $data['cover']['big']);
134
        static::assertEquals('http://example.com:8800/a/path/to/an/image2.png', $data['cover']['small']);
135
        static::assertEquals('http://example.com:8000/uploads/photo.jpg', $data['photo']);
136
        static::assertEquals('http://example.com:8800/a/path/to/an/image3.png', $data['photoThumb']);
137
    }
138
139
    /**
140
     * Test serialization with origin normalizer
141
     */
142 View Code Duplication
    public function testSerializationWithOriginNormalizer()
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...
143
    {
144
        $userPictures = new UserPictures();
145
        $this->generateCacheManager();
146
        $this->generateRequestContext();
147
        $data = $this->serializeObject($userPictures, [
148
            'includeHost' => false,
149
            'vichUploaderSerialize' => true,
150
            'includeOriginal' => true,
151
            'originUrlNormalizer' => OriginUrlNormalizer::class,
152
        ]);
153
154
        static::assertEquals('/uploads/newPhoto.jpg', $data['photoThumb']['original']);
155
        static::assertEquals('/uploads/newPhoto.jpg', $data['photo']);
156
    }
157
158
    /**
159
     * Test serialization with filtered normalizer
160
     */
161 View Code Duplication
    public function testSerializationWithFilteredNormalizer()
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...
162
    {
163
        $userPictures = new UserPictures();
164
        $this->generateCacheManager();
165
        $this->generateRequestContext();
166
        $data = $this->serializeObject($userPictures, [
167
            'includeHost' => true,
168
            'vichUploaderSerialize' => true,
169
            'includeOriginal' => true,
170
            'filteredUrlNormalizer' => FilteredUrlNormalizer::class,
171
        ]);
172
173
        static::assertEquals('http://img.example.com:8800/a/path/to/an/image3.png', $data['photoThumb']['thumb_filter']);
174
        static::assertEquals('http://img.example.com:8800/a/path/to/an/image1.png', $data['cover']['big']);
175
    }
176
177
    /**
178
     * Test serialization with event subscriber
179
     */
180
    public function testSerializationWithEventSubscriber()
181
    {
182
        $userPictures = new UserPictures();
183
        $this->generateCacheManager();
184
        $this->generateRequestContext();
185
        $this->eventManager->addNormalizerSubscriber();
186
        $data = $this->serializeObject($userPictures, [
187
            'includeHost' => true,
188
            'vichUploaderSerialize' => true,
189
            'includeOriginal' => true,
190
        ]);
191
192
        static::assertEquals('http://img.example.com:8800/a/path/to/an/image3.png', $data['photoThumb']['thumb_filter']);
193
        static::assertEquals('http://img.example.com:8800/a/path/to/an/image1.png', $data['cover']['big']);
194
        static::assertEquals('/uploads/newPhoto.jpg', $data['photoThumb']['original']);
195
        static::assertEquals('http://example.com/uploads/newPhoto.jpg', $data['photo']);
196
    }
197
198
    /**
199
     * Test serialization with url parse exception
200
     *
201
     * @expectedException \InvalidArgumentException
202
     */
203
    public function testSerializationWithUrlParseException()
204
    {
205
        $userPictures = new UserPictures();
206
        $this->generateCacheManager('http://blah.com:abcdef');
207
        $this->generateRequestContext();
208
        $this->serializeObject($userPictures, [
209
            'includeHost' => false,
210
        ]);
211
    }
212
213
    /**
214
     * Test serialization with included http host and port in the URI and include original option "true"
215
     */
216
    public function testHttpsSerialization()
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...
217
    {
218
        $userPictures = new UserPictures();
219
        $this->generateCacheManager();
220
        $this->generateRequestContext(true, true);
221
        $data = $this->serializeObject($userPictures, [
222
            'includeHost' => true,
223
            'vichUploaderSerialize' => true,
224
            'includeOriginal' => true,
225
        ]);
226
227
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
228
        static::assertEquals('http://example.com:8800/a/path/to/an/image1.png', $data['cover']['big']);
229
        static::assertEquals('http://example.com:8800/a/path/to/an/image2.png', $data['cover']['small']);
230
        static::assertEquals('http://example.com:8800/a/path/to/an/image3.png', $data['photoThumb']['thumb_filter']);
231
        static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
232
    }
233
234
    /**
235
     * Test serialization without host in url and one filter
236
     */
237 View Code Duplication
    public function testSerializationWithoutHost()
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...
238
    {
239
        $userPictures = new User();
240
        $this->generateCacheManager('/');
241
        $this->generateRequestContext(true, true);
242
        $data = $this->serializeObject($userPictures, [
243
            'includeHost' => false,
244
            'vichUploaderSerialize' => true,
245
            'includeOriginal' => false,
246
        ]);
247
248
        static::assertEquals('/a/path/to/an/image1.png', $data['cover']);
249
        static::assertEquals('/a/path/to/an/image2.png', $data['photo']);
250
    }
251
252
    /**
253
     * Test serialization with host in url for original
254
     */
255 View Code Duplication
    public function testSerializationWithHostForOriginal()
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...
256
    {
257
        $userPictures = new UserPictures();
258
        $this->generateCacheManager();
259
        $this->generateRequestContext(true, true);
260
        $data = $this->serializeObject($userPictures, [
261
            'includeHost' => false,
262
            'vichUploaderSerialize' => true,
263
            'includeOriginal' => true,
264
            'includeHostForOriginal' => true,
265
        ]);
266
267
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
268
        static::assertFalse(strpos($data['cover']['original'], 'https://example.com:8800'));
269
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photoThumb']['original']);
270
    }
271
272
    /**
273
     * Test serialization with host in url and host in url for original
274
     */
275 View Code Duplication
    public function testSerializationWithHostAndHostForOriginal()
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...
276
    {
277
        $userPictures = new UserPictures();
278
        $this->generateCacheManager();
279
        $this->generateRequestContext(true, true);
280
        $data = $this->serializeObject($userPictures, [
281
            'includeHost' => true,
282
            'vichUploaderSerialize' => true,
283
            'includeOriginal' => true,
284
            'includeHostForOriginal' => true,
285
        ]);
286
287
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
288
        static::assertFalse(strpos($data['cover']['original'], 'https://example.com:8800'));
289
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photoThumb']['original']);
290
    }
291
292
    /**
293
     * Test serialization with host in url and host in url for original and non-stored (resolve path) images
294
     */
295
    public function testSerializationWithHostAndHostForOriginalAndNonStoredImages()
296
    {
297
        $userPhotos = new UserPhotos();
298
        $this->generateCacheManager('https://example.com:8800/', false);
299
        $this->generateRequestContext(true, true);
300
        $data = $this->serializeObject($userPhotos, [
301
            'includeHost' => true,
302
            'vichUploaderSerialize' => true,
303
            'includeOriginal' => true,
304
            'includeHostForOriginal' => true,
305
        ]);
306
307
        static::assertEquals('https://example.com:8800/a/path/to/an/resolve/image1.png', $data['cover']['big']);
308
        static::assertEquals('https://example.com:8800/a/path/to/an/resolve/image2.png', $data['cover']['small']);
309
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
310
        static::assertFalse(strpos($data['cover']['original'], 'https://example.com:8800'));
311
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photoThumb']['original']);
312
    }
313
314
    /**
315
     * Test serialization with no host in url and no host in url for original and non-stored (resolve path) images
316
     */
317
    public function testSerializationWithNoHostAndNoHostForOriginalAndNonStoredImages()
318
    {
319
        $userPhotos = new UserPhotos();
320
        $this->generateCacheManager('https://example.com:8800/', false);
321
        $this->generateRequestContext(true, true);
322
        $data = $this->serializeObject($userPhotos, [
323
            'includeHost' => false,
324
            'vichUploaderSerialize' => true,
325
            'includeOriginal' => true,
326
            'includeHostForOriginal' => false,
327
        ]);
328
329
        static::assertEquals('/a/path/to/an/resolve/image1.png', $data['cover']['big']);
330
        static::assertEquals('/a/path/to/an/resolve/image2.png', $data['cover']['small']);
331
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
332
        static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
333
    }
334
335
    /**
336
     * Test serialization with no host in url and no host in url for original and ONE non-stored (resolve path) image
337
     */
338 View Code Duplication
    public function testSerializationWithNoHostAndNoHostForOriginalAndOneNonStoredImage()
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...
339
    {
340
        $userPictures = new UserPictures();
341
        $this->generateCacheManager('https://example.com:8800/', false);
342
        $this->generateRequestContext(true, true);
343
        $data = $this->serializeObject($userPictures, [
344
            'includeHost' => false,
345
            'vichUploaderSerialize' => true,
346
            'includeOriginal' => true,
347
            'includeHostForOriginal' => false,
348
        ]);
349
350
        static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
351
        static::assertEquals('/a/path/to/an/resolve/image3.png', $data['photoThumb']['thumb_filter']);
352
    }
353
354
    /**
355
     * Test serialization without host in url and array of filters
356
     */
357
    public function testSerializationWithoutHostManyFilters()
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...
358
    {
359
        $userPhotos = new UserPhotos();
360
        $this->generateCacheManager('/');
361
        $this->generateRequestContext(true, true);
362
        $data = $this->serializeObject($userPhotos, [
363
            'includeHost' => false,
364
            'vichUploaderSerialize' => true,
365
            'includeOriginal' => false,
366
        ]);
367
368
        static::assertEquals('/a/path/to/an/image1.png', $data['cover']['big']);
369
        static::assertEquals('/a/path/to/an/image2.png', $data['cover']['small']);
370
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
371
        static::assertEquals('/a/path/to/an/image3.png', $data['photoThumb']['thumb_big']);
372
        static::assertEquals('/a/path/to/an/image4.png', $data['photoThumb']['thumb_small']);
373
    }
374
375
    /**
376
     * @param User|UserPictures|UserPhotos $user
377
     * @param array                        $config JMS serializer listner config
378
     *
379
     * @return array
380
     */
381
    protected function serializeObject($user, array $config = [])
382
    {
383
        $serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) use ($config) {
384
            $this->eventManager->addEvents($dispatcher, $this->requestContext, $this->cacheManager, $this->vichStorage, $config);
385
        })->build();
386
        $result = $serializer->serialize($user, 'json');
387
388
        static::assertJson($result);
389
390
        return json_decode($result, true);
391
    }
392
393
    /**
394
     * @param bool $https
395
     * @param bool $port
396
     */
397
    protected function generateRequestContext($https = false, $port = false)
398
    {
399
        $this->requestContext = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')
400
            ->disableOriginalConstructor()
401
            ->getMock();
402
403
        $scheme = $https ? 'https':'http';
404
405
        $this->requestContext->expects(static::any())
406
            ->method('getScheme')
407
            ->willReturn($scheme);
408
409
        $this->requestContext->expects(static::any())
410
            ->method('getHost')
411
            ->willReturn('example.com');
412
413
        if ($port) {
414
            if ($https) {
415
                $this->requestContext->expects(static::any())
416
                    ->method('getHttpsPort')
417
                    ->willReturn(8800);
418
419
                return;
420
            }
421
422
            $this->requestContext->expects(static::any())
423
                ->method('getHttpPort')
424
                ->willReturn(8000);
425
        }
426
    }
427
428
    /**
429
     * Prepare mock of Liip cache manager
430
     *
431
     * @param string $urlPrefix
432
     * @param bool $isStored
433
     */
434
    protected function generateCacheManager($urlPrefix = 'http://example.com:8800/', $isStored = true)
435
    {
436
        $resolver = $this->getMockBuilder('Liip\ImagineBundle\Imagine\Cache\Resolver\ResolverInterface')->getMock();
437
        $resolver
438
            ->expects(static::any())
439
            ->method('isStored')
440
            ->will(static::returnValue($isStored))
441
        ;
442
        $resolver
443
            ->expects(static::any())
444
            ->method('resolve')
445
            ->will(static::onConsecutiveCalls($urlPrefix.'a/path/to/an/image1.png', $urlPrefix.'a/path/to/an/image2.png', $urlPrefix.'a/path/to/an/image3.png', $urlPrefix.'a/path/to/an/image4.png'))
446
        ;
447
448
        $config = $this->getMockBuilder('Liip\ImagineBundle\Imagine\Filter\FilterConfiguration')->getMock();
449
        $config->expects(static::any())
450
            ->method('get')
451
            ->will(static::returnValue(array(
452
                'size' => array(180, 180),
453
                'mode' => 'outbound',
454
                'cache' => null,
455
            )))
456
        ;
457
458
        $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
459
        $router->expects(static::any())
460
            ->method('generate')
461
            ->will(static::onConsecutiveCalls($urlPrefix.'a/path/to/an/resolve/image1.png', $urlPrefix.'a/path/to/an/resolve/image2.png', $urlPrefix.'a/path/to/an/resolve/image3.png', $urlPrefix.'a/path/to/an/resole/image4.png'))
462
        ;
463
464
        $eventDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
465
466
        /** @noinspection PhpParamsInspection */
467
        $this->cacheManager = new CacheManager($config, $router, new Signer('secret'), $eventDispatcher);
468
469
        /** @noinspection PhpParamsInspection */
470
        $this->cacheManager->addResolver('default', $resolver);
471
    }
472
473
    /**
474
     * Generate vichStorage mock
475
     */
476
    protected function generateVichStorage()
477
    {
478
        $this->vichStorage = $this->getMockBuilder('Vich\UploaderBundle\Storage\FileSystemStorage')
479
            ->disableOriginalConstructor()
480
            ->getMock();
481
        $this->vichStorage->expects(static::any())
482
            ->method('resolveUri')
483
            ->will(static::returnValue('/uploads/photo.jpg'));
484
    }
485
}
486