Skip to content

Commit

Permalink
Normalize token names but keep original ones
Browse files Browse the repository at this point in the history
  • Loading branch information
Toflar committed Jan 15, 2025
1 parent a1ddb2c commit 5840fb8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/Token/TokenCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,12 @@ public function addToken(Token $token): self
public function forSimpleTokenParser(): array
{
$data = [];
$normalized = [];

/** @var Token $token */
foreach ($this as $token) {
$data[$token->getName()] = $token->getParserValue();

// Replace everything that's not allowed from the beginning of a string (PHP
// variables cannot start with numbers for example)
$tokenName = preg_replace_callback(
Expand All @@ -84,7 +87,15 @@ static function (array $matches) {
(string) $tokenName,
);

$data[$tokenName] = $token->getParserValue();
if ($tokenName !== $token->getName()) {
$normalized[$tokenName] = $token->getParserValue();
}
}

foreach ($normalized as $tokenName => $value) {
if (!isset($data[$tokenName])) {
$data[$tokenName] = $value;
}
}

return $data;
Expand Down
7 changes: 6 additions & 1 deletion tests/Token/TokenCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,16 @@ public function testInvalidParserTokenNamesAreNormalized(): void
{
$tokenCollection = new TokenCollection();
$tokenCollection->add(Token::fromValue('invalid-because-of-dashes', 'foobar'));
$tokenCollection->add(Token::fromValue('invalid_because_of_dashes', 'foobar2'));
$tokenCollection->add(Token::fromValue('123invalid_because_of_numbers_at_the_start', 'foobar'));
$tokenCollection->add(Token::fromValue('1234-', 'foobar'));

$this->assertSame(
[
'invalid_because_of_dashes' => 'foobar',
'invalid-because-of-dashes' => 'foobar',
'invalid_because_of_dashes' => 'foobar2',
'123invalid_because_of_numbers_at_the_start' => 'foobar',
'1234-' => 'foobar',
'___invalid_because_of_numbers_at_the_start' => 'foobar',
'_____' => 'foobar',
],
Expand All @@ -121,6 +125,7 @@ public function testInvalidParserTokenNamesAreNormalized(): void
$this->assertSame(
[
'invalid-because-of-dashes' => 'foobar',
'invalid_because_of_dashes' => 'foobar2',
'123invalid_because_of_numbers_at_the_start' => 'foobar',
'1234-' => 'foobar',
],
Expand Down

0 comments on commit 5840fb8

Please sign in to comment.