Completed
Push — master ( e48220...15f13c )
by
unknown
07:36
created

AbstractProvider::supports()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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