[已弃用] PSR-7 中间件集合
Collection of PSR-7 middlewares.
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
function (RequestInterface $request, ResponseInterface $response, callable $next) {
// ...
}
So, you can use these midlewares with:
This package is installable and autoloadable via Composer as oscarotero/psr7-middlewares.
$ composer require oscarotero/psr7-middlewares
…
To generate access logs for each request using the Apache's access log format. This middleware requires a Psr log implementation, for example monolog:
use Psr7Middlewares\Middleware;
use Monolog\Logger;
use Monolog\Handler\ErrorLogHandler;
//Create the logger
$logger = new Logger('access');
$logger->pushHandler(new ErrorLogHandler());
$middlewares = [
//Required to get the Ip
Middleware::ClientIp(),
Middleware::AccessLog($logger) //Instance of Psr\Log\LoggerInterface
->combined(true) //(optional) To use the Combined Log Format instead the Common Log Format
];
Maps middleware specific attribute to regular request attribute under desired name:
…
To use Aura.Router (3.x) as a middleware:
…
Creates a new Aura.Session instance with the request.
use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\AuraSession;
$middlewares = [
Middleware::AuraSession(),
->factory($sessionFactory) //(optional) Intance of Aura\Session\SessionFactory
->name('my-session-name'), //(optional) custom session name
function ($request, $response, $next) {
//Get the session instance
$session = AuraSession::getSession($request);
return $response;
}
];
Removes the prefix from the uri path of the request. This is useful to combine with routers if the root of the website is in a subdirectory. For example, if the root of your website is /web/public, a request with the uri /web/public/post/34 will be converted to /post/34. You can provide the prefix to remove or let the middleware autodetect it. In the router you can retrieve the prefix removed or a callable to generate more urls with the base path.
use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\BasePath;
$middlewares = [
Middleware::BasePath('/web/public') // (optional) The path to remove...
->autodetect(true), // (optional) ...or/and autodetect the base path
function ($request, $response, $next) {
//Get the removed prefix
$basePath = BasePath::getBasePath($request);
//Get a callable to generate full paths
$generator = BasePath::getGenerator($request);
$generator('/other/path'); // /web/public/other/path
return $response;
}
];
Implements the basic http authentication. You have to provide an array with all users and password:
use Psr7Middlewares\Middleware;
$middlewares = [
Middleware::BasicAuthentication([
'username1' => 'password1',
'username2' => 'password2'
])
->realm('My realm'), //(optional) change the realm value
function ($request, $response, $next) {
$username = BasicAuthentication::getUsername($request);
return $next($request, $response);
}
];
To block referral spam using the piwik/referrer-spam-blacklist list
use Psr7Middlewares\Middleware;
$middlewares = [
Middleware::BlockSpam('spammers.txt'), //(optional) to set a custom spammers list instead the piwik's list
];
Requires micheh/psr7-cache. Saves the responses' headers in cache and returns a 304 response (Not modified) if the request is cached. It also adds Cache-Control and Last-Modified headers to the response. You need a cache library compatible with psr-6.
use Psr7Middlewares\Middleware;
$middlewares = [
Middleware::Cache(new Psr6CachePool()) //the PSR-6 cache implementation
->cacheControl('max-age=3600'), //(optional) to add this Cache-Control header to all responses
];
Detects the client ip(s).
…
To use the neomerx/cors-psr7 library:
…
To use the paragonie/csp-builder library to add the Content-Security-Policy header to the response.
$middlewares = [
Middleware::csp($directives) //(optional) the array with the directives.
->addSource('img-src', 'https://ytimg.com') //(optional) to add extra sources to whitelist
->addDirective('upgrade-insecure-requests', true) //(optional) to add new directives (if it doesn't already exist)
->supportOldBrowsers(false) //(optional) support old browsers (e.g. safari). True by default
];
To add a protection layer agains CSRF (Cross Site Request Forgery). The middleware injects a hidden input with a token in all POST forms and them check whether the token is valid or not. Use ->autoInsert() to insert automatically the token or, if you prefer, use the generator callable:
…
Inserts the PHP debug bar 1.x in the html body. This middleware requires Middleware::formatNegotiator executed before, to insert the debug bar only in Html responses.
use Psr7Middlewares\Middleware;
use DebugBar\StandardDebugBar;
$debugBar = new StandardDebugBar();
$middlewares = [
Middleware::FormatNegotiator(), //(recomended) to insert only in html responses
Middleware::DebugBar($debugBar) //(optional) Instance of debugbar
->captureAjax(true) //(optional) To send data in headers in ajax
];
Delays the response to simulate slow bandwidth in local environments. You can use a number or an array to generate random values in seconds.
use Psr7Middlewares\Middleware;
$middlewares = [
Middleware::delay(3.5), //delay the response 3.5 seconds
Middleware::delay([1, 2.5]), //delay the response between 1 and 1.5 seconds
];
Uses Mobile-Detect library to detect the client device.
use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\DetectDevice;
$middlewares = [
Middleware::DetectDevice(),
function ($request, $response, $next) {
//Get the device info
$device = DetectDevice::getDevice($request);
if ($device->isMobile()) {
//mobile stuff
}
elseif ($device->isTablet()) {
//tablet stuff
}
elseif ($device->is('bot')) {
//bot stuff
}
return $next($request, $response);
},
];
Implements the digest http authentication. You have to provide an array with the users and password:
use Psr7Middlewares\Middleware;
$middlewares = [
Middleware::DigestAuthentication([
'username1' => 'password1',
'username2' => 'password2'
])
->realm('My realm') //(optional) custom realm value
->nonce(uniqid()), //(optional) custom nonce value
function ($request, $response, $next) {
$username = DigestAuthentication::getUsername($request);
return $next($request, $response);
}
];
Uses willdurand/Negotiation (2.x) to detect and negotiate the encoding type of the document.
use Psr7Middlewares\Middleware;
use Psr7Middlewares\Middleware\EncodingNegotiator;
$middlewares = [
Middleware::EncodingNegotiator()
->encodings(['gzip', 'deflate']), //(optional) configure the supported encoding types
function ($request, $response, $next) {
//get the encoding (for example: gzip)
$encoding = EncodingNegotiator::getEncoding($request);
return $next($request, $response);
}
];
Executes a handler if the response returned by the next middlewares has any error (status code 400-599). You can catch also the exceptions throwed.
…
To use FastRoute as middleware.
use Psr7Middlewares\Middleware;
$router = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/blog/{id:[0-9]+}', function ($request, $response, $app) {
return 'This is the post number'.$request->getAttribute('id');
});
});
$middlewares = [
Middleware::FastRoute($router) //Instance of FastRoute\Dispatcher
->argument($myApp) //(optional) arguments appended to the controller
];
Uses M6Web/Firewall to provide an IP filtering. This middleware depends on ClientIp (to extract the ips from the headers).
See the ip formats allowed for trusted/untrusted options:
use Psr7Middlewares\Middleware;
$middlewares = [
//required to capture the user ips before
Middleware::ClientIp(),
//set the firewall
Middleware::Firewall()
->trusted(['123.0.0.*']) //(optional) i
暂无开放 Issues,或尚未同步最近议题。