Passed
Push — develop ( 4ddf62...944a5f )
by Andrew
04:25
created

Commerce::addProductDataFromLineItem()   B

Complexity

Conditions 10
Paths 21

Size

Total Lines 51
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 51
rs 7.6666
c 0
b 0
f 0
cc 10
nc 21
nop 4

How to fix   Long Method    Complexity   

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
 * 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\services;
12
13
use nystudio107\instantanalytics\InstantAnalytics;
14
use nystudio107\instantanalytics\helpers\IAnalytics;
15
16
use Craft;
17
use craft\base\Component;
18
use craft\elements\db\CategoryQuery;
19
use craft\elements\db\MatrixBlockQuery;
20
use craft\elements\db\TagQuery;
21
22
use craft\commerce\Plugin as CommercePlugin;
0 ignored issues
show
Bug introduced by
The type craft\commerce\Plugin was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
use craft\commerce\base\Purchasable;
0 ignored issues
show
Bug introduced by
The type craft\commerce\base\Purchasable was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
use craft\commerce\elements\Order;
0 ignored issues
show
Bug introduced by
The type craft\commerce\elements\Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
25
use craft\commerce\elements\Product;
0 ignored issues
show
Bug introduced by
The type craft\commerce\elements\Product was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use craft\commerce\elements\Variant;
0 ignored issues
show
Bug introduced by
The type craft\commerce\elements\Variant was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use craft\commerce\models\LineItem;
0 ignored issues
show
Bug introduced by
The type craft\commerce\models\LineItem was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
29
/**
30
 * Commerce Service
31
 *
32
 * @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...
33
 * @package   InstantAnalytics
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
34
 * @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...
35
 */
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...
36
class Commerce extends Component
37
{
38
    // Public Methods
39
    // =========================================================================
40
41
    /**
42
     * Send analytics information for the completed order
43
     *
44
     * @param Order  $order the Product or Variant
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter type; 2 found
Loading history...
45
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
46
    public function orderComplete($order = null)
47
    {
48
        if ($order) {
49
            $analytics = InstantAnalytics::$plugin->ia->eventAnalytics(
50
                'Commerce',
51
                'Purchase',
52
                $order->number,
53
                $order->totalPrice
54
            );
55
            
56
            if ($analytics) {
57
                $this->addCommerceOrderToAnalytics($analytics, $order);
58
                // Don't forget to set the product action, in this case to PURCHASE
59
                $analytics->setProductActionToPurchase();
60
                $analytics->sendEvent();
61
62
                Craft::info(Craft::t(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
63
                    'instant-analytics',
64
                    'orderComplete for `Commerce` - `Purchase` - `{number}` - `{price}`',
65
                    [ 'number' => $order->number, 'price' => $order->totalPrice ]
66
                ), __METHOD__);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
67
            }
68
        }
69
    }
70
71
    /**
72
     * Send analytics information for the item added to the cart
73
     * @param Order  $order the Product or Variant
0 ignored issues
show
Coding Style introduced by
There must be exactly one blank line before the tags in a doc comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 2 found
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
74
     * @param LineItem  $lineItem the line item that was added
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter type; 2 found
Loading history...
75
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
76
    public function addToCart(/** @noinspection PhpUnusedParameterInspection */ $order = null, $lineItem = null)
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...
77
    {
78
        if ($lineItem) {
79
            $title = $lineItem->purchasable->title;
80
            $quantity = $lineItem->qty;
81
            $analytics = InstantAnalytics::$plugin->ia->eventAnalytics('Commerce', 'Add to Cart', $title, $quantity);
82
            
83
            if ($analytics) {
84
                $title = $this->addProductDataFromLineItem($analytics, $lineItem);
85
                $analytics->setEventLabel($title);
86
                // Don't forget to set the product action, in this case to ADD
87
                $analytics->setProductActionToAdd();
88
                $analytics->sendEvent();
89
90
                Craft::info(Craft::t(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
91
                    'instant-analytics',
92
                    'addToCart for `Commerce` - `Add to Cart` - `{title}` - `{quantity}`',
93
                    [ 'title' => $title, 'quantity' => $quantity ]
94
                ), __METHOD__);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
95
            }
96
        }
97
    }
98
99
    /**
100
     * Send analytics information for the item removed from the cart
101
     *
102
     * @param Order|null    $order
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
103
     * @param LineItem|null $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
104
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
105
    public function removeFromCart(/** @noinspection PhpUnusedParameterInspection */ $order = null, $lineItem = null)
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...
106
    {
107
        if ($lineItem) {
108
            $title = $lineItem->purchasable->title;
109
            $quantity = $lineItem->qty;
110
            $analytics = InstantAnalytics::$plugin->ia->eventAnalytics(
111
                'Commerce',
112
                'Remove from Cart',
113
                $title,
114
                $quantity
115
            );
116
            
117
            if ($analytics) {
118
                $title = $this->addProductDataFromLineItem($analytics, $lineItem);
119
                $analytics->setEventLabel($title);
120
                // Don't forget to set the product action, in this case to ADD
121
                $analytics->setProductActionToRemove();
122
                $analytics->sendEvent();
123
124
                Craft::info(Craft::t(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
125
                    'instant-analytics',
126
                    'removeFromCart for `Commerce` - `Remove to Cart` - `{title}` - `{quantity}`',
127
                    [ 'title' => $title, 'quantity' => $quantity ]
128
                ), __METHOD__);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
129
            }
130
        }
131
    }
132
133
134
    /**
135
     * Add a Craft Commerce OrderModel to an Analytics object
136
     *
137
     * @param IAnalytics $analytics the Analytics object
138
     * @param Order  $order the Product or Variant
0 ignored issues
show
Coding Style introduced by
Expected 6 spaces after parameter type; 2 found
Loading history...
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
139
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
140
    public function addCommerceOrderToAnalytics($analytics = null, $order = null)
141
    {
142
        if ($order && $analytics) {
143
            // First, include the transaction data
144
            $analytics->setTransactionId($order->number)
145
                ->setRevenue($order->totalPrice)
146
                ->setTax($order->getAdjustmentsTotalByType('tax', true))
147
                ->setShipping($order->getAdjustmentsTotalByType('shipping', true));
148
            
149
            // Coupon code?
150
            if ($order->couponCode) {
151
                $analytics->setCouponCode($order->couponCode);
152
            }
153
154
            // Add each line item in the transaction
155
            // Two cases - variant and non variant products
156
            $index = 1;
157
158
            foreach ($order->lineItems as $key => $lineItem) {
159
                $this->addProductDataFromLineItem($analytics, $lineItem, $index, '');
160
                $index++;
161
            }
162
        }
163
    }
164
165
    /**
166
     * Add a Craft Commerce LineItem to an Analytics object
167
     *
168
     * @param IAnalytics|null   $analytics
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 1 spaces after parameter type; 3 found
Loading history...
169
     * @param LineItem|null   $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
170
     * @param int    $index
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 13 spaces after parameter type; 4 found
Loading history...
171
     * @param string $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
172
     *
173
     * @return string the title of the product
174
     */
175
    public function addProductDataFromLineItem($analytics = null, $lineItem = null, $index = 0, $listName = ''): string
176
    {
177
        $result = '';
178
        if ($lineItem && $analytics) {
179
            //This is the same for both variant and non variant products
180
            $productData = [
181
                'sku' => $lineItem->purchasable->sku,
182
                'price' => $lineItem->salePrice,
183
                'quantity' => $lineItem->qty,
184
            ];
185
186
            $productVariant = $lineItem->purchasable;
187
            $productData['name'] = $lineItem->purchasable->title;
188
            /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
189
             * @TODO: See if there is a Commerce 2 equivalent
190
            $productData['category'] = $lineItem->purchasable->type->name;
191
             */
192
193
            $result = $productData['name'];
194
195
            if ($index) {
196
                $productData['position'] = $index;
197
            }
198
199
            if ($listName) {
200
                $productData['list'] = $listName;
201
            }
202
203
            $settings = InstantAnalytics::$plugin->getSettings();
204
205
            if ($settings) {
206
                if (isset($settings['productCategoryField']) && !empty($settings['productCategoryField'])) {
207
                    $productData['category'] = $this->pullDataFromField(
208
                        $productVariant,
209
                        $settings['productCategoryField']
210
                    );
211
                }
212
213
                if (isset($settings['productBrandField']) && !empty($settings['productBrandField'])) {
214
                    $productData['brand'] = $this->pullDataFromField(
215
                        $productVariant,
216
                        $settings['productBrandField']
217
                    );
218
                }
219
            }
220
221
            //Add each product to the hit to be sent
222
            $analytics->addProduct($productData);
223
        }
224
225
        return $result;
226
    }
227
228
    /**
229
     * Add a product impression from a Craft Commerce Product or Variant
230
     *
231
     * @param IAnalytics      $analytics      the Analytics object
232
     * @param Product|Variant $productVariant the Product or Variant
233
     * @param int             $index          Where the product appears in the list
234
     * @param string          $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
235
     * @param int             $listIndex
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
236
     *
237
     * @throws \yii\base\InvalidConfigException
238
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
239
    public function addCommerceProductImpression(
240
        $analytics = null,
241
        $productVariant = null,
242
        $index = 0,
243
        $listName = 'default',
244
        $listIndex = 1
245
    ) {
246
        if ($productVariant && $analytics) {
247
            $productData = $this->getProductDataFromProduct($productVariant);
248
249
            /**
250
             * As per: https://github.com/theiconic/php-ga-measurement-protocol/issues/26
251
             */
252
            if ($listName && $listIndex) {
253
                $analytics->setProductImpressionListName($listName, $listIndex);
254
            }
255
256
            if ($index) {
257
                $productData['position'] = $index;
258
            }
259
260
            //Add the product to the hit to be sent
261
            $analytics->addProductImpression($productData, $listIndex);
262
263
            Craft::info(Craft::t(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
264
                'instant-analytics',
265
                'addCommerceProductImpression for `{sku}` - `{name}` - `{name}` - `{index}`',
266
                [ 'sku' => $productData['sku'], 'name' => $productData['name'], 'index' => $index ]
267
            ), __METHOD__);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
268
        }
269
    }
270
271
    /**
272
     * Add a product detail view from a Craft Commerce Product or Variant
273
     *
274
     * @param IAnalytics      $analytics      the Analytics object
275
     * @param Product|Variant $productVariant the Product or Variant
276
     *
277
     * @throws \yii\base\InvalidConfigException
278
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
279
    public function addCommerceProductDetailView($analytics = null, $productVariant = null)
280
    {
281
        if ($productVariant && $analytics) {
282
            $productData = $this->getProductDataFromProduct($productVariant);
283
284
            // Don't forget to set the product action, in this case to DETAIL
285
            $analytics->setProductActionToDetail();
286
287
            //Add the product to the hit to be sent
288
            $analytics->addProduct($productData);
289
290
            Craft::info(Craft::t(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
291
                'instant-analytics',
292
                'addCommerceProductDetailView for `{sku}` - `{name} - `{name}`',
293
                [ 'sku' => $productData['sku'], 'name' => $productData['name'] ]
294
            ), __METHOD__);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
295
        }
296
    }
297
298
    /**
299
     * Add a checkout step and option to an Analytics object
300
     *
301
     * @param IAnalytics $analytics the Analytics object
302
     * @param Order      $order     the Product or Variant
303
     * @param int        $step      the checkout step
304
     * @param string     $option    the checkout option
305
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
306
    public function addCommerceCheckoutStep($analytics = null, $order = null, $step = 1, $option = '')
307
    {
308
        if ($order && $analytics) {
309
            // Add each line item in the transaction
310
            // Two cases - variant and non variant products
311
            $index = 1;
312
313
            foreach ($order->lineItems as $key => $lineItem) {
314
                $this->addProductDataFromLineItem($analytics, $lineItem, $index, '');
315
                $index++;
316
            }
317
318
            $analytics->setCheckoutStep($step);
319
            
320
            if ($option) {
321
                $analytics->setCheckoutStepOption($option);
322
            }
323
324
            // Don't forget to set the product action, in this case to CHECKOUT
325
            $analytics->setProductActionToCheckout();
326
327
            Craft::info(Craft::t(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
328
                'instant-analytics',
329
                'addCommerceCheckoutStep step: `{step}` with option: `{option}`',
330
                [ 'step' => $step, 'option' => $option ]
331
            ), __METHOD__);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
332
        }
333
    }
334
335
    /**
336
     * Extract product data from a Craft Commerce Product or Variant
337
     *
338
     * @param Product|Variant $productVariant the Product or Variant
339
     *
340
     * @return array the product data
341
     * @throws \yii\base\InvalidConfigException
342
     */
343
    public function getProductDataFromProduct($productVariant = null): array
344
    {
345
        $result = [];
346
        
347
        // Extract the variant if it's a Product or Purchasable
348
        if ($productVariant && \is_object($productVariant)) {
349
            if (is_a($productVariant, Product::class)
350
                || is_a($productVariant, Purchasable::class)
351
            ) {
352
                $productType = property_exists($productVariant, 'typeId')
353
                    ? InstantAnalytics::$commercePlugin->getProductTypes()->getProductTypeById($productVariant->typeId)
0 ignored issues
show
Bug introduced by
The method getProductTypes() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

353
                    ? InstantAnalytics::$commercePlugin->/** @scrutinizer ignore-call */ getProductTypes()->getProductTypeById($productVariant->typeId)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
354
                    : null;
355
                
356
                if ($productType && $productType->hasVariants) {
357
                    $productVariants = $productVariant->getVariants();
358
                    $productVariant = reset($productVariants);
359
                    $product = $productVariant->getProduct();
360
                    
361
                    if ($product) {
362
                        $category = $product->getType()['name'];
363
                        $name = $product->title;
364
                        $variant = $productVariant->title;
365
                    } else {
366
                        $category = $productVariant->getType()['name'];
367
                        $name = $productVariant->title;
368
                        $variant = '';
369
                    }
370
                } else {
371
                    if (!empty($productVariant->defaultVariantId)) {
372
                        /** @var Variant $productVariant */
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...
373
                        $productVariant = InstantAnalytics::$commercePlugin->getVariants()->getVariantById(
374
                            $productVariant->defaultVariantId
375
                        );
376
                        $category = $productVariant->getProduct()->getType()['name'];
377
                        $name = $productVariant->title;
378
                        $variant = '';
379
                    } else {
380
                        if (isset($productVariant->product)) {
381
                            $category = $productVariant->product->getType()['name'];
382
                            $name = $productVariant->product->title;
383
                        } else {
384
                            $category = $productVariant->getType()['name'];
385
                            $name = $productVariant->title;
386
                        }
387
                        $variant = $productVariant->title;
388
                    }
389
                }
390
            }
391
392
            $productData = [
393
                'sku' => $productVariant->sku,
394
                'name' => $name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $name does not seem to be defined for all execution paths leading up to this point.
Loading history...
395
                'price' => number_format($productVariant->price, 2, '.', ''),
396
                'category' => $category,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $category does not seem to be defined for all execution paths leading up to this point.
Loading history...
397
            ];
398
399
            if ($variant) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $variant does not seem to be defined for all execution paths leading up to this point.
Loading history...
400
                $productData['variant'] = $variant;
401
            }
402
403
            $settings = InstantAnalytics::$plugin->getSettings();
404
            $isVariant = is_a($productVariant, Variant::class);
405
            
406
            if ($settings && isset($settings['productCategoryField']) && !empty($settings['productCategoryField'])) {
407
                $productData['category'] = $this->pullDataFromField(
408
                    $productVariant,
409
                    $settings['productCategoryField']
410
                );
411
412
                if (empty($productData['category']) && $isVariant) {
413
                    $productData['category'] = $this->pullDataFromField(
414
                        $productVariant->product,
415
                        $settings['productCategoryField']
416
                    );
417
                }
418
            }
419
420
            if ($settings && isset($settings['productBrandField']) && !empty($settings['productBrandField'])) {
421
                $productData['brand'] = $this->pullDataFromField(
422
                    $productVariant,
423
                    $settings['productBrandField'],
424
                    true
425
                );
426
427
                if (empty($productData['brand']) && $isVariant) {
428
                    $productData['brand'] = $this->pullDataFromField(
429
                        $productVariant,
430
                        $settings['productBrandField'],
431
                        true
432
                    );
433
                }
434
            }
435
436
            $result = $productData;
437
        }
438
439
        return $result;
440
    }
441
442
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
443
     * @param Product|Variant|null $productVariant
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
444
     * @param string $fieldHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 15 spaces after parameter type; 1 found
Loading history...
445
     * @param bool $isBrand
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 17 spaces after parameter type; 1 found
Loading history...
446
     *
447
     * @return string
448
     */
449
    private function pullDataFromField($productVariant, $fieldHandle, $isBrand = false): string
0 ignored issues
show
Coding Style introduced by
Private method name "Commerce::pullDataFromField" must be prefixed with an underscore
Loading history...
450
    {
451
        $result = '';
452
453
        if ($productVariant && $fieldHandle) {
454
            $srcField = $productVariant[$fieldHandle];
455
456
            if ($srcField === null) {
457
                $srcField = $productVariant->product->$fieldHandle;
458
            }
459
460
            switch (\get_class($srcField)) {
461
                case MatrixBlockQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
462
                    break;
463
                case TagQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
464
                    break;
465
                case CategoryQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
466
                    $cats = [];
467
468
                    if ($isBrand) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
469
                        // Because we can only have one brand, we'll get
470
                        // the very last category. This means if our
471
                        // brand is a sub-category, we'll get the child
472
                        // not the parent.
473
                        foreach ($srcField->all() as $cat) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
474
                            $cats = [$cat->title];
475
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
476
                    } else {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
477
                        // For every category, show its ancestors
478
                        // delimited by a slash.
479
                        foreach ($srcField->all() as $cat) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
480
                            $name = $cat->title;
481
482
                            while ($cat = $cat->parent) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
483
                                $name = $cat->title .'/'. $name;
484
                            }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
485
486
                            $cats[] = $name;
487
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
488
                    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
489
490
                    // Join separate categories with a pipe.
491
                    $result = implode('|', $cats);
492
                    break;
493
494
495
                default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
496
                    $result = strip_tags($srcField);
497
                    break;
498
            }
499
        }
500
501
        return $result;
502
    }
503
}
504