Passed
Push — master ( 0b518c...5d9f70 )
by Benjamin
08:02 queued 13s
created

SearchWidget::getSettingsHtml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 3
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * @link      https://dukt.net/twitter/
4
 * @copyright Copyright (c) 2021, Dukt
5
 * @license   https://github.com/dukt/twitter/blob/master/LICENSE.md
6
 */
7
8
namespace dukt\twitter\widgets;
9
10
use Craft;
11
use craft\base\Widget;
12
use craft\helpers\Json;
13
use craft\helpers\UrlHelper;
14
use dukt\twitter\models\Tweet;
15
use dukt\twitter\Plugin;
16
use dukt\twitter\web\assets\searchwidget\SearchWidgetAsset;
17
use GuzzleHttp\Exception\ClientException;
18
19
/**
20
 * Search Widget
21
 *
22
 * @author Dukt <[email protected]>
23
 * @since  3.0
24
 */
25
class SearchWidget extends Widget
26
{
27
    // Properties
28
    // =========================================================================
29
30
    /**
31
     * @var
32
     */
33
    public $query;
34
    /**
35
     * @var
36
     */
37
    public $count;
38
39
    // Static
40
    // =========================================================================
41
42
    /**
43
     * @inheritdoc
44
     */
45
    public static function displayName(): string
46
    {
47
        return Craft::t('twitter', 'Twitter Search');
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    public static function icon()
54
    {
55
        return Craft::getAlias('@dukt/twitter/icons/twitter.svg');
0 ignored issues
show
Bug Best Practice introduced by
The expression return Craft::getAlias('...ter/icons/twitter.svg') also could return the type boolean which is incompatible with the return type mandated by craft\base\WidgetInterface::icon() of null|string.
Loading history...
56
    }
57
58
    // Public Methods
59
    // =========================================================================
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function rules()
65
    {
66
        $rules = parent::rules();
67
        $rules[] = [['query', 'count'], 'required'];
68
        $rules[] = [['query'], 'string'];
69
        $rules[] = [['count'], 'integer', 'min' => 1];
70
71
        return $rules;
72
    }
73
74
    /**
75
     * @inheritdoc
76
     */
77
    public function getTitle(): string
78
    {
79
        $settings = $this->getSettings();
80
81
        if (!empty($settings['query'])) {
82
            return Craft::t('twitter', 'Tweets for “{query}”', ['query' => $settings['query']]);
83
        }
84
85
        return Craft::t('twitter', 'Twitter Search');
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function getBodyHtml()
92
    {
93
        $settings = $this->getSettings();
94
95
        $searchQuery = $settings['query'];
96
        $count = $settings['count'];
97
98
        $token = Plugin::getInstance()->getOauth()->getToken();
99
100
        if ($token) {
101
            if (!empty($searchQuery)) {
102
                try {
103
                    $q = $searchQuery;
104
105
                    if (Plugin::getInstance()->getSettings()->searchWidgetExtraQuery) {
106
                        $q .= ' '.Plugin::getInstance()->getSettings()->searchWidgetExtraQuery;
107
                    }
108
109
                    $response = Plugin::getInstance()->getApi()->get('search/tweets', [
110
                        'q' => $q,
111
                        'count' => $count,
112
                        'tweet_mode' => 'extended'
113
                    ]);
114
115
                    $tweets = [];
116
117
                    foreach ($response['statuses'] as $tweetData) {
118
                        $tweet = new Tweet();
119
                        Plugin::getInstance()->getApi()->populateTweetFromData($tweet, $tweetData);
120
                        array_push($tweets, $tweet);
121
                    }
122
123
                    $variables['tweets'] = $tweets;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$variables was never initialized. Although not strictly required by PHP, it is generally a good practice to add $variables = array(); before regardless.
Loading history...
124
125
                    Craft::$app->getView()->registerAssetBundle(SearchWidgetAsset::class);
126
                    Craft::$app->getView()->registerJs("new Craft.Twitter_SearchWidget('".$this->id."');");
127
128
                    return Craft::$app->getView()->renderTemplate('twitter/_components/widgets/Search/body', $variables);
129
                } catch (ClientException $e) {
130
                    $errorMsg = $e->getMessage();
131
                    $data = Json::decodeIfJson($e->getResponse()->getBody()->getContents());
132
133
                    if (isset($data['errors'][0]['message'])) {
134
                        $errorMsg = $data['errors'][0]['message'];
135
                    }
136
137
                    Craft::error('Couldn’t retrieve tweets: '.$e->getTraceAsString(), __METHOD__);
138
139
                    return Craft::$app->getView()->renderTemplate('twitter/_components/widgets/Search/_error', [
140
                        'errorMsg' => $errorMsg
141
                    ]);
142
                }
143
            } else {
144
                $variables['infoMsg'] = Craft::t('twitter', 'Please enter a search query in the widget’s settings.');
145
146
                return Craft::$app->getView()->renderTemplate('twitter/_components/widgets/Search/_error', $variables);
147
            }
148
        } else {
149
            $variables['infoMsg'] = Craft::t('twitter', 'Twitter is not configured, please check the <a href="{url}">plugin’s settings</a>.', [
150
                'url' => UrlHelper::url('twitter/settings')
151
            ]);
152
153
            return Craft::$app->getView()->renderTemplate('twitter/_components/widgets/Search/_error', $variables);
154
        }
155
    }
156
157
    /**
158
     * @inheritdoc
159
     */
160
    public function getSettingsHtml()
161
    {
162
        return Craft::$app->getView()->renderTemplate('twitter/_components/widgets/Search/settings', [
163
            'settings' => $this->getSettings()
164
        ]);
165
    }
166
}
167