Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HttpMessage] Helper Methods on Uri to make it easier to create Uri objects with query params #119

Merged
merged 2 commits into from
Nov 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Examples:
* [PR #59](https://github.com/SonsOfPHP/sonsofphp/pull/59) Added new HttpFactory component
* [PR #70](https://github.com/SonsOfPHP/sonsofphp/pull/70) Added new Core contract
* [PR #112](https://github.com/SonsOfPHP/sonsofphp/pull/112) [Cache] Added new component
* [PR #119](https://github.com/SonsOfPHP/sonsofphp/pull/119) [HttpMessage] Added `withQueryParams` and `withQueryParam` to `Uri`

## [0.3.8]

Expand Down
31 changes: 30 additions & 1 deletion docs/components/http-message/index.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
title: Http Message
title: Http Message (PSR-7)
description: PHP PSR-7 implementation
---

# Http Message Component
Expand All @@ -11,3 +12,31 @@ Simple PSR-7 Compatible Http Message Component
```shell
composer require sonsofphp/http-message
```

## Usage

### Uri

```php
<?php

use SonsOfPHP\Component\HttpMessage\Uri;

// Passing in the url is optional.
$uri = new Uri('https://docs.sonsofphp.com');

// You can also pass in a more detailed url
$uri = new Uri('https://docs.sonsofphp.com/search/results?q=test');

// You can also easily add additional query parameters
$uri = $uri->withQueryParams([
'page' => 1,
'limit' => 25,
'filters' => [
'isActive' => 1,
]
]);

// To remove all the query parameters, pass in `null`
$uri = $uri->withQueryParams(null);
```
104 changes: 85 additions & 19 deletions src/SonsOfPHP/Component/HttpMessage/Tests/UriTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,88 @@ public function testItImplementsCorrectInterface(): void
$this->assertInstanceOf(UriInterface::class, new Uri());
}

/**
* @covers ::withQueryParam
*/
public function testWithQueryParam(): void
{
$uri = new Uri('https://docs.sonsofphp.com');
$this->assertNotSame($uri, $uri->withQueryParam('page', 1));
$this->assertSame('page=1', $uri->withQueryParam('page', 1)->getQuery());
}

/**
* @covers ::withQueryParams
*/
public function testWithQueryParamsCanBeUsedToRemove(): void
{
$uri = new Uri('https://docs.sonsofphp.com?page=1&limit=100');
$this->assertSame('', $uri->withQueryParams(null)->getQuery());
}

/**
* @covers ::withQueryParams
*/
public function testWithQueryParamsWillAdd(): void
{
$uri = new Uri('https://docs.sonsofphp.com');
$this->assertSame('page=1&limit=100', $uri->withQueryParams(['page' => 1])->withQueryParams(['limit' => 100])->getQuery());
}

/**
* @covers ::withQueryParams
*/
public function testWithQueryParams(): void
{
$uri = new Uri('https://docs.sonsofphp.com');
$this->assertNotSame($uri, $uri->withQueryParams(['page' => 1]));
$this->assertSame('page=1', $uri->withQueryParams(['page' => 1])->getQuery());
}

/**
* @covers ::getQuery
*/
public function testGetQueryWorksAsExpectedWhenComplexQueryParams(): void
{
$uri = new Uri();
$this->assertSame(
'search=search%20term&filters[active]=1',
$uri->withQueryParams([
'search' => 'search term',
'filters' => [
'active' => '1',
],
])->getQuery()
);
}

/**
* @covers ::getQuery
*/
public function testGetQueryWorksAsExpected(): void
{
$uri = new Uri('https://docs.sonsofphp.com');
$this->assertSame('', $uri->getQuery());

$uri = new Uri('https://docs.sonsofphp.com?q');
$this->assertSame('q', $uri->getQuery());

$uri = new Uri('https://docs.sonsofphp.com?q=test%20query');
$this->assertSame('q=test%20query', $uri->getQuery());

$uri = new Uri('https://docs.sonsofphp.com?page=1&limit=100');
$this->assertSame('page=1&limit=100', $uri->getQuery());
}

/**
* @covers ::__construct
*/
public function testConstructWithQuery(): void
{
$uri = new Uri('https://docs.sonsofphp.com?q=test');
$this->assertSame('q=test', $uri->getQuery());
}

/**
* @covers ::__construct
*/
Expand Down Expand Up @@ -108,24 +190,6 @@ public function testGetPathWorksAsExpected(): void
$this->assertSame('/components', $uri->getPath());
}

/**
* @covers ::getQuery
*/
public function testGetQueryWorksAsExpected(): void
{
$uri = new Uri('https://docs.sonsofphp.com');
$this->assertSame('', $uri->getQuery());

$uri = new Uri('https://docs.sonsofphp.com?q');
$this->assertSame('q', $uri->getQuery());

$uri = new Uri('https://docs.sonsofphp.com?q=test%20query');
$this->assertSame('q=test%20query', $uri->getQuery());

$uri = new Uri('https://docs.sonsofphp.com?page=1&limit=100');
$this->assertSame('page=1&limit=100', $uri->getQuery());
}

/**
* @covers ::getFragment
*/
Expand Down Expand Up @@ -224,8 +288,10 @@ public function testWithPathWorksAsExpected(): void
public function testWithQueryWorksAsExpected(): void
{
$uri = new Uri('https://docs.sonsofphp.com');
$this->assertNotSame($uri, $uri->withQuery('/test'));
$this->assertNotSame($uri, $uri->withQuery('test=yes'));
$this->assertSame($uri, $uri->withQuery(''));

$this->assertSame('testing=yes', $uri->withQuery('testing=yes')->getQuery());
}

/**
Expand Down
74 changes: 72 additions & 2 deletions src/SonsOfPHP/Component/HttpMessage/Uri.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Uri implements UriInterface, \Stringable
private ?string $password;
private ?string $query;
private ?string $fragment;
private array $queryParams = [];

public function __construct(
private string $uri = '',
Expand All @@ -36,6 +37,10 @@ public function __construct(
$this->path = $parts['path'] ?? null;
$this->query = $parts['query'] ?? null;
$this->fragment = $parts['fragment'] ?? null;

if (!empty($parts['query'])) {
parse_str($parts['query'], $this->queryParams);
}
}
}

Expand Down Expand Up @@ -113,7 +118,29 @@ public function getPath(): string
*/
public function getQuery(): string
{
return $this->query ?? '';
//return http_build_query($this->queryParams, '', null, \PHP_QUERY_RFC3986);

$query = '';
foreach ($this->queryParams as $key => $value) {
if (is_array($value)) {
foreach ($value as $n => $v) {
$query .= sprintf('&%s[%s]', $key, $n);
if (!empty($v)) {
$query .= '=' . rawurlencode((string) $v);
}
}
continue;
}

$query .= '&' . $key;

// null or ''
if (!empty($value)) {
$query .= '=' . rawurlencode((string) $value);
continue;
}
}
return ltrim($query, '&');
}

/**
Expand Down Expand Up @@ -218,9 +245,12 @@ public function withQuery(string $query): UriInterface
return $this;
}

parse_str($query, $output);

$that = clone $this;

$that->query = $query;
//$that->query = $query;
$that->queryParams = $output;

return $that;
}
Expand Down Expand Up @@ -256,4 +286,44 @@ public function __toString(): string
($this->fragment ? '#' . $this->fragment : '')
;
}

/**
* Example:
* ->withQueryParams([
* 'query' => 'search string',
* 'page' => '1',
* 'limit' => '10',
* 'filters' => [
* 'active' => '1',
* ],
* ]);
* ?query=search%20string&page=1&limit=10&filters[active]=1
*/
public function withQueryParams(?array $params): static
{
$that = clone $this;

if (null === $params) {
$that->queryParams = [];
return $that;
}

$that->queryParams += $params;

return $that;
}

/**
* Examples
* ->withQueryParam('page', 1);
* ?page=1
*/
public function withQueryParam(string $name, int|string|array $value): static
{
$that = clone $this;

$that->queryParams[$name] = $value;

return $that;
}
}