Passed
Push — develop ( d084a5...5cdcfa )
by Andrew
04:21
created

Commerce::pullDataFromField()   C

Complexity

Conditions 12
Paths 13

Size

Total Lines 56
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 56
rs 6.9666
c 0
b 0
f 0
cc 12
nc 13
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 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
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
     *
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->number)
149
                ->setRevenue($order->totalPrice)
150
                ->setTax($order->getAdjustmentsTotalByType('tax', true))
151
                ->setShipping($order->getAdjustmentsTotalByType('shipping', true));
152
153
            // Coupon code?
154
            if ($order->couponCode) {
155
                $analytics->setCouponCode($order->couponCode);
156
            }
157
158
            // Add each line item in the transaction
159
            // Two cases - variant and non variant products
160
            $index = 1;
161
162
            foreach ($order->lineItems as $key => $lineItem) {
163
                $this->addProductDataFromLineItem($analytics, $lineItem, $index, '');
164
                $index++;
165
            }
166
        }
167
    }
168
169
    /**
170
     * Add a Craft Commerce LineItem to an Analytics object
171
     *
172
     * @param IAnalytics|null $analytics
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
173
     * @param LineItem|null   $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
174
     * @param int             $index
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
175
     * @param string          $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
176
     *
177
     * @return string the title of the product
178
     * @throws \yii\base\InvalidConfigException
179
     */
180
    public function addProductDataFromLineItem($analytics = null, $lineItem = null, $index = 0, $listName = ''): string
181
    {
182
        $result = '';
183
        if ($lineItem && $analytics) {
184
            $product = null;
185
            $purchasable = $lineItem->purchasable;
186
            //This is the same for both variant and non variant products
187
            $productData = [
188
                'name' => $purchasable->title,
189
                'sku' => $purchasable->sku,
190
                'price' => $lineItem->salePrice,
191
                'quantity' => $lineItem->qty,
192
            ];
193
            // Handle this purchasable being a Variant
194
            if (is_a($purchasable, Variant::class)) {
195
                /** @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...
196
                $product = $purchasable->getProduct();
197
                $variant = $purchasable;
198
                // Product with variants
199
                $productData['name'] = $product->title;
200
                $productData['variant'] = $variant->title;
201
                $productData['category'] = $product->getType();
202
            }
203
            // Handle this purchasable being a Product
204
            if (is_a($purchasable, Product::class)) {
205
                /** @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...
206
                $product = $purchasable;
207
                $productData['name'] = $product->title;
208
                $productData['variant'] = $product->title;
209
                $productData['category'] = $product->getType();
210
            }
211
            // Handle product lists
212
            if ($index) {
213
                $productData['position'] = $index;
214
            }
215
            if ($listName) {
216
                $productData['list'] = $listName;
217
            }
218
            // Add in any custom categories/brands that might be set
219
            if (InstantAnalytics::$settings && $product) {
220
                if (isset(InstantAnalytics::$settings['productCategoryField'])
221
                    && !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...
222
                    $productData['category'] = $this->pullDataFromField(
223
                        $product,
224
                        InstantAnalytics::$settings['productCategoryField']
225
                    );
226
                }
227
                if (isset(InstantAnalytics::$settings['productBrandField'])
228
                    && !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...
229
                    $productData['brand'] = $this->pullDataFromField(
230
                        $product,
231
                        InstantAnalytics::$settings['productBrandField']
232
                    );
233
                }
234
            }
235
            $result = $productData['name'];
236
            //Add each product to the hit to be sent
237
            $analytics->addProduct($productData);
238
        }
239
240
        return $result;
241
    }
242
243
    /**
244
     * Add a product impression from a Craft Commerce Product or Variant
245
     *
246
     * @param IAnalytics      $analytics      the Analytics object
247
     * @param Product|Variant $productVariant the Product or Variant
248
     * @param int             $index          Where the product appears in the
249
     *                                        list
250
     * @param string          $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
251
     * @param int             $listIndex
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
252
     *
253
     * @throws \yii\base\InvalidConfigException
254
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
255
    public function addCommerceProductImpression(
256
        $analytics = null,
257
        $productVariant = null,
258
        $index = 0,
259
        $listName = 'default',
260
        $listIndex = 1
261
    ) {
262
        if ($productVariant && $analytics) {
263
            $productData = $this->getProductDataFromProduct($productVariant);
264
265
            /**
266
             * As per: https://github.com/theiconic/php-ga-measurement-protocol/issues/26
267
             */
268
            if ($listName && $listIndex) {
269
                $analytics->setProductImpressionListName($listName, $listIndex);
270
            }
271
272
            if ($index) {
273
                $productData['position'] = $index;
274
            }
275
276
            //Add the product to the hit to be sent
277
            $analytics->addProductImpression($productData, $listIndex);
278
279
            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...
280
                'instant-analytics',
281
                'addCommerceProductImpression for `{sku}` - `{name}` - `{name}` - `{index}`',
282
                ['sku' => $productData['sku'], 'name' => $productData['name'], 'index' => $index]
283
            ), __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...
284
        }
285
    }
286
287
    /**
288
     * Add a product detail view from a Craft Commerce Product or Variant
289
     *
290
     * @param IAnalytics      $analytics      the Analytics object
291
     * @param Product|Variant $productVariant the Product or Variant
292
     *
293
     * @throws \yii\base\InvalidConfigException
294
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
295
    public function addCommerceProductDetailView($analytics = null, $productVariant = null)
296
    {
297
        if ($productVariant && $analytics) {
298
            $productData = $this->getProductDataFromProduct($productVariant);
299
300
            // Don't forget to set the product action, in this case to DETAIL
301
            $analytics->setProductActionToDetail();
302
303
            //Add the product to the hit to be sent
304
            $analytics->addProduct($productData);
305
306
            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...
307
                'instant-analytics',
308
                'addCommerceProductDetailView for `{sku}` - `{name} - `{name}`',
309
                ['sku' => $productData['sku'], 'name' => $productData['name']]
310
            ), __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...
311
        }
312
    }
313
314
    /**
315
     * Add a checkout step and option to an Analytics object
316
     *
317
     * @param IAnalytics $analytics the Analytics object
318
     * @param Order      $order     the Product or Variant
319
     * @param int        $step      the checkout step
320
     * @param string     $option    the checkout option
321
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
322
    public function addCommerceCheckoutStep($analytics = null, $order = null, $step = 1, $option = '')
323
    {
324
        if ($order && $analytics) {
325
            // Add each line item in the transaction
326
            // Two cases - variant and non variant products
327
            $index = 1;
328
329
            foreach ($order->lineItems as $key => $lineItem) {
330
                $this->addProductDataFromLineItem($analytics, $lineItem, $index, '');
331
                $index++;
332
            }
333
334
            $analytics->setCheckoutStep($step);
335
336
            if ($option) {
337
                $analytics->setCheckoutStepOption($option);
338
            }
339
340
            // Don't forget to set the product action, in this case to CHECKOUT
341
            $analytics->setProductActionToCheckout();
342
343
            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...
344
                'instant-analytics',
345
                'addCommerceCheckoutStep step: `{step}` with option: `{option}`',
346
                ['step' => $step, 'option' => $option]
347
            ), __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...
348
        }
349
    }
350
351
    /**
352
     * Extract product data from a Craft Commerce Product or Variant
353
     *
354
     * @param Product|Variant $productVariant the Product or Variant
355
     *
356
     * @return array the product data
357
     * @throws \yii\base\InvalidConfigException
358
     */
359
    public function getProductDataFromProduct($productVariant = null): array
360
    {
361
        $result = [];
362
363
        // Extract the variant if it's a Product or Purchasable
364
        if ($productVariant && \is_object($productVariant)) {
365
            if (is_a($productVariant, Product::class)
366
                || is_a($productVariant, Purchasable::class)
367
            ) {
368
                $productType = property_exists($productVariant, 'typeId')
369
                    ? 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

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

516
                    $result = strip_tags(/** @scrutinizer ignore-type */ $srcField);
Loading history...
517
                    break;
518
            }
519
        }
520
521
        return $result;
522
    }
523
}
524