From 656e759e8ad11062d88112d6747d9aa96b19b996 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Fri, 8 Sep 2023 19:45:13 +0100 Subject: [PATCH] Fix broken code that assumes array keys are strings (#120) Fix broken code that assumes array keys are strings see #119 --- uri/UriTemplate/Expression.php | 10 ++++++---- uri/UriTemplate/Template.php | 16 ++++++++-------- uri/UriTemplate/TemplateTest.php | 4 ++-- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/uri/UriTemplate/Expression.php b/uri/UriTemplate/Expression.php index 449efec8..5eb0e3a1 100644 --- a/uri/UriTemplate/Expression.php +++ b/uri/UriTemplate/Expression.php @@ -37,10 +37,12 @@ final class Expression private function __construct(public readonly Operator $operator, VarSpecifier ...$varSpecifiers) { $this->varSpecifiers = $varSpecifiers; - $this->variableNames = array_keys(array_fill_keys( - array_map(static fn (VarSpecifier $varSpecifier): string => $varSpecifier->name, $varSpecifiers), - 1 - )); + $this->variableNames = array_unique( + array_map( + static fn (VarSpecifier $varSpecifier): string => $varSpecifier->name, + $varSpecifiers + ) + ); $this->value = '{'.$operator->value.implode(',', array_map( static fn (VarSpecifier $varSpecifier): string => $varSpecifier->toString(), $varSpecifiers diff --git a/uri/UriTemplate/Template.php b/uri/UriTemplate/Template.php index 35f52417..471665da 100644 --- a/uri/UriTemplate/Template.php +++ b/uri/UriTemplate/Template.php @@ -43,14 +43,14 @@ final class Template implements Stringable private function __construct(public readonly string $value, Expression ...$expressions) { $this->expressions = $expressions; - $this->variableNames = array_keys(array_reduce( - $expressions, - fn (array $curry, Expression $expression): array => [ - ...$curry, - ...array_fill_keys($expression->variableNames, 1), - ], - [] - )); + $this->variableNames = array_unique( + array_merge( + ...array_map( + static fn (Expression $expression): array => $expression->variableNames, + $expressions + ) + ) + ); } /** diff --git a/uri/UriTemplate/TemplateTest.php b/uri/UriTemplate/TemplateTest.php index 1d425fc5..6f01c8dc 100644 --- a/uri/UriTemplate/TemplateTest.php +++ b/uri/UriTemplate/TemplateTest.php @@ -144,8 +144,8 @@ public static function expectedVariableNames(): iterable 'expected' => [], ], [ - 'template' => '{foo}{bar}', - 'expected' => ['foo', 'bar'], + 'template' => '{foo}{bar}{420}', + 'expected' => ['foo', 'bar', '420'], ], [ 'template' => '{foo}{foo:2}{+foo}',