Completed
Pull Request — 2.x (#161)
by Christian
05:03
created

TwitterEmbedTweetBlockService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 4
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\SeoBundle\Block\Social;
13
14
use GuzzleHttp\Exception\GuzzleException;
15
use Http\Client\HttpClient;
16
use Http\Message\MessageFactory;
17
use Sonata\AdminBundle\Form\FormMapper;
18
use Sonata\BlockBundle\Block\BlockContextInterface;
19
use Sonata\BlockBundle\Model\BlockInterface;
20
use Sonata\CoreBundle\Form\Type\ImmutableArrayType;
21
use Sonata\CoreBundle\Model\Metadata;
22
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
23
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
24
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
25
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
26
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
27
use Symfony\Component\Form\Extension\Core\Type\TextType;
28
use Symfony\Component\HttpFoundation\Response;
29
use Symfony\Component\OptionsResolver\OptionsResolver;
30
31
/**
32
 * This block service allows to embed a tweet by requesting the Twitter API.
33
 *
34
 * @see https://dev.twitter.com/docs/api/1/get/statuses/oembed
35
 *
36
 * @author Hugo Briand <[email protected]>
37
 */
38
class TwitterEmbedTweetBlockService extends BaseTwitterButtonBlockService
39
{
40
    const TWITTER_OEMBED_URI = 'https://api.twitter.com/1/statuses/oembed.json';
41
    const TWEET_URL_PATTERN = '%^(https://)(www.)?(twitter.com/)(.*)(/status)(es)?(/)([0-9]*)$%i';
42
    const TWEET_ID_PATTERN = '%^([0-9]*)$%';
43
44
    /**
45
     * @var HttpClient
46
     */
47
    private $httpClient;
48
49
    /**
50
     * @var MessageFactory
51
     */
52
    private $messageFactory;
53
54
    /**
55
     * @param string          $name
56
     * @param EngineInterface $templating
57
     * @param HttpClient      $httpClient
58
     * @param MessageFactory  $messageFactory
59
     */
60
    public function __construct($name, EngineInterface $templating, HttpClient $httpClient = null, MessageFactory $messageFactory = null)
61
    {
62
        parent::__construct($name, $templating);
63
64
        $this->httpClient = $httpClient;
65
        $this->messageFactory = $messageFactory;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function execute(BlockContextInterface $blockContext, Response $response = null)
72
    {
73
        return $this->renderResponse($blockContext->getTemplate(), [
74
            'block' => $blockContext->getBlock(),
75
            'tweet' => $this->loadTweet($blockContext),
76
        ], $response);
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function configureSettings(OptionsResolver $resolver)
83
    {
84
        $resolver->setDefaults([
85
            'template' => '@SonataSeo/Block/block_twitter_embed.html.twig',
86
            'tweet' => '',
87
            'maxwidth' => null,
88
            'hide_media' => false,
89
            'hide_thread' => false,
90
            'omit_script' => false,
91
            'align' => 'none',
92
            'related' => null,
93
            'lang' => null,
94
        ]);
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function buildEditForm(FormMapper $form, BlockInterface $block)
101
    {
102
        $form->add('settings', ImmutableArrayType::class, [
103
            'keys' => [
104
                ['tweet', TextareaType::class, [
105
                    'required' => true,
106
                    'label' => 'form.label_tweet',
107
                    'sonata_help' => 'form.help_tweet',
108
                ]],
109
                ['maxwidth', IntegerType::class, [
110
                    'required' => false,
111
                    'label' => 'form.label_maxwidth',
112
                    'sonata_help' => 'form.help_maxwidth',
113
                ]],
114
                ['hide_media', CheckboxType::class, [
115
                    'required' => false,
116
                    'label' => 'form.label_hide_media',
117
                    'sonata_help' => 'form.help_hide_media',
118
                ]],
119
                ['hide_thread', CheckboxType::class, [
120
                    'required' => false,
121
                    'label' => 'form.label_hide_thread',
122
                    'sonata_help' => 'form.help_hide_thread',
123
                ]],
124
                ['omit_script', CheckboxType::class, [
125
                    'required' => false,
126
                    'label' => 'form.label_omit_script',
127
                    'sonata_help' => 'form.help_omit_script',
128
                ]],
129
                ['align', ChoiceType::class, [
130
                    'required' => false,
131
                    'choices' => [
132
                        'left' => 'form.label_align_left',
133
                        'right' => 'form.label_align_right',
134
                        'center' => 'form.label_align_center',
135
                        'none' => 'form.label_align_none',
136
                    ],
137
                    'label' => 'form.label_align',
138
                ]],
139
                ['related', TextType::class, [
140
                    'required' => false,
141
                    'label' => 'form.label_related',
142
                    'sonata_help' => 'form.help_related',
143
                ]],
144
                ['lang', ChoiceType::class, [
145
                    'required' => true,
146
                    'choices' => $this->languageList,
147
                    'label' => 'form.label_lang',
148
                ]],
149
            ],
150
            'translation_domain' => 'SonataSeoBundle',
151
        ]);
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157
    public function getBlockMetadata($code = null)
158
    {
159
        return new Metadata($this->getName(), (null !== $code ? $code : $this->getName()), false, 'SonataSeoBundle', [
160
            'class' => 'fa fa-twitter',
161
        ]);
162
    }
163
164
    /**
165
     * Returns supported API parameters from settings.
166
     *
167
     * @return array
168
     */
169
    protected function getSupportedApiParams()
170
    {
171
        return [
172
            'maxwidth',
173
            'hide_media',
174
            'hide_thread',
175
            'omit_script',
176
            'align',
177
            'related',
178
            'lang',
179
            'url',
180
            'id',
181
        ];
182
    }
183
184
    /**
185
     * Builds the API query URI based on $settings.
186
     *
187
     * @param bool  $uriMatched
188
     * @param array $settings
189
     *
190
     * @return string
191
     */
192
    protected function buildUri($uriMatched, array $settings)
193
    {
194
        $apiParams = $settings;
195
        $supportedParams = $this->getSupportedApiParams();
196
197
        if ($uriMatched) {
198
            // We matched the uri
199
            $apiParams['url'] = $settings['tweet'];
200
        } else {
201
            $apiParams['id'] = $settings['tweet'];
202
        }
203
204
        unset($apiParams['tweet']);
205
206
        $parameters = [];
207
        foreach ($apiParams as $key => $value) {
208
            if ($value && in_array($key, $supportedParams)) {
209
                $parameters[] = $key.'='.$value;
210
            }
211
        }
212
213
        return sprintf('%s?%s', self::TWITTER_OEMBED_URI, implode('&', $parameters));
214
    }
215
216
    /**
217
     * Loads twitter tweet.
218
     *
219
     * @param BlockContextInterface $blockContext
220
     *
221
     * @return string|null
222
     */
223
    private function loadTweet(BlockContextInterface $blockContext)
224
    {
225
        $uriMatched = preg_match(self::TWEET_URL_PATTERN, $blockContext->getSetting('tweet'));
226
227
        if (!$uriMatched || !preg_match(self::TWEET_ID_PATTERN, $blockContext->getSetting('tweet'))) {
228
            return null;
229
        }
230
231
        if (null !== $this->httpClient && null !== $this->messageFactory) {
232
            $response = $this->httpClient->sendRequest(
233
                $this->messageFactory->createRequest('GET', $this->buildUri($uriMatched, $blockContext->getSettings()))
0 ignored issues
show
Documentation introduced by
$uriMatched is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
234
            );
235
236
            $apiTweet = json_decode($response->getBody(), true);
237
238
            return $apiTweet['html'];
239
        }
240
241
        // NEXT_MAJOR: Remove the old guzzle implementation
242
243
        // We matched an URL or an ID, we'll need to ask the API
244
        if (false === class_exists('GuzzleHttp\Client')) {
245
            throw new \RuntimeException(
246
                'The guzzle http client library is required to call the Twitter API. Make sure to add guzzle/guzzle to your composer.json.'
247
            );
248
        }
249
250
        @trigger_error('The direct Guzzle implementation is deprecated since 2.x and will be removed 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...
251
252
        // TODO cache API result
253
        $client = new \GuzzleHttp\Client();
254
        $client->setConfig(['curl.options' => [CURLOPT_CONNECTTIMEOUT_MS => 1000]]);
255
256
        try {
257
            $request = $client->get($this->buildUri($uriMatched, $blockContext->getSettings()));
0 ignored issues
show
Documentation introduced by
$uriMatched is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
258
            $apiTweet = json_decode($request->send()->getBody(true), true);
0 ignored issues
show
Bug introduced by
The method send() does not seem to exist on object<Psr\Http\Message\ResponseInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
259
260
            return $apiTweet['html'];
261
        } catch (GuzzleException $e) {
262
            // log error
263
            return null;
264
        }
265
        // END NEXT_MAJOR
266
    }
267
}
268