Passed
Push — develop-v3 ( 3380dd...b9b839 )
by Andrew
09:26 queued 04:44
created

Commerce::addProductDataFromLineItem()   C

Complexity

Conditions 12
Paths 160

Size

Total Lines 71
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 12
eloc 41
c 3
b 1
f 0
nc 160
nop 4
dl 0
loc 71
rs 6.4666

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
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\instantanalyticsGa4\services;
12
13
use Br33f\Ga4\MeasurementProtocol\Dto\Event\ItemBaseEvent;
14
use Br33f\Ga4\MeasurementProtocol\Dto\Event\PurchaseEvent;
15
use Br33f\Ga4\MeasurementProtocol\Dto\Parameter\ItemParameter;
16
use craft\base\Component;
17
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...
18
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...
19
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...
20
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...
21
use craft\commerce\Plugin as CommercePlugin;
0 ignored issues
show
Bug introduced by
The type craft\commerce\Plugin was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
22
use craft\elements\db\CategoryQuery;
23
use craft\elements\db\EntryQuery;
24
use craft\elements\db\MatrixBlockQuery;
25
use craft\elements\db\TagQuery;
26
use nystudio107\instantanalyticsGa4\InstantAnalytics;
27
use yii\base\InvalidConfigException;
28
use function get_class;
29
30
/**
31
 * Commerce Service
32
 *
33
 * @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...
34
 * @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...
35
 * @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...
36
 */
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...
37
class Commerce extends Component
38
{
39
    // Public Methods
40
    // =========================================================================
41
42
    /**
43
     * Enqueue analytics information for the completed order
44
     *
45
     * @param ?Order $order the Product or Variant
46
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
47
    public function triggerOrderCompleteEvent(Order $order = null)
48
    {
49
        if ($order) {
50
            $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->PurchaseEvent();
51
            $this->addCommerceOrderToEvent($event, $order);
52
53
            InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
54
55
            InstantAnalytics::$plugin->logAnalyticsEvent(
0 ignored issues
show
Bug introduced by
The method logAnalyticsEvent() 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

55
            InstantAnalytics::$plugin->/** @scrutinizer ignore-call */ 
56
                                       logAnalyticsEvent(

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...
56
                'Adding `Commerce - Order Complete event`: `{reference}` => `{price}`',
57
                ['reference' => $order->reference, 'price' => $order->totalPrice],
58
                __METHOD__
59
            );
60
        }
61
    }
62
63
    /**
64
     * Enqueue analytics information for a new checkout flow
65
     *
66
     * @param ?Order $order
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
67
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
68
    public function triggerBeginCheckoutEvent(Order $order = null)
69
    {
70
        if ($order) {
71
            $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->BeginCheckoutEvent();
72
            // First, include the transaction data
73
            $event->setCurrency($order->getPaymentCurrency())
74
                ->setValue($order->getTotalPrice());
75
76
            // Add each line item in the cart
77
            $index = 1;
78
            foreach ($order->lineItems as $lineItem) {
79
                $this->addProductDataFromLineItem($event, $lineItem, $index);
80
                $index++;
81
            }
82
83
            InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
84
85
            InstantAnalytics::$plugin->logAnalyticsEvent(
86
                'Adding `Commerce - Begin Checkout event``',
87
                [],
88
                __METHOD__
89
            );
90
        }
91
    }
92
93
    /**
94
     * Send analytics information for the item added to the cart
95
     *
96
     * @param LineItem $lineItem the line item that was added
97
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
98
    public function triggerAddToCartEvent(LineItem $lineItem): void
99
    {
100
        $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->AddToCartEvent();
101
        $this->addProductDataFromLineItem($event, $lineItem);
102
        InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
103
104
        InstantAnalytics::$plugin->logAnalyticsEvent(
105
            'Adding `Commerce - Add to Cart event`: `{title}` => `{quantity}`',
106
            ['title' => $lineItem->purchasable->title ?? $lineItem->getDescription(), 'quantity' => $lineItem->qty],
107
            __METHOD__
108
        );
109
    }
110
111
    /**
112
     * Send analytics information for the item removed from the cart
113
     *
114
     * @param LineItem $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
115
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
116
    public function triggerRemoveFromCartEvent(LineItem $lineItem)
117
    {
118
        $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->RemoveFromCartEvent();
119
        $this->addProductDataFromLineItem($event, $lineItem);
120
        InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
121
122
        InstantAnalytics::$plugin->logAnalyticsEvent(
123
            'Adding `Commerce - Remove from Cart event`: `{title}` => `{quantity}`',
124
            ['title' => $lineItem->purchasable->title ?? $lineItem->getDescription(), 'quantity' => $lineItem->qty],
125
            __METHOD__
126
        );
127
    }
128
129
130
    /**
131
     * Add a Craft Commerce OrderModel to a Purchase Event
132
     *
133
     * @param PurchaseEvent $event The PurchaseEvent
134
     * @param Order $order
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
135
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
136
    protected function addCommerceOrderToEvent(PurchaseEvent $event, Order $order)
137
    {
138
        // First, include the transaction data
139
        $event->setCurrency($order->getPaymentCurrency())
140
            ->setTransactionId($order->reference)
141
            ->setValue($order->getTotalPrice())
142
            ->setTax($order->getTotalTax())
143
            ->setShipping($order->getTotalShippingCost());
144
145
        // Coupon code
146
        if ($order->couponCode) {
147
            $event->setCoupon($order->couponCode);
148
        }
149
150
        // Add each line item in the transaction
151
        // Two cases - variant and non variant products
152
        $index = 1;
153
154
        foreach ($order->lineItems as $lineItem) {
155
            $this->addProductDataFromLineItem($event, $lineItem, $index);
156
            $index++;
157
        }
158
    }
159
160
    /**
161
     * Add a Craft Commerce LineItem to an Analytics object
162
     *
163
     * @param ItemBaseEvent $event
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
164
     * @param LineItem $lineItem
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
165
     * @param int $index
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
166
     * @param string $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
167
     *
168
     * @return string the title of the product
169
     * @throws InvalidConfigException
170
     */
171
    protected function addProductDataFromLineItem(ItemBaseEvent $event, LineItem $lineItem, int $index = 0, string $listName = ''): string
172
    {
173
        $eventItem = $this->getNewItemParameter();
174
175
        $product = null;
176
        $purchasable = $lineItem->purchasable;
177
178
        if ($purchasable === null) {
179
            $eventItem->setItemName($lineItem->getDescription());
180
            $eventItem->setItemId($lineItem->getSku());
181
        } else {
182
            $eventItem->setItemName($purchasable->title ?? $lineItem->getDescription());
183
            $eventItem->setItemId($purchasable->getSku() ?? $lineItem->getSku());
184
        }
185
        $eventItem->setPrice($lineItem->salePrice);
186
        $eventItem->setQuantity($lineItem->qty);
187
188
        // Handle this purchasable being a Variant
189
        if (is_a($purchasable, Variant::class)) {
190
            /** @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...
191
            $product = $purchasable->getProduct();
192
            $variant = $purchasable;
193
            // Product with variants
194
            $eventItem->setItemName($product->title);
195
            $eventItem->setItemVariant($variant->title);
196
            $eventItem->setItemCategory($product->getType());
197
        }
198
199
        // Handle this purchasable being a Product
200
        if (is_a($purchasable, Product::class)) {
201
            /** @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...
202
            $product = $purchasable;
203
            $eventItem->setItemName($product->title);
204
            $eventItem->setItemVariant($product->title);
205
            $eventItem->setItemCategory($product->getType());
206
        }
207
208
        // Handle product lists
209
        if ($index) {
210
            $eventItem->setIndex($index);
211
        }
212
213
        if ($listName) {
214
            $eventItem->setItemListName($listName);
215
        }
216
217
        // Add in any custom categories/brands that might be set
218
        if (InstantAnalytics::$settings && $product) {
219
            if (isset(InstantAnalytics::$settings['productCategoryField'])
220
                && !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...
221
                $category = $this->pullDataFromField(
222
                    $product,
223
                    InstantAnalytics::$settings['productCategoryField']
224
                );
225
                $eventItem->setItemCategory($category);
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
                $brand = $this->pullDataFromField(
230
                    $product,
231
                    InstantAnalytics::$settings['productBrandField']
232
                );
233
234
                $eventItem->setItemBrand($brand);
235
            }
236
        }
237
238
        //Add each product to the hit to be sent
239
        $event->addItem($eventItem);
240
241
        return $eventItem->getItemName();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $eventItem->getItemName() could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
242
    }
243
244
    /**
245
     * Add a product impression from a Craft Commerce Product or Variant
246
     *
247
     * @param Product|Variant $productVariant the Product or Variant
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
248
     * @throws InvalidConfigException
0 ignored issues
show
Coding Style introduced by
Tag @throws cannot be grouped with parameter tags in a doc comment
Loading history...
249
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
250
    public function addCommerceProductImpression($productVariant): void
251
    {
252
        if ($productVariant) {
253
            $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->ViewItemEvent();
254
            $this->addProductDataFromProductOrVariant($event, $productVariant);
255
256
            InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
257
258
            $sku = $productVariant instanceof Product ? $productVariant->getDefaultVariant()->sku : $productVariant->sku;
259
            $name = $productVariant instanceof Product ? $productVariant->getName() : $productVariant->getProduct()->getName();
260
            InstantAnalytics::$plugin->logAnalyticsEvent(
261
                'Adding view item event for `{sku}` - `{name}` - `{name}` - `{index}`',
262
                ['sku' => $sku, 'name' => $name],
263
                __METHOD__
264
            );
265
        }
266
    }
267
268
    /**
269
     * Add a product list impression from a Craft Commerce Product or Variant list
270
     *
271
     * @param Product[]|Variant[] $products
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
272
     * @param string $listName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
273
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
274
    public function addCommerceProductListImpression(array $products, string $listName = 'default'): void
275
    {
276
        if (!empty($products)) {
277
            $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->ViewItemListEvent();
278
            foreach ($products as $index => $productVariant) {
279
                $this->addProductDataFromProductOrVariant($event, $productVariant, $index, $listName);
280
            }
281
282
            InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
283
284
            InstantAnalytics::$plugin->logAnalyticsEvent(
285
                'Adding view item list event. Listing {number} of items from the `{listName}` list.',
286
                ['number' => count($products), 'listName' => $listName],
287
                __METHOD__
288
            );
289
        }
290
    }
291
292
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $event should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $index should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $listName should have a doc-comment as per coding-style.
Loading history...
293
     * Extract product data from a Craft Commerce Product or Variant
294
     *
295
     * @param Product|Variant|null $productVariant the Product or Variant
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $productVariant does not match actual variable name $event
Loading history...
296
     *
297
     * @throws InvalidConfigException
298
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
299
    protected function addProductDataFromProductOrVariant(ItemBaseEvent $event, $productVariant = null, $index = null, $listName = ''): void
300
    {
301
        if ($productVariant === null) {
302
            return;
303
        }
304
305
        $eventItem = $this->getNewItemParameter();
306
307
        $isVariant = $productVariant instanceof Variant;
308
        $variant = $isVariant ? $productVariant : $productVariant->getDefaultVariant();
309
310
        if (!$variant) {
311
            return;
312
        }
313
314
        $eventItem->setItemId($variant->sku);
315
        $eventItem->setItemName($variant->title);
316
        $eventItem->setPrice(number_format($variant->price, 2, '.', ''));
0 ignored issues
show
Bug introduced by
number_format($variant->price, 2, '.', '') of type string is incompatible with the type double|null expected by parameter $price of Br33f\Ga4\MeasurementPro...emParameter::setPrice(). ( Ignorable by Annotation )

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

316
        $eventItem->setPrice(/** @scrutinizer ignore-type */ number_format($variant->price, 2, '.', ''));
Loading history...
317
318
        $category = ($isVariant ? $variant->getProduct() : $productVariant)->getType()['name'];
319
320
        if (InstantAnalytics::$settings) {
321
            if (isset(InstantAnalytics::$settings['productCategoryField'])
322
                && !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...
323
                $category = $this->pullDataFromField(
324
                    $productVariant,
325
                    InstantAnalytics::$settings['productCategoryField']
326
                );
327
                if (empty($productData['category']) && $isVariant) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $productData does not exist. Did you maybe mean $productVariant?
Loading history...
328
                    $category = $this->pullDataFromField(
329
                        $productVariant->product,
330
                        InstantAnalytics::$settings['productCategoryField']
331
                    );
332
                }
333
            }
334
            $eventItem->setItemCategory($category);
335
336
            if (isset(InstantAnalytics::$settings['productBrandField'])
337
                && !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...
338
                $brand = $this->pullDataFromField(
339
                    $productVariant,
340
                    InstantAnalytics::$settings['productBrandField'],
341
                    true
342
                );
343
344
                if (empty($productData['brand']) && $isVariant) {
345
                    $brand = $this->pullDataFromField(
346
                        $productVariant,
347
                        InstantAnalytics::$settings['productBrandField'],
348
                        true
349
                    );
350
                }
351
                $eventItem->setItemBrand($brand);
352
            }
353
        }
354
355
        if ($index !== null) {
356
            $eventItem->setIndex($index);
357
        }
358
359
        if (!empty($listName)) {
360
            $eventItem->setItemListName($listName);
361
        }
362
363
        // Add item info to the event
364
        $event->addItem($eventItem);
365
    }
366
367
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
368
     * @param Product|Variant|null $productVariant
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
369
     * @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...
370
     * @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...
371
     *
372
     * @return string
373
     */
374
    protected function pullDataFromField($productVariant, $fieldHandle, $isBrand = false): string
375
    {
376
        $result = '';
377
        if ($productVariant && $fieldHandle) {
378
            $srcField = $productVariant[$fieldHandle] ?? $productVariant->product[$fieldHandle] ?? null;
379
            // Handle eager loaded elements
380
            if (is_array($srcField)) {
381
                return $this->getDataFromElements($isBrand, $srcField);
382
            }
383
            // If the source field isn't an object, return nothing
384
            if (!is_object($srcField)) {
385
                return $result;
386
            }
387
            switch (get_class($srcField)) {
388
                case MatrixBlockQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
389
                case TagQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
390
                    break;
391
                case CategoryQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
392
                case EntryQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
393
                    $result = $this->getDataFromElements($isBrand, $srcField->all());
394
                    break;
395
396
397
                default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
398
                    $result = strip_tags($srcField);
0 ignored issues
show
Bug introduced by
$srcField of type object is incompatible with the type string expected by parameter $string 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

398
                    $result = strip_tags(/** @scrutinizer ignore-type */ $srcField);
Loading history...
399
                    break;
400
            }
401
        }
402
403
        return $result;
404
    }
405
406
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
407
     * @param bool $isBrand
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
408
     * @param array $elements
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
409
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
410
     */
411
    protected function getDataFromElements(bool $isBrand, array $elements): string
412
    {
413
        $cats = [];
414
415
        if ($isBrand) {
416
            // Because we can only have one brand, we'll get
417
            // the very last category. This means if our
418
            // brand is a sub-category, we'll get the child
419
            // not the parent.
420
            foreach ($elements as $cat) {
421
                $cats = [$cat->title];
422
            }
423
        } else {
424
            // For every category, show its ancestors
425
            // delimited by a slash.
426
            foreach ($elements as $cat) {
427
                $name = $cat->title;
428
429
                while ($cat = $cat->parent) {
430
                    $name = $cat->title . '/' . $name;
431
                }
432
433
                $cats[] = $name;
434
            }
435
        }
436
437
        // Join separate categories with a pipe.
438
        return implode('|', $cats);
439
    }
440
441
    /**
442
     * Create an item parameter and set affiliation on it, if any exists.
443
     *
444
     * @return ItemParameter
445
     */
446
    protected function getNewItemParameter(): ItemParameter
447
    {
448
        $parameter = new ItemParameter();
449
        $parameter->setAffiliation(InstantAnalytics::$plugin->ga4->getAnalytics()->getAffiliation());
450
        $parameter->setCurrency(CommercePlugin::getInstance()->getPaymentCurrencies()->getPrimaryPaymentCurrencyIso());
451
452
        return $parameter;
453
    }
454
}
455