1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Autarky\Routing;
12:
13: use Symfony\Component\HttpFoundation\RequestStack;
14:
15: 16: 17:
18: class UrlGenerator
19: {
20: 21: 22:
23: protected $router;
24:
25: 26: 27:
28: protected $routePathGenerator;
29:
30: 31: 32:
33: protected $requests;
34:
35: 36: 37: 38: 39:
40: protected $assetRoot;
41:
42: 43: 44: 45: 46: 47:
48: public function __construct(
49: Router $router,
50: RoutePathGeneratorInterface $routePathGenerator,
51: RequestStack $requests,
52: $validateParams = false
53: ) {
54: $this->router = $router;
55: $this->routePathGenerator = $routePathGenerator;
56: $this->requests = $requests;
57: $this->setValidateParams($validateParams);
58: }
59:
60: 61: 62: 63: 64:
65: public function setAssetRoot($assetRoot)
66: {
67: $this->assetRoot = rtrim($assetRoot, '/');
68: }
69:
70: 71: 72: 73: 74: 75:
76: public function setValidateParams($validateParams)
77: {
78: $this->routePathGenerator->setValidateParams($validateParams);
79: }
80:
81: 82: 83: 84: 85: 86: 87: 88: 89:
90: public function getRouteUrl($name, array $params = array(), $relative = false)
91: {
92: $route = $this->router->getRoute($name);
93:
94: $routeParams = [];
95: $query = [];
96: foreach ($params as $key => $value) {
97: if (is_int($key)) {
98: $routeParams[] = $value;
99: } else {
100: $query[$key] = $value;
101: }
102: }
103:
104: $path = $this->routePathGenerator->getRoutePath($route, $routeParams);
105:
106: if ($query) {
107: $path .= '?'.http_build_query($query);
108: }
109:
110: if ($relative) {
111: $root = $this->requests->getCurrentRequest()
112: ->getBaseUrl();
113: } else {
114: $root = $this->getRootUrl();
115: }
116:
117: return $root . $path;
118: }
119:
120: 121: 122: 123: 124: 125: 126: 127:
128: public function getAssetUrl($path, $relative = false)
129: {
130: if (substr($path, 0, 1) !== '/') {
131: $path = '/'.$path;
132: }
133:
134: if ($this->assetRoot !== null) {
135: $base = $this->assetRoot;
136: } else if ($relative) {
137: $base = $this->requests
138: ->getCurrentRequest()
139: ->getBaseUrl();
140: } else {
141: $base = $this->getRootUrl();
142: }
143:
144: return $base . $path;
145: }
146:
147: 148: 149: 150: 151:
152: public function getRootUrl()
153: {
154: $request = $this->requests->getCurrentRequest();
155: $host = $request->getHttpHost();
156: $base = $request->getBaseUrl();
157:
158: return rtrim("//$host/$base", '/');
159: }
160: }
161: