Completed
Pull Request — 2.x (#161)
by Christian
04:25
created

TwitterEmbedTweetBlockService::loadTweet()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 52
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 6.8493
c 0
b 0
f 0
cc 8
eloc 26
nc 8
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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