Completed
Push — master ( 5ea189...465cbc )
by
unknown
06:10
created

AbstractOembedProvider::getUrlData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 2
1
<?php
2
3
namespace MediaMonks\SonataMediaBundle\Provider;
4
5
use MediaMonks\SonataMediaBundle\Model\AbstractMedia;
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
abstract class AbstractOembedProvider extends AbstractProvider implements OembedProviderInterface
12
{
13
    /**
14
     * @var array
15
     */
16
    protected $oembedDataCache;
17
18
    /**
19
     * @param AbstractMedia $media
20
     * @param bool $providerReferenceUpdated
21
     * @throws \Exception
22
     */
23
    public function update(AbstractMedia $media, $providerReferenceUpdated)
24
    {
25
        if ($providerReferenceUpdated) {
26
            $media->setProviderReference($this->parseProviderReference($media->getProviderReference()));
27
28
            $data = $this->getOembedDataCache($media->getProviderReference());
29
30
            $media->setProviderMetaData($data);
31
32
            if (empty($media->getTitle()) && isset($data['title'])) {
33
                $media->setTitle($data['title']);
34
            }
35
            if (empty($media->getDescription()) && isset($data['description'])) {
36
                $media->setDescription($data['description']);
37
            }
38
            if (empty($media->getAuthorName()) && isset($data['author_name'])) {
39
                $media->setAuthorName($data['author_name']);
40
            }
41
            if (empty($media->getImage())) {
42
                $this->refreshImage($media);
43
            }
44
        }
45
46
        parent::update($media, $providerReferenceUpdated);
47
    }
48
49
    /**
50
     * @param FormMapper $formMapper
51
     */
52
    public function buildProviderCreateForm(FormMapper $formMapper)
53
    {
54
        $formMapper->add(
55
            'providerReference',
56
            TextType::class,
57
            ['label' => $this->getReferenceLabel()]
58
        );
59
    }
60
61
    /**
62
     * @param FormMapper $formMapper
63
     */
64
    public function buildProviderEditFormBefore(FormMapper $formMapper)
65
    {
66
        $formMapper->add(
67
            'providerReference',
68
            TextType::class,
69
            ['label' => $this->getReferenceLabel()]
70
        );
71
    }
72
73
    /**
74
     * @param ErrorElement $errorElement
75
     * @param AbstractMedia $media
76
     */
77
    public function validate(ErrorElement $errorElement, AbstractMedia $media)
78
    {
79
        try {
80
            $this->getOembedDataCache($this->parseProviderReference($media->getProviderReference()));
81
        }
82
        catch (\Exception $e) {
83
            $errorElement->with('providerReference')->addViolation($e->getMessage());
84
        }
85
    }
86
87
    /**
88
     * @param \MediaMonks\SonataMediaBundle\Model\AbstractMedia $media
89
     */
90
    public function refreshImage(AbstractMedia $media)
91
    {
92
        $filename = sprintf('%s_%d.%s', sha1($media->getProviderReference()), time(), 'jpg');
93
        $thumbnailUrl = $this->getImageUrl($media->getProviderReference());
94
95
        $this->getFilesystem()->write($filename, $this->getUrlData($thumbnailUrl));
96
97
        $media->setImage($filename);
98
    }
99
100
    /**
101
     * @param string $id
102
     * @return string
103
     */
104
    public function getImageUrl($id)
105
    {
106
        return $this->getOembedDataCache($id)['thumbnail_url'];
107
    }
108
109
    /**
110
     * @param $id
111
     * @return mixed
112
     * @throws \Exception
113
     */
114
    protected function getOembedDataCache($id)
115
    {
116
        if (empty($this->oembedDataCache[$id])) {
117
118
            $this->disableErrorHandler();
119
            $data = json_decode($this->getUrlData($this->getOembedUrl($id)), true);
120
            $this->restoreErrorHandler();
121
122
            if (empty($data['title'])) {
123
                throw new \Exception($this->getTranslator()->trans('error.provider_reference', [
124
                    '%provider%' => $this->getName(),
125
                    '%reference%' => $id
126
                ]));
127
            }
128
129
            $this->oembedDataCache[$id] = $data;
130
        }
131
132
        return $this->oembedDataCache[$id];
133
    }
134
135
    /**
136
     * @return string
137
     */
138
    public function getReferenceLabel()
139
    {
140
        return sprintf('form.%s.reference', $this->getName());
141
    }
142
143
    /**
144
     * @return bool
145
     */
146
    public function supportsDownload()
147
    {
148
        return false;
149
    }
150
151
    /**
152
     * @return bool
153
     */
154
    public function supportsEmbed()
155
    {
156
        return true;
157
    }
158
159
    /**
160
     * @return bool
161
     */
162
    public function supportsImage()
163
    {
164
        return true;
165
    }
166
167
    /**
168
     * @param $url
169
     * @return mixed
170
     */
171
    protected function getUrlData($url)
172
    {
173
        $ch = curl_init();
174
175
        curl_setopt($ch, CURLOPT_HEADER, 0);
176
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
177
        curl_setopt($ch, CURLOPT_URL, $url);
178
179
        $data = curl_exec($ch);
180
        curl_close($ch);
181
182
        return $data;
183
    }
184
185
    /**
186
     * @param string $url
187
     * @return bool
188
     */
189
    protected function urlExists($url)
190
    {
191
        $ch = curl_init();
192
        curl_setopt($ch, CURLOPT_URL, $url);
193
        curl_setopt($ch, CURLOPT_NOBODY, true);
194
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
195
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
196
        curl_setopt($ch, CURLOPT_HEADER, false);
197
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
198
199
        curl_exec($ch);
200
        $info = curl_getinfo($ch);
201
        curl_close($ch);
202
203
        return $info === Response::HTTP_OK;
204
    }
205
}
206