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