Skip to content

Instantly share code, notes, and snippets.

@Mika-
Created January 21, 2020 17:30
Show Gist options
  • Save Mika-/b0e86f93b9f22b5a1c93244a0e8368f6 to your computer and use it in GitHub Desktop.
Save Mika-/b0e86f93b9f22b5a1c93244a0e8368f6 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
final class Kernel extends Routes implements HttpKernelInterface
{
public function handle(Request $request, int $type = HttpKernelInterface::MASTER_REQUEST, bool $catch = true) : Response
{
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($this->routes, $context);
try {
$attributes = $matcher->match($request->getPathInfo());
$controller = $attributes['controller'];
$response = new Response();
$response = $controller($request, $response);
} catch (ResourceNotFoundException $e) {
$response = new Response('Not found!', Response::HTTP_NOT_FOUND);
}
return $response;
}
}
<?php
declare(strict_types=1);
namespace App;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class Routes
{
protected RouteCollection $routes;
public function __construct()
{
$this->routes = new RouteCollection();
}
public function getRouteCollection() : RouteCollection
{
return $this->routes;
}
public function route(string $path, callable $controller) : void
{
$this->routes->add($path, new Route($path, [
'controller' => $controller,
]));
}
public function with(string $path, callable $routes) : void
{
$subRoutes = new Routes();
$routes($subRoutes);
$subCollection = $subRoutes->getRouteCollection();
$subCollection->addNamePrefix($path);
$subCollection->addPrefix($path);
$this->routes->addCollection($subCollection);
}
}
<?php
declare(strict_types=1);
include('vendor/autoload.php');
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new App\Kernel();
$app->route('/', function (Request $request, Response $response) : Response {
$response->setContent('Root');
return $response;
});
$app->with('/news', function (App\Routes $app) {
$app->route('/', function (Request $request, Response $response) : Response {
$response->setContent('News root');
return $response;
});
$app->route('/{year<[0-9]{4}>}', function (Request $request, Response $response) : Response {
$response->setContent('News from ' . $request->getRequestUri());
return $response;
});
});
$request = Request::createFromGlobals();
$response = $app->handle($request);
$response->send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment