Passed
Push — develop-v3 ( 2011c7...a56f50 )
by Andrew
09:00
created

Commerce::addProductDataFromLineItem()   B

Complexity

Conditions 11
Paths 80

Size

Total Lines 66
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 37
nc 80
nop 4
dl 0
loc 66
rs 7.3166
c 0
b 0
f 0

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

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

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

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