Completed
Push — master ( 0e5803...f3fa63 )
by
unknown
05:14
created

AbstractProvider::getTitle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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