Completed
Push — development ( ef9e73...b2c3e4 )
by Andrij
20:27
created

Ga_dashboard::createOrderProductsData()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 22
rs 8.9197
1
<?php
2
3
use CMSFactory\assetManager;
4
use CMSFactory\Events;
5
use Propel\Runtime\Exception\PropelException;
6
7
(defined('BASEPATH')) OR exit('No direct script access allowed');
8
9
/**
10
 * Image CMS
11
 * Module Frame
12
 * @property Cms_base $cms_base
13
 * @link https://enhancedecommerce.appspot.com/
14
 */
15
class Ga_dashboard extends MY_Controller
16
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
17
18
    /**
19
     * Ga_dashboard constructor.
20
     */
21
    public function __construct() {
22
23
        parent::__construct();
24
        $lang = new MY_Lang();
25
        $lang->load('ga_dashboard');
26
    }
27
28
    /**
29
     * @throws Exception
0 ignored issues
show
introduced by
Comment missing or not on the next line for @throws tag in function comment
Loading history...
30
     */
31
    public function autoload() {
32
33
        $settings = $this->cms_base->get_settings();
34
35
        if ($settings['yandex_metric'] != '') {
36
            assetManager::create()->registerJsScript('window.dataLayer = window.dataLayer || [];', false, 'before');
37
            Events::create()->onProductPageLoad()->setListener('YMProductPageLoad');
38
            Events::create()->onShopOrderView()->setListener('YMShopOrderView');
39
        }
40
41
        if ($settings['google_analytics_ee'] == 1 and $settings['google_analytics_id'] != '') {
42
            Events::create()->onProductPageLoad()->setListener('ProductPageLoad');
43
            //            Events::create()->onAddItemToCart()->setListener('ProductAddToCart');
44
            Events::create()->onCategoryPageLoad()->setListener('CategorySearchPageLoad');
45
            Events::create()->onSearchPageLoad()->setListener('CategorySearchPageLoad');
46
            Events::create()->onBrandPageLoad()->setListener('CategorySearchPageLoad');
47
            Events::create()->onShopOrderView()->setListener('ShopOrderView');
48
        }
49
    }
50
51
    /**
52
     * @param Search $categoryObj
53
     * @throws PropelException
0 ignored issues
show
introduced by
Comment missing or not on the next line for @throws tag in function comment
Loading history...
54
     */
55
    public static function CategorySearchPageLoad($categoryObj) {
56
57
        $products = $categoryObj->data['products'] ?: $categoryObj['products'];
58
59
        if (count($products) > 0) {
60
61
            $url = CI::$APP->uri->uri_string();
62
63
            if (false !== strpos($url, 'shop/search')) {
64
                $list = 'search_page';
65
            } elseif (false !== strpos($url, 'shop/category')) {
66
                $list = 'category_page';
67
            } elseif (false !== strpos($url, 'shop/brand')) {
68
                $list = 'brand_page';
69
            }
70
71
            /* @var $product SProducts */
72
            $gaProducts = [];
73
            foreach ($products as $key => $product) {
74
                $SBrands = $product->getBrand();
75
                $brand = $SBrands ? $SBrands->getName() : '';
76
                $gaProducts[$key]['id'] = $product->getId();
77
                $gaProducts[$key]['name'] = $product->getName();
78
                $gaProducts[$key]['price'] = $product->getFirstVariant()->toCurrency();
79
                $gaProducts[$key]['brand'] = $brand;
80
                $gaProducts[$key]['category'] = $product->getMainCategory()->getName();
81
                $gaProducts[$key]['list'] = $list;
82
                $gaProducts[$key]['position'] = $key;
83
            }
84
            assetManager::create()
85
                ->registerJsScript('var gaProducts = ' . json_encode($gaProducts) . ';', FALSE, 'before')
86
                ->registerScript('category', TRUE, 'after');
87
        }
88
    }
89
90
    /**
91
     * @param $data
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
92
     */
93
    public static function ProductAddToCart($data) {
94
        return;
95
        if ($data['instance'] != 'SProducts') {
0 ignored issues
show
Unused Code introduced by
if ($data['instance'] !=...ducts') { return; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
96
            return;
97
        }
98
        $model = SProductsQuery::create()
99
            ->joinProductVariant()
100
            ->useProductVariantQuery()
101
            ->filterById($data['id'])
102
            ->endUse()
103
            ->findOne();
104
105
        assetManager::create()
106
            ->registerJsScript("var id = {$model->getId()};", true, 'before')
107
            ->registerJsScript("var name = {$model->getName()};", FALSE, 'before')
108
            ->registerJsScript("var price = {$model->getFirstVariant()->toCurrency()};", FALSE, 'before')
109
            ->registerJsScript("var brand = {$model->getId()};", FALSE, 'before')
110
            ->registerJsScript("var category = {$model->getId()};", FALSE, 'before')
111
            ->registerScript('addToCart', TRUE, 'after');
112
    }
113
114
    public static function ProductPageLoad($data) {
115
        assetManager::create()
116
            ->registerJsScript('var gaProduct = ' . self::createProductData($data) . ';', FALSE, 'before')
117
            ->registerScript('product', FALSE, 'after');
118
    }
119
120
    public static function YMProductPageLoad($data) {
121
122
        assetManager::create()
123
            ->registerJsScript(
124
                'window.dataLayer.push({
125
                                    "ecommerce": {
126
                                        "detail" : {
127
                                            "products" : [' . self::createProductData($data) . ']
128
                                        }
129
                                    }
130
                                });',
131
                false,
132
                'before'
133
            );
134
        assetManager::create();
135
    }
136
137
    /**
138
     * @param array $data
139
     * @throws PropelException
0 ignored issues
show
introduced by
Comment missing or not on the next line for @throws tag in function comment
Loading history...
140
     */
141
    public static function YMShopOrderView($data) {
142
143
        /** @var $data SOrders */
144
        if ($data instanceof SOrders && CI::$APP->session->flashdata('makeOrderForGA')) {
0 ignored issues
show
Bug introduced by
The class SOrders does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
145
146
            assetManager::create()
147
                ->registerJsScript(
148
                    'window.dataLayer.push({
149
                                    "ecommerce": {
150
                                        "purchase" : {
151
                                            "actionField": ' . self::createOrderData($data, true) . ',
152
                                            "products" : ' . self::createOrderProductsData($data) . '
153
                                        }
154
                                    }
155
                                });',
156
                    false,
157
                    'before'
158
                );
159
        }
160
    }
161
162
    private static function createProductData($data) {
163
        /* @var $model SProducts */
164
        $model = $data['model'];
165
166
        $gaProduct = [];
167
        $gaProduct['id'] = $model->getId();
168
        $gaProduct['name'] = $model->getName();
169
        $gaProduct['price'] = $model->getFirstVariant()->toCurrency();
170
        $SBrands = $model->getBrand();
171
        $gaProduct['brand'] = $SBrands ? $SBrands->getName() : '';
172
        $gaProduct['category'] = $model->getMainCategory()->getName();
173
174
        return json_encode($gaProduct);
175
    }
176
177
    private static function createOrderData($data, $ym = false) {
178
        $order['id'] = $data->getKey();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$order was never initialized. Although not strictly required by PHP, it is generally a good practice to add $order = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
179
        $order['revenue'] = $data->getTotalPrice();
180
        if (!$ym) {
181
            $order['shipping'] = $data->getDeliveryPrice() ?: 0;
182
        }
183
        return json_encode($order);
184
    }
185
186
    private static function createOrderProductsData($data) {
187
        $products = [];
188
        foreach ($data->getSOrderProductss() as $key => $orderProduct) {
189
            $productVariant = $orderProduct->getVariant();
190
            if ($productVariant instanceof SProductVariants) {
0 ignored issues
show
Bug introduced by
The class SProductVariants does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
191
                $product = $productVariant->getSProducts();
192
193
                $products[$key]['id'] = $productVariant->getId();
194
                $products[$key]['name'] = $orderProduct->getProductName();
195
                $products[$key]['price'] = $orderProduct->getPrice();
196
                $SBrands = $product->getBrand();
197
                $products[$key]['brand'] = $SBrands ? $SBrands->getName() : '';
198
                $products[$key]['category'] = $product->getMainCategory()->getName();
199
                $products[$key]['variant'] = $productVariant->getName();
200
                $products[$key]['position'] = $key;
201
                $products[$key]['quantity'] = $orderProduct->getQuantity();
202
            }
203
204
        }
205
206
        return json_encode($products);
207
    }
208
209
    /**
210
     * @param array $data
211
     * @throws PropelException
0 ignored issues
show
introduced by
Comment missing or not on the next line for @throws tag in function comment
Loading history...
212
     */
213
    public static function ShopOrderView($data) {
214
215
        /** @var $data SOrders */
216
        if ($data instanceof SOrders && CI::$APP->session->flashdata('makeOrderForGA')) {
0 ignored issues
show
Bug introduced by
The class SOrders does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
217
218
            assetManager::create()
219
                ->registerJsScript('var gaOrderObject = ' . self::createOrderData($data) . ';')
220
                ->registerJsScript('var gaOrderProductsObject = ' . self::createOrderProductsData($data) . ';')
221
                ->registerScript('order_view', FALSE, 'after');
222
        }
223
    }
224
225
    public function index() {
226
    }
227
228
    public function _deinstall() {
229
    }
230
231
    public function _install() {
232
        $this->db
233
            ->where('name', 'ga_dashboard')
234
            ->update('components', ['autoload' => '1', 'enabled' => '1']);
235
    }
236
237
}
238
239
/* End of file sample_module.php */