Completed
Push — master ( 847f63...4433bd )
by
unknown
02:42
created

BaseVideoProvider::generatePrivateUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\MediaBundle\Provider;
15
16
use Buzz\Browser;
17
use Gaufrette\Filesystem;
18
use Imagine\Image\Box;
19
use Sonata\AdminBundle\Form\FormMapper;
20
use Sonata\CoreBundle\Model\Metadata;
21
use Sonata\MediaBundle\CDN\CDNInterface;
22
use Sonata\MediaBundle\Generator\GeneratorInterface;
23
use Sonata\MediaBundle\Metadata\MetadataBuilderInterface;
24
use Sonata\MediaBundle\Model\MediaInterface;
25
use Sonata\MediaBundle\Thumbnail\ThumbnailInterface;
26
use Symfony\Component\Form\Extension\Core\Type\TextType;
27
use Symfony\Component\Form\FormBuilder;
28
use Symfony\Component\Validator\Constraints\NotBlank;
29
use Symfony\Component\Validator\Constraints\NotNull;
30
31
abstract class BaseVideoProvider extends BaseProvider
32
{
33
    /**
34
     * @var Browser
35
     */
36
    protected $browser;
37
38
    /**
39
     * @var MetadataBuilderInterface
40
     */
41
    protected $metadata;
42
43
    /**
44
     * @param string                        $name
45
     * @param Filesystem                    $filesystem
46
     * @param CDNInterface                  $cdn
47
     * @param GeneratorInterface            $pathGenerator
48
     * @param ThumbnailInterface            $thumbnail
49
     * @param Browser                       $browser
50
     * @param MetadataBuilderInterface|null $metadata
51
     */
52
    public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, Browser $browser, MetadataBuilderInterface $metadata = null)
53
    {
54
        parent::__construct($name, $filesystem, $cdn, $pathGenerator, $thumbnail);
55
56
        // NEXT_MAJOR: remove this check!
57
        if (!method_exists($this, 'getReferenceUrl')) {
58
            @trigger_error('The method "getReferenceUrl" is required with the next major release.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
59
        }
60
61
        $this->browser = $browser;
62
        $this->metadata = $metadata;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function getProviderMetadata()
69
    {
70
        return new Metadata($this->getName(), $this->getName().'.description', null, 'SonataMediaBundle', ['class' => 'fa fa-video-camera']);
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function getReferenceImage(MediaInterface $media)
77
    {
78
        return $media->getMetadataValue('thumbnail_url');
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function getReferenceFile(MediaInterface $media)
85
    {
86
        $key = $this->generatePrivateUrl($media, MediaProviderInterface::FORMAT_REFERENCE);
87
88
        // the reference file is remote, get it and store it with the 'reference' format
89
        if ($this->getFilesystem()->has($key)) {
90
            $referenceFile = $this->getFilesystem()->get($key);
91
        } else {
92
            $referenceFile = $this->getFilesystem()->get($key, true);
93
            $metadata = $this->metadata ? $this->metadata->get($media, $referenceFile->getName()) : [];
94
            $referenceFile->setContent($this->browser->get($this->getReferenceImage($media))->getContent(), $metadata);
95
        }
96
97
        return $referenceFile;
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function generatePublicUrl(MediaInterface $media, $format)
104
    {
105
        return $this->getCdn()->getPath(sprintf('%s/thumb_%s_%s.jpg',
106
            $this->generatePath($media),
107
            $media->getId(),
108
            $format
109
        ), $media->getCdnIsFlushable());
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function generatePrivateUrl(MediaInterface $media, $format)
116
    {
117
        return sprintf('%s/thumb_%s_%s.jpg',
118
            $this->generatePath($media),
119
            $media->getId(),
120
            $format
121
        );
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127
    public function buildEditForm(FormMapper $formMapper): void
128
    {
129
        $formMapper->add('name');
130
        $formMapper->add('enabled', null, ['required' => false]);
131
        $formMapper->add('authorName');
132
        $formMapper->add('cdnIsFlushable');
133
        $formMapper->add('description');
134
        $formMapper->add('copyright');
135
        $formMapper->add('binaryContent', TextType::class, ['required' => false]);
136
    }
137
138
    /**
139
     * {@inheritdoc}
140
     */
141
    public function buildCreateForm(FormMapper $formMapper): void
142
    {
143
        $formMapper->add('binaryContent', TextType::class, [
144
            'constraints' => [
145
                new NotBlank(),
146
                new NotNull(),
147
            ],
148
        ]);
149
    }
150
151
    /**
152
     * {@inheritdoc}
153
     */
154
    public function buildMediaType(FormBuilder $formBuilder): void
155
    {
156
        $formBuilder->add('binaryContent', TextType::class, [
157
            'label' => 'widget_label_binary_content',
158
        ]);
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164
    public function postUpdate(MediaInterface $media): void
165
    {
166
        $this->postPersist($media);
167
    }
168
169
    /**
170
     * {@inheritdoc}
171
     */
172
    public function postPersist(MediaInterface $media): void
173
    {
174
        if (!$media->getBinaryContent()) {
175
            return;
176
        }
177
178
        $this->generateThumbnails($media);
179
180
        $media->resetBinaryContent();
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     */
186
    public function postRemove(MediaInterface $media): void
187
    {
188
    }
189
190
    // NEXT_MAJOR: Uncomment this method
191
    /*
192
     * Get provider reference url.
193
     *
194
     * @param MediaInterface $media
195
     *
196
     * @return string
197
     */
198
    // abstract public function getReferenceUrl(MediaInterface $media);
199
200
    /**
201
     * @param MediaInterface $media
202
     * @param string         $url
203
     *
204
     * @throws \RuntimeException
205
     *
206
     * @return mixed
207
     */
208
    protected function getMetadata(MediaInterface $media, $url)
0 ignored issues
show
Unused Code introduced by
The parameter $media is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
209
    {
210
        try {
211
            $response = $this->browser->get($url);
212
        } catch (\RuntimeException $e) {
213
            throw new \RuntimeException('Unable to retrieve the video information for :'.$url, null, $e);
214
        }
215
216
        $metadata = json_decode($response->getContent(), true);
217
218
        if (!$metadata) {
219
            throw new \RuntimeException('Unable to decode the video information for :'.$url);
220
        }
221
222
        return $metadata;
223
    }
224
225
    /**
226
     * @param MediaInterface $media
227
     * @param string         $format
228
     * @param array          $options
229
     *
230
     * @return Box
231
     */
232
    protected function getBoxHelperProperties(MediaInterface $media, $format, $options = [])
233
    {
234
        if (MediaProviderInterface::FORMAT_REFERENCE === $format) {
235
            return $media->getBox();
236
        }
237
238
        if (isset($options['width']) || isset($options['height'])) {
239
            $settings = [
240
                'width' => $options['width'] ?? null,
241
                'height' => $options['height'] ?? null,
242
            ];
243
        } else {
244
            $settings = $this->getFormat($format);
245
        }
246
247
        return $this->resizer->getBox($media, $settings);
0 ignored issues
show
Security Bug introduced by
It seems like $settings defined by $this->getFormat($format) on line 244 can also be of type false; however, Sonata\MediaBundle\Resiz...izerInterface::getBox() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
248
    }
249
}
250