| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\GCP\Rize; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\GCP\Rize\UriTemplate\Parser; |
| 6 |
/** |
| 7 |
* URI Template. |
| 8 |
*/ |
| 9 |
class UriTemplate |
| 10 |
{ |
| 11 |
protected Parser $parser; |
| 12 |
protected array $parsed = []; |
| 13 |
public function __construct(protected string $base_uri = '', protected array $params = [], ?Parser $parser = null) |
| 14 |
{ |
| 15 |
$this->parser = $parser ?: $this->createNodeParser(); |
| 16 |
} |
| 17 |
/** |
| 18 |
* Expands URI Template. |
| 19 |
* |
| 20 |
* @param mixed $params |
| 21 |
*/ |
| 22 |
public function expand(string $uri, $params = []) : string |
| 23 |
{ |
| 24 |
$params += $this->params; |
| 25 |
$uri = $this->base_uri . $uri; |
| 26 |
$result = []; |
| 27 |
// quick check |
| 28 |
if (!\str_contains($uri, '{')) { |
| 29 |
return $uri; |
| 30 |
} |
| 31 |
$parser = $this->parser; |
| 32 |
$nodes = $parser->parse($uri); |
| 33 |
foreach ($nodes as $node) { |
| 34 |
$result[] = $node->expand($parser, $params); |
| 35 |
} |
| 36 |
return \implode('', $result); |
| 37 |
} |
| 38 |
/** |
| 39 |
* Extracts variables from URI. |
| 40 |
* |
| 41 |
* @return null|array params or null if not match and $strict is true |
| 42 |
*/ |
| 43 |
public function extract(string $template, string $uri, bool $strict = \false) : ?array |
| 44 |
{ |
| 45 |
$params = []; |
| 46 |
$nodes = $this->parser->parse($template); |
| 47 |
// PHP 8.1.0RC4-dev still throws deprecation warning for `strlen`. |
| 48 |
// $uri = (string) $uri; |
| 49 |
foreach ($nodes as $node) { |
| 50 |
// if strict is given, and there's no remaining uri just return null |
| 51 |
if ($strict && (string) $uri === '') { |
| 52 |
return null; |
| 53 |
} |
| 54 |
// URI will be truncated from the start when a match is found |
| 55 |
$match = $node->match($this->parser, $uri, $params, $strict); |
| 56 |
if ($match === null) { |
| 57 |
return null; |
| 58 |
} |
| 59 |
[$uri, $params] = $match; |
| 60 |
} |
| 61 |
// if there's remaining $uri, matching is failed |
| 62 |
if ($strict && (string) $uri !== '') { |
| 63 |
return null; |
| 64 |
} |
| 65 |
return $params; |
| 66 |
} |
| 67 |
public function getParser() : Parser |
| 68 |
{ |
| 69 |
return $this->parser; |
| 70 |
} |
| 71 |
protected function createNodeParser() : Parser |
| 72 |
{ |
| 73 |
static $parser; |
| 74 |
if ($parser) { |
| 75 |
return $parser; |
| 76 |
} |
| 77 |
return $parser = new Parser(); |
| 78 |
} |
| 79 |
} |
| 80 |
|