Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Created December 8, 2016 14:38
Show Gist options
  • Save mcaskill/1b27165ba8bb5c334c29cfdeecd06624 to your computer and use it in GitHub Desktop.
Save mcaskill/1b27165ba8bb5c334c29cfdeecd06624 to your computer and use it in GitHub Desktop.
Charcoal : Route Aliases & Redirections for Slim
<?php
/**
* Route Aliases & Redirections
*
* @global App $app The Charcoal application.
* @global Container $container The DIC.
* @todo Add support for request method lookup, not just response method.
*/
// From PSR-7 (HTTP Messaging)
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
// From Charcoal
use Charcoal\App\App;
use Charcoal\App\AppContainer as Container;
use Charcoal\Translation\TranslationString;
/** @var Container $container The DI container used by the application. */
$container = $app->getContainer();
$routes = $container['config']['routes'];
$router = $container['router'];
if (isset($routes['redirections']) && is_array($routes['redirections'])) {
foreach ($routes['redirections'] as $path => $resolution) {
if (is_string($resolution)) {
$resolution = [ 'route' => $resolution ];
}
if (!is_array($resolution)) {
throw new Exception('The redirection resolution must be an array.');
}
$dest = isset($resolution['route'])
? $resolution['route']
: '/';
if (is_string($dest) && isset($routes['templates'])) {
if (isset($routes['templates'][$dest])) {
$route = $routes['templates'][$dest];
} else {
foreach ($routes['templates'] as $route) {
if (isset($route['ident']) && $route['ident'] === $dest) {
break;
}
}
}
}
if (!$route) {
$route = new TranslationString($dest);
}
$status = isset($resolution['status'])
? $resolution['status']
: 302;
$app->get(
$path,
function (
RequestInterface $request,
ResponseInterface $response,
array $args = []
) use (
$route,
$status
) {
if ($route instanceof TranslationString) {
if (isset($args['lang'])) {
$route = $route[$args['lang']];
}
} elseif (isset($route['template_data']['route_endpoint'])) {
$endpoint = new TranslationString($route['template_data']['route_endpoint']);
$args = array_merge(
[
'route_endpoint' => (isset($args['lang']) ? $endpoint[$args['lang']] : (string) $endpoint )
],
$args
);
$route = $this->get('router')->pathFor($route['ident'], $args);
} elseif (isset($route['ident']) && $route['route']) {
$route = $this->get('router')->pathFor($route['ident']);
}
return $response->withRedirect($route, $status);
}
);
}
}
"redirections": {
"/{lang:en|fr}/contact": { "route": "contact", "status": 301 },
"/{lang:en|fr}/12/{slug}": {
"status": 301,
"route": {
"en": "/fr/evenements/2015/vendredi",
"fr": "/en/events/2015/friday"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment