Passed
Push — develop-v4 ( 6b7cab...de824e )
by Andrew
05:17 queued 13s
created

Commerce::triggerBeginCheckoutEvent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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