Completed
Push — master ( 1d38e8...81c238 )
by
unknown
04:02
created

YouTubeProvider::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
crap 6
1
<?php
2
3
namespace MediaMonks\SonataMediaBundle\Provider;
4
5
use MediaMonks\SonataMediaBundle\Entity\Media;
6
use Sonata\AdminBundle\Form\FormMapper;
7
use Sonata\CoreBundle\Validator\ErrorElement;
8
use Symfony\Component\Form\Extension\Core\Type\TextType;
9
use Symfony\Component\HttpFoundation\Response;
10
11
class YouTubeProvider extends AbstractProvider implements ProviderInterface
12
{
13
    const URL_OEMBED = 'http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=%s&format=json';
14
    const URL_IMAGE_MAX_RES = 'https://i.ytimg.com/vi/%s/maxresdefault.jpg';
15
    const URL_IMAGE_HQ = 'https://i.ytimg.com/vi/%s/hqdefault.jpg';
16
17
    /**
18
     * @param FormMapper $formMapper
19
     */
20
    public function buildProviderCreateForm(FormMapper $formMapper)
21
    {
22
        $formMapper->add('providerReference', TextType::class, ['label' => 'YouTube ID']);
23
    }
24
25
    /**
26
     * @param FormMapper $formMapper
27
     */
28
    public function buildProviderEditForm(FormMapper $formMapper)
29
    {
30
        $formMapper->add('providerReference', TextType::class, ['label' => 'YouTube ID']);
31
    }
32
33
    /**
34
     * @param ErrorElement $errorElement
35
     * @param Media $media
36
     */
37
    public function validate(ErrorElement $errorElement, Media $media)
38
    {
39
        try {
40
            $this->getDataByYouTubeId($this->parseYouTubeId($media->getProviderReference()));
41
        }
42
        catch (\Exception $e) {
43
            $errorElement->with('providerReference')->addViolation($e->getMessage());
44
        }
45
    }
46
47
    /**
48
     * @param Media $media
49
     * @param bool $providerReferenceUpdated
50
     */
51
    public function update(Media $media, $providerReferenceUpdated)
52
    {
53
        if ($providerReferenceUpdated) {
54
            $media->setProviderReference($this->parseYouTubeId($media->getProviderReference()));
55
56
            if ($media->getProviderReference()) {
57
                $data = $this->getDataByYouTubeId($media->getProviderReference());
58
59
                if (empty($media->getTitle())) {
60
                    $media->setTitle($data['title']);
61
                }
62
                if (empty($media->getAuthorName())) {
63
                    $media->setAuthorName($data['author_name']);
64
                }
65
66
                if (empty($media->getImage())) {
67
                    $this->refreshThumbnail($media);
68
                }
69
            }
70
        }
71
72
        parent::update($media, $providerReferenceUpdated);
73
    }
74
75
    /**
76
     * @param Media $media
77
     */
78
    public function refreshThumbnail(Media $media)
79
    {
80
        $filename = sprintf('%s_%d.%s', sha1($media->getProviderReference()), time(), 'jpg');
81
        $thumbnailUrl = $this->getThumbnailUrlByYouTubeId($media->getProviderReference());
82
        $this->getFilesystem()->write(
83
            $filename,
84
            file_get_contents($thumbnailUrl)
85
        );
86
        $media->setImage($filename);
87
    }
88
89
    /**
90
     * @param string $id
91
     * @return string
92
     */
93
    public function getThumbnailUrlByYouTubeId($id)
94
    {
95
        // try to get max res image (only available for 720P videos)
96
        $urlMaxRes = sprintf(self::URL_IMAGE_MAX_RES, $id);
97
        stream_context_set_default(['http' => ['method' => 'HEAD']]);
98
        $headers = get_headers($urlMaxRes);
99
        stream_context_set_default(['http' => ['method' => 'GET']]);
100
        if ((int)substr($headers[0], 9, 3) === Response::HTTP_OK) {
101
            return $urlMaxRes;
102
        }
103
104
        return sprintf(self::URL_IMAGE_HQ, $id); // this one always exists
105
    }
106
107
    /**
108
     * @param $id
109
     * @return mixed
110
     * @throws \Exception
111
     */
112 View Code Duplication
    protected function getDataByYouTubeId($id)
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...
113
    {
114
        $this->disableErrorHandler();
115
        $data = json_decode(file_get_contents(sprintf(self::URL_OEMBED, $id)), true);
116
        $this->restoreErrorHandler();
117
118
        if (empty($data['title'])) {
119
            throw new \Exception(sprintf('YouTube ID "%s" seems to be incorrect', $id));
120
        }
121
122
        return $data;
123
    }
124
125
    /**
126
     * @param $value
127
     * @return string
128
     * @throws \Exception
129
     */
130
    protected function parseYouTubeId($value)
131
    {
132
        if (strpos($value, 'youtube.com')) {
133
            $url = parse_url($value);
134
            if (empty($url['query'])) {
135
                throw new \Exception('The supplied URL does not look like a Youtube URL');
136
            }
137
            parse_str($url['query'], $params);
138
            if (empty($params['v'])) {
139
                throw new \Exception('The supplied URL does not look like a Youtube URL');
140
            }
141
142
            return $params['v'];
143
        }
144
145
        if (strpos($value, 'youtu.be')) {
146
            $url = parse_url($value);
147
            $id = substr($url['path'], 1);
148
149
            return $id;
150
        }
151
152
        return $value;
153
    }
154
155
    /**
156
     * @return string
157
     */
158
    public function getIcon()
159
    {
160
        return 'youtube-play';
161
    }
162
163
    /**
164
     * @return string
165
     */
166
    public function getTitle()
167
    {
168
        return 'YouTube Video';
169
    }
170
171
    public function getType()
172
    {
173
        return 'youtube';
174
    }
175
176
    /**
177
     * @return string
178
     */
179
    public function getEmbedTemplate()
180
    {
181
        return 'MediaMonksSonataMediaBundle:Provider:youtube_embed.html.twig';
182
    }
183
184
    /**
185
     * @return bool
186
     */
187
    public function supportsDownload()
188
    {
189
        return false;
190
    }
191
192
    /**
193
     * @return bool
194
     */
195
    public function supportsEmbed()
196
    {
197
        return true;
198
    }
199
200
    /**
201
     * @return bool
202
     */
203
    public function supportsImage()
204
    {
205
        return true;
206
    }
207
}
208