Each middleware can be associated with a particular path; if that
path is matched when that middleware is invoked, it will be processed;
otherwise it is skipped.
No path means it should be executed every request cycle.
A handler CAN implement MiddlewareInterface, but MUST be callable.
Handlers with arity >= 4 or those implementing ErrorMiddlewareInterface
are considered error handlers, and will be executed when a handler calls
$next with an error or raises an exception.
public function __invoke(ContainerInterface $container) : callable { $pipeline = new MiddlewarePipe(); $pipeline->pipe($container->get('Mwop\\Auth\\UserSession')); $pipeline->pipe(new Page($container->get(TemplateRendererInterface::class), $container->get(UnauthorizedResponseFactory::class))); return $pipeline; }
public function __invoke($services) { $pipeline = new MiddlewarePipe(); $pipeline->pipe($services->get('Mwop\\Auth\\UserSession')); $pipeline->pipe(new Page('mwop::comics.page', $services->get(TemplateRendererInterface::class))); return $pipeline; }
/** * @param Application $app * @return \Zend\Stratigility\MiddlewareInterface */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $pipe->pipe(new ApiServer()); $pipe->pipe(new AdminServer()); $pipe->pipe(new ForumServer()); return $pipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $path = config('hyn.laravel-flarum.paths.api'); // if ($app->isInstalled() && $app->isUpToDate()) { $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($path, $app->make('Flarum\\Api\\Middleware\\FakeHttpMethods')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\RememberFromCookie')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithHeader')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\SetLocale')); event(new ConfigureMiddleware($pipe, $path, $this)); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.api.routes')])); $pipe->pipe($path, $app->make('Flarum\\Api\\Middleware\\HandleErrors')); // } else { // $pipe->pipe($path, function () { // $document = new Document; // $document->setErrors([ // [ // 'code' => 503, // 'title' => 'Service Unavailable' // ] // ]); // // return new JsonApiResponse($document, 503); // }); // } return $pipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); if ($app->isInstalled()) { $app->register('Flarum\\Admin\\AdminServiceProvider'); $adminPath = parse_url($app->url('admin'), PHP_URL_PATH); $routes = $app->make('flarum.admin.routes'); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithCookie')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($adminPath, $app->make('Flarum\\Admin\\Middleware\\RequireAdministrateAbility')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', compact('routes'))); $pipe->pipe(new HandleErrors(__DIR__ . '/../../error', $app->inDebugMode())); } return $pipe; }
/** * Marshal a middleware pipe from an array of middleware. * * Each item in the array can be one of the following: * * - A callable middleware * - A string service name of middleware to retrieve from the container * - A string class name of a constructor-less middleware class to * instantiate * * As each middleware is verified, it is piped to the middleware pipe. * * @param array $middlewares * @param null|ContainerInterface $container * @param bool $forError Whether or not the middleware pipe generated is * intended to be populated with error middleware; defaults to false. * @return MiddlewarePipe * @throws Exception\InvalidMiddlewareException for any invalid middleware items. */ private function marshalMiddlewarePipe(array $middlewares, ContainerInterface $container = null, $forError = false) { $middlewarePipe = new MiddlewarePipe(); foreach ($middlewares as $middleware) { $middlewarePipe->pipe($this->prepareMiddleware($middleware, $container, $forError)); } return $middlewarePipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $installed = $app->isInstalled(); $basePath = parse_url($app->url(), PHP_URL_PATH); if ($installed) { $app->register('Flarum\\Forum\\ForumServiceProvider'); $routes = $app->make('flarum.forum.routes'); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithCookie')); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); } else { $app->register('Flarum\\Install\\InstallServiceProvider'); $routes = $app->make('flarum.install.routes'); } $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', compact('routes'))); $pipe->pipe(new HandleErrors(__DIR__ . '/../../error', $app->inDebugMode() || !$installed)); return $pipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $apiPath = parse_url($app->url('api'), PHP_URL_PATH); if ($app->isInstalled() && $app->isUpToDate()) { $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($apiPath, $app->make('Flarum\\Api\\Middleware\\FakeHttpMethods')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\RememberFromCookie')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithSession')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithHeader')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\SetLocale')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.api.routes')])); $pipe->pipe($apiPath, $app->make('Flarum\\Api\\Middleware\\HandleErrors')); } else { $pipe->pipe($apiPath, function () { $document = new Document(); $document->setErrors([['code' => 503, 'title' => 'Service Unavailable']]); return new JsonApiResponse($document, 503); }); } return $pipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); if ($app->isInstalled()) { $adminPath = parse_url($app->url('admin'), PHP_URL_PATH); $errorDir = __DIR__ . '/../../error'; if ($app->isUpToDate()) { $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\RememberFromCookie')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithSession')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\SetLocale')); $pipe->pipe($adminPath, $app->make('Flarum\\Admin\\Middleware\\RequireAdministrateAbility')); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.admin.routes')])); $pipe->pipe($adminPath, new HandleErrors($errorDir, $app->inDebugMode())); } else { $app->register('Flarum\\Update\\UpdateServiceProvider'); $pipe->pipe($adminPath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.update.routes')])); $pipe->pipe($adminPath, new HandleErrors($errorDir, true)); } } return $pipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); if ($app->isInstalled()) { $app->register('Flarum\\Api\\ApiServiceProvider'); $routes = $app->make('flarum.api.routes'); $apiPath = parse_url($app->url('api'), PHP_URL_PATH); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithCookie')); $pipe->pipe($apiPath, $app->make('Flarum\\Api\\Middleware\\AuthenticateWithHeader')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($apiPath, $app->make('Flarum\\Api\\Middleware\\FakeHttpMethods')); $pipe->pipe($apiPath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', compact('routes'))); $pipe->pipe($apiPath, $app->make('Flarum\\Api\\Middleware\\HandleErrors')); } return $pipe; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $basePath = parse_url($app->url(), PHP_URL_PATH); $errorDir = __DIR__ . '/../../error'; if (!$app->isInstalled()) { $app->register('Flarum\\Install\\InstallServiceProvider'); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.install.routes')])); $pipe->pipe($basePath, new HandleErrors($errorDir, true)); } elseif ($app->isUpToDate()) { $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithCookie')); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($basePath, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.forum.routes')])); $pipe->pipe($basePath, new HandleErrors($errorDir, $app->inDebugMode())); } else { $pipe->pipe($basePath, function () use($errorDir) { return new HtmlResponse(file_get_contents($errorDir . '/503.html', 503)); }); } return $pipe; }
/** * @todo Remove for 2.0.0, as error middleware is removed in that version. * @group error-handling */ public function testEnablingRaiseThrowablesCausesProcessToThrowExceptions() { $expected = new RuntimeException('To throw from middleware'); $pipeline = new MiddlewarePipe(); $pipeline->raiseThrowables(); $middleware = $this->prophesize(ServerMiddlewareInterface::class); $middleware->process(Argument::type(ServerRequestInterface::class), Argument::type(DelegateInterface::class))->will(function () use($expected) { throw $expected; }); $pipeline->pipe($middleware->reveal()); $done = $this->prophesize(DelegateInterface::class); $done->process(Argument::any())->shouldNotBeCalled(); try { $pipeline->process($this->request, $done->reveal()); $this->fail('Pipeline with middleware that throws did not result in exception!'); } catch (RuntimeException $e) { $this->assertSame($expected, $e); } catch (Throwable $e) { $this->fail(sprintf('Unexpected throwable raised by pipeline: %s', $e->getMessage())); } catch (\Exception $e) { $this->fail(sprintf('Unexpected exception raised by pipeline: %s', $e->getMessage())); } }
/** * Overload pipe() operation. * * Middleware piped may be either callables or service names. Middleware * specified as services will be wrapped in a closure similar to the * following: * * <code> * function ($request, $response, $next = null) use ($container, $middleware) { * $invokable = $container->get($middleware); * if (! is_callable($invokable)) { * throw new Exception\InvalidMiddlewareException(sprintf( * 'Lazy-loaded middleware "%s" is not invokable', * $middleware * )); * } * return $invokable($request, $response, $next); * }; * </code> * * This is done to delay fetching the middleware until it is actually used; * the upshot is that you will not be notified if the service is invalid to * use as middleware until runtime. * * Additionally, ensures that the route middleware is only ever registered * once. * * @param string|callable $path Either a URI path prefix, or middleware. * @param null|string|callable $middleware Middleware * @return self */ public function pipe($path, $middleware = null) { // Lazy-load middleware from the container when possible $container = $this->container; if (null === $middleware && is_string($path) && $container && $container->has($path)) { $middleware = $this->marshalLazyMiddlewareService($path, $container); $path = '/'; } elseif (is_string($middleware) && !is_callable($middleware) && $container && $container->has($middleware)) { $middleware = $this->marshalLazyMiddlewareService($middleware, $container); } elseif (null === $middleware && is_callable($path)) { $middleware = $path; $path = '/'; } if ($middleware === [$this, 'routeMiddleware'] && $this->routeMiddlewareIsRegistered) { return $this; } parent::pipe($path, $middleware); if ($middleware === [$this, 'routeMiddleware']) { $this->routeMiddlewareIsRegistered = true; } return $this; }
use Flarum\Forum\Middleware\HandleErrors; use Franzl\Middleware\Whoops\Middleware as WhoopsMiddleware; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; $app = (require __DIR__ . '/flarum/bootstrap.php'); // If Flarum's configuration exists, then we can assume that installation has // been completed. We will set up a middleware pipe to route the request through // to one of the main forum actions. if (Core::isInstalled()) { $app->register('Flarum\\Forum\\ForumServiceProvider'); $flarum = new MiddlewarePipe(); $flarum->pipe($app->make('Flarum\\Forum\\Middleware\\LoginWithCookie')); $flarum->pipe($app->make('Flarum\\Api\\Middleware\\ReadJsonParameters')); $basePath = parse_url(Core::url(), PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.forum.routes')]); $flarum->pipe($basePath, $router); if (Core::inDebugMode()) { $flarum->pipe(new WhoopsMiddleware()); } else { $flarum->pipe(new HandleErrors(base_path('error'))); } } else { $app->register('Flarum\\Install\\InstallServiceProvider'); $flarum = new MiddlewarePipe(); $basePath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.install.routes')]); $flarum->pipe($basePath, $router); $flarum->pipe(new WhoopsMiddleware()); } $server = Server::createServer($flarum, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
public function pipe(callable $middleware) { $this->pipe->pipe($this->path, $middleware); }
use ReputationVIP\QueueClient\Adapter\FileAdapter; $adapter = new FileAdapter('/tmp'); $queueClient = new QueueClient($adapter); //$queueClient->createQueue('testQueue'); $queueClient->addMessage('testQueue', 'testMessage'); $messages = $queueClient->getMessages('testQueue'); $message = $messages[0]; $queueClient->deleteMessage('testQueue', $message); echo $message['Body']; */ $container = (include 'config/container.php'); $tableName = 'test_res_http'; //'index_php_table'; //include 'createTable.php'; $app = new MiddlewarePipe(); $authPipeLine = new MiddlewarePipe(); $identificationFactory = new \zaboy\Auth\Middleware\IdentificationFactory(); $aclFactory = new \zaboy\Acl\Middleware\AclFactory(); $authErrorFactory = new \zaboy\Auth\Middleware\AuthErrorHandlerFactory(); $authPipeLine->pipe('/', $identificationFactory($container)); $authPipeLine->pipe('/', $aclFactory($container)); $authPipeLine->pipe('/', $aclFactory($container)); $authPipeLine->pipe('/', $authErrorFactory($container)); $app->pipe('/', $authPipeLine); $server = Server::createServer($app, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen(); //$deleteStatementStr = "DROP TABLE IF EXISTS " . $quoteTableName; //$deleteStatement = $adapter->query($deleteStatementStr); //$deleteStatement->execute();
<?php use Zend\Stratigility\MiddlewarePipe; use Zend\Diactoros\Server; use Middleware\RouteManager; require_once __DIR__ . '/../vendor/autoload.php'; $app = new MiddlewarePipe(); $app->pipe(new RouteManager(require_once __DIR__ . '/../config/routes.php')); $server = Server::createServer($app, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
// Change to the project root, to simplify resolving paths chdir(dirname(__DIR__)); // Setup autoloading require '/vendor/autoload.php'; use Zend\Stratigility\MiddlewarePipe; use Zend\Diactoros\Server; use zaboy\middleware\Middleware; $container = (include 'config/container.php'); $app = new MiddlewarePipe(); $head = new MiddlewarePipe(); $head->pipe('/', new Middleware\HTML\Head()); $head->pipe('/', new Middleware\Dojo\DojoInHead()); $head->pipe('/', new Middleware\Dojo\Grid\GetAllRequestHeaders()); $head->pipe('/', new Middleware\Dojo\Grid\GetAllAllType()); $head->pipe('/', new Middleware\Returner()); $app->pipe('/HTML', $head); $app->pipe('/HTML', new Middleware\HTML\Html()); $app->pipe('/HTML', new Middleware\HTML\Body()); //$app->pipe('/', new Middleware\WriteURI()); $app->pipe('/HTML', new Middleware\Rql\RqlParser()); $app->pipe('/GetAllRequestHeaders', new Middleware\API\Get\GetAllRequestHeaders()); $app->pipe('/AllType', $container->get('GetAllAllType')); $rest = new MiddlewarePipe(); //set Attribute 'Resource-Name' //It can do router if you use zend-expressive $rest->pipe('/', new Middleware\ResourceResolver()); $restMiddlewareLazy = function ($request, $response, $next = null) use($container) { $resourceName = $request->getAttribute('Resource-Name'); $restActionPipeFactory = new RestActionPipeFactory(); $restActionPipe = $restActionPipeFactory($container, $resourceName); return $restActionPipe($request, $response, $next);
<?php use Zend\Stratigility\MiddlewarePipe; use Application\NotFound; return call_user_func(function () { $services = (include 'config/services.php'); $app = new MiddlewarePipe(); // basics eg.redirect // site 1 $app->pipe($services->get('application')); // errors $app->pipe(new NotFound()); // authentication // error handler $app->pipe($services->get('ErrorHandler')); return $app; });
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Flarum\Core; use Flarum\Forum\Middleware\HandleErrors; use Franzl\Middleware\Whoops\Middleware as WhoopsMiddleware; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; $app = (require __DIR__ . '/flarum/bootstrap.php'); $app->register('Flarum\\Admin\\AdminServiceProvider'); $admin = new MiddlewarePipe(); $admin->pipe($app->make('Flarum\\Api\\Middleware\\ReadJsonParameters')); $admin->pipe($app->make('Flarum\\Admin\\Middleware\\LoginWithCookieAndCheckAdmin')); $adminPath = parse_url(Core::url('admin'), PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.admin.routes')]); $admin->pipe($adminPath, $router); if (Core::inDebugMode()) { $admin->pipe(new WhoopsMiddleware()); } else { $admin->pipe(new HandleErrors(base_path('error'))); } $server = Server::createServer($admin, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Flarum\Api\Middleware\JsonApiErrors; use Flarum\Core; use Franzl\Middleware\Whoops\Middleware as WhoopsMiddleware; use Zend\Diactoros\Server; use Zend\Stratigility\MiddlewarePipe; $app = (require __DIR__ . '/flarum/bootstrap.php'); $app->register('Flarum\\Api\\ApiServiceProvider'); $api = new MiddlewarePipe(); $api->pipe($app->make('Flarum\\Api\\Middleware\\ReadJsonParameters')); $api->pipe($app->make('Flarum\\Api\\Middleware\\LoginWithHeader')); $apiPath = parse_url(Core::url('api'), PHP_URL_PATH); $router = $app->make('Flarum\\Http\\RouterMiddleware', ['routes' => $app->make('flarum.api.routes')]); $api->pipe($apiPath, $router); if (Core::inDebugMode()) { $api->pipe(new WhoopsMiddleware()); } else { $api->pipe(new JsonApiErrors()); } $server = Server::createServer($api, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
/** * Test that FinalHandler is passed the original response. * * Tests that MiddlewarePipe passes the original response passed to it when * creating the FinalHandler instance, and that FinalHandler compares the * response passed to it on invocation to its original response. * * If the two differ, the response passed during invocation should be * returned unmodified; this is an indication that a middleware has provided * a response, and is simply passing further up the chain to allow further * processing (e.g., to allow an application-wide logger at the end of the * request). * * @group nextChaining */ public function testPassesOriginalResponseToFinalHandler() { $request = new Request([], [], 'http://local.example.com/foo', 'GET', 'php://memory'); $response = new Response(); $test = new Response(); $pipeline = new MiddlewarePipe(); $pipeline->pipe(function ($req, $res, $next) use($test) { return $next($req, $test); }); // Pipeline MUST return response passed to $next if it differs from the // original. $result = $pipeline($request, $response); $this->assertSame($test, $result); }
/** * Overload pipe() operation. * * Middleware piped may be either callables or service names. Middleware * specified as services will be wrapped in a closure similar to the * following: * * <code> * function ($request, $response, $next = null) use ($container, $middleware) { * $invokable = $container->get($middleware); * if (! is_callable($invokable)) { * throw new Exception\InvalidMiddlewareException(sprintf( * 'Lazy-loaded middleware "%s" is not invokable', * $middleware * )); * } * return $invokable($request, $response, $next); * }; * </code> * * This is done to delay fetching the middleware until it is actually used; * the upshot is that you will not be notified if the service is invalid to * use as middleware until runtime. * * Middleware may also be passed as an array; each item in the array must * resolve to middleware eventually (i.e., callable or service name). * * Finally, ensures that the route middleware is only ever registered * once. * * @param string|array|callable $path Either a URI path prefix, or middleware. * @param null|string|array|callable $middleware Middleware * @return self */ public function pipe($path, $middleware = null) { if (null === $middleware) { $middleware = $this->prepareMiddleware($path, $this->container); $path = '/'; } if (!is_callable($middleware) && (is_string($middleware) || is_array($middleware))) { $middleware = $this->prepareMiddleware($middleware, $this->container); } if ($middleware === [$this, 'routeMiddleware'] && $this->routeMiddlewareIsRegistered) { return $this; } if ($middleware === [$this, 'dispatchMiddleware'] && $this->dispatchMiddlewareIsRegistered) { return $this; } parent::pipe($path, $middleware); if ($middleware === [$this, 'routeMiddleware']) { $this->routeMiddlewareIsRegistered = true; } if ($middleware === [$this, 'dispatchMiddleware']) { $this->dispatchMiddlewareIsRegistered = true; } return $this; }
/** * {@inheritdoc} */ protected function getMiddleware(Application $app) { $pipe = new MiddlewarePipe(); $path = parse_url($app->url(), PHP_URL_PATH); $errorDir = __DIR__ . '/../../error'; if (!$app->isInstalled()) { $app->register('Flarum\\Install\\InstallServiceProvider'); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.install.routes')])); $pipe->pipe($path, new HandleErrors($errorDir, $app->make('log'), true)); } elseif ($app->isUpToDate() && !$app->isDownForMaintenance()) { $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\ParseJsonBody')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\StartSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\RememberFromCookie')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\AuthenticateWithSession')); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\SetLocale')); event(new ConfigureMiddleware($pipe, $path, $this)); $pipe->pipe($path, $app->make('Flarum\\Http\\Middleware\\DispatchRoute', ['routes' => $app->make('flarum.forum.routes')])); $pipe->pipe($path, new HandleErrors($errorDir, $app->make('log'), $app->inDebugMode())); } else { $pipe->pipe($path, function () use($errorDir) { return new HtmlResponse(file_get_contents($errorDir . '/503.html', 503)); }); } return $pipe; }
array( 'driver' => 'Pdo_Mysql', 'database' => 'zav_res', 'username' => 'root', 'password' => '' ) ); $qi = function($name) use ($adapter) { return $adapter->platform->quoteIdentifier($name); }; $fp = function($name) use ($adapter) { return $adapter->driver->formatParameterName($name); }; $statement = $adapter->query('SELECT * FROM ' . $qi('res_test') . ' WHERE id = ' . $fp('val_id')); $results = $statement->execute(array('val_id' => 3)); $row = $results->current(); $name = $row['notes']; */ $memory = $container->get('testMemory'); var_dump($memory); $app = new MiddlewarePipe(); // Landing page $app->pipe('/', function ($req, $res, $next) { if (!in_array($req->getUri()->getPath(), ['/', ''], true)) { return $next($req, $res); } return $res->end('Hello world!'); }); $restPipe = (new RestActionPipeFactory())->__invoke(); // Another page $app->pipe('/rest', $restPipe); $server = Server::createServer($app, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
/** * Marshal a middleware pipe from an array of middleware. * * Each item in the array can be one of the following: * * - A callable middleware * - A string service name of middleware to retrieve from the container * - A string class name of a constructor-less middleware class to * instantiate * * As each middleware is verified, it is piped to the middleware pipe. * * @param array $middlewares * @return MiddlewarePipe * @throws Exception\InvalidMiddlewareException for any invalid middleware items. */ private function marshalMiddlewarePipe(array $middlewares) { $middlewarePipe = new MiddlewarePipe(); foreach ($middlewares as $middleware) { $middlewarePipe->pipe($this->marshalMiddleware($middleware)); } return $middlewarePipe; }
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Zend\Diactoros\Server; use Zend\Stratigility\Http\Response as ZendResponse; use Zend\Stratigility\MiddlewarePipe; // Instantiate the application, register providers etc. $app = (require __DIR__ . '/system/bootstrap.php'); // Build a middleware pipeline for Flarum $flarum = new MiddlewarePipe(); $flarum->pipe($app->make('Flarum\\Forum\\Middleware\\LoginWithCookie')); $api = new MiddlewarePipe(); $api->pipe($app->make('Flarum\\Api\\Middleware\\ReadJsonParameters')); $api->pipe($app->make('Flarum\\Api\\Middleware\\LoginWithHeader')); $admin = new MiddlewarePipe(); $admin->pipe($app->make('Flarum\\Admin\\Middleware\\LoginWithCookieAndCheckAdmin')); $flarum->pipe('/api', $api); $flarum->pipe('/admin', $admin); $flarum->pipe(function (Request $request, Response $response, $next) use($app) { /** @var Flarum\Http\Router $router */ $router = $app->make('Flarum\\Http\\Router'); $response = new ZendResponse($router->dispatch($request)); return $next($request, $response); }); $server = Server::createServer($flarum, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server->listen();
/** * Overload pipe() operation * * Ensures that the route middleware is only ever registered once. * * @param string|callable|object $path Either a URI path prefix, or middleware. * @param null|callable|object $middleware Middleware * @return self */ public function pipe($path, $middleware = null) { if (null === $middleware && is_callable($path)) { $middleware = $path; $path = '/'; } if ($middleware === [$this, 'routeMiddleware'] && $this->routeMiddlewareIsRegistered) { return $this; } parent::pipe($path, $middleware); if ($middleware === [$this, 'routeMiddleware']) { $this->routeMiddlewareIsRegistered = true; } return $this; }
/** * @param string|callable $pathOrMiddleware * @param null|callable $middleware */ public function add($pathOrMiddleware, $middleware = null) { $this->pipe->pipe($pathOrMiddleware, $middleware); }
/** * Pipe an error handler. * * Middleware piped may be either callables or service names. Middleware * specified as services will be wrapped in a closure similar to the * following: * * <code> * function ($error, $request, $response, $next) use ($container, $middleware) { * $invokable = $container->get($middleware); * if (! is_callable($invokable)) { * throw new Exception\InvalidMiddlewareException(sprintf( * 'Lazy-loaded middleware "%s" is not invokable', * $middleware * )); * } * return $invokable($error, $request, $response, $next); * }; * </code> * * This is done to delay fetching the middleware until it is actually used; * the upshot is that you will not be notified if the service is invalid to * use as middleware until runtime. * * Once middleware detection and wrapping (if necessary) is complete, * proxies to pipe(). * * @param string|callable $path Either a URI path prefix, or middleware. * @param null|string|callable $middleware Middleware * @return self */ public function pipeErrorHandler($path, $middleware = null) { if (null === $middleware) { $middleware = $this->prepareMiddleware($path, $this->container, $forError = true); $path = '/'; } if (!is_callable($middleware) && (is_string($middleware) || is_array($middleware))) { $middleware = $this->prepareMiddleware($middleware, $this->container, $forError = true); } parent::pipe($path, $middleware); return $this; }