Completed
Push — master ( 8cca00...50a95d )
by
unknown
06:53
created

AbstractProvider::setImageConstraintOptions()   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 1
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\HttpFoundation\File\UploadedFile;
14
use Symfony\Component\Validator\Constraints as Constraint;
15
16
abstract class AbstractProvider implements ProviderInterface
17
{
18
    const TYPE_EMBED = 'embed';
19
    const TYPE_IMAGE = 'image';
20
    const TYPE_DOWNLOAD = 'download';
21
22
    /**
23
     * @var Filesystem
24
     */
25
    protected $filesystem;
26
27
    /**
28
     * @var array
29
     */
30
    private $imageConstraintOptions = [];
31
32
    /**
33
     * @param Filesystem $filesystem
34
     */
35
    public function setFilesystem(Filesystem $filesystem)
36
    {
37
        $this->filesystem = $filesystem;
38
    }
39
40
    /**
41
     * @param array $options
42
     */
43
    public function setImageConstraintOptions(array $options)
44
    {
45
        $this->imageConstraintOptions = $options;
46
    }
47
48
    /**
49
     * @return Filesystem
50
     */
51
    public function getFilesystem()
52
    {
53
        return $this->filesystem;
54
    }
55
56
    /**
57
     * @param Media $media
58
     * @param $providerReferenceUpdated
59
     */
60
    public function update(Media $media, $providerReferenceUpdated)
61
    {
62
        $this->updateImage($media);
63
    }
64
65
    /**
66
     * @return string
67
     */
68
    public function getTranslationDomain()
69
    {
70
        return 'MediaMonksSonataMediaBundle';
71
    }
72
73
    /**
74
     * @param MediaInterface $media
75
     * @param array $options
76
     * @return array
77
     */
78
    public function toArray(MediaInterface $media, array $options = [])
79
    {
80
        return [
81
            'type'        => $this->getType(),
82
            'title'       => $media->getTitle(),
83
            'description' => $media->getDescription(),
84
            'authorName'  => $media->getAuthorName(),
85
            'copyright'   => $media->getCopyright(),
86
            'reference'   => $media->getProviderReference(),
87
        ];
88
    }
89
90
    /**
91
     * @return array
92
     */
93
    protected function getPointOfInterestChoices()
94
    {
95
        return array_flip(
96
            [
97
                'top-left'     => 'Top Left',
98
                'top'          => 'Top',
99
                'top-right'    => 'Top Right',
100
                'left'         => 'Left',
101
                'center'       => 'Center',
102
                'right'        => 'Right',
103
                'bottom-left'  => 'Bottom Left',
104
                'bottom'       => 'Bottom',
105
                'bottom-right' => 'Bottom Right',
106
            ]
107
        );
108
    }
109
110
    /**
111
     * @param FormMapper $formMapper
112
     */
113
    public function buildCreateForm(FormMapper $formMapper)
114
    {
115
        $formMapper
116
            ->add('provider', 'hidden');
117
118
        $this->buildProviderCreateForm($formMapper);
119
    }
120
121
    /**
122
     * @param FormMapper $formMapper
123
     */
124
    public function buildEditForm(FormMapper $formMapper)
125
    {
126
        $formMapper
127
            ->with('General')
128
            ->add('provider', HiddenType::class);
129
130
        $this->buildProviderEditForm($formMapper);
131
132
        $formMapper->add(
133
            'imageContent',
134
            'file',
135
            [
136
                'required'    => false,
137
                'constraints' => [
138
                    new Constraint\File(),
139
                ],
140
                'label'       => 'Replacement Image',
141
            ]
142
        )
143
            ->add('title')
144
            ->add('description')
145
            ->add('authorName')
146
            ->add('copyright')
147
            ->add(
148
                'pointOfInterest',
149
                ChoiceType::class,
150
                [
151
                    'required' => false,
152
                    'label'    => 'Image Point Of Interest',
153
                    'choices'  => $this->getPointOfInterestChoices(),
154
                ]
155
            )
156
            ->end();
157
    }
158
159
    /**
160
     * @param FormMapper $formMapper
161
     */
162
    public function buildProviderEditForm(FormMapper $formMapper)
163
    {
164
    }
165
166
    /**
167
     * @param Media $media
168
     * @param bool $useAsImage
169
     * @return string|void
170
     */
171
    protected function handleFileUpload(Media $media, $useAsImage = false)
172
    {
173
        /**
174
         * @var UploadedFile $file
175
         */
176
        $file = $media->getBinaryContent();
177
178
        if (empty($file)) {
179
            return;
180
        }
181
182
        $filename = $this->getFilenameByFile($file);
183
        $this->writeToFilesystem($file, $filename);
184
185
        $media->setProviderMetadata(array_merge($media->getProviderMetaData(), $this->getFileMetaData($file)));
186
187
        if (empty($media->getImage()) && $useAsImage) {
188
            $media->setImage($filename);
189
            $media->setImageMetaData($media->getProviderMetaData());
190
        }
191
192
        if (empty($media->getTitle())) {
193
            $media->setTitle(str_replace('_', ' ', pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)));
194
        }
195
196
        return $filename;
197
    }
198
199
    /**
200
     * @param UploadedFile $file
201
     * @return array
202
     */
203
    protected function getFileMetaData(UploadedFile $file)
204
    {
205
        return [
206
            'originalName'      => $file->getClientOriginalName(),
207
            'originalExtension' => $file->getClientOriginalExtension(),
208
            'mimeType'          => $file->getClientMimeType(),
209
            'size'              => $file->getSize(),
210
        ];
211
    }
212
213
    /**
214
     * @param Media $media
215
     */
216
    public function updateImage(Media $media)
217
    {
218
        /**
219
         * @var UploadedFile $file
220
         */
221
        $file = $media->getImageContent();
222
        if (empty($file)) {
223
            return;
224
        }
225
226
        $filename = $this->getFilenameByFile($file);
227
        $this->writeToFilesystem($file, $filename);
228
229
        $media->setImage($filename);
230
        $media->setImageMetaData($this->getFileMetaData($file));
231
    }
232
233
    protected function doAddFileField(FormMapper $formMapper, $name, $label, $required, $constraints = [])
234
    {
235
        if ($required) {
236
            $constraints = array_merge([
237
                new Constraint\NotBlank(),
238
                new Constraint\NotNull(),
239
            ], $constraints);
240
        }
241
242
        $formMapper
243
            ->add(
244
                $name,
245
                FileType::class,
246
                [
247
                    'multiple'    => false,
248
                    'data_class'  => null,
249
                    'constraints' => $constraints,
250
                    'label'       => $label,
251
                    'required'    => $required,
252
                ]
253
            );
254
    }
255
256
    /**
257
     * @param FormMapper $formMapper
258
     * @param string $name
259
     * @param string $label
260
     * @param array $options
261
     */
262
    public function addImageField(FormMapper $formMapper, $name, $label, $options = [])
263
    {
264
        $this->doAddFileField($formMapper, $name, $label, false, [
265
            new Constraint\Image(array_merge($this->imageConstraintOptions, $options))
266
        ]);
267
    }
268
269
    /**
270
     * @param FormMapper $formMapper
271
     * @param $name
272
     * @param $label
273
     * @param array $options
274
     */
275
    public function addRequiredImageField(FormMapper $formMapper, $name, $label, $options = [])
276
    {
277
        $this->doAddFileField($formMapper, $name, $label, true, [
278
            new Constraint\Image(array_merge($this->imageConstraintOptions, $options))
279
        ]);
280
    }
281
282
    /**
283
     * @param UploadedFile $file
284
     * @return string
285
     */
286
    protected function getFilenameByFile(UploadedFile $file)
287
    {
288
        return sprintf(
289
            '%s_%d.%s',
290
            sha1($file->getClientOriginalName()),
291
            time(),
292
            $file->getClientOriginalExtension()
293
        );
294
    }
295
296
    /**
297
     * @param UploadedFile $file
298
     * @param $filename
299
     * @throws \Exception
300
     */
301
    protected function writeToFilesystem(UploadedFile $file, $filename)
302
    {
303
        set_error_handler(
304
            function () {
305
            }
306
        );
307
        $stream = fopen($file->getRealPath(), 'r+');
308
        $written = $this->getFilesystem()->writeStream($filename, $stream);
309
        fclose($stream); // this sometime messes up
310
        restore_error_handler();
311
312
        if (!$written) {
313
            throw new \Exception('Could not write to file system');
314
        }
315
    }
316
317
    /**
318
     * @param $type
319
     * @return boolean
320
     */
321
    public function supports($type)
322
    {
323
        if ($type === self::TYPE_EMBED) {
324
            return $this->supportsEmbed();
325
        }
326
        if ($type === self::TYPE_IMAGE) {
327
            return $this->supportsImage();
328
        }
329
        if ($type === self::TYPE_DOWNLOAD) {
330
            return $this->supportsDownload();
331
        }
332
333
        return false;
334
    }
335
336
    /**
337
     *
338
     */
339
    protected function disableErrorHandler()
340
    {
341
        set_error_handler(
342
            function () {
343
            }
344
        );
345
    }
346
347
    /**
348
     *
349
     */
350
    protected function restoreErrorHandler()
351
    {
352
        restore_error_handler();
353
    }
354
355
    /**
356
     * @param ErrorElement $errorElement
357
     * @param Media $media
358
     */
359
    public function validate(ErrorElement $errorElement, Media $media)
360
    {
361
    }
362
}
363