From 1905be167964648961779cb87647764177c871b4 Mon Sep 17 00:00:00 2001 From: Piotr Olaszewski Date: Tue, 27 Jun 2023 15:24:58 +0200 Subject: [PATCH] Strings::sprintAssoc should treat null and empty string the same --- src/Ouzo/Goodies/Utilities/Strings.php | 3 ++- test/src/Ouzo/Goodies/Utilities/StringsTest.php | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Ouzo/Goodies/Utilities/Strings.php b/src/Ouzo/Goodies/Utilities/Strings.php index 8e57a525..bcaada5f 100644 --- a/src/Ouzo/Goodies/Utilities/Strings.php +++ b/src/Ouzo/Goodies/Utilities/Strings.php @@ -449,7 +449,8 @@ public static function sprintAssoc(string|array|null $string, ?array $params): a return $string; } foreach ($params as $key => $value) { - if (!is_null($key) && !is_null($value)) { + if (!is_null($key)) { + $value ??= Strings::EMPTY; $string = preg_replace("/%{($key)}/", $value, $string); } } diff --git a/test/src/Ouzo/Goodies/Utilities/StringsTest.php b/test/src/Ouzo/Goodies/Utilities/StringsTest.php index 076d4097..b425e503 100644 --- a/test/src/Ouzo/Goodies/Utilities/StringsTest.php +++ b/test/src/Ouzo/Goodies/Utilities/StringsTest.php @@ -486,7 +486,8 @@ public static function sprintAssoc(): array ['This is %{what}! %{what}? This is %{place}! And %{invalid_placeholder}!', ['what' => 'madness', 'place' => 'Sparta'], 'This is madness! madness? This is Sparta! And %{invalid_placeholder}!'], [null, ['what' => 'madness', 'place' => 'Sparta'], null], ['This is %{what}! %{what}? This is %{place}!', null, 'This is %{what}! %{what}? This is %{place}!'], - ['This is %{what}! %{what}? This is %{place}!', ['what' => 'madness', 'place' => null, null => 'Sparta'], 'This is madness! madness? This is %{place}!'], + ['This is %{what}! %{what}? This is %{place}!', ['what' => 'madness', 'place' => '', null => 'Sparta'], 'This is madness! madness? This is !'], + ['This is %{what}! %{what}? This is %{place}!', ['what' => 'madness', 'place' => null, null => 'Sparta'], 'This is madness! madness? This is !'], ]; }