Skip to content

Commit 584c9da

Browse files
author
Alex Westergaard
committed
Add arrayAccess, update types minor changes
1 parent 02adcfc commit 584c9da

File tree

8 files changed

+146
-69
lines changed

8 files changed

+146
-69
lines changed

src/Analytics.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ public function setUserId(string $id)
8484
/**
8585
* @param int|float $microOrUnix time() or microtime(true)
8686
*/
87-
public function setTimestamp($microOrUnix)
87+
public function setTimestamp(int|float $microOrUnix)
8888
{
8989
$secondInMicro = intval(strtr('1_000_000', ['_' => '']));
9090
$offsetLimit = strtotime('-3 days') * $secondInMicro;

src/Event/Refund.php

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,6 @@ class Refund extends Model\Event implements Facade\Refund
2222
/**
2323
* Full refunds does not require items to be passed. \
2424
* This will skip the items check if true
25-
*
26-
* @param boolean $is
27-
* @return static
2825
*/
2926
public function isFullRefund(bool $is)
3027
{

src/Helper/Helper.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
3+
namespace AlexWestergaard\PhpGa4\Helper;
4+
5+
class Helper
6+
{
7+
/** @return array<int,string> */
8+
public const RESERVED_EVENT_NAMES = [
9+
'ad_activeview',
10+
'ad_click',
11+
'ad_exposure',
12+
'ad_impression',
13+
'ad_query',
14+
'adunit_exposure',
15+
'app_clear_data',
16+
'app_install',
17+
'app_update',
18+
'app_remove',
19+
'error',
20+
'first_open',
21+
'first_visit',
22+
'in_app_purchase',
23+
'notification_dismiss',
24+
'notification_foreground',
25+
'notification_open',
26+
'notification_receive',
27+
'os_update',
28+
'screen_view',
29+
'session_start',
30+
'user_engagement',
31+
];
32+
33+
/** @return array<int,string> */
34+
public const RESERVED_USER_PROPERTY_NAMES = [
35+
'first_open_time',
36+
'first_visit_time',
37+
'last_deep_link_referrer',
38+
'user_id',
39+
'first_open_after_install',
40+
];
41+
42+
/**
43+
* @param string $input
44+
* @return string snake_case
45+
*/
46+
public static function snake(string $input)
47+
{
48+
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $input));
49+
}
50+
51+
/**
52+
* @param string $input
53+
* @return string CamelCase
54+
*/
55+
public static function camel(string $input)
56+
{
57+
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $input))));
58+
}
59+
}

src/Item.php

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,8 @@ public function setCurrency(string $iso)
5656
return $this;
5757
}
5858

59-
/**
60-
* @param int|float $amount
61-
*/
62-
public function setDiscount($amount)
59+
public function setDiscount(int|float $amount)
6360
{
64-
if (!is_numeric($amount)) {
65-
throw new GA4Exception("setDiscount value must be numeric");
66-
}
67-
6861
$this->discount = $amount;
6962
return $this;
7063
}
@@ -111,15 +104,8 @@ public function setLocationId(string $id)
111104
return $this;
112105
}
113106

114-
/**
115-
* @param int|float $amount
116-
*/
117-
public function setPrice($amount)
107+
public function setPrice(int|float $amount)
118108
{
119-
if (!is_numeric($amount)) {
120-
throw new GA4Exception("setPrice value must be numeric");
121-
}
122-
123109
$this->price = 0 + $amount;
124110
return $this;
125111
}
@@ -191,14 +177,12 @@ public static function fromArray(array $params = [])
191177
return $item;
192178
}
193179

194-
/**
195-
* @param GA4Exception $childErrors
196-
*/
197-
public function toArray(bool $isParent = false, $childErrors = null): array
180+
public function toArray(bool $isParent = false, GA4Exception|null $childErrors = null): array
198181
{
199182
if (!($childErrors instanceof GA4Exception) && $childErrors !== null) {
200183
throw new GA4Exception("$childErrors is neither NULL of instance of GA4Exception");
201184
}
185+
202186
$return = parent::toArray($isParent, $childErrors);
203187

204188
if (isset($return['item_category'])) {

src/Model/Event.php

Lines changed: 58 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
namespace AlexWestergaard\PhpGa4\Model;
44

5+
use ArrayAccess;
56
use AlexWestergaard\PhpGa4\Facade;
67
use AlexWestergaard\PhpGa4\GA4Exception;
8+
use AlexWestergaard\PhpGa4\Helper\Helper;
79

8-
abstract class Event extends ToArray implements Facade\Export
10+
abstract class Event extends ToArray implements Facade\Export, ArrayAccess
911
{
1012
private $debug = false;
1113

@@ -19,10 +21,60 @@ abstract public function getName(): string;
1921
public function debug($on = true)
2022
{
2123
$this->debug = boolval($on);
22-
24+
2325
return $this;
2426
}
2527

28+
public function offsetExists(mixed $offset): bool
29+
{
30+
return property_exists($this, Helper::snake($offset));
31+
}
32+
33+
public function offsetGet(mixed $offset): mixed
34+
{
35+
$callable = Helper::snake($offset);
36+
return $this->offsetExists($callable) ? $this->$callable : null;
37+
}
38+
39+
public function offsetSet(mixed $offset, mixed $value): void
40+
{
41+
$callable = Helper::camel($offset);
42+
if ($this->offsetExists($offset)) {
43+
$this->$callable = $value;
44+
if (method_exists($this, ($method = 'add' . $callable))) {
45+
$this->$method($value);
46+
} elseif (method_exists($this, ($method = 'set' . $callable))) {
47+
$this->$method($value);
48+
}
49+
50+
if (is_array($value)) {
51+
$callable = substr($callable, -1) === 's' ? substr($callable, 0, -1) : $callable;
52+
53+
foreach ($value as $paramRow) {
54+
if (method_exists($this, ($method = 'add' . $callable))) {
55+
$this->$method($paramRow);
56+
} elseif (method_exists($this, ($method = 'set' . $callable))) {
57+
$this->$method($paramRow);
58+
}
59+
}
60+
} else {
61+
if (method_exists($this, ($method = 'add' . $callable))) {
62+
$this->$method($value);
63+
} elseif (method_exists($this, ($method = 'set' . $callable))) {
64+
$this->$method($value);
65+
}
66+
}
67+
}
68+
}
69+
70+
public function offsetUnset(mixed $offset): void
71+
{
72+
$var = Helper::snake($offset);
73+
if ($this->offsetExists($offset)) {
74+
$this->$var = null;
75+
}
76+
}
77+
2678
/**
2779
* @param GA4Exception $childErrors
2880
*/
@@ -31,7 +83,7 @@ public function toArray(bool $isParent = false): array
3183
$return = [];
3284

3385
if (!method_exists($this, 'getName')) {
34-
GA4Exception::push("'self::getName()' does not exist");
86+
GA4Exception::push("'getName()' does not exist");
3587
} else {
3688
$name = $this->getName();
3789
if (empty($name)) {
@@ -40,30 +92,7 @@ public function toArray(bool $isParent = false): array
4092
GA4Exception::push("Name '{$name}' can not be longer than 40 characters");
4193
} elseif (preg_match('/[^\w\d\-]/', $name)) {
4294
GA4Exception::push("Name '{$name}' can only be letters, numbers, underscores and dashes");
43-
} elseif (in_array($name, [
44-
'ad_activeview',
45-
'ad_click',
46-
'ad_exposure',
47-
'ad_impression',
48-
'ad_query',
49-
'adunit_exposure',
50-
'app_clear_data',
51-
'app_install',
52-
'app_update',
53-
'app_remove',
54-
'error',
55-
'first_open',
56-
'first_visit',
57-
'in_app_purchase',
58-
'notification_dismiss',
59-
'notification_foreground',
60-
'notification_open',
61-
'notification_receive',
62-
'os_update',
63-
'screen_view',
64-
'session_start',
65-
'user_engagement',
66-
])) {
95+
} elseif (in_array($name, Helper::RESERVED_EVENT_NAMES)) {
6796
GA4Exception::push("Name '{$name}' is reserved");
6897
} else {
6998
$return['name'] = $name;
@@ -98,7 +127,7 @@ public static function fromArray(array $params = [])
98127
continue;
99128
}
100129

101-
$callableName = implode('', array_map('ucfirst', explode('_', $insertable)));
130+
$callableName = Helper::camel($insertable);
102131

103132
if (is_array($param)) {
104133
$callableName = substr($callableName, -1) === 's' ? substr($callableName, 0, -1) : $callableName;
@@ -117,6 +146,7 @@ public static function fromArray(array $params = [])
117146
}
118147
}
119148
}
149+
120150
return $event;
121151
}
122152

src/Model/ToArray.php

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,15 @@
22

33
namespace AlexWestergaard\PhpGa4\Model;
44

5-
use AlexWestergaard\PhpGa4\GA4Exception;
65
use AlexWestergaard\PhpGa4\Facade;
6+
use AlexWestergaard\PhpGa4\GA4Exception;
77

88
abstract class ToArray implements Facade\Export
99
{
1010
abstract public function getParams(): array;
1111

1212
abstract public function getRequiredParams(): array;
1313

14-
/**
15-
* @param GA4Exception $childErrors
16-
*/
1714
public function toArray(bool $isParent = false): array
1815
{
1916
$return = [];

src/UserProperty.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace AlexWestergaard\PhpGa4;
44

55
use AlexWestergaard\PhpGa4\Facade;
6+
use AlexWestergaard\PhpGa4\Helper\Helper;
67

78
class UserProperty implements Facade\Export
89
{
@@ -12,13 +13,7 @@ class UserProperty implements Facade\Export
1213
public function setName(string $name)
1314
{
1415
if (
15-
in_array($name, [
16-
'first_open_time',
17-
'first_visit_time',
18-
'last_deep_link_referrer',
19-
'user_id',
20-
'first_open_after_install',
21-
])
16+
in_array($name, Helper::RESERVED_USER_PROPERTY_NAMES)
2217
|| substr($name, 0, 9) == 'firebase_'
2318
|| substr($name, 0, 7) == 'google_'
2419
|| substr($name, 0, 4) == 'ga_'

test/AnalyticsTest.php

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public function testItem()
6767
$this->assertInstanceOf(Item::class, $this->item);
6868

6969
$arr = $this->item->toArray();
70-
$this->assertTrue(is_array($arr));
70+
$this->assertIsArray($arr);
7171
$this->assertArrayHasKey('item_id', $arr);
7272
$this->assertArrayHasKey('item_name', $arr);
7373
$this->assertArrayHasKey('currency', $arr);
@@ -88,7 +88,7 @@ public function testItemFromArray()
8888
$this->assertInstanceOf(Item::class, $item);
8989

9090
$arr = $item->toArray();
91-
$this->assertTrue(is_array($arr));
91+
$this->assertIsArray($arr);
9292
$this->assertArrayHasKey('item_id', $arr);
9393
$this->assertArrayHasKey('item_name', $arr);
9494
$this->assertArrayHasKey('currency', $arr);
@@ -103,7 +103,7 @@ public function testUserProperty()
103103
->setValue('premium');
104104

105105
$this->assertInstanceOf(UserProperty::class, $userProperty);
106-
$this->assertTrue(is_array($userProperty->toArray()));
106+
$this->assertIsArray($userProperty->toArray());
107107

108108
$this->analytics->addUserProperty($userProperty);
109109

@@ -132,7 +132,7 @@ public function testPartialRefundWithItems()
132132
$this->analytics->addEvent($refund);
133133

134134
$arr = $this->analytics->toArray();
135-
$this->assertTrue(is_array($arr));
135+
$this->assertIsArray($arr);
136136

137137
$arr = $refund->toArray();
138138
$this->assertArrayHasKey('params', $arr);
@@ -239,7 +239,7 @@ public function testPrebuildEvents()
239239
$event->setGroupId('999');
240240
}
241241

242-
$this->assertTrue(is_array($event->toArray()), $eventName);
242+
$this->assertIsArray($event->toArray(), $eventName);
243243

244244
$this->analytics->addEvent($event);
245245
}
@@ -263,9 +263,24 @@ public function testBuildEventFromArray()
263263
'items' => [$this->item],
264264
]);
265265

266-
$this->assertTrue(is_array($event->toArray()), get_class($event));
266+
$this->assertIsArray($event->toArray(), get_class($event));
267267

268268
$this->analytics->addEvent($event);
269269
$this->assertTrue($this->analytics->post());
270270
}
271+
272+
public function testEventArrayable()
273+
{
274+
$event = new Event\AddToCart();
275+
$event['currency'] = $this->prefill['currency'];
276+
$event['value'] = ($value = rand(1000, 10000) / 100);
277+
278+
$this->assertArrayHasKey('currency', $event);
279+
$this->assertArrayHasKey('value', $event);
280+
$this->assertArrayHasKey('items', $event);
281+
282+
$this->assertEquals($this->prefill['currency'], $event['currency']);
283+
$this->assertEquals($value, $event['value']);
284+
$this->assertIsArray($event['items']);
285+
}
271286
}

0 commit comments

Comments
 (0)