From 29b34cbcaca61b22edf81b4c2a3484aa14593b76 Mon Sep 17 00:00:00 2001 From: Mac Date: Wed, 14 Dec 2022 05:26:11 +0100 Subject: [PATCH] lazy evaluate Url::getQueryParameter default argument --- README.md | 8 ++++++++ src/QueryParameterBag.php | 6 +++++- tests/QueryParameterBagTest.php | 3 +++ tests/UrlQueryParametersTest.php | 3 +++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8a05691..a77f4f3 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,15 @@ Retrieve and transform query parameters: $url = Url::fromString('https://spatie.be/opensource?utm_source=github&utm_campaign=packages'); echo $url->getQuery(); // 'utm_source=github&utm_campaign=packages' + echo $url->getQueryParameter('utm_source'); // 'github' +echo $url->getQueryParameter('utm_medium'); // null +echo $url->getQueryParameter('utm_medium', 'social'); // 'social' +echo $url->getQueryParameter('utm_medium', function() { + //some logic + return 'email'; +}); // 'email' + echo $url->withoutQueryParameter('utm_campaign'); // 'https://spatie.be/opensource?utm_source=github' echo $url->withQueryParameters(['utm_campaign' => 'packages']); // 'https://spatie.be/opensource?utm_source=github&utm_campaign=packages' ``` diff --git a/src/QueryParameterBag.php b/src/QueryParameterBag.php index 311944d..4e4c205 100644 --- a/src/QueryParameterBag.php +++ b/src/QueryParameterBag.php @@ -25,7 +25,11 @@ public static function fromString(string $query = ''): static public function get(string $key, mixed $default = null): mixed { - return $this->parameters[$key] ?? $default; + if ($this->has($key)) { + return $this->parameters[$key]; + } + + return is_callable($default) ? $default() : $default; } public function has(string $key): bool diff --git a/tests/QueryParameterBagTest.php b/tests/QueryParameterBagTest.php index 78817d8..55f870c 100644 --- a/tests/QueryParameterBagTest.php +++ b/tests/QueryParameterBagTest.php @@ -20,6 +20,9 @@ $queryParameterBag = new QueryParameterBag(['offset' => 10]); expect($queryParameterBag)->get('limit', 20)->toEqual(20); + expect($queryParameterBag)->get('limit', function () { + return 100; + })->toEqual(100); }); diff --git a/tests/UrlQueryParametersTest.php b/tests/UrlQueryParametersTest.php index d80d983..5758418 100644 --- a/tests/UrlQueryParametersTest.php +++ b/tests/UrlQueryParametersTest.php @@ -20,6 +20,9 @@ $url = Url::create()->withQuery('offset=10'); expect($url)->getQueryParameter('limit', 20)->toEqual(20); + expect($url)->getQueryParameter('limit', function () { + return 100; + })->toEqual(100); });