-
-
Notifications
You must be signed in to change notification settings - Fork 223
/
EventSourcedFrontendNodeRoutePartHandler.php
416 lines (376 loc) · 17.8 KB
/
EventSourcedFrontendNodeRoutePartHandler.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<?php
/*
* This file is part of the Neos.Neos package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
declare(strict_types=1);
namespace Neos\Neos\FrontendRouting;
use Neos\ContentRepository\Core\ContentRepository;
use Neos\ContentRepository\Core\DimensionSpace\DimensionSpacePoint;
use Neos\ContentRepository\Core\SharedModel\Workspace\WorkspaceName;
use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry;
use Neos\Flow\Mvc\Routing\RoutingMiddleware;
use Neos\Neos\FrontendRouting\Exception\NodeNotFoundException;
use Neos\Neos\FrontendRouting\Exception\InvalidShortcutException;
use Neos\Neos\FrontendRouting\Projection\DocumentUriPathFinder;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\Routing\AbstractRoutePart;
use Neos\Flow\Mvc\Routing\Dto\MatchResult;
use Neos\Flow\Mvc\Routing\Dto\ResolveResult;
use Neos\Flow\Mvc\Routing\Dto\RouteParameters;
use Neos\Flow\Mvc\Routing\Dto\UriConstraints;
use Neos\Flow\Mvc\Routing\DynamicRoutePartInterface;
use Neos\Flow\Mvc\Routing\ParameterAwareRoutePartInterface;
use Neos\Neos\FrontendRouting\CrossSiteLinking\CrossSiteLinkerInterface;
use Neos\Neos\FrontendRouting\DimensionResolution\DelegatingResolver;
use Neos\Neos\FrontendRouting\DimensionResolution\RequestToDimensionSpacePointContext;
use Neos\Neos\FrontendRouting\DimensionResolution\DimensionResolverInterface;
use Neos\Neos\FrontendRouting\SiteDetection\SiteDetectionFailedException;
use Neos\Neos\FrontendRouting\SiteDetection\SiteDetectionMiddleware;
use Neos\Neos\FrontendRouting\SiteDetection\SiteDetectionResult;
use Psr\Http\Message\UriInterface;
use Neos\Neos\Domain\Repository\SiteRepository;
use Neos\Neos\FrontendRouting\Exception\TargetSiteNotFoundException;
use Neos\Neos\FrontendRouting\Exception\ResolvedSiteNotFoundException;
/**
* A route part handler for finding nodes in the website's frontend. Like every RoutePartHandler,
* this handles both directions:
* - from URL to NodeAddress (via {@see EventSourcedFrontendNodeRoutePartHandler::matchWithParameters})
* - from NodeAddress to URL (via {@see EventSourcedFrontendNodeRoutePartHandler::resolveWithParameters})
*
* For performance reasons, this uses a special projection {@see DocumentUriPathFinder}, and
* does NOT use the graph projection in any way.
*
*
* ## Match Direction (URL to NodeAddress)
*
* This is usually simply triggered ONCE per request, before the controller starts working.
* The RoutePartHandler is invoked from {@see RoutingMiddleware} (which handles the routing).
*
* The overall process is as follows:
*
* ```
* (*) = Extension Point ┌───────────────────────────────────────────────┐
* ┌──────────────┐ │ EventSourcedFrontendNodeRoutePartHandler │
* │SiteDetection │ │ ┌─────────────────────┐ │
* │Middleware (*)│────────────────────▶│ │DimensionResolver (*)│─────▶ Finding the ─┼─▶NodeAddress
* └──────────────┘ current site │ └─────────────────────┘ NodeId │
* └───────────────────────────────────────────────┘
* current Content current
* Repository DimensionSpacePoint
* ```
*
*
* ### {@see SiteDetectionMiddleware}: Multi-Site Support
* and Multiple Content Repository Support
*
* The Dimension Resolving configuration might be site-specific, f.e. one site maps a subdomain to a different language;
* and another site which wants to use the UriPathSegment.
* Additionally, we want to support using different content repositories for different sites
* (e.g. to have different NodeTypes configured, or differing dimension configuration).
*
* Thus, the {@see DimensionResolverInterface} and the frontend routing in general needs the result of the site
* detection as input.
*
* Because of this, the site detection is done before the routing; inside the {@see SiteDetectionMiddleware},
* which runs the routing.
* **Feel free to replace the Site Detection with your own custom Middleware (it's very little code).**
*
* The Site Detection is done at **every** request.
*
*
* ### {@see DimensionResolverInterface}: Custom Dimension Resolving
*
* Especially the {@see DimensionSpacePoint} matching must be very extensible, because
* people might want to map domains, subdomains, URL slugs, ... to different dimensions; and
* maybe even handle every dimension individually.
*
* This is why the {@see EventSourcedFrontendNodeRoutePartHandler} calls the {@see DelegatingResolver},
* which calls potentially multiple {@see DimensionResolverInterface}s.
*
* **For details on how to customize the Dimension Resolving, please see {@see DimensionResolverInterface}.**
*
* Because the Dimension Resolving runs inside the RoutePartHandler, this is all cached (via the Routing Cache).
*
*
* ### Reading the Uri Path Segment and finding the node
*
* This is the core capability of this class (the {@see EventSourcedFrontendNodeRoutePartHandler}).
*
*
* ### Result of the Routing
*
* The **result** of the {@see EventSourcedFrontendNodeRoutePartHandler::matchWithParameters} call is a
* {@see NodeAddress} (wrapped in a {@see MatchResult}); so to build the NodeAddress, we need:
* - the {@see WorkspaceName} (which is always **live** in our case)
* - the {@see ContentStreamId} of the Live workspace
* - The {@see DimensionSpacePoint} we want to see the page in (i.e. in language=de)
* - resolved by {@see DimensionResolverInterface}
* - The {@see NodeAggregateId} (of the Document Node we want to show)
* - resolved by {@see EventSourcedFrontendNodeRoutePartHandler}
*
*
* ## Resolve Direction (NodeAddress to URL)
*
* ```
* ┌────────────────────────────────────────────────────────────────────────┐
* │ EventSourcedFrontendNodeRoutePartHandler │
* │ ┌─────────────────────┐ ┌─────────────────────┐ │
* NodeAddress────┼▶ Finding the ────▶│ CrossSiteLinker (*) │─────▶│DimensionResolver (*)│─┼──▶ URL
* │ URL └─────────────────────┘ └─────────────────────┘ │
* └────────────────────────────────────────────────────────────────────────┘
* ```
*
* First, the URL path is resolved by checking the {@see DocumentUriPathFinder} projection.
*
* Then, the {@see CrossSiteLinkerInterface} is responsible for adjusting the built URL in case it needs to
* be generated for a different Site. It is basically a global singleton, but can be replaced globally
* if needed.
*
* Then, the {@see DimensionResolverInterface} of the target site is called for adjusting the URL.
*
* @Flow\Scope("singleton")
*/
final class EventSourcedFrontendNodeRoutePartHandler extends AbstractRoutePart implements
DynamicRoutePartInterface,
ParameterAwareRoutePartInterface,
FrontendNodeRoutePartHandlerInterface
{
private string $splitString = '';
#[Flow\Inject]
protected ContentRepositoryRegistry $contentRepositoryRegistry;
#[Flow\Inject]
protected NodeShortcutResolver $nodeShortcutResolver;
#[Flow\Inject]
protected DelegatingResolver $delegatingResolver;
#[Flow\Inject]
protected CrossSiteLinkerInterface $crossSiteLinker;
#[Flow\Inject]
protected SiteRepository $siteRepository;
/**
* Incoming URLs
*
* @param mixed $requestPath
* @param RouteParameters $parameters
* @return bool|MatchResult
*/
public function matchWithParameters(&$requestPath, RouteParameters $parameters)
{
if (!is_string($requestPath)) {
return false;
}
try {
$siteDetectionResult = SiteDetectionResult::fromRouteParameters($parameters);
} catch (SiteDetectionFailedException) {
return false;
}
$resolvedSite = $this->siteRepository->findOneByNodeName($siteDetectionResult->siteNodeName);
if ($resolvedSite === null) {
throw new ResolvedSiteNotFoundException(sprintf('No site found for siteNodeName "%s"', $siteDetectionResult->siteNodeName->value));
}
$remainingRequestPath = $this->truncateRequestPathAndReturnRemainder($requestPath, $resolvedSite->getConfiguration()->uriPathSuffix);
$dimensionResolvingResult = $this->delegatingResolver->fromRequestToDimensionSpacePoint(
RequestToDimensionSpacePointContext::fromUriPathAndRouteParametersAndResolvedSite(
$requestPath,
$parameters,
$resolvedSite,
)
);
$dimensionSpacePoint = $dimensionResolvingResult->resolvedDimensionSpacePoint;
// TODO Validate for full context
// TODO validate dsp == complete (ContentDimensionZookeeper::getAllowedDimensionSubspace()->contains()...)
// if incomplete -> no match + log
$contentRepository = $this->contentRepositoryRegistry->get($siteDetectionResult->contentRepositoryId);
try {
$matchResult = $this->matchUriPath(
$dimensionResolvingResult->remainingUriPath,
$dimensionSpacePoint,
$siteDetectionResult,
$contentRepository
);
} catch (NodeNotFoundException $exception) {
// we silently swallow the Node Not Found case, as you'll see this in the server log if it interests you
// (and other routes could still handle this).
return false;
}
$requestPath = $remainingRequestPath;
return $matchResult;
}
/**
* @param string $uriPath
* @param DimensionSpacePoint $dimensionSpacePoint
* @return MatchResult
* @throws NodeNotFoundException
*/
private function matchUriPath(
string $uriPath,
DimensionSpacePoint $dimensionSpacePoint,
SiteDetectionResult $siteDetectionResult,
ContentRepository $contentRepository
): MatchResult {
$uriPath = trim($uriPath, '/');
$documentUriPathFinder = $contentRepository->projectionState(DocumentUriPathFinder::class);
$nodeInfo = $documentUriPathFinder->getEnabledBySiteNodeNameUriPathAndDimensionSpacePointHash(
$siteDetectionResult->siteNodeName,
$uriPath,
$dimensionSpacePoint->hash
);
$nodeAddress = NodeAddressFactory::create($contentRepository)->createFromContentStreamIdAndDimensionSpacePointAndNodeAggregateId(
$documentUriPathFinder->getLiveContentStreamId(),
$dimensionSpacePoint,
$nodeInfo->getNodeAggregateId(),
);
return new MatchResult($nodeAddress->serializeForUri(), $nodeInfo->getRouteTags());
}
/**
* Outgoing URLs (link generation)
*
* @param array<string,mixed> &$routeValues
*/
public function resolveWithParameters(array &$routeValues, RouteParameters $parameters): ResolveResult|false
{
if ($this->name === null || $this->name === '' || !\array_key_exists($this->name, $routeValues)) {
return false;
}
$currentRequestSiteDetectionResult = SiteDetectionResult::fromRouteParameters($parameters);
$nodeAddress = $routeValues[$this->name];
// TODO: for cross-CR links: NodeAddressInContentRepository as a new value object
if (!$nodeAddress instanceof NodeAddress) {
return false;
}
try {
$resolveResult = $this->resolveNodeAddress($nodeAddress, $currentRequestSiteDetectionResult);
} catch (NodeNotFoundException | InvalidShortcutException $exception) {
// TODO log exception
return false;
}
unset($routeValues[$this->name]);
return $resolveResult;
}
/**
* Resolves a node address for uri building.
*
* NOTE: The resolving of nodes is also done for disabled/hidden nodes.
* To disallow showing a node actually disabled/hidden itself has to be ensured in matching a request path,
* not in building one.
*
* @param NodeAddress $nodeAddress
* @param SiteDetectionResult $currentRequestSiteDetectionResult
* @return ResolveResult
* @throws InvalidShortcutException
* @throws NodeNotFoundException
*/
private function resolveNodeAddress(
NodeAddress $nodeAddress,
SiteDetectionResult $currentRequestSiteDetectionResult
): ResolveResult {
// TODO: SOMEHOW FIND OTHER CONTENT REPOSITORY HERE FOR CROSS-CR LINKS!!
$contentRepository = $this->contentRepositoryRegistry->get(
$currentRequestSiteDetectionResult->contentRepositoryId
);
$documentUriPathFinder = $contentRepository->projectionState(DocumentUriPathFinder::class);
$nodeInfo = $documentUriPathFinder->getByIdAndDimensionSpacePointHash(
$nodeAddress->nodeAggregateId,
$nodeAddress->dimensionSpacePoint->hash
);
if ($nodeInfo->isShortcut()) {
$nodeInfo = $this->nodeShortcutResolver->resolveNode($nodeInfo, $contentRepository);
if ($nodeInfo instanceof UriInterface) {
return $this->buildResolveResultFromUri($nodeInfo);
}
}
$targetSite = $this->siteRepository->findOneByNodeName($nodeInfo->getSiteNodeName()->value);
if ($targetSite === null) {
throw new TargetSiteNotFoundException(sprintf('No site found for siteNodeName "%s"', $nodeInfo->getSiteNodeName()->value));
}
$uriConstraints = UriConstraints::create();
if (!$targetSite->getNodeName()->equals($currentRequestSiteDetectionResult->siteNodeName)) {
$uriConstraints = $this->crossSiteLinker->applyCrossSiteUriConstraints(
$targetSite,
$uriConstraints
);
}
$uriConstraints = $this->delegatingResolver->fromDimensionSpacePointToUriConstraints(
$nodeAddress->dimensionSpacePoint,
$nodeInfo,
$targetSite,
$uriConstraints
);
if ($targetSite->getConfiguration()->uriPathSuffix !== '' && $nodeInfo->hasUriPath()) {
$uriConstraints = $uriConstraints->withPathSuffix($targetSite->getConfiguration()->uriPathSuffix);
}
return new ResolveResult($nodeInfo->getUriPath(), $uriConstraints, $nodeInfo->getRouteTags());
}
private function truncateRequestPathAndReturnRemainder(string &$requestPath, string $uriPathSuffix): string
{
if ($uriPathSuffix !== '') {
$suffixPosition = strpos($requestPath, $uriPathSuffix);
if ($suffixPosition === false) {
return '';
}
$requestPath = substr($requestPath, 0, $suffixPosition);
}
if ($this->splitString === '' || $this->splitString === '/') {
return '';
}
$splitStringPosition = strpos($requestPath, $this->splitString);
if ($splitStringPosition === false) {
return '';
}
$fullRequestPath = $requestPath;
$requestPath = substr($requestPath, 0, $splitStringPosition);
return substr($fullRequestPath, $splitStringPosition);
}
private function buildResolveResultFromUri(UriInterface $uri): ResolveResult
{
$uriConstraints = UriConstraints::create();
if (!empty($uri->getScheme())) {
$uriConstraints = $uriConstraints->withScheme($uri->getScheme());
}
if (!empty($uri->getHost())) {
$uriConstraints = $uriConstraints->withHost($uri->getHost());
}
if ($uri->getPort() !== null) {
$uriConstraints = $uriConstraints->withPort($uri->getPort());
} elseif (!empty($uri->getScheme())) {
$uriConstraints = $uriConstraints->withPort($uri->getScheme() === 'https' ? 443 : 80);
}
if (!empty($uri->getQuery())) {
$uriConstraints = $uriConstraints->withQueryString($uri->getQuery());
}
if (!empty($uri->getFragment())) {
$uriConstraints = $uriConstraints->withFragment($uri->getFragment());
}
return new ResolveResult($uri->getPath(), $uriConstraints);
}
public function setSplitString($splitString): void
{
$this->splitString = $splitString;
}
public function match(&$routePath): bool
{
return false;
/*
throw new \BadMethodCallException(
'match() is not supported by this Route Part Handler, use "matchWithParameters" instead',
1568287772
);*/
}
/**
* @param array<int|string,mixed> $routeValues
*/
public function resolve(array &$routeValues): bool
{
return false;
/*
throw new \BadMethodCallException(
'resolve() is not supported by this Route Part Handler, use "resolveWithParameters" instead',
1611600169
);*/
}
}