Completed
Push — master ( 298bee...635a0b )
by Bukashk0zzz
12:34
created

JmsSerializeListenerTest::generateCacheManager()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 24
nc 1
nop 2
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 url parse exception
179
     *
180
     * @expectedException \InvalidArgumentException
181
     */
182
    public function testSerializationWithUrlParseException()
183
    {
184
        $userPictures = new UserPictures();
185
        $this->generateCacheManager('http://blah.com:abcdef');
186
        $this->generateRequestContext();
187
        $this->serializeObject($userPictures, [
188
            'includeHost' => false,
189
        ]);
190
    }
191
192
    /**
193
     * Test serialization with included http host and port in the URI and include original option "true"
194
     */
195
    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...
196
    {
197
        $userPictures = new UserPictures();
198
        $this->generateCacheManager();
199
        $this->generateRequestContext(true, true);
200
        $data = $this->serializeObject($userPictures, [
201
            'includeHost' => true,
202
            'vichUploaderSerialize' => true,
203
            'includeOriginal' => true,
204
        ]);
205
206
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
207
        static::assertEquals('http://example.com:8800/a/path/to/an/image1.png', $data['cover']['big']);
208
        static::assertEquals('http://example.com:8800/a/path/to/an/image2.png', $data['cover']['small']);
209
        static::assertEquals('http://example.com:8800/a/path/to/an/image3.png', $data['photoThumb']['thumb_filter']);
210
        static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
211
    }
212
213
    /**
214
     * Test serialization without host in url and one filter
215
     */
216 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...
217
    {
218
        $userPictures = new User();
219
        $this->generateCacheManager('/');
220
        $this->generateRequestContext(true, true);
221
        $data = $this->serializeObject($userPictures, [
222
            'includeHost' => false,
223
            'vichUploaderSerialize' => true,
224
            'includeOriginal' => false,
225
        ]);
226
227
        static::assertEquals('/a/path/to/an/image1.png', $data['cover']);
228
        static::assertEquals('/a/path/to/an/image2.png', $data['photo']);
229
    }
230
231
    /**
232
     * Test serialization with host in url for original
233
     */
234 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...
235
    {
236
        $userPictures = new UserPictures();
237
        $this->generateCacheManager();
238
        $this->generateRequestContext(true, true);
239
        $data = $this->serializeObject($userPictures, [
240
            'includeHost' => false,
241
            'vichUploaderSerialize' => true,
242
            'includeOriginal' => true,
243
            'includeHostForOriginal' => true,
244
        ]);
245
246
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
247
        static::assertFalse(strpos($data['cover']['original'], 'https://example.com:8800'));
248
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photoThumb']['original']);
249
    }
250
251
    /**
252
     * Test serialization with host in url and host in url for original
253
     */
254 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...
255
    {
256
        $userPictures = new UserPictures();
257
        $this->generateCacheManager();
258
        $this->generateRequestContext(true, true);
259
        $data = $this->serializeObject($userPictures, [
260
            'includeHost' => true,
261
            'vichUploaderSerialize' => true,
262
            'includeOriginal' => true,
263
            'includeHostForOriginal' => true,
264
        ]);
265
266
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
267
        static::assertFalse(strpos($data['cover']['original'], 'https://example.com:8800'));
268
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photoThumb']['original']);
269
    }
270
271
    /**
272
     * Test serialization with host in url and host in url for original and non-stored (resolve path) images
273
     */
274
    public function testSerializationWithHostAndHostForOriginalAndNonStoredImages()
275
    {
276
        $userPhotos = new UserPhotos();
277
        $this->generateCacheManager('https://example.com:8800/', false);
278
        $this->generateRequestContext(true, true);
279
        $data = $this->serializeObject($userPhotos, [
280
            'includeHost' => true,
281
            'vichUploaderSerialize' => true,
282
            'includeOriginal' => true,
283
            'includeHostForOriginal' => true,
284
        ]);
285
286
        static::assertEquals('https://example.com:8800/a/path/to/an/resolve/image1.png', $data['cover']['big']);
287
        static::assertEquals('https://example.com:8800/a/path/to/an/resolve/image2.png', $data['cover']['small']);
288
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
289
        static::assertFalse(strpos($data['cover']['original'], 'https://example.com:8800'));
290
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photoThumb']['original']);
291
    }
292
293
    /**
294
     * Test serialization with no host in url and no host in url for original and non-stored (resolve path) images
295
     */
296
    public function testSerializationWithNoHostAndNoHostForOriginalAndNonStoredImages()
297
    {
298
        $userPhotos = new UserPhotos();
299
        $this->generateCacheManager('https://example.com:8800/', false);
300
        $this->generateRequestContext(true, true);
301
        $data = $this->serializeObject($userPhotos, [
302
            'includeHost' => false,
303
            'vichUploaderSerialize' => true,
304
            'includeOriginal' => true,
305
            'includeHostForOriginal' => false,
306
        ]);
307
308
        static::assertEquals('/a/path/to/an/resolve/image1.png', $data['cover']['big']);
309
        static::assertEquals('/a/path/to/an/resolve/image2.png', $data['cover']['small']);
310
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
311
        static::assertEquals('/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 ONE non-stored (resolve path) image
316
     */
317 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...
318
    {
319
        $userPictures = new UserPictures();
320
        $this->generateCacheManager('https://example.com:8800/', false);
321
        $this->generateRequestContext(true, true);
322
        $data = $this->serializeObject($userPictures, [
323
            'includeHost' => false,
324
            'vichUploaderSerialize' => true,
325
            'includeOriginal' => true,
326
            'includeHostForOriginal' => false,
327
        ]);
328
329
        static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
330
        static::assertEquals('/a/path/to/an/resolve/image3.png', $data['photoThumb']['thumb_filter']);
331
    }
332
333
    /**
334
     * Test serialization without host in url and array of filters
335
     */
336
    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...
337
    {
338
        $userPhotos = new UserPhotos();
339
        $this->generateCacheManager('/');
340
        $this->generateRequestContext(true, true);
341
        $data = $this->serializeObject($userPhotos, [
342
            'includeHost' => false,
343
            'vichUploaderSerialize' => true,
344
            'includeOriginal' => false,
345
        ]);
346
347
        static::assertEquals('/a/path/to/an/image1.png', $data['cover']['big']);
348
        static::assertEquals('/a/path/to/an/image2.png', $data['cover']['small']);
349
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
350
        static::assertEquals('/a/path/to/an/image3.png', $data['photoThumb']['thumb_big']);
351
        static::assertEquals('/a/path/to/an/image4.png', $data['photoThumb']['thumb_small']);
352
    }
353
354
    /**
355
     * @param User|UserPictures|UserPhotos $user
356
     * @param array                        $config JMS serializer listner config
357
     *
358
     * @return array
359
     */
360
    protected function serializeObject($user, array $config = [])
361
    {
362
        $serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) use ($config) {
363
            $this->eventManager->addEvents($dispatcher, $this->requestContext, $this->cacheManager, $this->vichStorage, $config);
364
        })->build();
365
        $result = $serializer->serialize($user, 'json');
366
367
        static::assertJson($result);
368
369
        return json_decode($result, true);
370
    }
371
372
    /**
373
     * @param bool $https
374
     * @param bool $port
375
     */
376
    protected function generateRequestContext($https = false, $port = false)
377
    {
378
        $this->requestContext = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')
379
            ->disableOriginalConstructor()
380
            ->getMock();
381
382
        $scheme = $https ? 'https':'http';
383
384
        $this->requestContext->expects(static::any())
385
            ->method('getScheme')
386
            ->willReturn($scheme);
387
388
        $this->requestContext->expects(static::any())
389
            ->method('getHost')
390
            ->willReturn('example.com');
391
392
        if ($port) {
393
            if ($https) {
394
                $this->requestContext->expects(static::any())
395
                    ->method('getHttpsPort')
396
                    ->willReturn(8800);
397
398
                return;
399
            }
400
401
            $this->requestContext->expects(static::any())
402
                ->method('getHttpPort')
403
                ->willReturn(8000);
404
        }
405
    }
406
407
    /**
408
     * Prepare mock of Liip cache manager
409
     *
410
     * @param string $urlPrefix
411
     * @param bool $isStored
412
     */
413
    protected function generateCacheManager($urlPrefix = 'http://example.com:8800/', $isStored = true)
414
    {
415
        $resolver = $this->getMockBuilder('Liip\ImagineBundle\Imagine\Cache\Resolver\ResolverInterface')->getMock();
416
        $resolver
417
            ->expects(static::any())
418
            ->method('isStored')
419
            ->will(static::returnValue($isStored))
420
        ;
421
        $resolver
422
            ->expects(static::any())
423
            ->method('resolve')
424
            ->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'))
425
        ;
426
427
        $config = $this->getMockBuilder('Liip\ImagineBundle\Imagine\Filter\FilterConfiguration')->getMock();
428
        $config->expects(static::any())
429
            ->method('get')
430
            ->will(static::returnValue(array(
431
                'size' => array(180, 180),
432
                'mode' => 'outbound',
433
                'cache' => null,
434
            )))
435
        ;
436
437
        $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
438
        $router->expects(static::any())
439
            ->method('generate')
440
            ->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'))
441
        ;
442
443
        $eventDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
444
445
        /** @noinspection PhpParamsInspection */
446
        $this->cacheManager = new CacheManager($config, $router, new Signer('secret'), $eventDispatcher);
447
448
        /** @noinspection PhpParamsInspection */
449
        $this->cacheManager->addResolver('default', $resolver);
450
    }
451
452
    /**
453
     * Generate vichStorage mock
454
     */
455
    protected function generateVichStorage()
456
    {
457
        $this->vichStorage = $this->getMockBuilder('Vich\UploaderBundle\Storage\FileSystemStorage')
458
            ->disableOriginalConstructor()
459
            ->getMock();
460
        $this->vichStorage->expects(static::any())
461
            ->method('resolveUri')
462
            ->will(static::returnValue('/uploads/photo.jpg'));
463
    }
464
}
465