BaseVideoProvider::getReferenceFile()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 3
nc 3
nop 1
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\MediaBundle\CDN\CDNInterface;
21
use Sonata\MediaBundle\Generator\GeneratorInterface;
22
use Sonata\MediaBundle\Metadata\MetadataBuilderInterface;
23
use Sonata\MediaBundle\Model\MediaInterface;
24
use Sonata\MediaBundle\Thumbnail\ThumbnailInterface;
25
use Symfony\Component\Form\Extension\Core\Type\TextType;
26
use Symfony\Component\Form\FormBuilder;
27
use Symfony\Component\Validator\Constraints\NotBlank;
28
use Symfony\Component\Validator\Constraints\NotNull;
29
30
abstract class BaseVideoProvider extends BaseProvider
31
{
32
    /**
33
     * @var Browser
34
     */
35
    protected $browser;
36
37
    /**
38
     * @var MetadataBuilderInterface
39
     */
40
    protected $metadata;
41
42
    /**
43
     * @param string $name
44
     */
45
    public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, Browser $browser, ?MetadataBuilderInterface $metadata = null)
46
    {
47
        parent::__construct($name, $filesystem, $cdn, $pathGenerator, $thumbnail);
48
49
        // NEXT_MAJOR: remove this check!
50
        if (!method_exists($this, 'getReferenceUrl')) {
51
            @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...
52
        }
53
54
        $this->browser = $browser;
55
        $this->metadata = $metadata;
56
    }
57
58
    public function getProviderMetadata()
59
    {
60
        return new Metadata($this->getName(), $this->getName().'.description', null, 'SonataMediaBundle', ['class' => 'fa fa-video-camera']);
61
    }
62
63
    public function getReferenceImage(MediaInterface $media)
64
    {
65
        return $media->getMetadataValue('thumbnail_url');
66
    }
67
68
    public function getReferenceFile(MediaInterface $media)
69
    {
70
        $key = $this->generatePrivateUrl($media, MediaProviderInterface::FORMAT_REFERENCE);
71
72
        // the reference file is remote, get it and store it with the 'reference' format
73
        if ($this->getFilesystem()->has($key)) {
74
            $referenceFile = $this->getFilesystem()->get($key);
75
        } else {
76
            $referenceFile = $this->getFilesystem()->get($key, true);
77
            $metadata = $this->metadata ? $this->metadata->get($media, $referenceFile->getName()) : [];
78
            $referenceFile->setContent($this->browser->get($this->getReferenceImage($media))->getContent(), $metadata);
79
        }
80
81
        return $referenceFile;
82
    }
83
84
    public function generatePublicUrl(MediaInterface $media, $format)
85
    {
86
        return $this->getCdn()->getPath(sprintf(
87
            '%s/thumb_%s_%s.jpg',
88
            $this->generatePath($media),
89
            $media->getId(),
90
            $format
91
        ), $media->getCdnIsFlushable());
92
    }
93
94
    public function generatePrivateUrl(MediaInterface $media, $format)
95
    {
96
        return sprintf(
97
            '%s/thumb_%s_%s.jpg',
98
            $this->generatePath($media),
99
            $media->getId(),
100
            $format
101
        );
102
    }
103
104
    public function buildEditForm(FormMapper $formMapper): void
105
    {
106
        $formMapper->add('name');
107
        $formMapper->add('enabled', null, ['required' => false]);
108
        $formMapper->add('authorName');
109
        $formMapper->add('cdnIsFlushable');
110
        $formMapper->add('description');
111
        $formMapper->add('copyright');
112
        $formMapper->add('binaryContent', TextType::class, ['required' => false]);
113
    }
114
115
    public function buildCreateForm(FormMapper $formMapper): void
116
    {
117
        $formMapper->add('binaryContent', TextType::class, [
118
            'constraints' => [
119
                new NotBlank(),
120
                new NotNull(),
121
            ],
122
        ]);
123
    }
124
125
    public function buildMediaType(FormBuilder $formBuilder): void
126
    {
127
        $formBuilder->add('binaryContent', TextType::class, [
128
            'label' => 'widget_label_binary_content',
129
        ]);
130
    }
131
132
    public function postUpdate(MediaInterface $media): void
133
    {
134
        $this->postPersist($media);
135
    }
136
137
    public function postPersist(MediaInterface $media): void
138
    {
139
        if (!$media->getBinaryContent()) {
140
            return;
141
        }
142
143
        $this->generateThumbnails($media);
144
145
        $media->resetBinaryContent();
146
    }
147
148
    public function postRemove(MediaInterface $media): void
149
    {
150
    }
151
152
    // NEXT_MAJOR: Uncomment this method
153
    /*
154
     * Get provider reference url.
155
     *
156
     * @param MediaInterface $media
157
     *
158
     * @return string
159
     */
160
    // abstract public function getReferenceUrl(MediaInterface $media);
161
162
    /**
163
     * @param string $url
164
     *
165
     * @throws \RuntimeException
166
     *
167
     * @return mixed
168
     */
169
    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...
170
    {
171
        try {
172
            $response = $this->browser->get($url);
173
        } catch (\RuntimeException $e) {
174
            throw new \RuntimeException('Unable to retrieve the video information for :'.$url, $e->getCode(), $e);
175
        }
176
177
        $metadata = json_decode($response->getContent(), true);
178
179
        if (!$metadata) {
180
            throw new \RuntimeException('Unable to decode the video information for :'.$url);
181
        }
182
183
        return $metadata;
184
    }
185
186
    /**
187
     * @param string $format
188
     * @param array  $options
189
     *
190
     * @return Box
191
     */
192
    protected function getBoxHelperProperties(MediaInterface $media, $format, $options = [])
193
    {
194
        if (MediaProviderInterface::FORMAT_REFERENCE === $format) {
195
            return $media->getBox();
196
        }
197
198
        if (isset($options['width']) || isset($options['height'])) {
199
            $settings = [
200
                'width' => $options['width'] ?? null,
201
                'height' => $options['height'] ?? null,
202
            ];
203
        } else {
204
            $settings = $this->getFormat($format);
205
        }
206
207
        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 204 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...
208
    }
209
}
210