TwitterEmbedTweetBlockService::validate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
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\SeoBundle\Block\Social;
15
16
use GuzzleHttp\Exception\GuzzleException;
17
use Psr\Http\Client\ClientExceptionInterface;
18
use Psr\Http\Client\ClientInterface;
19
use Psr\Http\Message\RequestFactoryInterface;
20
use Sonata\BlockBundle\Block\BlockContextInterface;
21
use Sonata\BlockBundle\Block\Service\EditableBlockService;
22
use Sonata\BlockBundle\Form\Mapper\FormMapper;
23
use Sonata\BlockBundle\Meta\Metadata;
24
use Sonata\BlockBundle\Meta\MetadataInterface;
25
use Sonata\BlockBundle\Model\BlockInterface;
26
use Sonata\Form\Type\ImmutableArrayType;
27
use Sonata\Form\Validator\ErrorElement;
28
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
29
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
30
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
31
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
32
use Symfony\Component\Form\Extension\Core\Type\TextType;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\OptionsResolver\OptionsResolver;
35
use Twig\Environment;
36
37
/**
38
 * This block service allows to embed a tweet by requesting the Twitter API.
39
 *
40
 * @see https://dev.twitter.com/docs/api/1/get/statuses/oembed
41
 *
42
 * @author Hugo Briand <[email protected]>
43
 */
44
class TwitterEmbedTweetBlockService extends BaseTwitterButtonBlockService implements EditableBlockService
45
{
46
    public const TWITTER_OEMBED_URI = 'https://api.twitter.com/1/statuses/oembed.json';
47
    private const TWEET_URL_PATTERN = '%^(https://)(www.)?(twitter.com/)(.*)(/status)(es)?(/)([0-9]*)$%i';
48
    private const TWEET_ID_PATTERN = '%^([0-9]*)$%';
49
50
    /**
51
     * @var ClientInterface|null
52
     */
53
    private $httpClient;
54
55
    /**
56
     * @var RequestFactoryInterface|null
57
     */
58
    private $messageFactory;
59
60
    public function __construct(
61
        Environment $twig,
62
        ?ClientInterface $httpClient = null,
63
        ?RequestFactoryInterface $messageFactory = null
64
    ) {
65
        parent::__construct($twig);
66
67
        $this->httpClient = $httpClient;
68
        $this->messageFactory = $messageFactory;
69
    }
70
71
    public function execute(BlockContextInterface $blockContext, ?Response $response = null): Response
72
    {
73
        return $this->renderResponse($blockContext->getTemplate(), [
74
            'block' => $blockContext->getBlock(),
75
            'tweet' => $this->loadTweet($blockContext),
76
        ], $response);
77
    }
78
79
    public function configureSettings(OptionsResolver $resolver): void
80
    {
81
        $resolver->setDefaults([
82
            'template' => '@SonataSeo/Block/block_twitter_embed.html.twig',
83
            'tweet' => '',
84
            'maxwidth' => null,
85
            'hide_media' => false,
86
            'hide_thread' => false,
87
            'omit_script' => false,
88
            'align' => 'none',
89
            'related' => null,
90
            'lang' => null,
91
        ]);
92
    }
93
94
    public function configureCreateForm(FormMapper $formMapper, BlockInterface $block): void
95
    {
96
        $this->configureEditForm($formMapper, $block);
97
    }
98
99
    public function configureEditForm(FormMapper $formMapper, BlockInterface $block): void
100
    {
101
        $formMapper->add('settings', ImmutableArrayType::class, [
102
            'keys' => [
103
                ['tweet', TextareaType::class, [
104
                    'required' => true,
105
                    'label' => 'form.label_tweet',
106
                    'sonata_help' => 'form.help_tweet',
107
                ]],
108
                ['maxwidth', IntegerType::class, [
109
                    'required' => false,
110
                    'label' => 'form.label_maxwidth',
111
                    'sonata_help' => 'form.help_maxwidth',
112
                ]],
113
                ['hide_media', CheckboxType::class, [
114
                    'required' => false,
115
                    'label' => 'form.label_hide_media',
116
                    'sonata_help' => 'form.help_hide_media',
117
                ]],
118
                ['hide_thread', CheckboxType::class, [
119
                    'required' => false,
120
                    'label' => 'form.label_hide_thread',
121
                    'sonata_help' => 'form.help_hide_thread',
122
                ]],
123
                ['omit_script', CheckboxType::class, [
124
                    'required' => false,
125
                    'label' => 'form.label_omit_script',
126
                    'sonata_help' => 'form.help_omit_script',
127
                ]],
128
                ['align', ChoiceType::class, [
129
                    'required' => false,
130
                    'choices' => [
131
                        'left' => 'form.label_align_left',
132
                        'right' => 'form.label_align_right',
133
                        'center' => 'form.label_align_center',
134
                        'none' => 'form.label_align_none',
135
                    ],
136
                    'label' => 'form.label_align',
137
                ]],
138
                ['related', TextType::class, [
139
                    'required' => false,
140
                    'label' => 'form.label_related',
141
                    'sonata_help' => 'form.help_related',
142
                ]],
143
                ['lang', ChoiceType::class, [
144
                    'required' => true,
145
                    'choices' => $this->languageList,
146
                    'label' => 'form.label_lang',
147
                ]],
148
            ],
149
            'translation_domain' => 'SonataSeoBundle',
150
        ]);
151
    }
152
153
    public function validate(ErrorElement $errorElement, BlockInterface $block): void
154
    {
155
    }
156
157
    public function getMetadata(): MetadataInterface
158
    {
159
        return new Metadata('sonata.seo.block.twitter.embed', null, null, '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
     *
189
     * @return string
190
     */
191
    protected function buildUri($uriMatched, array $settings)
192
    {
193
        $apiParams = $settings;
194
        $supportedParams = $this->getSupportedApiParams();
195
196
        if ($uriMatched) {
197
            // We matched the uri
198
            $apiParams['url'] = $settings['tweet'];
199
        } else {
200
            $apiParams['id'] = $settings['tweet'];
201
        }
202
203
        unset($apiParams['tweet']);
204
205
        $parameters = [];
206
        foreach ($apiParams as $key => $value) {
207
            if ($value && \in_array($key, $supportedParams, true)) {
208
                $parameters[] = $key.'='.$value;
209
            }
210
        }
211
212
        return sprintf('%s?%s', self::TWITTER_OEMBED_URI, implode('&', $parameters));
213
    }
214
215
    /**
216
     * Loads twitter tweet.
217
     */
218
    private function loadTweet(BlockContextInterface $blockContext): ?string
219
    {
220
        $uriMatched = preg_match(self::TWEET_URL_PATTERN, $blockContext->getSetting('tweet'));
221
222
        if (!$uriMatched || !preg_match(self::TWEET_ID_PATTERN, $blockContext->getSetting('tweet'))) {
223
            return null;
224
        }
225
226
        if (null !== $this->httpClient && null !== $this->messageFactory) {
227
            try {
228
                $response = $this->httpClient->sendRequest(
229
                    $this->messageFactory->createRequest(
230
                        'GET',
231
                        $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...
232
                    )
233
                );
234
            } catch (ClientExceptionInterface $e) {
235
                // log error
236
                return null;
237
            }
238
239
            $apiTweet = json_decode($response->getBody(), true);
240
241
            return $apiTweet['html'];
242
        }
243
244
        // NEXT_MAJOR: Remove the old guzzle implementation
245
246
        // We matched an URL or an ID, we'll need to ask the API
247
        if (false === class_exists('GuzzleHttp\Client')) {
248
            throw new \RuntimeException(
249
                'The guzzle http client library is required to call the Twitter API.'.
250
                'Make sure to add psr/http-client or guzzlehttp/guzzle to your composer.json.'
251
            );
252
        }
253
254
        @trigger_error(
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...
255
            'The direct Guzzle implementation is deprecated since 2.10 and will be removed with the next major release.',
256
            E_USER_DEPRECATED
257
        );
258
259
        // TODO cache API result
260
        $client = new \GuzzleHttp\Client();
261
        $client->setConfig(['curl.options' => [CURLOPT_CONNECTTIMEOUT_MS => 1000]]);
262
263
        try {
264
            $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...
265
            $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...
266
267
            return $apiTweet['html'];
268
        } catch (GuzzleException $e) {
269
            // log error
270
            return null;
271
        }
272
        // END NEXT_MAJOR
273
    }
274
}
275