Skip to content

Commit

Permalink
Api: Add native support for Error4xx presenter and route.
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek authored Nov 29, 2020
1 parent 6cf2291 commit bea6688
Showing 1 changed file with 35 additions and 18 deletions.
53 changes: 35 additions & 18 deletions src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,12 @@ private function renderInjectTagsByData(string $route, array $data): array
private function findLocalData(string $route): array
{
if ($this->data !== []) {
$selectors = [];
if (preg_match('/^([^:]+):([^:]+):([^:]+)$/', trim($route, ':'), $routeParser)) {
$selectors[] = $routeParser[1] . ':' . $routeParser[2] . ':*';
$selectors[] = $routeParser[1] . ':' . $routeParser[2] . ':' . $routeParser[3];
} else {
AssetLoaderException::routeIsInInvalidFormat($route);
}
$routeParser = $this->parseRoute($route);

return $this->findDataBySelectors($selectors);
return $this->findDataBySelectors([
$routeParser['module'] . ':' . $routeParser['presenter'] . ':*',
$routeParser['module'] . ':' . $routeParser['presenter'] . ':' . $routeParser['action'],
]);
}

return $this->data;
Expand All @@ -148,15 +145,10 @@ private function findLocalData(string $route): array
private function findGlobalData(string $route): array
{
if ($this->data !== []) {
$selectors = [];
if (preg_match('/^([^:]+):([^:]+):([^:]+)$/', trim($route, ':'), $routeParser)) {
$selectors[] = '*';
$selectors[] = $routeParser[1] . ':*';
} else {
AssetLoaderException::routeIsInInvalidFormat($route);
}

return $this->findDataBySelectors($selectors);
return $this->findDataBySelectors([
'*',
$this->parseRoute($route)['module'] . ':*',
]);
}

return [];
Expand All @@ -169,11 +161,36 @@ private function findGlobalData(string $route): array
*/
private function findDataBySelectors(array $selectors): array
{
$selectors = array_map(fn (string $item): string => trim($item, ':'), $selectors);
$return = [];
foreach ($selectors as $selector) {
foreach (array_unique($selectors) as $selector) {
$return[] = $this->data[$selector] ?? [];
}

return array_merge_recursive([], ...$return);
}


/**
* @return string[]
*/
private function parseRoute(string $route): array
{
if ($route === 'Error4xx:default') {
return [
'module' => '',
'presenter' => 'Error4xx',
'action' => 'default',
];
}
if (preg_match('/^(?<module>[^:]+):(?<presenter>[^:]+):(?<action>[^:]+)$/', trim($route, ':'), $routeParser)) {
return $routeParser;
}

throw new AssetLoaderException(
'Route "' . $route . '" is invalid. '
. 'Route must be absolute "Module:Presenter:action" or end '
. 'with dynamic part in format "Module:*" or "Module:Presenter:*".'
);
}
}

0 comments on commit bea6688

Please sign in to comment.