Passed
Push — v4 ( 483dd2...9bab8e )
by Andrew
15:49 queued 09:35
created

Commerce   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 409
Duplicated Lines 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 174
c 6
b 1
f 0
dl 0
loc 409
rs 4.08
wmc 59

12 Methods

Rating   Name   Duplication   Size   Complexity  
A triggerOrderCompleteEvent() 0 12 2
A addCommerceProductListImpression() 0 14 3
B pullDataFromField() 0 30 9
A addCommerceOrderToEvent() 0 21 3
A getDataFromElements() 0 28 5
A addCommerceProductImpression() 0 14 4
C addProductDataFromProductOrVariant() 0 66 16
A getNewItemParameter() 0 5 1
B addProductDataFromLineItem() 0 66 11
A triggerAddToCartEvent() 0 10 1
A triggerRemoveFromCartEvent() 0 10 1
A triggerBeginCheckoutEvent() 0 21 3

How to fix   Complexity   

Complex Class

Complex classes like Commerce often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Commerce, and based on these observations, apply Extract Interface, too.

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

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

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

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