1: <?php
2:
3: namespace PHPixie\Route;
4:
5: class Translator
6: {
7: protected $builder;
8: protected $resolver;
9: protected $httpContextContainer;
10:
11: protected $basePath;
12: protected $baseHost;
13:
14: public function __construct($builder, $resolver, $configData, $httpContextContainer = null)
15: {
16: $this->builder = $builder;
17: $this->resolver = $resolver;
18: $this->httpContextContainer = $httpContextContainer;
19:
20: $this->basePath = $configData->get('basePath', '/');
21: $this->baseHost = $configData->get('baseHost', '');
22: }
23:
24: public function match($serverRequest = null)
25: {
26: if($serverRequest === null) {
27: $serverRequest = $this->currentServerRequest();
28: }
29: $uri = $serverRequest->getUri();
30:
31: $host = $this->stripPrefix($uri->getHost(), $this->baseHost);
32: if($host === null) {
33: return null;
34: }
35:
36: $path = urldecode($uri->getPath());
37: $path = $this->stripPrefix($path, $this->basePath);
38: if($path === null) {
39: return null;
40: }
41:
42: $fragment = $this->builder->translatorFragment(
43: $path,
44: $host,
45: $serverRequest
46: );
47:
48: return $this->resolver->match($fragment);
49: }
50:
51: public function generatePath($resolverPath = null, $attributes = array())
52: {
53: $fragment = $this->generateFragment($resolverPath, $attributes);
54: return $this->basePath.$fragment->path();
55: }
56:
57: public function generateUri(
58: $resolverPath = null,
59: $attributes = array(),
60: $withHost = false,
61: $serverRequest = null
62: )
63: {
64: if($serverRequest === null) {
65: $serverRequest = $this->currentServerRequest();
66: }
67: $uri = $serverRequest->getUri();
68:
69: $fragment = $this->generateFragment($resolverPath, $attributes, $withHost, $serverRequest);
70:
71: $uri = $uri->withPath($this->basePath.$fragment->path());
72: if($withHost) {
73: $uri = $uri->withHost($this->baseHost.$fragment->host());
74: }
75:
76: return $uri;
77: }
78:
79: protected function generateFragment($resolverPath, $attributes, $withHost = false, $serverRequest = null)
80: {
81: $match = $this->builder->translatorMatch(
82: $attributes,
83: $resolverPath
84: );
85:
86: return $this->resolver->generate($match, $withHost);
87: }
88:
89: protected function stripPrefix($string, $prefix)
90: {
91: $length = strlen($prefix);
92: if(substr($string, 0, $length) !== $prefix) {
93: return null;
94: }
95:
96: return (string) substr($string, $length);
97: }
98:
99: protected function currentServerRequest()
100: {
101: if($this->httpContextContainer === null)
102: {
103: throw new \PHPixie\Route\Exception("HTTP context container was not set");
104: }
105:
106: $context = $this->httpContextContainer->httpContext();
107: return $context->request()->serverRequest();
108: }
109: }
110: