Passed
Push — develop ( 944a5f...7418f3 )
by Andrew
03:37
created

Commerce::addProductDataFromLineItem()   C

Complexity

Conditions 12
Paths 61

Size

Total Lines 62
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 62
rs 6.9666
c 0
b 0
f 0
cc 12
nc 61
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\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...
23
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...
24
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...
25
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...
26
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...
27
28
/**
29
 * Commerce Service
30
 *
31
 * @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...
32
 * @package   InstantAnalytics
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
33
 * @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...
34
 */
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...
35
class Commerce extends Component
36
{
37
    // Public Methods
38
    // =========================================================================
39
40
    /**
41
     * Send analytics information for the completed order
42
     *
43
     * @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...
44
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
45
    public function orderComplete($order = null)
46
    {
47
        if ($order) {
48
            $analytics = InstantAnalytics::$plugin->ia->eventAnalytics(
49
                'Commerce',
50
                'Purchase',
51
                $order->number,
52
                $order->totalPrice
53
            );
54
            
55
            if ($analytics) {
56
                $this->addCommerceOrderToAnalytics($analytics, $order);
57
                // Don't forget to set the product action, in this case to PURCHASE
58
                $analytics->setProductActionToPurchase();
59
                $analytics->sendEvent();
60
61
                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...
62
                    'instant-analytics',
63
                    'orderComplete for `Commerce` - `Purchase` - `{number}` - `{price}`',
64
                    [ 'number' => $order->number, 'price' => $order->totalPrice ]
65
                ), __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...
66
            }
67
        }
68
    }
69
70
    /**
71
     * Send analytics information for the item added to the cart
72
     * @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...
73
     * @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...
74
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
75
    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...
76
    {
77
        if ($lineItem) {
78
            $title = $lineItem->purchasable->title;
79
            $quantity = $lineItem->qty;
80
            $analytics = InstantAnalytics::$plugin->ia->eventAnalytics('Commerce', 'Add to Cart', $title, $quantity);
81
            
82
            if ($analytics) {
83
                $title = $this->addProductDataFromLineItem($analytics, $lineItem);
84
                $analytics->setEventLabel($title);
85
                // Don't forget to set the product action, in this case to ADD
86
                $analytics->setProductActionToAdd();
87
                $analytics->sendEvent();
88
89
                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...
90
                    'instant-analytics',
91
                    'addToCart for `Commerce` - `Add to Cart` - `{title}` - `{quantity}`',
92
                    [ 'title' => $title, 'quantity' => $quantity ]
93
                ), __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...
94
            }
95
        }
96
    }
97
98
    /**
99
     * Send analytics information for the item removed from the cart
100
     *
101
     * @param Order|null    $order
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
102
     * @param LineItem|null $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
103
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
104
    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...
105
    {
106
        if ($lineItem) {
107
            $title = $lineItem->purchasable->title;
108
            $quantity = $lineItem->qty;
109
            $analytics = InstantAnalytics::$plugin->ia->eventAnalytics(
110
                'Commerce',
111
                'Remove from Cart',
112
                $title,
113
                $quantity
114
            );
115
            
116
            if ($analytics) {
117
                $title = $this->addProductDataFromLineItem($analytics, $lineItem);
118
                $analytics->setEventLabel($title);
119
                // Don't forget to set the product action, in this case to ADD
120
                $analytics->setProductActionToRemove();
121
                $analytics->sendEvent();
122
123
                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...
124
                    'instant-analytics',
125
                    'removeFromCart for `Commerce` - `Remove to Cart` - `{title}` - `{quantity}`',
126
                    [ 'title' => $title, 'quantity' => $quantity ]
127
                ), __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...
128
            }
129
        }
130
    }
131
132
133
    /**
134
     * Add a Craft Commerce OrderModel to an Analytics object
135
     *
136
     * @param IAnalytics $analytics the Analytics object
137
     * @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...
138
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
139
    public function addCommerceOrderToAnalytics($analytics = null, $order = null)
140
    {
141
        if ($order && $analytics) {
142
            // First, include the transaction data
143
            $analytics->setTransactionId($order->number)
144
                ->setRevenue($order->totalPrice)
145
                ->setTax($order->getAdjustmentsTotalByType('tax', true))
146
                ->setShipping($order->getAdjustmentsTotalByType('shipping', true));
147
            
148
            // Coupon code?
149
            if ($order->couponCode) {
150
                $analytics->setCouponCode($order->couponCode);
151
            }
152
153
            // Add each line item in the transaction
154
            // Two cases - variant and non variant products
155
            $index = 1;
156
157
            foreach ($order->lineItems as $key => $lineItem) {
158
                $this->addProductDataFromLineItem($analytics, $lineItem, $index, '');
159
                $index++;
160
            }
161
        }
162
    }
163
164
    /**
165
     * Add a Craft Commerce LineItem to an Analytics object
166
     *
167
     * @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...
168
     * @param LineItem|null   $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
169
     * @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...
170
     * @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...
171
     *
172
     * @return string the title of the product
173
     */
174
    public function addProductDataFromLineItem($analytics = null, $lineItem = null, $index = 0, $listName = ''): string
175
    {
176
        $result = '';
177
        if ($lineItem && $analytics) {
178
            //This is the same for both variant and non variant products
179
            $productData = [
180
                'sku' => $lineItem->purchasable->sku,
181
                'price' => $lineItem->salePrice,
182
                'quantity' => $lineItem->qty,
183
            ];
184
185
            if (isset($lineItem->purchasable->product)) {
186
                $productVariant = $lineItem->purchasable->product;
187
                $hasVariants = $lineItem->purchasable->product->type->hasVariants ?? null;
188
                if (!$hasVariants) {
189
                    //No variants (i.e. default variant)
190
                    $productData['name'] = $lineItem->purchasable->title;
191
                    $productData['category'] = $lineItem->purchasable->product->type['name'];
192
                } else {
193
                    // Product with variants
194
                    $productData['name'] = $lineItem->purchasable->product->title;
195
                    $productData['category'] = $lineItem->purchasable->product->type['name'];
196
                    $productData['variant'] = $lineItem->purchasable->title;
197
                }
198
            } else {
199
                $productVariant = $lineItem->purchasable;
200
                $productData['name'] = $lineItem->purchasable->title;
201
            }
202
203
            $result = $productData['name'];
204
205
            if ($index) {
206
                $productData['position'] = $index;
207
            }
208
209
            if ($listName) {
210
                $productData['list'] = $listName;
211
            }
212
213
            $settings = InstantAnalytics::$plugin->getSettings();
214
215
            if ($settings) {
216
                if (isset($settings['productCategoryField']) && !empty($settings['productCategoryField'])) {
217
                    $productData['category'] = $this->pullDataFromField(
218
                        $productVariant,
219
                        $settings['productCategoryField']
220
                    );
221
                }
222
223
                if (isset($settings['productBrandField']) && !empty($settings['productBrandField'])) {
224
                    $productData['brand'] = $this->pullDataFromField(
225
                        $productVariant,
226
                        $settings['productBrandField']
227
                    );
228
                }
229
            }
230
231
            //Add each product to the hit to be sent
232
            $analytics->addProduct($productData);
233
        }
234
235
        return $result;
236
    }
237
238
    /**
239
     * Add a product impression from a Craft Commerce Product or Variant
240
     *
241
     * @param IAnalytics      $analytics      the Analytics object
242
     * @param Product|Variant $productVariant the Product or Variant
243
     * @param int             $index          Where the product appears in the list
244
     * @param string          $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
245
     * @param int             $listIndex
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
246
     *
247
     * @throws \yii\base\InvalidConfigException
248
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
249
    public function addCommerceProductImpression(
250
        $analytics = null,
251
        $productVariant = null,
252
        $index = 0,
253
        $listName = 'default',
254
        $listIndex = 1
255
    ) {
256
        if ($productVariant && $analytics) {
257
            $productData = $this->getProductDataFromProduct($productVariant);
258
259
            /**
260
             * As per: https://github.com/theiconic/php-ga-measurement-protocol/issues/26
261
             */
262
            if ($listName && $listIndex) {
263
                $analytics->setProductImpressionListName($listName, $listIndex);
264
            }
265
266
            if ($index) {
267
                $productData['position'] = $index;
268
            }
269
270
            //Add the product to the hit to be sent
271
            $analytics->addProductImpression($productData, $listIndex);
272
273
            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...
274
                'instant-analytics',
275
                'addCommerceProductImpression for `{sku}` - `{name}` - `{name}` - `{index}`',
276
                [ 'sku' => $productData['sku'], 'name' => $productData['name'], 'index' => $index ]
277
            ), __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...
278
        }
279
    }
280
281
    /**
282
     * Add a product detail view from a Craft Commerce Product or Variant
283
     *
284
     * @param IAnalytics      $analytics      the Analytics object
285
     * @param Product|Variant $productVariant the Product or Variant
286
     *
287
     * @throws \yii\base\InvalidConfigException
288
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
289
    public function addCommerceProductDetailView($analytics = null, $productVariant = null)
290
    {
291
        if ($productVariant && $analytics) {
292
            $productData = $this->getProductDataFromProduct($productVariant);
293
294
            // Don't forget to set the product action, in this case to DETAIL
295
            $analytics->setProductActionToDetail();
296
297
            //Add the product to the hit to be sent
298
            $analytics->addProduct($productData);
299
300
            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...
301
                'instant-analytics',
302
                'addCommerceProductDetailView for `{sku}` - `{name} - `{name}`',
303
                [ 'sku' => $productData['sku'], 'name' => $productData['name'] ]
304
            ), __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...
305
        }
306
    }
307
308
    /**
309
     * Add a checkout step and option to an Analytics object
310
     *
311
     * @param IAnalytics $analytics the Analytics object
312
     * @param Order      $order     the Product or Variant
313
     * @param int        $step      the checkout step
314
     * @param string     $option    the checkout option
315
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
316
    public function addCommerceCheckoutStep($analytics = null, $order = null, $step = 1, $option = '')
317
    {
318
        if ($order && $analytics) {
319
            // Add each line item in the transaction
320
            // Two cases - variant and non variant products
321
            $index = 1;
322
323
            foreach ($order->lineItems as $key => $lineItem) {
324
                $this->addProductDataFromLineItem($analytics, $lineItem, $index, '');
325
                $index++;
326
            }
327
328
            $analytics->setCheckoutStep($step);
329
            
330
            if ($option) {
331
                $analytics->setCheckoutStepOption($option);
332
            }
333
334
            // Don't forget to set the product action, in this case to CHECKOUT
335
            $analytics->setProductActionToCheckout();
336
337
            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...
338
                'instant-analytics',
339
                'addCommerceCheckoutStep step: `{step}` with option: `{option}`',
340
                [ 'step' => $step, 'option' => $option ]
341
            ), __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...
342
        }
343
    }
344
345
    /**
346
     * Extract product data from a Craft Commerce Product or Variant
347
     *
348
     * @param Product|Variant $productVariant the Product or Variant
349
     *
350
     * @return array the product data
351
     * @throws \yii\base\InvalidConfigException
352
     */
353
    public function getProductDataFromProduct($productVariant = null): array
354
    {
355
        $result = [];
356
        
357
        // Extract the variant if it's a Product or Purchasable
358
        if ($productVariant && \is_object($productVariant)) {
359
            if (is_a($productVariant, Product::class)
360
                || is_a($productVariant, Purchasable::class)
361
            ) {
362
                $productType = property_exists($productVariant, 'typeId')
363
                    ? 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

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