Completed
Push — master ( 748d22...072987 )
by Bukashk0zzz
18:35
created

testSerializationWithoutHost()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
rs 9.4285
cc 1
eloc 10
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 Doctrine\Common\Annotations\AnnotationRegistry;
17
use JMS\Serializer\DeserializationContext;
18
use JMS\Serializer\SerializerBuilder;
19
use Symfony\Component\Routing\RequestContext;
20
use JMS\Serializer\EventDispatcher\EventDispatcher;
21
use Vich\UploaderBundle\Storage\StorageInterface;
22
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
23
use Liip\ImagineBundle\Imagine\Cache\Signer;
24
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Fixtures\User;
25
26
/**
27
 * JmsSerializeListenerTest
28
 *
29
 * @author Denis Golubovskiy <[email protected]>
30
 */
31
class JmsSerializeListenerTest extends \PHPUnit_Framework_TestCase
32
{
33
    /**
34
     * @var RequestContext $requestContext Request context
35
     */
36
    private $requestContext;
37
38
    /**
39
     * @var CacheManager $cacheManager LiipImagineBundle Cache Manager
40
     */
41
    private $cacheManager;
42
43
    /**
44
     * @var StorageInterface $storage Vich storage
45
     */
46
    private $vichStorage;
47
48
    /**
49
     * @var JmsSerializeEventsManager $eventManager JMS Serialize test event manager
50
     */
51
    private $eventManager;
52
53
    /**
54
     * @var DeserializationContext $context JMS context
55
     */
56
    private $context;
57
58
    /**
59
     * @var string $filePath Image file path
60
     */
61
    private $filePath;
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function setUp()
67
    {
68
        AnnotationRegistry::registerLoader('class_exists');
69
        $this->filePath = (new User())->getCoverUrl();
70
        $this->generateVichStorage();
71
        $this->context = (new JmsSerializeContextGenerator())->generateContext();
72
        $this->eventManager = new JmsSerializeEventsManager();
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    protected function tearDown()
79
    {
80
        $this->requestContext = null;
81
        $this->eventManager = null;
82
        $this->cacheManager = null;
83
        $this->vichStorage = null;
84
        $this->filePath = null;
85
    }
86
87
    /**
88
     * Test virtualField serialization
89
     */
90
    public function testVirtualFieldSerialization()
91
    {
92
        $user = new User();
93
        $this->generateCacheManager();
94
        $this->generateRequestContext();
95
        $this->eventManager->addEventListeners($this->requestContext, $this->cacheManager, $this->vichStorage);
96
        $serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) {
97
            $this->eventManager->addEvents($dispatcher, $this->requestContext, $this->cacheManager, $this->vichStorage);
98
        })->build();
99
        $result = $serializer->serialize($user, 'json');
100
101
        static::assertJson($result);
102
        $data = json_decode($result, true);
103
        static::assertEquals('http://a/path/to/an/image3.png', $data['imageThumb']);
104
    }
105
106
    /**
107
     * Test serialization
108
     */
109
    public function testSerialization()
110
    {
111
        $user = new User();
112
        $this->generateCacheManager();
113
        $this->generateRequestContext();
114
        $this->eventManager->addEventListeners($this->requestContext, $this->cacheManager, $this->vichStorage);
115
        $this->eventManager->dispatchEvents($this->context, $user);
116
        static::assertEquals('http://a/path/to/an/image1.png', $user->getCoverUrl());
117
        static::assertEquals('http://a/path/to/an/image2.png', $user->getPhotoName());
118
    }
119
120
    /**
121
     * Test serialization of proxy object and field with array of filters
122
     */
123
    public function testProxySerialization()
124
    {
125
        $userPictures = new UserPictures();
126
        $this->generateCacheManager();
127
        $this->generateRequestContext(false, true);
128
        $this->eventManager->addEventListeners($this->requestContext, $this->cacheManager, $this->vichStorage);
129
        $data = $this->serializeObject($userPictures);
130
131
        static::assertEquals('http://a/path/to/an/image1.png', $data['cover']['big']);
132
        static::assertEquals('http://a/path/to/an/image2.png', $data['cover']['small']);
133
        static::assertEquals('http://example.com:8000/uploads/photo.jpg', $data['photo']);
134
        static::assertEquals('http://a/path/to/an/image3.png', $data['photoThumb']);
135
    }
136
137
    /**
138
     * Test serialization with included http host and port in the URI and include original option "true"
139
     */
140 View Code Duplication
    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...
141
    {
142
        $userPictures = new UserPictures();
143
        $this->generateCacheManager();
144
        $this->generateRequestContext(true, true);
145
        $data = $this->serializeObject($userPictures, [
146
            'includeHost' => true,
147
            'vichUploaderSerialize' => true,
148
            'includeOriginal' => true,
149
        ]);
150
151
        static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
152
        static::assertEquals('http://a/path/to/an/image1.png', $data['cover']['big']);
153
        static::assertEquals('http://a/path/to/an/image2.png', $data['cover']['small']);
154
        static::assertEquals('http://a/path/to/an/image3.png', $data['photoThumb']['thumb_filter']);
155
        static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
156
    }
157
158
    /**
159
     * Test serialization without host in url and one filter
160
     */
161
    public function testSerializationWithoutHost()
162
    {
163
        $userPictures = new User();
164
        $this->generateCacheManager('/');
165
        $this->generateRequestContext(true, true);
166
        $data = $this->serializeObject($userPictures, [
167
            'includeHost' => false,
168
            'vichUploaderSerialize' => true,
169
            'includeOriginal' => false,
170
        ]);
171
172
        static::assertEquals('/a/path/to/an/image1.png', $data['cover']);
173
        static::assertEquals('/a/path/to/an/image2.png', $data['photo']);
174
    }
175
176
    /**
177
     * Test serialization without host in url and array of filters
178
     */
179 View Code Duplication
    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...
180
    {
181
        $userPhotos = new UserPhotos();
182
        $this->generateCacheManager('/');
183
        $this->generateRequestContext(true, true);
184
        $data = $this->serializeObject($userPhotos, [
0 ignored issues
show
Documentation introduced by
$userPhotos is of type object<Bukashk0zzz\LiipI...ts\Fixtures\UserPhotos>, but the function expects a object<Bukashk0zzz\LiipI...\Fixtures\UserPictures>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
185
            'includeHost' => false,
186
            'vichUploaderSerialize' => true,
187
            'includeOriginal' => false,
188
        ]);
189
190
        static::assertEquals('/a/path/to/an/image1.png', $data['cover']['big']);
191
        static::assertEquals('/a/path/to/an/image2.png', $data['cover']['small']);
192
        static::assertEquals('/uploads/photo.jpg', $data['photo']);
193
        static::assertEquals('/a/path/to/an/image3.png', $data['photoThumb']['thumb_big']);
194
        static::assertEquals('/a/path/to/an/image4.png', $data['photoThumb']['thumb_small']);
195
    }
196
197
    /**
198
     * @param User|UserPictures $user
199
     * @param array             $config JMS serializer listner config
200
     * @return array
201
     */
202
    protected function serializeObject($user, array $config = [])
203
    {
204
        $serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) use ($config) {
205
            $this->eventManager->addEvents($dispatcher, $this->requestContext, $this->cacheManager, $this->vichStorage, $config);
206
        })->build();
207
        $result = $serializer->serialize($user, 'json');
208
209
        static::assertJson($result);
210
211
        return json_decode($result, true);
212
    }
213
214
    /**
215
     * @param bool $https
216
     * @param bool $port
217
     */
218
    protected function generateRequestContext($https = false, $port = false)
219
    {
220
        $this->requestContext = $this->getMockBuilder('Symfony\Component\Routing\RequestContext')
221
            ->disableOriginalConstructor()
222
            ->getMock();
223
224
        $scheme = $https ? 'https':'http';
225
226
        $this->requestContext->expects(static::any())
227
            ->method('getScheme')
228
            ->willReturn($scheme);
229
230
        $this->requestContext->expects(static::any())
231
            ->method('getHost')
232
            ->willReturn('example.com');
233
234
        if ($port) {
235
            if ($https) {
236
                $this->requestContext->expects(static::any())
237
                    ->method('getHttpsPort')
238
                    ->willReturn(8800);
239
240
                return;
241
            }
242
243
            $this->requestContext->expects(static::any())
244
                ->method('getHttpPort')
245
                ->willReturn(8000);
246
        }
247
    }
248
249
    /**
250
     * Prepare mock of Liip cache manager
251
     *
252
     * @param string $urlPrefix
253
     */
254
    protected function generateCacheManager($urlPrefix = 'http://')
255
    {
256
        $resolver = $this->createMock('Liip\ImagineBundle\Imagine\Cache\Resolver\ResolverInterface');
257
        $resolver
258
            ->expects(static::any())
259
            ->method('isStored')
260
            ->will(static::returnValue(true))
261
        ;
262
        $resolver
263
            ->expects(static::any())
264
            ->method('resolve')
265
            ->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'))
266
        ;
267
268
        $config = $this->createMock('Liip\ImagineBundle\Imagine\Filter\FilterConfiguration');
269
        $config->expects(static::any())
270
            ->method('get')
271
            ->will(static::returnValue(array(
272
                'size' => array(180, 180),
273
                'mode' => 'outbound',
274
                'cache' => null,
275
            )))
276
        ;
277
278
        $router = $this->createMock('Symfony\Component\Routing\RouterInterface');
279
        $router->expects(static::never())
280
            ->method('generate')
281
        ;
282
283
        $eventDispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
284
285
        /** @noinspection PhpParamsInspection */
286
        $this->cacheManager = new CacheManager($config, $router, new Signer('secret'), $eventDispatcher);
287
288
        /** @noinspection PhpParamsInspection */
289
        $this->cacheManager->addResolver('default', $resolver);
290
    }
291
292
    /**
293
     * Generate vichStorage mock
294
     */
295
    protected function generateVichStorage()
296
    {
297
        $this->vichStorage = $this->getMockBuilder('Vich\UploaderBundle\Storage\FileSystemStorage')
298
            ->disableOriginalConstructor()
299
            ->getMock();
300
        $this->vichStorage->expects(static::any())
301
            ->method('resolveUri')
302
            ->will(static::returnValue('/uploads/photo.jpg'));
303
    }
304
}
305