123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189 |
- <?php
- use demo\Controllers\BlogController;
- use demo\Controllers\FeedbackController;
- use demo\Controllers\UserController;
- use Silex\Application;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\HttpKernel\Exception\HttpException;
- use Symfony\Component\HttpKernel\HttpKernelInterface;
- //Request::setTrustedProxies(array('127.0.0.1'));
- // Fixed parameters for after() global middleware.
- $afterAllMiddleware = function (Request $request, Response $response, Application $app) {
- $MESSAGE = "<p>In aAM</p>\n";
- if ($response instanceof JsonResponse) {
- $content = $response->getContent();
- $raw = json_decode($content, TRUE);
- $raw[] = $MESSAGE;
- $newContent = json_encode($raw);
- $response->setContent($newContent);
- return $response;
- }
- // Only echo info on text responses.
- $ct = $response->headers->get('Content-Type');
- if (isset($ct) && strpos($ct, 'text') !== 0) {
- return;
- }
- echo $MESSAGE;
- };
- $beforeAllMiddleware = function (Request $request, Application $app) {
- // Only add info on requests URIs containing "json".
- if (!preg_match('/json/', $request->getRequestUri())) {
- echo "<p>In bAM</p>\n";
- }
- };
- // This type of global configuration does not apply to mounted controllers,
- // which have their own "global" configuration.
- $app->before($beforeAllMiddleware);
- $app->after($afterAllMiddleware);
- $app->get('/', function () use ($app) {
- return $app['twig']->render('index.html.twig', []);
- })->bind('homepage');
- // Redirect via response header
- $app->get('/home', function () use ($app) {
- return $app->redirect('/', Response::HTTP_TEMPORARY_REDIRECT); // Default 302.
- });
- // Forward to another controller to avoid redirection.
- $app->get('/blogz', function () use ($app) {
- $subRequest = Request::create('/blogs', 'GET');
- return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
- });
- $app->get('/all_blogs', function () use ($app) {
- /** @var \Symfony\Component\Routing\Generator\UrlGeneratorInterface $generator */
- $generator = $app['url_generator'];
- $subRequest = Request::create($generator->generate('blog_list', 'GET'));
- return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
- });
- $blogPosts = [
- 1 => [
- 'date' => '2011-03-29',
- 'author' => 'igorw',
- 'title' => 'Using Silex',
- 'body' => '...It takes time on version changes...',
- ],
- 2 => [
- 'date' => '2015-03-29',
- 'author' => 'igorw',
- 'title' => 'Using Silex 2',
- 'body' => '...Especialy S1 to S2...',
- ],
- ];
- // Available automatic arguments on controllers: Application, Request.
- $app->get('/blogs', function () use ($blogPosts) {
- $output = "<ul>\n";
- foreach ($blogPosts as $post) {
- $output .= "<li>" . $post ['title'] . "</li>\n";
- }
- $output .= "</ul>\n";
- return $output;
- })->bind('blog_list');
- $app->get('/blogs-json', function () use ($app, $blogPosts) {
- return $app->json($blogPosts);
- });
- $app->get('/blogs-json-view', function () use ($blogPosts) {
- return $blogPosts; // Rely on the view handler.
- });
- // Default: http://blog, not http://blog/
- $app->get('/blog/{id}', BlogController::class . '::fifiAction')
- ->assert('id', '\d+')
- ->when("request.headers.get('User-Agent') matches '/firefox/i'");
- $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
- if (!isset ($blogPosts [$id])) {
- // Will trigger the error() (or built-in) error handler.1
- $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
- }
- $post = $blogPosts [$id];
- return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
- })->assert('id', '\d+')
- ->value('id', 1)
- ->bind('blog_post');
- $app->post('/feedback', FeedbackController::class . '::feedbackAction');
- $app->get('/hello/{name}', function ($name, Application $app) {
- return $app->escape("Hello, $name");
- });
- $app->get('/hello-json/{name}', function ($name, Application $app) {
- return $app->json(['name' => $name]);
- });
- $app->get('/noise', function (Application $app) {
- $noise = base64_encode(random_bytes(2048));
- $stream = fopen('php://memory', 'r+');
- fwrite($stream, $noise);
- rewind($stream);
- $streamer = function () use($stream) {
- while (!feof($stream)) {
- echo fread($stream, 1024);
- ob_flush();
- flush();
- }
- fclose($stream);
- };
- return $app->stream($streamer, Response::HTTP_OK, ['Content-type' => 'text/plain']);
- });
- $app->get('/pass', function (Application $app) {
- return $app->sendFile('/etc/passwd');
- });
- $app->get('/user/{user}', UserController::class . '::itemAction')
- ->convert('user', 'converter.user:convert');
- // Register a view handler. They can also receive Request $request as 2nd arg,
- // e.g. for basic content negotiation.
- $app->view(function (array $controllerResult) use ($app) {
- // Does limited escaping using JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT.
- // Try /hello-json/<script>alert('Yo');<script> : Chrome with JSON Decode
- // extension throws JS error, which proves interpretation is triggered. This
- // is actually due to the extension.
- return $app->json($controllerResult);
- });
- // Handlers are examined in order, and called in a chain with the result of the
- // previous one. The last one must return a string or Response.
- /* Error handlers receive exactly these arguments, in that order. */
- $app->error(function (HttpException $e, Request $request, $code) {
- $response = new Response('HTTP Error caught: skipping generic error handler.',
- // This status is ignored by Silex, which tries to ensure status code
- // consistency with the exception.
- Response::HTTP_NOT_FOUND,
- // But we can force it with this fake header, which is removed before
- // sending the response to the user agent.
- ['X-Status-Code' => Response::HTTP_OK]);
- return $response;
- });
- /* Custom error handlers registered with error() take precedence over the
- built-in error handler provider by Silex, but the formatted error messages it
- provides can be accessed in debug mode by returning based on $app['debug']
- like this.
- */
- $app->error(function (\Exception $e, Request $request, $code) use ($app) {
- // Use the default handler in debug mode.
- if ($app['debug']) {
- return;
- }
- // Use our error formats otherwise.
- // 404.html, or 40x.html, or 4xx.html, or error.html
- $templates = [
- 'errors/' . $code . '.html.twig',
- 'errors/' . substr($code, 0, 2) . 'x.html.twig',
- 'errors/' . substr($code, 0, 1) . 'xx.html.twig',
- 'errors/default.html.twig',
- ];
- return new Response($app['twig']->resolveTemplate($templates)
- ->render(['code' => $code]), $code);
- });
|