| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* League.Uri (https://uri.thephpleague.com) |
| 5 |
* |
| 6 |
* (c) Ignace Nyamagana Butera <[email protected]> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
declare(strict_types=1); |
| 13 |
|
| 14 |
namespace League\Uri\UriTemplate; |
| 15 |
|
| 16 |
use League\Uri\Exceptions\SyntaxError; |
| 17 |
use function preg_match; |
| 18 |
|
| 19 |
final class VarSpecifier |
| 20 |
{ |
| 21 |
/** |
| 22 |
* Variables specification regular expression pattern. |
| 23 |
* |
| 24 |
* @link https://tools.ietf.org/html/rfc6570#section-2.3 |
| 25 |
*/ |
| 26 |
private const REGEXP_VARSPEC = '/^ |
| 27 |
(?<name>(?:[A-z0-9_\.]|%[0-9a-fA-F]{2})+) |
| 28 |
(?<modifier>\:(?<position>\d+)|\*)? |
| 29 |
$/x'; |
| 30 |
|
| 31 |
private string $name; |
| 32 |
private string $modifier; |
| 33 |
private int $position; |
| 34 |
|
| 35 |
private function __construct(string $name, string $modifier, int $position) |
| 36 |
{ |
| 37 |
$this->name = $name; |
| 38 |
$this->modifier = $modifier; |
| 39 |
$this->position = $position; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* {@inheritDoc} |
| 44 |
*/ |
| 45 |
public static function __set_state(array $properties): self |
| 46 |
{ |
| 47 |
return new self($properties['name'], $properties['modifier'], $properties['position']); |
| 48 |
} |
| 49 |
|
| 50 |
public static function createFromString(string $specification): self |
| 51 |
{ |
| 52 |
if (1 !== preg_match(self::REGEXP_VARSPEC, $specification, $parsed)) { |
| 53 |
throw new SyntaxError('The variable specification "'.$specification.'" is invalid.'); |
| 54 |
} |
| 55 |
|
| 56 |
$parsed += ['modifier' => '', 'position' => '']; |
| 57 |
if ('' !== $parsed['position']) { |
| 58 |
$parsed['position'] = (int) $parsed['position']; |
| 59 |
$parsed['modifier'] = ':'; |
| 60 |
} |
| 61 |
|
| 62 |
if ('' === $parsed['position']) { |
| 63 |
$parsed['position'] = 0; |
| 64 |
} |
| 65 |
|
| 66 |
if (10000 <= $parsed['position']) { |
| 67 |
throw new SyntaxError('The variable specification "'.$specification.'" is invalid the position modifier must be lower than 10000.'); |
| 68 |
} |
| 69 |
|
| 70 |
return new self($parsed['name'], $parsed['modifier'], $parsed['position']); |
| 71 |
} |
| 72 |
|
| 73 |
public function toString(): string |
| 74 |
{ |
| 75 |
if (0 < $this->position) { |
| 76 |
return $this->name.$this->modifier.$this->position; |
| 77 |
} |
| 78 |
|
| 79 |
return $this->name.$this->modifier; |
| 80 |
} |
| 81 |
|
| 82 |
public function name(): string |
| 83 |
{ |
| 84 |
return $this->name; |
| 85 |
} |
| 86 |
|
| 87 |
public function modifier(): string |
| 88 |
{ |
| 89 |
return $this->modifier; |
| 90 |
} |
| 91 |
|
| 92 |
public function position(): int |
| 93 |
{ |
| 94 |
return $this->position; |
| 95 |
} |
| 96 |
} |
| 97 |
|