Completed
Pull Request — master (#1175)
by Grégoire
03:04
created

FileProviderTest   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 375
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 0
loc 375
rs 10
c 3
b 0
f 0
wmc 18
lcom 1
cbo 9

14 Methods

Rating   Name   Duplication   Size   Complexity  
A testHelperProperies() 0 16 1
A testForm() 0 21 2
A testThumbnail() 0 10 1
A testDownload() 0 16 1
B mediaProvider() 0 27 1
B testTransform() 0 27 4
B testBinaryContentWithRealPath() 0 39 1
B testBinaryContentStreamWrapped() 0 40 1
B getProvider() 0 25 1
B testEvent() 0 35 1
A testProvider() 0 17 1
A testValidate() 0 11 1
B testValidateUploadSize() 0 31 1
B testValidateUploadType() 0 31 1
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->getMock('Sonata\MediaBundle\Resizer\ResizerInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
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->getMock('Gaufrette\Filesystem', array('get'), array($adapter));
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
31
        $file = $this->getMock('Gaufrette\File', array(), array('foo', $filesystem));
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
32
        $filesystem->expects($this->any())->method('get')->will($this->returnValue($file));
33
34
        $cdn = new \Sonata\MediaBundle\CDN\Server('/uploads/media');
35
36
        $generator = new \Sonata\MediaBundle\Generator\DefaultGenerator();
37
38
        $thumbnail = new FormatThumbnail('jpg');
39
40
        $metadata = $this->getMock('Sonata\MediaBundle\Metadata\MetadataBuilderInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
41
42
        $provider = new FileProvider('file', $filesystem, $cdn, $generator, $thumbnail, array('txt'), array('foo/bar'), $metadata);
43
        $provider->setResizer($resizer);
44
45
        return $provider;
46
    }
47
48
    public function testProvider()
49
    {
50
        $provider = $this->getProvider();
51
52
        $media = new Media();
53
        $media->setName('test.txt');
54
        $media->setProviderReference('ASDASD.txt');
55
        $media->setContext('default');
56
57
        $media->setId(1023456);
58
        $this->assertSame('default/0011/24/ASDASD.txt', $provider->getReferenceImage($media));
59
60
        $this->assertSame('default/0011/24', $provider->generatePath($media));
61
62
        // default icon image
63
        $this->assertSame('/uploads/media/sonatamedia/files/big/file.png', $provider->generatePublicUrl($media, 'big'));
64
    }
65
66
    public function testHelperProperies()
67
    {
68
        $provider = $this->getProvider();
69
70
        $provider->addFormat('admin', array('width' => 100));
71
        $media = new Media();
72
        $media->setName('test.png');
73
        $media->setProviderReference('ASDASDAS.png');
74
        $media->setId(10);
75
        $media->setHeight(100);
76
77
        $properties = $provider->getHelperProperties($media, 'admin');
78
79
        $this->assertInternalType('array', $properties);
80
        $this->assertSame('test.png', $properties['title']);
81
    }
82
83
    public function testForm()
84
    {
85
        if (!class_exists('Sonata\AdminBundle\Form\FormMapper')) {
86
            $this->markTestSkipped("AdminBundle doesn't seem to be installed");
87
        }
88
89
        $provider = $this->getProvider();
90
91
        $admin = $this->getMock('Sonata\AdminBundle\Admin\AdminInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
92
        $admin->expects($this->any())
93
            ->method('trans')
94
            ->will($this->returnValue('message'));
95
96
        $formMapper = $this->getMock('Sonata\AdminBundle\Form\FormMapper', array('add', 'getAdmin'), array(), '', false);
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
97
        $formMapper->expects($this->exactly(8))
98
            ->method('add')
99
            ->will($this->returnValue(null));
100
101
        $provider->buildCreateForm($formMapper);
102
        $provider->buildEditForm($formMapper);
103
    }
104
105
    public function testThumbnail()
106
    {
107
        $provider = $this->getProvider();
108
109
        $media = new Media();
110
        $media->setName('test.png');
111
        $media->setId(1023456);
112
113
        $provider->generateThumbnails($media);
114
    }
115
116
    public function testEvent()
117
    {
118
        $provider = $this->getProvider();
119
120
        $provider->addFormat('big', array('width' => 200, 'height' => 100, 'constraint' => true));
121
122
        $file = __DIR__.'/../fixtures/file.txt';
123
124
        $media = new Media();
125
        $provider->preUpdate($media);
126
        $this->assertNull($media->getProviderReference());
127
128
        $media->setBinaryContent($file);
129
        $provider->transform($media);
130
131
        $this->assertInstanceOf('\DateTime', $media->getUpdatedAt());
132
        $this->assertNotNull($media->getProviderReference());
133
134
        $provider->postUpdate($media);
135
136
        $file = new \Symfony\Component\HttpFoundation\File\File(realpath(__DIR__.'/../fixtures/file.txt'));
137
138
        $media = new Media();
139
        $media->setBinaryContent($file);
140
        $media->setId(1023456);
141
142
        // pre persist the media
143
        $provider->transform($media);
144
145
        $this->assertSame('file.txt', $media->getName(), '::getName() return the file name');
146
        $this->assertNotNull($media->getProviderReference(), '::getProviderReference() is set');
147
148
        $this->assertFalse($provider->generatePrivateUrl($media, 'big'), '::generatePrivateUrl() return false on non reference formate');
149
        $this->assertNotNull($provider->generatePrivateUrl($media, 'reference'), '::generatePrivateUrl() return path for reference formate');
150
    }
151
152
    public function testDownload()
153
    {
154
        $provider = $this->getProvider();
155
156
        $file = new File(realpath(__DIR__.'/../fixtures/FileProviderTest/0011/24/file.txt'));
157
158
        $media = new Media();
159
        $media->setBinaryContent($file);
160
        $media->setProviderReference('file.txt');
161
        $media->setContext('FileProviderTest');
162
        $media->setId(1023456);
163
164
        $response = $provider->getDownloadResponse($media, 'reference', 'X-Accel-Redirect');
165
166
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\BinaryFileResponse', $response);
167
    }
168
169
    /**
170
     * @dataProvider mediaProvider
171
     */
172
    public function testTransform($expected, $media, $overridePhpSapiName = true)
173
    {
174
        $self = $this;
175
176
        $closure = function () use ($self, $expected, $media, $overridePhpSapiName) {
177
            if ($overridePhpSapiName) {
178
                require_once 'phpSapiNameOverride.php';
179
            }
180
181
            $provider = $self->getProvider();
182
183
            try {
184
                $provider->transform($media);
185
186
                $self->assertInstanceOf($expected, $media->getBinaryContent());
187
            } catch (\Exception $e) {
188
                if ($overridePhpSapiName) {
189
                    $self->assertInstanceOf('\RuntimeException', $e);
190
                    $self->assertNull($media->getContentType());
191
                } else {
192
                    $self->assertEquals('The current process cannot be executed in cli environment', $e->getMessage());
193
                }
194
            }
195
        };
196
197
        $closure();
198
    }
199
200
    public function mediaProvider()
201
    {
202
        $file = new \Symfony\Component\HttpFoundation\File\File(realpath(__DIR__.'/../fixtures/file.txt'));
203
        $content = file_get_contents(realpath(__DIR__.'/../fixtures/file.txt'));
204
        $request = new Request(array(), array(), array(), array(), array(), array(), $content);
205
206
        $media1 = new Media();
207
        $media1->setBinaryContent($file);
208
        $media1->setContentType('foo');
209
        $media1->setId(1023456);
210
211
        $media2 = new Media();
212
        $media2->setBinaryContent($request);
213
        $media2->setContentType('text/plain');
214
        $media2->setId(1023456);
215
216
        $media3 = new Media();
217
        $media3->setBinaryContent($request);
218
        $media3->setId(1023456);
219
220
        return array(
221
            array('\Symfony\Component\HttpFoundation\File\File', $media1, false),
222
            array('\Symfony\Component\HttpFoundation\File\File', $media1),
223
            array('\Symfony\Component\HttpFoundation\File\File', $media2),
224
            array(null, $media3),
225
        );
226
    }
227
228
    /**
229
     * @requires PHP 5.6
230
     *
231
     * @see https://github.com/sebastianbergmann/phpunit/issues/1409
232
     */
233
    public function testBinaryContentWithRealPath()
234
    {
235
        $media = $this->getMock('Sonata\MediaBundle\Model\MediaInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
236
237
        $media->expects($this->any())
238
            ->method('getProviderReference')
239
            ->willReturn('provider');
240
241
        $media->expects($this->any())
242
            ->method('getId')
243
            ->willReturn(10000);
244
245
        $media->expects($this->any())
246
            ->method('getContext')
247
            ->willReturn('context');
248
249
        $binaryContent = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
250
            ->setMethods(array('getRealPath', 'getPathname'))
251
            ->disableOriginalConstructor()
252
            ->getMock();
253
254
        $binaryContent->expects($this->atLeastOnce())
255
            ->method('getRealPath')
256
            ->willReturn(__DIR__.'/../fixtures/file.txt');
257
258
        $binaryContent->expects($this->never())
259
            ->method('getPathname');
260
261
        $media->expects($this->any())
262
            ->method('getBinaryContent')
263
            ->willReturn($binaryContent);
264
265
        $provider = $this->getProvider();
266
267
        $setFileContents = new \ReflectionMethod('Sonata\MediaBundle\Provider\FileProvider', 'setFileContents');
268
        $setFileContents->setAccessible(true);
269
270
        $setFileContents->invoke($provider, $media);
271
    }
272
273
    /**
274
     * @requires PHP 5.6
275
     *
276
     * @see https://github.com/sebastianbergmann/phpunit/issues/1409
277
     */
278
    public function testBinaryContentStreamWrapped()
279
    {
280
        $media = $this->getMock('Sonata\MediaBundle\Model\MediaInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
281
282
        $media->expects($this->any())
283
            ->method('getProviderReference')
284
            ->willReturn('provider');
285
286
        $media->expects($this->any())
287
            ->method('getId')
288
            ->willReturn(10000);
289
290
        $media->expects($this->any())
291
            ->method('getContext')
292
            ->willReturn('context');
293
294
        $binaryContent = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
295
            ->setMethods(array('getRealPath', 'getPathname'))
296
            ->disableOriginalConstructor()
297
            ->getMock();
298
299
        $binaryContent->expects($this->atLeastOnce())
300
            ->method('getRealPath')
301
            ->willReturn(false);
302
303
        $binaryContent->expects($this->atLeastOnce())
304
            ->method('getPathname')
305
            ->willReturn(__DIR__.'/../fixtures/file.txt');
306
307
        $media->expects($this->any())
308
            ->method('getBinaryContent')
309
            ->willReturn($binaryContent);
310
311
        $provider = $this->getProvider();
312
313
        $setFileContents = new \ReflectionMethod('Sonata\MediaBundle\Provider\FileProvider', 'setFileContents');
314
        $setFileContents->setAccessible(true);
315
316
        $setFileContents->invoke($provider, $media);
317
    }
318
319
    public function testValidate()
320
    {
321
        $errorElement = $this->getMockBuilder('Sonata\CoreBundle\Validator\ErrorElement')
322
            ->disableOriginalConstructor()
323
            ->getMock();
324
325
        $media = new Media();
326
327
        $provider = $this->getProvider();
328
        $provider->validate($errorElement, $media);
329
    }
330
331
    public function testValidateUploadSize()
332
    {
333
        $errorElement = $this->getMockBuilder('Sonata\CoreBundle\Validator\ErrorElement')
334
            ->disableOriginalConstructor()
335
            ->getMock();
336
        $errorElement->expects($this->once())->method('with')
337
            ->will($this->returnSelf());
338
        $errorElement->expects($this->once())->method('addViolation')
339
            ->with($this->stringContains('The file is too big, max size:'))
340
            ->will($this->returnSelf());
341
        $errorElement->expects($this->once())->method('end')
342
            ->will($this->returnSelf());
343
344
        $upload = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
345
            ->setConstructorArgs(array(tempnam(sys_get_temp_dir(), ''), 'dummy'))
346
            ->getMock();
347
        $upload->expects($this->any())->method('getClientSize')
348
            ->will($this->returnValue(0));
349
        $upload->expects($this->any())->method('getFilename')
350
            ->will($this->returnValue('test.txt'));
351
        $upload->expects($this->any())->method('getClientOriginalName')
352
            ->will($this->returnValue('test.txt'));
353
        $upload->expects($this->any())->method('getMimeType')
354
            ->will($this->returnValue('foo/bar'));
355
356
        $media = new Media();
357
        $media->setBinaryContent($upload);
358
359
        $provider = $this->getProvider();
360
        $provider->validate($errorElement, $media);
361
    }
362
363
    public function testValidateUploadType()
364
    {
365
        $errorElement = $this->getMockBuilder('Sonata\CoreBundle\Validator\ErrorElement')
366
            ->disableOriginalConstructor()
367
            ->getMock();
368
        $errorElement->expects($this->once())->method('with')
369
            ->will($this->returnSelf());
370
        $errorElement->expects($this->once())->method('addViolation')
371
            ->with($this->stringContains('Invalid mime type : %type%', array('type' => 'bar/baz')))
0 ignored issues
show
Documentation introduced by
array('type' => 'bar/baz') is of type array<string,string,{"type":"string"}>, but the function expects a boolean.

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...
372
            ->will($this->returnSelf());
373
        $errorElement->expects($this->once())->method('end')
374
            ->will($this->returnSelf());
375
376
        $upload = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
377
            ->setConstructorArgs(array(tempnam(sys_get_temp_dir(), ''), 'dummy'))
378
            ->getMock();
379
        $upload->expects($this->any())->method('getClientSize')
380
            ->will($this->returnValue(23));
381
        $upload->expects($this->any())->method('getFilename')
382
            ->will($this->returnValue('test.txt'));
383
        $upload->expects($this->any())->method('getClientOriginalName')
384
            ->will($this->returnValue('test.txt'));
385
        $upload->expects($this->any())->method('getMimeType')
386
            ->will($this->returnValue('bar/baz'));
387
388
        $media = new Media();
389
        $media->setBinaryContent($upload);
390
391
        $provider = $this->getProvider();
392
        $provider->validate($errorElement, $media);
393
    }
394
}
395