Example #1
0
$container['router'] = function ($c) {
    $app_path = $c['app_path'];
    $routes = $c['routes'];
    return new \pew\router\Router($routes);
};
$container['routes'] = function ($c) {
    $app_folder = $c['app_path'];
    $routes_path = $app_folder . DIRECTORY_SEPARATOR . $c['config_folder'] . DIRECTORY_SEPARATOR . 'routes.php';
    $definitions = (require $routes_path);
    $routes = [];
    foreach ($definitions as $path => $handler) {
        if (is_a($handler, \pew\router\Route::class)) {
            $routes[] = $handler;
        } elseif (is_string($handler) || is_callable($handler)) {
            // convert simple route to array route
            $handler = \pew\router\Route::from($path)->handler($handler)->methods('GET', 'POST');
            $routes[] = $handler;
        } elseif (is_array($handler) && isset($handler['resource'])) {
            // create CRUD routes from resource route
            $controller_class = $handler['resource'];
            $slug = \Stringy\Stringy::create($controller_class)->humanize()->slugify();
            $underscored = $slug->underscored();
            $routes[] = ['path' => "/{$slug}/{id}/edit", 'handler' => "{$controller_class}@edit", 'methods' => 'GET POST', 'name' => "{$underscored}_edit", 'defaults' => $handler['defaults'] ?? [], 'conditions' => $handler['conditions'] ?? []];
            $routes[] = ['path' => "/{$slug}/{id}/delete", 'handler' => "{$controller_class}@delete", 'methods' => 'GET POST', 'name' => "{$underscored}_delete", 'defaults' => $handler['defaults'] ?? [], 'conditions' => $handler['conditions'] ?? []];
            $routes[] = ['path' => "/{$slug}/add", 'handler' => "{$controller_class}@add", 'methods' => 'GET POST', 'name' => "{$underscored}_add", 'defaults' => $handler['defaults'] ?? [], 'conditions' => $handler['conditions'] ?? []];
            $routes[] = ['path' => "/{$slug}/{id}", 'handler' => "{$controller_class}@view", 'name' => "{$underscored}_view", 'defaults' => $handler['defaults'] ?? [], 'conditions' => $handler['conditions'] ?? []];
            $routes[] = ['path' => "/{$slug}", 'handler' => "{$controller_class}@index", 'name' => "{$underscored}_index", 'defaults' => $handler['defaults'] ?? [], 'conditions' => $handler['conditions'] ?? []];
        } elseif (isset($handler['handler'], $handler['path'])) {
            $routes[] = $handler;
        } else {
            throw new \InvalidArgumentException("Invalid route: missing path or handler");