Completed
Push — master ( c0c854...e06edc )
by
unknown
05:03
created

AbstractOembedProvider::urlExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 12
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 $oembedData;
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->getOembedData($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->getOembedData($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(
96
            $filename,
97
            file_get_contents($thumbnailUrl)
98
        );
99
        $media->setImage($filename);
100
    }
101
102
    /**
103
     * @param string $id
104
     * @return string
105
     */
106
    public function getImageUrl($id)
107
    {
108
        return $this->getOembedData($id)['thumbnail_url'];
109
    }
110
111
    /**
112
     * @param $id
113
     * @return mixed
114
     * @throws \Exception
115
     */
116
    protected function getOembedData($id)
117
    {
118
        if (empty($this->oembedData)) {
119
120
            $this->disableErrorHandler();
121
            $data = json_decode($this->getUrlData($this->getOembedUrl($id)), true);
122
            $this->restoreErrorHandler();
123
124
            if (empty($data['title'])) {
125
                throw new \Exception($this->getTranslator()->trans('error.provider_reference', [
126
                    '%provider%' => $this->getName(),
127
                    '%reference%' => $id
128
                ]));
129
            }
130
131
            $this->oembedData = $data;
0 ignored issues
show
Documentation Bug introduced by
It seems like $data of type * is incompatible with the declared type array of property $oembedData.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
132
        }
133
134
        return $this->oembedData;
135
    }
136
137
    /**
138
     * @return string
139
     */
140
    public function getReferenceLabel()
141
    {
142
        return sprintf('form.%s.reference', $this->getName());
143
    }
144
145
    /**
146
     * @return bool
147
     */
148
    public function supportsDownload()
149
    {
150
        return false;
151
    }
152
153
    /**
154
     * @return bool
155
     */
156
    public function supportsEmbed()
157
    {
158
        return true;
159
    }
160
161
    /**
162
     * @return bool
163
     */
164
    public function supportsImage()
165
    {
166
        return true;
167
    }
168
169
    /**
170
     * @param $url
171
     * @return mixed
172
     */
173
    protected function getUrlData($url)
174
    {
175
        $ch = curl_init();
176
177
        curl_setopt($ch, CURLOPT_HEADER, 0);
178
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
179
        curl_setopt($ch, CURLOPT_URL, $url);
180
181
        $data = curl_exec($ch);
182
        curl_close($ch);
183
184
        return $data;
185
    }
186
187
    /**
188
     * @param string $url
189
     * @return bool
190
     */
191
    protected function urlExists($url)
192
    {
193
        $ch = curl_init();
194
        curl_setopt($ch, CURLOPT_URL, $url);
195
        curl_setopt($ch, CURLOPT_NOBODY, true);
196
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
197
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
198
        curl_setopt($ch, CURLOPT_HEADER, false);
199
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
200
201
        curl_exec($ch);
202
        $info = curl_getinfo($ch);
203
        curl_close($ch);
204
205
        return $info === Response::HTTP_OK;
206
    }
207
}
208