segmentType = $segmentType; $this->value = $value; $this->key = $key; $this->template = $template; switch ($this->segmentType) { case Segment::LITERAL_SEGMENT: $this->stringRepr = "{$this->value}"; break; case Segment::WILDCARD_SEGMENT: $this->stringRepr = "*"; break; case Segment::DOUBLE_WILDCARD_SEGMENT: $this->stringRepr = "**"; break; case Segment::VARIABLE_SEGMENT: $this->stringRepr = "{{$this->key}={$this->template}}"; break; default: throw new ValidationException( "Unexpected Segment type: {$this->segmentType}" ); } } /** * @return string A string representation of the segment. */ public function __toString() { return $this->stringRepr; } /** * Checks if $value matches the current segment, and creates a new literal Segment with value * equal to $value. If $value does not match the current Segment, throws a ValidationException. * * @param string $value * @return Segment * @throws ValidationException */ public function bindTo($value) { $value = (string) $value; if ($this->matches($value)) { return new Segment(Segment::LITERAL_SEGMENT, $value); } else { throw new ValidationException( "Cannot bind segment '$this' to value '$value'" ); } } /** * Checks if $value matches this Segment. * * @param string $value * @return bool * @throws ValidationException */ public function matches($value) { switch ($this->segmentType) { case Segment::LITERAL_SEGMENT: return $this->value === $value; case Segment::WILDCARD_SEGMENT: return self::isValidBinding($value); case Segment::DOUBLE_WILDCARD_SEGMENT: return self::isValidDoubleWildcardBinding($value); case Segment::VARIABLE_SEGMENT: return $this->template->matches($value); default: throw new ValidationException( "Unexpected Segment type: {$this->segmentType}" ); } } /** * @return int */ public function getSegmentType() { return $this->segmentType; } /** * @return string|null */ public function getKey() { return $this->key; } /** * @return string|null */ public function getValue() { return $this->value; } /** * @return RelativeResourceTemplate|null */ public function getTemplate() { return $this->template; } /** * Check if $binding is a valid segment binding. Segment bindings may contain any characters * except a forward slash ('/'), and may not be empty. * * @param $binding * @return bool */ private static function isValidBinding($binding) { return preg_match("-^[^/]+$-", $binding) === 1; } /** * Check if $binding is a valid double wildcard binding. Segment bindings may contain any * characters, but may not be empty. * * @param $binding * @return bool */ private static function isValidDoubleWildcardBinding($binding) { return preg_match("-^.+$-", $binding) === 1; } }