diff --git a/src/Helper/EventHelper.php b/src/Helper/EventHelper.php index e68daaf..baa111e 100644 --- a/src/Helper/EventHelper.php +++ b/src/Helper/EventHelper.php @@ -73,7 +73,7 @@ public function toArray(): array throw Ga4EventException::throwNameMissing(); } elseif (strlen($name) > 40) { throw Ga4EventException::throwNameTooLong(); - } elseif (preg_match('/[^\w\d\-]/', $name)) { + } elseif (preg_match('/[^\w\d\-]|^\-|\-$/', $name)) { throw Ga4EventException::throwNameInvalid(); } elseif (in_array($name, EventType::RESERVED_NAMES) && !($this instanceof GtmEventType)) { throw Ga4EventException::throwNameReserved($name); diff --git a/test/Unit/EventTest.php b/test/Unit/EventTest.php index d02738a..80c8b82 100644 --- a/test/Unit/EventTest.php +++ b/test/Unit/EventTest.php @@ -679,6 +679,42 @@ public function getName(): string $class->toArray(); } + public function test_throw_name_invalid_starting_line() + { + $mock = new class extends Event\Refund + { + public function getName(): string + { + return '-almost-valid-name'; + } + }; + + $class = $mock::new()->setTransactionId(1); + + $this->expectException(Ga4EventException::class); + $this->expectExceptionCode(Ga4Exception::EVENT_NAME_INVALID); + + $class->toArray(); + } + + public function test_throw_name_invalid_ending_line() + { + $mock = new class extends Event\Refund + { + public function getName(): string + { + return 'almost-valid-name-'; + } + }; + + $class = $mock::new()->setTransactionId(1); + + $this->expectException(Ga4EventException::class); + $this->expectExceptionCode(Ga4Exception::EVENT_NAME_INVALID); + + $class->toArray(); + } + public function test_throw_name_reserved() { $mock = new class extends Event\Refund