Skip to content

Commit

Permalink
thephpleague#1 Extract variables from uri
Browse files Browse the repository at this point in the history
  • Loading branch information
Douglasdc3 committed Nov 27, 2022
1 parent 99ddb48 commit fb04b91
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
37 changes: 37 additions & 0 deletions uri/UriTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,41 @@ public function expand(VariableBag|array $variables = []): UriInterface
)
);
}

public function extract(string|UriInterface|\Psr\Http\Message\UriInterface $uri): VariableBag
{
$uri = Uri::createFromString($uri);

$pattern = preg_replace_callback(
'/\{[^}]*}.?/x',
function ($match) {
if (substr($match[0], -1) === '}') {
return '(.*)$';
}

$character = preg_quote(substr($match[0], -1));

return '([^' . $character . ']*)' . $character;
},
$this->getTemplate(),
);
$pattern = str_replace('/', '\/', $pattern);
$pattern = "/$pattern/";

$variableBag = new VariableBag();

preg_match_all($pattern, $uri->toString(), $matches);
for ($i = 1, $matchCount = count($matches) ; $i < $matchCount; $i++) {
if (count($matches[$i]) === 0) {
continue;
}

$variableBag->assign(
$this->template->variableNames[$i - 1],
urldecode($matches[$i][0])
);
}

return $variableBag;
}
}
18 changes: 18 additions & 0 deletions uri/UriTemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use League\Uri\Exceptions\SyntaxError;
use League\Uri\Exceptions\TemplateCanNotBeExpanded;
use League\Uri\UriTemplate\VariableBag;
use PHPUnit\Framework\TestCase;

/**
Expand Down Expand Up @@ -407,4 +408,21 @@ public function testExpansionWithMultipleSameExpression(): void

self::assertSame('foo/foo', (new UriTemplate($template, $data))->expand()->__toString());
}

/**
* @covers \League\Uri\UriTemplate\Template
*/
public function testExtractVariableBagWithUriString(): void
{
$template = 'https://example.com/hotels/{hotel}/bookings/{booking}';
$uriString = 'https://example.com/hotels/Rest%20%26%20Relax/bookings/42';

$uriTemplate = new UriTemplate($template);
$variables = $uriTemplate->extract($uriString);

self::assertInstanceOf(VariableBag::class, $variables);
self::assertCount(2, $variables);
self::assertSame('Rest & Relax', $variables['hotel']);
self::assertSame('42', $variables['booking']);
}
}

0 comments on commit fb04b91

Please sign in to comment.