Completed
Push — master ( 623579...d5cc97 )
by Jordi Sala
02:41
created

FileProviderTest::mediaProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
rs 9.2
cc 1
eloc 16
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[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 Sonata\MediaBundle\Tests\Provider;
13
14
use Sonata\MediaBundle\Provider\FileProvider;
15
use Sonata\MediaBundle\Tests\Entity\Media;
16
use Sonata\MediaBundle\Thumbnail\FormatThumbnail;
17
use Symfony\Component\HttpFoundation\File\File;
18
use Symfony\Component\HttpFoundation\Request;
19
20
class FileProviderTest extends AbstractProviderTest
21
{
22
    public function getProvider()
23
    {
24
        $resizer = $this->createMock('Sonata\MediaBundle\Resizer\ResizerInterface');
25
        $resizer->expects($this->any())->method('resize')->will($this->returnValue(true));
26
27
        $adapter = $this->getMockBuilder('Sonata\MediaBundle\Filesystem\Local')->disableOriginalConstructor()->getMock();
28
        $adapter->expects($this->any())->method('getDirectory')->will($this->returnValue(realpath(__DIR__).'/../fixtures'));
29
30
        $filesystem = $this->getMockBuilder('Gaufrette\Filesystem')
31
            ->setMethods(['get'])
32
            ->setConstructorArgs([$adapter])
33
            ->getMock();
34
        $file = $this->getMockBuilder('Gaufrette\File')
35
            ->setConstructorArgs(['foo', $filesystem])
36
            ->getMock();
37
        $filesystem->expects($this->any())->method('get')->will($this->returnValue($file));
38
39
        $cdn = new \Sonata\MediaBundle\CDN\Server('/uploads/media');
40
41
        $generator = new \Sonata\MediaBundle\Generator\DefaultGenerator();
42
43
        $thumbnail = new FormatThumbnail('jpg');
44
45
        $metadata = $this->createMock('Sonata\MediaBundle\Metadata\MetadataBuilderInterface');
46
47
        $provider = new FileProvider('file', $filesystem, $cdn, $generator, $thumbnail, ['txt'], ['foo/bar'], $metadata);
48
        $provider->setResizer($resizer);
49
50
        return $provider;
51
    }
52
53
    public function testProvider()
54
    {
55
        $provider = $this->getProvider();
56
57
        $media = new Media();
58
        $media->setName('test.txt');
59
        $media->setProviderReference('ASDASD.txt');
60
        $media->setContext('default');
61
62
        $media->setId(1023456);
63
        $this->assertSame('default/0011/24/ASDASD.txt', $provider->getReferenceImage($media));
64
65
        $this->assertSame('default/0011/24', $provider->generatePath($media));
66
67
        // default icon image
68
        $this->assertSame('/uploads/media/sonatamedia/files/big/file.png', $provider->generatePublicUrl($media, 'big'));
69
    }
70
71
    public function testHelperProperies()
72
    {
73
        $provider = $this->getProvider();
74
75
        $provider->addFormat('admin', ['width' => 100]);
76
        $media = new Media();
77
        $media->setName('test.png');
78
        $media->setProviderReference('ASDASDAS.png');
79
        $media->setId(10);
80
        $media->setHeight(100);
81
82
        $properties = $provider->getHelperProperties($media, 'admin');
83
84
        $this->assertInternalType('array', $properties);
85
        $this->assertSame('test.png', $properties['title']);
86
    }
87
88
    public function testForm()
89
    {
90
        $provider = $this->getProvider();
91
92
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AdminInterface');
93
        $admin->expects($this->any())
94
            ->method('trans')
95
            ->will($this->returnValue('message'));
96
97
        $formMapper = $this->getMockBuilder('Sonata\AdminBundle\Form\FormMapper')
98
            ->setMethods(['add', 'getAdmin'])
99
            ->disableOriginalConstructor()
100
            ->getMock();
101
        $formMapper->expects($this->exactly(8))
102
            ->method('add')
103
            ->will($this->returnValue(null));
104
105
        $provider->buildCreateForm($formMapper);
106
        $provider->buildEditForm($formMapper);
107
    }
108
109
    public function testThumbnail()
110
    {
111
        $provider = $this->getProvider();
112
113
        $media = new Media();
114
        $media->setName('test.png');
115
        $media->setId(1023456);
116
117
        $provider->generateThumbnails($media);
118
    }
119
120
    public function testEvent()
121
    {
122
        $provider = $this->getProvider();
123
124
        $provider->addFormat('big', ['width' => 200, 'height' => 100, 'constraint' => true]);
125
126
        $file = __DIR__.'/../fixtures/file.txt';
127
128
        $media = new Media();
129
        $provider->preUpdate($media);
130
        $this->assertNull($media->getProviderReference());
131
132
        $media->setBinaryContent($file);
133
        $provider->transform($media);
134
135
        $this->assertInstanceOf('\DateTime', $media->getUpdatedAt());
136
        $this->assertNotNull($media->getProviderReference());
137
138
        $provider->postUpdate($media);
139
140
        $file = new \Symfony\Component\HttpFoundation\File\File(realpath(__DIR__.'/../fixtures/file.txt'));
141
142
        $media = new Media();
143
        $media->setBinaryContent($file);
144
        $media->setId(1023456);
145
146
        // pre persist the media
147
        $provider->transform($media);
148
149
        $this->assertSame('file.txt', $media->getName(), '::getName() return the file name');
150
        $this->assertNotNull($media->getProviderReference(), '::getProviderReference() is set');
151
152
        $this->assertFalse($provider->generatePrivateUrl($media, 'big'), '::generatePrivateUrl() return false on non reference formate');
153
        $this->assertNotNull($provider->generatePrivateUrl($media, 'reference'), '::generatePrivateUrl() return path for reference formate');
154
    }
155
156
    public function testDownload()
157
    {
158
        $provider = $this->getProvider();
159
160
        $file = new File(realpath(__DIR__.'/../fixtures/FileProviderTest/0011/24/file.txt'));
161
162
        $media = new Media();
163
        $media->setBinaryContent($file);
164
        $media->setProviderReference('file.txt');
165
        $media->setContext('FileProviderTest');
166
        $media->setId(1023456);
167
168
        $response = $provider->getDownloadResponse($media, 'reference', 'X-Accel-Redirect');
169
170
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\BinaryFileResponse', $response);
171
    }
172
173
    /**
174
     * @dataProvider mediaProvider
175
     */
176
    public function testTransform($expected, $media)
177
    {
178
        $self = $this;
179
180
        $closure = function () use ($self, $expected, $media) {
181
            $provider = $self->getProvider();
182
183
            $provider->transform($media);
184
185
            $self->assertInstanceOf($expected, $media->getBinaryContent());
186
        };
187
188
        $closure();
189
    }
190
191
    public function mediaProvider()
192
    {
193
        $file = new \Symfony\Component\HttpFoundation\File\File(realpath(__DIR__.'/../fixtures/file.txt'));
194
        $content = file_get_contents(realpath(__DIR__.'/../fixtures/file.txt'));
195
        $request = new Request([], [], [], [], [], [], $content);
196
197
        $media1 = new Media();
198
        $media1->setBinaryContent($file);
199
        $media1->setContentType('foo');
200
        $media1->setId(1023456);
201
202
        $media2 = new Media();
203
        $media2->setBinaryContent($request);
204
        $media2->setContentType('text/plain');
205
        $media2->setId(1023456);
206
207
        return [
208
            ['\Symfony\Component\HttpFoundation\File\File', $media1],
209
            ['\Symfony\Component\HttpFoundation\File\File', $media1],
210
            ['\Symfony\Component\HttpFoundation\File\File', $media2],
211
        ];
212
    }
213
214
    /**
215
     * @requires PHP 5.6
216
     *
217
     * @see https://github.com/sebastianbergmann/phpunit/issues/1409
218
     */
219
    public function testBinaryContentWithRealPath()
220
    {
221
        $media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
222
223
        $media->expects($this->any())
224
            ->method('getProviderReference')
225
            ->willReturn('provider');
226
227
        $media->expects($this->any())
228
            ->method('getId')
229
            ->willReturn(10000);
230
231
        $media->expects($this->any())
232
            ->method('getContext')
233
            ->willReturn('context');
234
235
        $binaryContent = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
236
            ->setMethods(['getRealPath', 'getPathname'])
237
            ->disableOriginalConstructor()
238
            ->getMock();
239
240
        $binaryContent->expects($this->atLeastOnce())
241
            ->method('getRealPath')
242
            ->willReturn(__DIR__.'/../fixtures/file.txt');
243
244
        $binaryContent->expects($this->never())
245
            ->method('getPathname');
246
247
        $media->expects($this->any())
248
            ->method('getBinaryContent')
249
            ->willReturn($binaryContent);
250
251
        $provider = $this->getProvider();
252
253
        $setFileContents = new \ReflectionMethod('Sonata\MediaBundle\Provider\FileProvider', 'setFileContents');
254
        $setFileContents->setAccessible(true);
255
256
        $setFileContents->invoke($provider, $media);
257
    }
258
259
    /**
260
     * @requires PHP 5.6
261
     *
262
     * @see https://github.com/sebastianbergmann/phpunit/issues/1409
263
     */
264
    public function testBinaryContentStreamWrapped()
265
    {
266
        $media = $this->createMock('Sonata\MediaBundle\Model\MediaInterface');
267
268
        $media->expects($this->any())
269
            ->method('getProviderReference')
270
            ->willReturn('provider');
271
272
        $media->expects($this->any())
273
            ->method('getId')
274
            ->willReturn(10000);
275
276
        $media->expects($this->any())
277
            ->method('getContext')
278
            ->willReturn('context');
279
280
        $binaryContent = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
281
            ->setMethods(['getRealPath', 'getPathname'])
282
            ->disableOriginalConstructor()
283
            ->getMock();
284
285
        $binaryContent->expects($this->atLeastOnce())
286
            ->method('getRealPath')
287
            ->willReturn(false);
288
289
        $binaryContent->expects($this->atLeastOnce())
290
            ->method('getPathname')
291
            ->willReturn(__DIR__.'/../fixtures/file.txt');
292
293
        $media->expects($this->any())
294
            ->method('getBinaryContent')
295
            ->willReturn($binaryContent);
296
297
        $provider = $this->getProvider();
298
299
        $setFileContents = new \ReflectionMethod('Sonata\MediaBundle\Provider\FileProvider', 'setFileContents');
300
        $setFileContents->setAccessible(true);
301
302
        $setFileContents->invoke($provider, $media);
303
    }
304
305
    public function testValidate()
306
    {
307
        $errorElement = $this->getMockBuilder('Sonata\CoreBundle\Validator\ErrorElement')
308
            ->disableOriginalConstructor()
309
            ->getMock();
310
311
        $media = new Media();
312
313
        $provider = $this->getProvider();
314
        $provider->validate($errorElement, $media);
315
    }
316
317
    public function testValidateUploadSize()
318
    {
319
        $errorElement = $this->getMockBuilder('Sonata\CoreBundle\Validator\ErrorElement')
320
            ->disableOriginalConstructor()
321
            ->getMock();
322
        $errorElement->expects($this->once())->method('with')
323
            ->will($this->returnSelf());
324
        $errorElement->expects($this->once())->method('addViolation')
325
            ->with($this->stringContains('The file is too big, max size:'))
326
            ->will($this->returnSelf());
327
        $errorElement->expects($this->once())->method('end')
328
            ->will($this->returnSelf());
329
330
        $upload = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
331
            ->setConstructorArgs([tempnam(sys_get_temp_dir(), ''), 'dummy'])
332
            ->getMock();
333
        $upload->expects($this->any())->method('getClientSize')
334
            ->will($this->returnValue(0));
335
        $upload->expects($this->any())->method('getFilename')
336
            ->will($this->returnValue('test.txt'));
337
        $upload->expects($this->any())->method('getClientOriginalName')
338
            ->will($this->returnValue('test.txt'));
339
        $upload->expects($this->any())->method('getMimeType')
340
            ->will($this->returnValue('foo/bar'));
341
342
        $media = new Media();
343
        $media->setBinaryContent($upload);
344
345
        $provider = $this->getProvider();
346
        $provider->validate($errorElement, $media);
347
    }
348
349
    public function testValidateUploadType()
350
    {
351
        $errorElement = $this->getMockBuilder('Sonata\CoreBundle\Validator\ErrorElement')
352
            ->disableOriginalConstructor()
353
            ->getMock();
354
        $errorElement->expects($this->once())->method('with')
355
            ->will($this->returnSelf());
356
        $errorElement->expects($this->once())->method('addViolation')
357
            ->with($this->stringContains('Invalid mime type : %type%', ['type' => 'bar/baz']))
358
            ->will($this->returnSelf());
359
        $errorElement->expects($this->once())->method('end')
360
            ->will($this->returnSelf());
361
362
        $upload = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
363
            ->setConstructorArgs([tempnam(sys_get_temp_dir(), ''), 'dummy'])
364
            ->getMock();
365
        $upload->expects($this->any())->method('getClientSize')
366
            ->will($this->returnValue(23));
367
        $upload->expects($this->any())->method('getFilename')
368
            ->will($this->returnValue('test.txt'));
369
        $upload->expects($this->any())->method('getClientOriginalName')
370
            ->will($this->returnValue('test.txt'));
371
        $upload->expects($this->any())->method('getMimeType')
372
            ->will($this->returnValue('bar/baz'));
373
374
        $media = new Media();
375
        $media->setBinaryContent($upload);
376
377
        $provider = $this->getProvider();
378
        $provider->validate($errorElement, $media);
379
    }
380
}
381