Passed
Push — develop ( d38550...af508d )
by Benjamin
09:14
created

Report::icon()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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