Passed
Branch v4 (ee4d75)
by Benjamin
05:42 queued 01:10
created

Report::getBodyHtml()   B

Complexity

Conditions 7
Paths 30

Size

Total Lines 63
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 34
nc 30
nop 0
dl 0
loc 63
rs 7.2689
c 0
b 0
f 0

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
 * @link      https://dukt.net/craft/analytics/
4
 * @copyright Copyright (c) 2018, Dukt
5
 * @license   https://dukt.net/craft/analytics/docs/license
6
 */
7
8
namespace dukt\analytics\widgets;
9
10
use Craft;
11
use craft\helpers\Json;
12
use craft\helpers\StringHelper;
13
use dukt\analytics\web\assets\reportwidget\ReportWidgetAsset;
14
use dukt\analytics\Plugin as Analytics;
15
16
class Report extends \craft\base\Widget
17
{
18
    // Properties
19
    // =========================================================================
20
21
    /**
22
     * @var string|null
23
     */
24
    public $viewId;
25
26
    /**
27
     * @var bool|null
28
     */
29
    public $realtime;
30
31
    /**
32
     * @var string|null
33
     */
34
    public $chart;
35
36
    /**
37
     * @var string|null
38
     */
39
    public $period;
40
41
    /**
42
     * @var array|null
43
     */
44
    public $options;
45
46
    // Public Methods
47
    // =========================================================================
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public static function displayName(): string
53
    {
54
        return Craft::t('analytics', 'Analytics Report');
55
    }
56
57
    /**
58
     * @inheritDoc IWidget::getTitle()
59
     *
60
     * @return string
61
     */
62
    public function getTitle(): string
63
    {
64
        $reportTitle = $this->_getReportTitle();
65
66
        if ($reportTitle) {
67
            return $reportTitle;
68
        }
69
70
        return Craft::t('analytics', 'Analytics Report');
71
    }
72
73
    /**
74
     * @inheritdoc
75
     */
76
    public static function iconPath()
77
    {
78
        return Craft::getAlias('@dukt/analytics/icons/report.svg');
0 ignored issues
show
Bug Best Practice introduced by
The expression return Craft::getAlias('...tics/icons/report.svg') also could return the type boolean which is incompatible with the return type mandated by craft\base\WidgetInterface::iconPath() of null|string.
Loading history...
79
    }
80
81
    /**
82
     * @inheritDoc IWidget::getBodyHtml()
83
     *
84
     * @return string|false
85
     * @throws \Twig_Error_Loader
86
     * @throws \yii\base\Exception
87
     */
88
    public function getBodyHtml()
89
    {
90
        $view = Craft::$app->getView();
91
92
        try {
93
            if (Analytics::$plugin->getAnalytics()->checkPluginRequirements()) {
94
                if (Analytics::$plugin->getSettings()->enableWidgets) {
95
                    $reportingViews = Analytics::$plugin->getViews()->getViews();
96
97
                    if (count($reportingViews) > 0) {
98
                        $widgetSettings = $this->settings;
99
100
                        $reportingView = Analytics::$plugin->getViews()->getViewById($widgetSettings['viewId']);
101
102
                        if ($reportingView) {
103
                            $request = [
104
                                'viewId' => $widgetSettings['viewId'] ?? null,
105
                                'chart' => $widgetSettings['chart'] ?? null,
106
                                'period' => $widgetSettings['period'] ?? null,
107
                                'options' => $widgetSettings['options'][$widgetSettings['chart']] ?? null,
108
                            ];
109
110
111
                            // use cached response if available
112
113
                            if (Analytics::$plugin->getSettings()->enableCache === true) {
114
                                $cacheId = ['getReport', $request];
115
                                $cachedResponse = Analytics::$plugin->cache->get($cacheId);
116
                            }
117
118
119
                            // render
120
121
                            $localeDefinition = Analytics::$plugin->getAnalytics()->getD3LocaleDefinition(['currency' => $reportingView->gaViewCurrency]);
122
123
                            $jsOptions = [
124
                                'localeDefinition' => $localeDefinition,
125
                                'chartLanguage' => Analytics::$plugin->getAnalytics()->getChartLanguage(),
126
                                'request' => $request,
127
                                'cachedResponse' => $cachedResponse ?? null,
128
                            ];
129
130
                            $view->registerJsFile('//www.gstatic.com/charts/loader.js');
131
                            $view->registerAssetBundle(ReportWidgetAsset::class);
132
133
                            $view->registerJs('new Analytics.ReportWidget("widget'.$this->id.'", '.Json::encode($jsOptions).');');
134
135
                            return $view->renderTemplate('analytics/_components/widgets/Report/body');
136
                        }
137
138
                        return $view->renderTemplate('analytics/_special/view-not-configured');
139
                    }
140
141
                    return $view->renderTemplate('analytics/_special/no-views');
142
                }
143
144
                return $view->renderTemplate('analytics/_components/widgets/Report/disabled');
145
            }
146
147
            return $view->renderTemplate('analytics/_special/not-connected');
148
        } catch (\Exception $e) {
149
            Craft::info('Couldn’t load report widget: '.$e->getMessage(), __METHOD__);
150
            return $view->renderTemplate('analytics/_special/error');
151
        }
152
    }
153
154
    /**
155
     * ISavableComponentType::getSettingsHtml()
156
     *
157
     * @return null|string
158
     * @throws \Twig_Error_Loader
159
     * @throws \yii\base\Exception
160
     * @throws \yii\base\InvalidConfigException
161
     */
162
    public function getSettingsHtml()
163
    {
164
        Craft::$app->getView()->registerAssetBundle(ReportWidgetAsset::class);
165
166
        $reportingViews = Analytics::$plugin->getViews()->getViews();
167
168
        if (count($reportingViews) > 0) {
169
            $id = 'analytics-settings-'.StringHelper::randomString();
170
            $namespaceId = Craft::$app->getView()->namespaceInputId($id);
171
172
            Craft::$app->getView()->registerJs("new Analytics.ReportWidgetSettings('".$namespaceId."');");
173
174
            $settings = $this->getSettings();
175
176
177
            // select options
178
179
            $chartTypes = ['area', 'counter', 'pie', 'table', 'geo'];
180
181
            $selectOptions = [];
182
183
            foreach ($chartTypes as $chartType) {
184
                $selectOptions[$chartType] = $this->_geSelectOptionsByChartType($chartType);
185
            }
186
187
            // view options
188
189
            return Craft::$app->getView()->renderTemplate('analytics/_components/widgets/Report/settings', [
190
                'id' => $id,
191
                'settings' => $settings,
192
                'selectOptions' => $selectOptions,
193
                'reportingViews' => $reportingViews,
194
            ]);
195
        }
196
197
        return null;
198
    }
199
200
    // Private Methods
201
    // =========================================================================
202
203
    /**
204
     * Returns the dimension & metrics options for a given chart type
205
     *
206
     * @param $chartType
207
     *
208
     * @return array
209
     */
210
    private function _geSelectOptionsByChartType($chartType)
211
    {
212
        switch ($chartType) {
213
            case 'area':
214
215
                $options = [
216
                    'metrics' => Analytics::$plugin->metadata->getSelectMetricOptions()
217
                ];
218
219
                break;
220
221
            case 'counter':
222
223
                $options = [
224
                    'metrics' => Analytics::$plugin->metadata->getSelectMetricOptions()
225
                ];
226
227
                break;
228
229
            case 'geo':
230
231
                $options = [
232
                    'dimensions' => Analytics::$plugin->metadata->getSelectDimensionOptions(['ga:city', 'ga:country', 'ga:continent', 'ga:subContinent']),
233
                    'metrics' => Analytics::$plugin->metadata->getSelectMetricOptions()
234
                ];
235
236
                break;
237
238
            default:
239
240
                $options = [
241
                    'dimensions' => Analytics::$plugin->metadata->getSelectDimensionOptions(),
242
                    'metrics' => Analytics::$plugin->metadata->getSelectMetricOptions()
243
                ];
244
        }
245
246
        return $options;
247
    }
248
249
    /**
250
     * Returns the title of the report
251
     *
252
     * @return string|null
253
     */
254
    private function _getReportTitle()
255
    {
256
        try {
257
            $name = [];
258
            $chartType = $this->settings['chart'];
259
260
            if (isset($this->settings['options'][$chartType])) {
261
                $options = $this->settings['options'][$chartType];
262
263
                if (!empty($options['dimension'])) {
264
                    $name[] = Craft::t('analytics', Analytics::$plugin->metadata->getDimMet($options['dimension']));
265
                }
266
267
                if (!empty($options['metric'])) {
268
                    $name[] = Craft::t('analytics', Analytics::$plugin->metadata->getDimMet($options['metric']));
269
                }
270
            }
271
272
            if (!empty($this->settings['period'])) {
273
                $name[] = Craft::t('analytics', ucfirst($this->settings['period']));
274
            }
275
276
            if (count($name) > 0) {
277
                return implode(' - ', $name);
278
            }
279
        } catch (\Exception $e) {
280
            Craft::info('Couldn’t get Analytics Report’s title: '.$e->getMessage(), __METHOD__);
281
        }
282
283
        return null;
284
    }
285
}
286