Skip to content

Commit

Permalink
Merge pull request #61 from bryanlopezinc/lazyEvaluate
Browse files Browse the repository at this point in the history
lazy evaluate Url::getQueryParameter default argument
  • Loading branch information
freekmurze authored Dec 14, 2022
2 parents 6278986 + 29b34cb commit 8a52d66
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
```
Expand Down
6 changes: 5 additions & 1 deletion src/QueryParameterBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions tests/QueryParameterBagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});


Expand Down
3 changes: 3 additions & 0 deletions tests/UrlQueryParametersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});


Expand Down

0 comments on commit 8a52d66

Please sign in to comment.