Completed
Pull Request — 2.x (#161)
by Christian
08:27
created

TwitterEmbedTweetBlockService::loadTweet()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 7.7155
c 0
b 0
f 0
cc 8
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
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 Http\Client\Exception;
18
use Http\Client\HttpClient;
19
use Http\Message\MessageFactory;
20
use Sonata\AdminBundle\Form\FormMapper;
21
use Sonata\BlockBundle\Block\BlockContextInterface;
22
use Sonata\BlockBundle\Model\BlockInterface;
23
use Sonata\CoreBundle\Form\Type\ImmutableArrayType;
24
use Sonata\CoreBundle\Model\Metadata;
25
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
26
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
27
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
28
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
29
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
30
use Symfony\Component\Form\Extension\Core\Type\TextType;
31
use Symfony\Component\HttpFoundation\Response;
32
use Symfony\Component\OptionsResolver\OptionsResolver;
33
34
/**
35
 * This block service allows to embed a tweet by requesting the Twitter API.
36
 *
37
 * @see https://dev.twitter.com/docs/api/1/get/statuses/oembed
38
 *
39
 * @author Hugo Briand <[email protected]>
40
 */
41
class TwitterEmbedTweetBlockService extends BaseTwitterButtonBlockService
42
{
43
    public const TWITTER_OEMBED_URI = 'https://api.twitter.com/1/statuses/oembed.json';
44
    public const TWEET_URL_PATTERN = '%^(https://)(www.)?(twitter.com/)(.*)(/status)(es)?(/)([0-9]*)$%i';
45
    public const TWEET_ID_PATTERN = '%^([0-9]*)$%';
46
47
    /**
48
     * @var HttpClient|null
49
     */
50
    private $httpClient;
51
52
    /**
53
     * @var MessageFactory|null
54
     */
55
    private $messageFactory;
56
57
    /**
58
     * @param string          $name
59
     * @param EngineInterface $templating
60
     * @param HttpClient      $httpClient
61
     * @param MessageFactory  $messageFactory
62
     */
63
    public function __construct($name, EngineInterface $templating, HttpClient $httpClient = null, MessageFactory $messageFactory = null)
64
    {
65
        parent::__construct($name, $templating);
66
67
        $this->httpClient = $httpClient;
68
        $this->messageFactory = $messageFactory;
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function execute(BlockContextInterface $blockContext, Response $response = null)
75
    {
76
        return $this->renderResponse($blockContext->getTemplate(), [
77
            'block' => $blockContext->getBlock(),
78
            'tweet' => $this->loadTweet($blockContext),
79
        ], $response);
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function configureSettings(OptionsResolver $resolver)
86
    {
87
        $resolver->setDefaults([
88
            'template' => '@SonataSeo/Block/block_twitter_embed.html.twig',
89
            'tweet' => '',
90
            'maxwidth' => null,
91
            'hide_media' => false,
92
            'hide_thread' => false,
93
            'omit_script' => false,
94
            'align' => 'none',
95
            'related' => null,
96
            'lang' => null,
97
        ]);
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function buildEditForm(FormMapper $form, BlockInterface $block)
104
    {
105
        $form->add('settings', ImmutableArrayType::class, [
106
            'keys' => [
107
                ['tweet', TextareaType::class, [
108
                    'required' => true,
109
                    'label' => 'form.label_tweet',
110
                    'sonata_help' => 'form.help_tweet',
111
                ]],
112
                ['maxwidth', IntegerType::class, [
113
                    'required' => false,
114
                    'label' => 'form.label_maxwidth',
115
                    'sonata_help' => 'form.help_maxwidth',
116
                ]],
117
                ['hide_media', CheckboxType::class, [
118
                    'required' => false,
119
                    'label' => 'form.label_hide_media',
120
                    'sonata_help' => 'form.help_hide_media',
121
                ]],
122
                ['hide_thread', CheckboxType::class, [
123
                    'required' => false,
124
                    'label' => 'form.label_hide_thread',
125
                    'sonata_help' => 'form.help_hide_thread',
126
                ]],
127
                ['omit_script', CheckboxType::class, [
128
                    'required' => false,
129
                    'label' => 'form.label_omit_script',
130
                    'sonata_help' => 'form.help_omit_script',
131
                ]],
132
                ['align', ChoiceType::class, [
133
                    'required' => false,
134
                    'choices' => [
135
                        'left' => 'form.label_align_left',
136
                        'right' => 'form.label_align_right',
137
                        'center' => 'form.label_align_center',
138
                        'none' => 'form.label_align_none',
139
                    ],
140
                    'label' => 'form.label_align',
141
                ]],
142
                ['related', TextType::class, [
143
                    'required' => false,
144
                    'label' => 'form.label_related',
145
                    'sonata_help' => 'form.help_related',
146
                ]],
147
                ['lang', ChoiceType::class, [
148
                    'required' => true,
149
                    'choices' => $this->languageList,
150
                    'label' => 'form.label_lang',
151
                ]],
152
            ],
153
            'translation_domain' => 'SonataSeoBundle',
154
        ]);
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function getBlockMetadata($code = null)
161
    {
162
        return new Metadata($this->getName(), (null !== $code ? $code : $this->getName()), false, 'SonataSeoBundle', [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Sonata\CoreB...' => 'fa fa-twitter')); (Sonata\CoreBundle\Model\Metadata) is incompatible with the return type declared by the interface Sonata\BlockBundle\Block...rface::getBlockMetadata of type Sonata\BlockBundle\Meta\MetadataInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
Deprecated Code introduced by
The class Sonata\CoreBundle\Model\Metadata has been deprecated with message: since version 3.x, to be removed in 4.0. Use Sonata\BlockBundle\Meta\Metadata instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
163
            'class' => 'fa fa-twitter',
164
        ]);
165
    }
166
167
    /**
168
     * Returns supported API parameters from settings.
169
     *
170
     * @return array
171
     */
172
    protected function getSupportedApiParams()
173
    {
174
        return [
175
            'maxwidth',
176
            'hide_media',
177
            'hide_thread',
178
            'omit_script',
179
            'align',
180
            'related',
181
            'lang',
182
            'url',
183
            'id',
184
        ];
185
    }
186
187
    /**
188
     * Builds the API query URI based on $settings.
189
     *
190
     * @param bool  $uriMatched
191
     * @param array $settings
192
     *
193
     * @return string
194
     */
195
    protected function buildUri($uriMatched, array $settings)
196
    {
197
        $apiParams = $settings;
198
        $supportedParams = $this->getSupportedApiParams();
199
200
        if ($uriMatched) {
201
            // We matched the uri
202
            $apiParams['url'] = $settings['tweet'];
203
        } else {
204
            $apiParams['id'] = $settings['tweet'];
205
        }
206
207
        unset($apiParams['tweet']);
208
209
        $parameters = [];
210
        foreach ($apiParams as $key => $value) {
211
            if ($value && \in_array($key, $supportedParams)) {
212
                $parameters[] = $key.'='.$value;
213
            }
214
        }
215
216
        return sprintf('%s?%s', self::TWITTER_OEMBED_URI, implode('&', $parameters));
217
    }
218
219
    /**
220
     * Loads twitter tweet.
221
     */
222
    private function loadTweet(BlockContextInterface $blockContext): ?string
223
    {
224
        $uriMatched = preg_match(self::TWEET_URL_PATTERN, $blockContext->getSetting('tweet'));
225
226
        if (!$uriMatched || !preg_match(self::TWEET_ID_PATTERN, $blockContext->getSetting('tweet'))) {
227
            return null;
228
        }
229
230
        if (null !== $this->httpClient && null !== $this->messageFactory) {
231
            try {
232
                $response = $this->httpClient->sendRequest(
233
                    $this->messageFactory->createRequest(
234
                        'GET',
235
                        $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...
236
                    )
237
                );
238
            } catch (Exception $e) {
239
                // log error
240
                return null;
241
            }
242
243
            $apiTweet = json_decode($response->getBody(), true);
244
245
            return $apiTweet['html'];
246
        }
247
248
        // NEXT_MAJOR: Remove the old guzzle implementation
249
250
        // We matched an URL or an ID, we'll need to ask the API
251
        if (false === class_exists('GuzzleHttp\Client')) {
252
            throw new \RuntimeException(
253
                'The guzzle http client library is required to call the Twitter API.'.
254
                'Make sure to add php-http/httplug-bundle or guzzlehttp/guzzle to your composer.json.'
255
            );
256
        }
257
258
        @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...
259
            'The direct Guzzle implementation is deprecated since 2.x and will be removed with the next major release.',
260
            E_USER_DEPRECATED
261
        );
262
263
        // TODO cache API result
264
        $client = new \GuzzleHttp\Client();
265
        $client->setConfig(['curl.options' => [CURLOPT_CONNECTTIMEOUT_MS => 1000]]);
266
267
        try {
268
            $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...
269
            $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...
270
271
            return $apiTweet['html'];
272
        } catch (GuzzleException $e) {
273
            // log error
274
            return null;
275
        }
276
        // END NEXT_MAJOR
277
    }
278
}
279