forked from netgen/TagsBundle
/
TagRouter.php
299 lines (262 loc) · 10.1 KB
/
TagRouter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<?php
namespace Netgen\TagsBundle\Routing;
use eZ\Publish\Core\MVC\ConfigResolverInterface;
use InvalidArgumentException;
use LogicException;
use Netgen\TagsBundle\API\Repository\TagsService;
use Netgen\TagsBundle\API\Repository\Values\Tags\Tag;
use Netgen\TagsBundle\Routing\Generator\TagUrlGenerator;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RuntimeException;
use Symfony\Cmf\Component\Routing\ChainedRouterInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route as SymfonyRoute;
use Symfony\Component\Routing\RouteCollection;
class TagRouter implements ChainedRouterInterface, RequestMatcherInterface
{
const TAG_URL_ROUTE_NAME = 'eztags_tag_url';
const TAG_VIEW_ACTION_CONTROLLER = 'eztags.controller.tag_view:viewAction';
/**
* @var \Netgen\TagsBundle\API\Repository\TagsService
*/
protected $tagsService;
/**
* @var \Netgen\TagsBundle\Routing\Generator\TagUrlGenerator
*/
protected $generator;
/**
* @var \Symfony\Component\Routing\RequestContext
*/
protected $requestContext;
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* @var \eZ\Publish\Core\MVC\ConfigResolverInterface
*/
protected $configResolver;
/**
* Constructor.
*
* @param \Netgen\TagsBundle\API\Repository\TagsService $tagsService
* @param \Netgen\TagsBundle\Routing\Generator\TagUrlGenerator $generator
* @param \Symfony\Component\Routing\RequestContext $requestContext
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(
TagsService $tagsService,
TagUrlGenerator $generator,
RequestContext $requestContext,
LoggerInterface $logger = null
) {
$this->tagsService = $tagsService;
$this->generator = $generator;
$this->requestContext = $requestContext ?: new RequestContext();
$this->logger = $logger ?: new NullLogger();
}
/**
* @param \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver
*/
public function setConfigResolver(ConfigResolverInterface $configResolver)
{
$this->configResolver = $configResolver;
}
/**
* Tries to match a request with a set of routes.
*
* If the matcher can not find information, it must throw one of the exceptions documented
* below.
*
* @param \Symfony\Component\HttpFoundation\Request $request The request to match
*
* @throws \Symfony\Component\Routing\Exception\ResourceNotFoundException If no matching resource could be found
*
* @return array An array of parameters
*/
public function matchRequest(Request $request)
{
if ($this->configResolver->getParameter('routing.enable_tag_router', 'eztags') === false) {
throw new ResourceNotFoundException('Config says to bypass TagRouter');
}
$requestedPath = rawurldecode($request->attributes->get('semanticPathinfo', $request->getPathInfo()));
$pathPrefix = $this->generator->getPathPrefix();
if (mb_stripos($requestedPath, $pathPrefix) !== 0) {
throw new ResourceNotFoundException();
}
$requestedPath = $this->removePathPrefix($requestedPath, $pathPrefix);
$requestedPath = trim($requestedPath, '/');
if (empty($requestedPath)) {
throw new ResourceNotFoundException();
}
$languages = $this->configResolver->getParameter('languages');
$tag = $this->tagsService->sudo(
function (TagsService $tagsService) use ($requestedPath, $languages) {
return $tagsService->loadTagByUrl(
$requestedPath,
$languages
);
}
);
// We specifically pass tag ID so tag view builder will reload the tag and check for permissions
// Unfortunately, since at this point user is still anonymous (why!?), this is the best we can do
$params = array(
'_route' => self::TAG_URL_ROUTE_NAME,
'_controller' => static::TAG_VIEW_ACTION_CONTROLLER,
'tagId' => $tag->id,
);
$request->attributes->set('tagId', $tag->id);
$this->logger->info(
"TagRouter matched tag #{$tag->id}. Forwarding to tag view controller"
);
return $params;
}
/**
* Generates a URL for a tag, from the given parameters.
*
* It is possible to directly pass a Tag object as the route name, as the ChainRouter allows it through ChainedRouterInterface
*
* If $name is a route name, the "tag" key in $parameters must be set to a valid Netgen\TagsBundle\API\Repository\Values\Tags\Tag object.
* "tagId" can also be provided.
*
* If the generator is not able to generate the URL, it must throw the RouteNotFoundException as documented below.
*
* @param string|\Netgen\TagsBundle\API\Repository\Values\Tags\Tag $name The name of the route or a Tag instance
* @param mixed $parameters An array of parameters
* @param int $referenceType The type of reference to be generated (one of the constants)
*
* @throws \LogicException
* @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
* @throws \InvalidArgumentException
*
* @return string The generated URL
*/
public function generate($name, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
// Direct access to Tag
if ($name instanceof Tag) {
return $this->generator->generate($name, $parameters, $referenceType);
}
// Normal route name
if ($name === self::TAG_URL_ROUTE_NAME) {
if (isset($parameters['tag']) || isset($parameters['tagId'])) {
// Check if tag is a valid Tag object
if (isset($parameters['tag']) && !$parameters['tag'] instanceof Tag) {
throw new LogicException(
"When generating a Tag route, 'tag' parameter must be a valid Netgen\\TagsBundle\\API\\Repository\\Values\\Tags\\Tag."
);
}
$tag = isset($parameters['tag']) ? $parameters['tag'] : $this->tagsService->loadTag($parameters['tagId']);
unset($parameters['tag'], $parameters['tagId'], $parameters['viewType'], $parameters['layout']);
return $this->generator->generate($tag, $parameters, $referenceType);
}
throw new InvalidArgumentException(
"When generating a Tag route, either 'tag' or 'tagId' must be provided."
);
}
throw new RouteNotFoundException('Could not match route');
}
/**
* Gets the RouteCollection instance associated with this Router.
*
* @return \Symfony\Component\Routing\RouteCollection A RouteCollection instance
*/
public function getRouteCollection()
{
return new RouteCollection();
}
/**
* Sets the request context.
*
* @param \Symfony\Component\Routing\RequestContext $context The context
*/
public function setContext(RequestContext $context)
{
$this->requestContext = $context;
$this->generator->setRequestContext($context);
}
/**
* Gets the request context.
*
* @return \Symfony\Component\Routing\RequestContext The context
*/
public function getContext()
{
return $this->requestContext;
}
/**
* Tries to match a URL path with a set of routes.
*
* If the matcher can not find information, it must throw one of the exceptions documented
* below.
*
* @param string $pathinfo The path info to be parsed (raw format, i.e. not urldecoded)
*
* @throws \Symfony\Component\Routing\Exception\ResourceNotFoundException If the resource could not be found
* @throws \Symfony\Component\Routing\Exception\MethodNotAllowedException If the resource was found but the request method is not allowed
*
* @return array An array of parameters
*/
public function match($pathinfo)
{
throw new RuntimeException("The TagRouter doesn't support the match() method. Please use matchRequest() instead.");
}
/**
* Whether this generator supports the supplied $name.
*
* This check does not need to look if the specific instance can be
* resolved to a route, only whether the router can generate routes from
* objects of this class.
*
* @param mixed $name The route "name" which may also be an object or anything
*
* @return bool
*/
public function supports($name)
{
return $name instanceof Tag || $name === self::TAG_URL_ROUTE_NAME;
}
/**
* Convert a route identifier (name, content object etc) into a string
* usable for logging and other debug/error messages.
*
* @param mixed $name
* @param array $parameters which should contain a content field containing a RouteReferrersReadInterface object
*
* @return string
*/
public function getRouteDebugMessage($name, array $parameters = array())
{
if ($name instanceof RouteObjectInterface) {
return 'Route with key ' . $name->getRouteKey();
}
if ($name instanceof SymfonyRoute) {
return 'Route with pattern ' . $name->getPath();
}
return $name;
}
/**
* Removes prefix from path.
*
* Checks for presence of $prefix and removes it from $path if found.
*
* @param string $path
* @param string $prefix
*
* @return string
*/
protected function removePathPrefix($path, $prefix)
{
if ($prefix !== '/' && mb_stripos($path, $prefix) === 0) {
$path = mb_substr($path, mb_strlen($prefix));
}
return $path;
}
}