Passed
Push — v4 ( 140115...483dd2 )
by Andrew
26:45 queued 20:28
created

Commerce::addCommerceProductListImpression()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 14
rs 9.9666
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;
17
use craft\base\Component;
18
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...
19
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...
20
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...
21
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...
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
28
/**
29
 * Commerce Service
30
 *
31
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
32
 * @package   InstantAnalytics
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
33
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
34
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
35
class Commerce extends Component
36
{
37
    // Public Methods
38
    // =========================================================================
39
40
    /**
41
     * Enqueue 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 triggerOrderCompleteEvent(Order $order = null)
46
    {
47
        if ($order) {
48
            $event = InstantAnalytics::$plugin->ga4->getAnalytics()->create()->PurchaseEvent();
49
            $this->addCommerceOrderToEvent($event, $order);
50
51
            InstantAnalytics::$plugin->ga4->getAnalytics()->addEvent($event);
52
53
            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

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

269
        $variant = $isVariant ? $productVariant : $productVariant->/** @scrutinizer ignore-call */ getDefaultVariant();

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...
270
271
        if (!$variant) {
272
            return;
273
        }
274
275
        $eventItem->setItemId($variant->sku);
276
        $eventItem->setItemName($variant->title);
277
        $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

277
        $eventItem->setPrice(/** @scrutinizer ignore-type */ number_format($variant->price, 2, '.', ''));
Loading history...
278
279
        $category = ($isVariant ? $variant->getProduct() : $productVariant)->getType()['name'];
0 ignored issues
show
Bug introduced by
The method getType() 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

279
        $category = ($isVariant ? $variant->getProduct() : $productVariant)->/** @scrutinizer ignore-call */ getType()['name'];

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...
280
281
        if (InstantAnalytics::$settings) {
282
            if (isset(InstantAnalytics::$settings['productCategoryField'])
283
                && !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...
284
                $category = $this->pullDataFromField(
285
                    $productVariant,
286
                    InstantAnalytics::$settings['productCategoryField']
287
                );
288
                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...
289
                    $category = $this->pullDataFromField(
290
                        $productVariant->product,
291
                        InstantAnalytics::$settings['productCategoryField']
292
                    );
293
                }
294
            }
295
            $eventItem->setItemCategory($category);
296
297
            if (isset(InstantAnalytics::$settings['productBrandField'])
298
                && !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...
299
                $brand = $this->pullDataFromField(
300
                    $productVariant,
301
                    InstantAnalytics::$settings['productBrandField'],
302
                    true
303
                );
304
305
                if (empty($productData['brand']) && $isVariant) {
306
                    $brand = $this->pullDataFromField(
307
                        $productVariant,
308
                        InstantAnalytics::$settings['productBrandField'],
309
                        true
310
                    );
311
                }
312
                $eventItem->setItemBrand($brand);
313
            }
314
        }
315
316
        $eventItem->setIndex($index);
317
        $eventItem->setItemListName($listName);
318
319
        // Add item info to the event
320
        $event->addItem($eventItem);
321
    }
322
323
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
324
     * @param Product|Variant|null $productVariant
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
325
     * @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...
326
     * @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...
327
     *
328
     * @return string
329
     */
330
    protected function pullDataFromField($productVariant, $fieldHandle, $isBrand = false): string
331
    {
332
        $result = '';
333
        if ($productVariant && $fieldHandle) {
334
            $srcField = $productVariant[$fieldHandle] ?? $productVariant->product[$fieldHandle] ?? null;
335
            // Handle eager loaded elements
336
            if (is_array($srcField)) {
337
                return $this->getDataFromElements($isBrand, $srcField);
338
            }
339
            // If the source field isn't an object, return nothing
340
            if (!is_object($srcField)) {
341
                return $result;
342
            }
343
            switch (\get_class($srcField)) {
344
                case MatrixBlockQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
345
                case TagQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
346
                    break;
347
                case CategoryQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
348
                case EntryQuery::class:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
349
                    $result = $this->getDataFromElements($isBrand, $srcField->all());
350
                    break;
351
352
353
                default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
354
                    $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

354
                    $result = strip_tags(/** @scrutinizer ignore-type */ $srcField);
Loading history...
355
                    break;
356
            }
357
        }
358
359
        return $result;
360
    }
361
362
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
363
     * @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...
364
     * @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...
365
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
366
     */
367
    protected function getDataFromElements(bool $isBrand, array $elements): string
368
    {
369
        $cats = [];
370
371
        if ($isBrand) {
372
            // Because we can only have one brand, we'll get
373
            // the very last category. This means if our
374
            // brand is a sub-category, we'll get the child
375
            // not the parent.
376
            foreach ($elements as $cat) {
377
                $cats = [$cat->title];
378
            }
379
        } else {
380
            // For every category, show its ancestors
381
            // delimited by a slash.
382
            foreach ($elements as $cat) {
383
                $name = $cat->title;
384
385
                while ($cat = $cat->parent) {
386
                    $name = $cat->title . '/' . $name;
387
                }
388
389
                $cats[] = $name;
390
            }
391
        }
392
393
        // Join separate categories with a pipe.
394
        return implode('|', $cats);
395
    }
396
397
    /**
398
     * Create an item parameter and set affiliation on it, if any exists.
399
     *
400
     * @return ItemParameter
401
     */
402
    protected function getNewItemParameter(): ItemParameter
403
    {
404
        $parameter = new ItemParameter();
405
        $parameter->setAffiliation(InstantAnalytics::$plugin->ga4->getAnalytics()->getAffiliation());
406
        return $parameter;
407
    }
408
}
409