Passed
Push — v1 ( 4c8497...ae9471 )
by Andrew
22:19 queued 10:54
created

Commerce::pullDataFromField()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 51
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 27
c 2
b 0
f 0
dl 0
loc 51
rs 7.3166
cc 11
nc 7
nop 3

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

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

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

512
                    $result = strip_tags(/** @scrutinizer ignore-type */ $srcField);
Loading history...
513
                    break;
514
            }
515
        }
516
517
        return $result;
518
    }
519
}
520