Skip to content

Instantly share code, notes, and snippets.

@tnrn9b
Last active March 17, 2020 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnrn9b/3cd6172b66aba2a326703381bc18a001 to your computer and use it in GitHub Desktop.
Save tnrn9b/3cd6172b66aba2a326703381bc18a001 to your computer and use it in GitHub Desktop.
Automatically generate ZF3/Laminas route config from a controller factory key
$factories = array(
'Your\Namespace\ControllerName' => 'Your\Namespace\Factory\ControllerNameControllerFactory',
...
);
$writeRouteFromControllerKey = static function (array $factories, $namespace)
{
$createRoute = static function (string $controller, array $actions) use ($namespace) {
$controller = lcfirst($controller);
$childRoutes = "";
foreach ($actions as $key => $action) {
$action = lcfirst($action);
$childRoutes .= <<<TEMP
'$action' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/$action',
'defaults' => [
'__NAMESPACE__' => '$namespace',
'controller' => '$controller',
'action' => '$action',
],
]
],
TEMP;
}
return <<<PAR
'$controller' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/$controller'
],
'may_terminate' => false,// You can change this default
'child_routes' => [
$childRoutes
]
]
PAR;
};
$childRoutes = [];
foreach ($factories as $controllerClass => $controllerFactory) {
$controller = str_replace($namespace, '', $controllerClass);
$class = sprintf('%sController', $controllerClass);
$refl = new \ReflectionClass($class);
$actions = array_reduce($refl->getMethods(ReflectionMethod::IS_PUBLIC), function ($prev, $next) use ($class) {
if ($next->class === $class) {
if (substr($next->name, -6) === 'Action') {
$prev[] = (str_replace("Action", "", $next->name));
}
}
return $prev;
}, []);
$childRoutes[] = $createRoute($controller, $actions);
}
$childRoutes = implode(',' . PHP_EOL, $childRoutes);
return <<<ROUTE
'__YOUR_PARENT_ROUTE_KEY__' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/__YOUR_PARENT_ROUTE_KEY__'
],
'may_terminate' => false,
'child_routes' => [
$childRoutes
]
]
ROUTE;
};
echo '<pre>';
echo $writeRouteFromControllerKey($factories,'Your\\Namespace\\');
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment