Passed
Push — develop ( 3a86a8...a74a25 )
by Andrew
06:23
created

InstantAnalytics::installEventListeners()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 23
rs 8.8333
c 0
b 0
f 0
cc 7
nc 4
nop 0
1
<?php
2
/**
3
 * Instant Analytics plugin for Craft CMS 3.x
4
 *
5
 * Instant Analytics brings full Google Analytics support to your Twig templates
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2017 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\instantanalytics;
12
13
use nystudio107\instantanalytics\helpers\IAnalytics;
14
use nystudio107\instantanalytics\helpers\Field as FieldHelper;
15
use nystudio107\instantanalytics\models\Settings;
16
use nystudio107\instantanalytics\services\Commerce as CommerceService;
17
use nystudio107\instantanalytics\services\IA as IAService;
18
use nystudio107\instantanalytics\variables\InstantAnalyticsVariable;
19
use nystudio107\instantanalytics\twigextensions\InstantAnalyticsTwigExtension;
20
21
use Craft;
22
use craft\base\Plugin;
23
use craft\events\PluginEvent;
24
use craft\events\RegisterUrlRulesEvent;
25
use craft\events\TemplateEvent;
26
use craft\helpers\UrlHelper;
27
use craft\services\Plugins;
28
use craft\web\twig\variables\CraftVariable;
29
use craft\web\UrlManager;
30
use craft\web\View;
31
32
use yii\base\Event;
33
use yii\base\Exception;
34
35
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
36
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 4
Loading history...
37
 * @package   InstantAnalytics
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
38
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 3 spaces but found 5
Loading history...
39
 *
40
 * @property  IAService       $ia
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 2
Loading history...
41
 * @property  CommerceService $commerce
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 2
Loading history...
42
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
43
class InstantAnalytics extends Plugin
44
{
45
    // Static Properties
46
    // =========================================================================
47
48
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
49
     * @var InstantAnalytics
50
     */
51
    public static $plugin;
52
53
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
54
     * @var Plugin|null
55
     */
56
    public static $commercePlugin;
57
58
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
59
     * @var Plugin|null
60
     */
61
    public static $seomaticPlugin;
62
63
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
64
     * @var string
65
     */
66
    public static $currentTemplate = '';
67
68
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
69
     * @var bool
70
     */
71
    public static $pageViewSent = false;
72
73
    // Public Methods
74
    // =========================================================================
75
76
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
77
     * @inheritdoc
78
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
79
    public function init()
80
    {
81
        parent::init();
82
        self::$plugin = $this;
83
84
        // Determine if Craft Commerce is installed & enabled
85
        self::$commercePlugin = Craft::$app->getPlugins()->getPlugin('commerce');
86
        // Determine if SEOmatic is installed & enabled
87
        self::$seomaticPlugin = Craft::$app->getPlugins()->getPlugin('seomatic');
88
        // Add in our Craft components
89
        $this->addComponents();
90
        // Install our global event handlers
91
        $this->installEventListeners();
92
93
        Craft::info(
94
            Craft::t(
95
                'instant-analytics',
96
                '{name} plugin loaded',
97
                ['name' => $this->name]
98
            ),
99
            __METHOD__
100
        );
101
    }
102
103
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
104
     * @inheritdoc
105
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
106
    public function settingsHtml()
107
    {
108
        $commerceFields = [];
109
110
        if (self::$commercePlugin) {
111
            /**
112
             * TODO: pending Commerce for Craft 3
113
             * $productTypes = craft()->commerce_productTypes->getAllProductTypes();
114
             * foreach ($productTypes as $productType) {
115
             * $productFields = $this->_getPullFieldsFromLayoutId($productType->fieldLayoutId);
116
             * $commerceFields = array_merge($commerceFields, $productFields);
117
             * if ($productType->hasVariants) {
118
             * $variantFields = $this->_getPullFieldsFromLayoutId($productType->variantFieldLayoutId);
119
             * $commerceFields = array_merge($commerceFields, $variantFields);
120
             * }
121
             * }
122
             */
123
        }
124
125
        // Rend the settings template
126
        try {
127
            return Craft::$app->getView()->renderTemplate(
128
                'instant-analytics/settings',
129
                [
130
                    'settings'       => $this->getSettings(),
131
                    'commerceFields' => $commerceFields,
132
                ]
133
            );
134
        } catch (\Twig_Error_Loader $e) {
135
            Craft::error($e->getMessage(), __METHOD__);
136
        } catch (Exception $e) {
137
            Craft::error($e->getMessage(), __METHOD__);
138
        }
139
    }
140
141
    // Protected Methods
142
    // =========================================================================
143
144
145
    /**
146
     * Add in our Craft components
147
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
148
    protected function addComponents()
149
    {
150
        $view = Craft::$app->getView();
151
        // Add in our Twig extensions
152
        $view->registerTwigExtension(new InstantAnalyticsTwigExtension());
153
        // Install our template hook
154
        $view->hook('iaSendPageView', [$this, 'iaSendPageView']);
155
        // Register our variables
156
        Event::on(
157
            CraftVariable::class,
158
            CraftVariable::EVENT_INIT,
159
            function (Event $event) {
160
                /** @var CraftVariable $variable */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
161
                $variable = $event->sender;
162
                $variable->set('instantAnalytics', InstantAnalyticsVariable::class);
163
            }
164
        );
165
    }
166
167
    /**
168
     * Install our event listeners
169
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
170
    protected function installEventListeners()
171
    {
172
        // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN
173
        Event::on(
174
            Plugins::class,
175
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
176
            function (PluginEvent $event) {
177
                if ($event->plugin === $this) {
178
                    $request = Craft::$app->getRequest();
179
                    if ($request->isCpRequest) {
180
                        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('instant-analytics/welcome'))->send();
181
                    }
182
                }
183
            }
184
        );
185
        $request = Craft::$app->getRequest();
186
        // Install only for non-console site requests
187
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
188
            $this->installSiteEventListeners();
189
        }
190
        // Install only for non-console AdminCP requests
191
        if ($request->getIsCpRequest() && !$request->getIsConsoleRequest()) {
192
            $this->installCpEventListeners();
193
        }
194
    }
195
196
    /**
197
     * Install site event listeners for site requests only
198
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
199
    protected function installSiteEventListeners()
200
    {
201
        // Handler: UrlManager::EVENT_REGISTER_SITE_URL_RULES
202
        Event::on(
203
            UrlManager::class,
204
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
205
            function (RegisterUrlRulesEvent $event) {
206
                Craft::debug(
207
                    'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
208
                    __METHOD__
209
                );
210
                // Register our AdminCP routes
211
                $event->rules = array_merge(
212
                    $event->rules,
213
                    $this->customFrontendRoutes()
214
                );
215
            }
216
        );
217
        // Remember the name of the currently rendering template
218
        Event::on(
219
            View::class,
220
            View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE,
221
            function (TemplateEvent $event) {
222
                self::$currentTemplate = $event->template;
223
            }
224
        );
225
        // Remember the name of the currently rendering template
226
        Event::on(
227
            View::class,
228
            View::EVENT_AFTER_RENDER_PAGE_TEMPLATE,
229
            function (TemplateEvent $event) {
230
                $settings = InstantAnalytics::$plugin->getSettings();
231
                if ($settings->autoSendPageView) {
232
                    $this->sendPageView();
233
                }
234
            }
235
        );
236
        // Register our site routes
237
        Event::on(
238
            UrlManager::class,
239
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
240
            function (RegisterUrlRulesEvent $event) {
241
                $event->rules['instantanalytics/pageViewTrack/<filename:[-\w\.*]+>?'] =
0 ignored issues
show
Coding Style introduced by
Multi-line assignments must have the equal sign on the second line
Loading history...
242
                    'instant-analytics/track/track-page-view-url';
243
                $event->rules['instantanalytics/eventTrack/<filename:[-\w\.*]+>?'] =
0 ignored issues
show
Coding Style introduced by
Multi-line assignments must have the equal sign on the second line
Loading history...
244
                    'instant-analytics/track/track-event-url';
245
            }
246
        );
247
        // Commerce-specific hooks
248
        if (self::$commercePlugin) {
249
            // TODO: pending Commerce for Craft 3
250
        }
251
    }
252
253
    /**
254
     * Install site event listeners for AdminCP requests only
255
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
256
    protected function installCpEventListeners()
257
    {
258
    }
259
260
    /**
261
     * Return the custom frontend routes
262
     *
263
     * @return array
264
     */
265
    protected function customFrontendRoutes(): array
266
    {
267
        return [
268
            // Make webpack async bundle loading work out of published AssetBundles
269
            '/cpresources/instant-analytics/<resourceType:{handle}>/<fileName>' => 'instant-analytics/cp-nav/resource',
270
        ];
271
    }
272
273
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
274
     * @inheritdoc
275
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
276
    protected function createSettingsModel()
277
    {
278
        return new Settings();
279
    }
280
281
    // Private Methods
282
    // =========================================================================
283
284
    private function sendPageView()
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
Coding Style introduced by
Private method name "InstantAnalytics::sendPageView" must be prefixed with an underscore
Loading history...
285
    {
286
        if (!self::$pageViewSent) {
287
            self::$pageViewSent = true;
288
            /** @var IAnalytics $analytics */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
289
            $analytics = InstantAnalytics::$plugin->ia->getGlobals(self::$currentTemplate);
290
            // Send the page view
291
            if ($analytics) {
0 ignored issues
show
introduced by
$analytics is of type nystudio107\instantanalytics\helpers\IAnalytics, thus it always evaluated to true. If $analytics can have other possible types, add them to src/InstantAnalytics.php:288
Loading history...
292
                $response = $analytics->sendPageView();
293
                Craft::info(
294
                    "pageView sent, response: ".print_r($response, true),
295
                    __METHOD__
296
                );
297
            } else {
298
                Craft::error(
299
                    "Analytics not sent because googleAnalyticsTracking is not set",
300
                    __METHOD__
301
                );
302
            }
303
        }
304
    }
305
306
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $context should have a doc-comment as per coding-style.
Loading history...
307
     * Send a page view with the pre-loaded IAnalytics object
308
     *
309
     * @param array &$context
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter &$context does not match actual variable name $context
Loading history...
310
     *
311
     * @return string|null
312
     */
313
    private function iaSendPageView(array &$context)
0 ignored issues
show
Coding Style introduced by
Private method name "InstantAnalytics::iaSendPageView" must be prefixed with an underscore
Loading history...
314
    {
315
        $request = Craft::$app->getRequest();
316
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
317
            // If SEOmatic is installed, set the page title from it
318
            if (self::$seomaticPlugin && isset($context['seomaticMeta'])) {
319
                /**
320
                 * TODO: fix for SEOmatic
321
                 * $seomaticMeta = $context['seomaticMeta'];
322
                 * $analytics->setDocumentTitle($seomaticMeta['seoTitle']);
323
                 */
324
            }
325
            $this->sendPageView();
326
        }
327
328
        return '';
329
    }
330
}
331