Completed
Push — master ( 062693...6b78cb )
by
unknown
10:53
created

AbstractProvider::getTranslator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace MediaMonks\SonataMediaBundle\Provider;
4
5
use League\Flysystem\Filesystem;
6
use MediaMonks\SonataMediaBundle\Client\HttpClientInterface;
7
use MediaMonks\SonataMediaBundle\Model\AbstractMedia;
8
use MediaMonks\SonataMediaBundle\Form\Type\MediaFocalPointType;
9
use MediaMonks\SonataMediaBundle\Model\MediaInterface;
10
use Sonata\AdminBundle\Form\FormMapper;
11
use Sonata\CoreBundle\Validator\ErrorElement;
12
use Symfony\Component\Form\Extension\Core\Type\FileType;
13
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
14
use Symfony\Component\Form\Extension\Core\Type\TextType;
15
use Symfony\Component\HttpFoundation\File\UploadedFile;
16
use Symfony\Component\Translation\TranslatorInterface;
17
use Symfony\Component\Validator\Constraints as Constraint;
18
19
abstract class AbstractProvider implements ProviderInterface
20
{
21
    const SUPPORT_EMBED = 'embed';
22
    const SUPPORT_IMAGE = 'image';
23
    const SUPPORT_DOWNLOAD = 'download';
24
25
    const TYPE_AUDIO = 'audio';
26
    const TYPE_IMAGE = 'image';
27
    const TYPE_FILE = 'file';
28
    const TYPE_VIDEO = 'video';
29
30
    /**
31
     * @var Filesystem
32
     */
33
    protected $filesystem;
34
35
    /**
36
     * @var TranslatorInterface
37
     */
38
    private $translator;
39
40
    /**
41
     * @var array
42
     */
43
    private $imageConstraintOptions = [];
44
45
    /**
46
     * @var HttpClientInterface
47
     */
48
    private $httpClient;
49
50
    /**
51
     * @var AbstractMedia
52
     */
53
    private $media;
54
55
    /**
56
     * @param Filesystem $filesystem
57
     */
58 13
    public function setFilesystem(Filesystem $filesystem)
59
    {
60 13
        $this->filesystem = $filesystem;
61 13
    }
62
63
    /**
64
     * @param TranslatorInterface $translator
65
     */
66 13
    public function setTranslator(TranslatorInterface $translator)
67
    {
68 13
        $this->translator = $translator;
69 13
    }
70
71
    /**
72
     * @return \Symfony\Component\Translation\TranslatorInterface
73
     */
74 1
    public function getTranslator()
75
    {
76 1
        return $this->translator;
77
    }
78
79
    /**
80
     * @param array $options
81
     */
82 13
    public function setImageConstraintOptions(array $options)
83
    {
84 13
        $this->imageConstraintOptions = $options;
85 13
    }
86
87
    /**
88
     * @param HttpClientInterface $httpClient
89
     */
90 13
    public function setHttpClient(HttpClientInterface $httpClient)
91
    {
92 13
        $this->httpClient = $httpClient;
93 13
    }
94
95
    /**
96
     * @return HttpClientInterface
97
     */
98 4
    public function getHttpClient()
99
    {
100 4
        return $this->httpClient;
101
    }
102
103
    /**
104
     * @return Filesystem
105
     */
106 7
    public function getFilesystem()
107
    {
108 7
        return $this->filesystem;
109
    }
110
111
    /**
112
     * @param AbstractMedia $media
113
     * @return AbstractProvider
114
     */
115 11
    public function setMedia($media)
116
    {
117 11
        $this->media = $media;
118
119 11
        return $this;
120
    }
121
122
    /**
123
     * @param AbstractMedia $media
124
     * @param $providerReferenceUpdated
125
     */
126 7
    public function update(AbstractMedia $media, $providerReferenceUpdated)
127
    {
128 7
        $this->updateImage($media);
129 7
    }
130
131
    /**
132
     * @param FormMapper $formMapper
133
     */
134 11
    public function buildCreateForm(FormMapper $formMapper)
135
    {
136
        $formMapper
137 11
            ->add('provider', 'hidden');
138
139 11
        $this->buildProviderCreateForm($formMapper);
140 11
    }
141
142
    /**
143
     * @param FormMapper $formMapper
144
     */
145 7
    public function buildEditForm(FormMapper $formMapper)
146
    {
147
        $formMapper
148 7
            ->tab('general')
149 7
            ->add('provider', HiddenType::class);
150
151 7
        $this->buildProviderEditFormBefore($formMapper);
152
153 7
        $formMapper->add(
154 7
            'imageContent',
155 7
            'file',
156
            [
157 7
                'required'    => false,
158
                'constraints' => [
159 7
                    new Constraint\File(),
160
                ],
161 7
                'label'       => 'form.replacement_image',
162
            ]
163
        )
164 7
            ->add('title', TextType::class, ['label' => 'form.title'])
165 7
            ->add(
166 7
                'description',
167 7
                TextType::class,
168 7
                ['label' => 'form.description', 'required' => false]
169
            )
170 7
            ->add(
171 7
                'authorName',
172 7
                TextType::class,
173 7
                ['label' => 'form.authorName', 'required' => false]
174
            )
175 7
            ->add(
176 7
                'copyright',
177 7
                TextType::class,
178 7
                ['label' => 'form.copyright', 'required' => false]
179
            )
180 7
            ->end()
181 7
            ->end()
182 7
            ->tab('image')
183 7
            ->add('focalPoint', MediaFocalPointType::class, [
184 7
                'media' => $this->media
185
            ])
186 7
            ->end()
187 7
            ->end()
188
        ;
189
190 7
        $this->buildProviderEditFormAfter($formMapper);
191 7
    }
192
193
    /**
194
     * @param FormMapper $formMapper
195
     */
196
    public function buildProviderEditFormBefore(FormMapper $formMapper)
197
    {
198
    }
199
200
    /**
201
     * @param FormMapper $formMapper
202
     */
203 6
    public function buildProviderEditFormAfter(FormMapper $formMapper)
204
    {
205 6
    }
206
207
    /**
208
     * @param AbstractMedia $media
209
     * @param bool $useAsImage
210
     * @return string|void
211
     */
212 4
    protected function handleFileUpload(AbstractMedia $media, $useAsImage = false)
213
    {
214
        /**
215
         * @var UploadedFile $file
216
         */
217 4
        $file = $media->getBinaryContent();
218
219 4
        if (empty($file)) {
220
            return;
221
        }
222
223 4
        $filename = $this->getFilenameByFile($file);
224 4
        $this->writeToFilesystem($file, $filename);
225
226 4
        $media->setProviderMetadata(
227 4
            array_merge(
228 4
                $media->getProviderMetaData(),
229 4
                $this->getFileMetaData($file)
230
            )
231
        );
232
233 4
        if (empty($media->getImage()) && $useAsImage) {
234 2
            $media->setImage($filename);
235 2
            $media->setImageMetaData($media->getProviderMetaData());
236
        }
237
238 4
        if (empty($media->getTitle())) {
239 4
            $media->setTitle(
240 4
                str_replace(
241 4
                    '_',
242 4
                    ' ',
243 4
                    pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)
244
                )
245
            );
246
        }
247
248 4
        return $filename;
249
    }
250
251
    /**
252
     * @param UploadedFile $file
253
     * @return array
254
     */
255 4
    protected function getFileMetaData(UploadedFile $file)
256
    {
257
        $fileData = [
258 4
            'originalName'      => $file->getClientOriginalName(),
259 4
            'originalExtension' => $file->getClientOriginalExtension(),
260 4
            'mimeType'          => $file->getClientMimeType(),
261 4
            'size'              => $file->getSize(),
262
        ];
263
264
265 4
        $this->disableErrorHandler();
266 4
        $imageSize = getimagesize($file->getRealPath());
267 4
        if (is_array($imageSize)) {
268 4
            if (is_int($imageSize[0]) && is_int($imageSize[1])) {
269 4
                $fileData['height'] = $imageSize[0];
270 4
                $fileData['width']  = $imageSize[1];
271
            }
272 4
            if (isset($imageSize['bits'])) {
273 4
                $fileData['bits'] = $imageSize['bits'];
274
            }
275 4
            if (isset($imageSize['channels'])) {
276 2
                $fileData['channels'] = $imageSize['channels'];
277
            }
278
        }
279 4
        $this->restoreErrorHandler();
280
281 4
        return $fileData;
282
    }
283
284
    /**
285
     * @param AbstractMedia $media
286
     */
287 7
    public function updateImage(AbstractMedia $media)
288
    {
289
        /**
290
         * @var UploadedFile $file
291
         */
292 7
        $file = $media->getImageContent();
293 7
        if (empty($file)) {
294 5
            return;
295
        }
296
297 2
        $filename = $this->getFilenameByFile($file);
298 2
        $this->writeToFilesystem($file, $filename);
299
300 2
        $media->setImage($filename);
301 2
        $media->setImageMetaData($this->getFileMetaData($file));
302 2
    }
303
304
    /**
305
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
306
     * @param $name
307
     * @param $label
308
     * @param $required
309
     * @param array $constraints
310
     */
311 7
    protected function doAddFileField(
312
        FormMapper $formMapper,
313
        $name,
314
        $label,
315
        $required,
316
        $constraints = []
317
    ) {
318 7
        if ($required) {
319 7
            $constraints = array_merge(
320
                [
321 7
                    new Constraint\NotBlank(),
322 7
                    new Constraint\NotNull(),
323
                ],
324 7
                $constraints
325
            );
326
        }
327
328
        $formMapper
329 7
            ->add(
330
                $name,
331 7
                FileType::class,
332
                [
333 7
                    'multiple'    => false,
334
                    'data_class'  => null,
335 7
                    'constraints' => $constraints,
336 7
                    'label'       => $label,
337 7
                    'required'    => $required,
338
                ]
339
            );
340 7
    }
341
342
    /**
343
     * @param FormMapper $formMapper
344
     * @param string $name
345
     * @param string $label
346
     * @param array $options
347
     */
348 2 View Code Duplication
    public function addImageField(
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...
349
        FormMapper $formMapper,
350
        $name,
351
        $label,
352
        $options = []
353
    ) {
354 2
        $this->doAddFileField(
355
            $formMapper,
356
            $name,
357
            $label,
358 2
            false,
359
            [
360 2
                new Constraint\Image(
361 2
                    array_merge($this->imageConstraintOptions, $options)
362
                ),
363
            ]
364
        );
365 2
    }
366
367
    /**
368
     * @param FormMapper $formMapper
369
     * @param $name
370
     * @param $label
371
     * @param array $options
372
     */
373 3 View Code Duplication
    public function addRequiredImageField(
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...
374
        FormMapper $formMapper,
375
        $name,
376
        $label,
377
        $options = []
378
    ) {
379 3
        $this->doAddFileField(
380
            $formMapper,
381
            $name,
382
            $label,
383 3
            true,
384
            [
385 3
                new Constraint\Image(
386 3
                    array_merge($this->imageConstraintOptions, $options)
387
                ),
388
            ]
389
        );
390 3
    }
391
392
    /**
393
     * @param UploadedFile $file
394
     * @return string
395
     */
396 4
    protected function getFilenameByFile(UploadedFile $file)
397
    {
398 4
        return sprintf(
399 4
            '%s_%d.%s',
400 4
            sha1($file->getClientOriginalName()),
401 4
            time(),
402 4
            $file->getClientOriginalExtension()
403
        );
404
    }
405
406
    /**
407
     * @param UploadedFile $file
408
     * @param $filename
409
     * @throws \Exception
410
     */
411 4
    protected function writeToFilesystem(UploadedFile $file, $filename)
412
    {
413 4
        $this->disableErrorHandler();
414 4
        $stream = fopen($file->getRealPath(), 'r+');
415 4
        $written = $this->getFilesystem()->writeStream($filename, $stream);
416 4
        fclose($stream); // this sometime messes up
417 4
        $this->restoreErrorHandler();
418
419 4
        if (!$written) {
420
            throw new \Exception('Could not write to file system');
421
        }
422 4
    }
423
424
    /**
425
     * @param $renderType
426
     * @return boolean
427
     */
428 7
    public function supports($renderType)
429
    {
430 7
        if ($renderType === self::SUPPORT_EMBED) {
431 7
            return $this->supportsEmbed();
432
        }
433 7
        if ($renderType === self::SUPPORT_IMAGE) {
434 7
            return $this->supportsImage();
435
        }
436 7
        if ($renderType === self::SUPPORT_DOWNLOAD) {
437 7
            return $this->supportsDownload();
438
        }
439
440
        return false;
441
    }
442
443
    /**
444
     *
445
     */
446 8
    protected function disableErrorHandler()
447
    {
448 8
        set_error_handler(
449 8
            function () {
450 8
            }
451
        );
452 8
    }
453
454
    /**
455
     *
456
     */
457 8
    protected function restoreErrorHandler()
458
    {
459 8
        restore_error_handler();
460 8
    }
461
462
    /**
463
     * @param ErrorElement $errorElement
464
     * @param AbstractMedia $media
465
     */
466 7
    public function validate(ErrorElement $errorElement, AbstractMedia $media)
467
    {
468 7
    }
469
470
    /**
471
     * @return string
472
     */
473 2
    public function getEmbedTemplate()
474
    {
475 2
        return sprintf(
476 2
            'MediaMonksSonataMediaBundle:Provider:%s_embed.html.twig',
477 2
            $this->getName()
478
        );
479
    }
480
}
481