Skip to content

Instantly share code, notes, and snippets.

@igorw
Created June 30, 2013 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorw/5894929 to your computer and use it in GitHub Desktop.
Save igorw/5894929 to your computer and use it in GitHub Desktop.
Conditional Strategy Stack Middleware.
<?php
class Conditional implements HttpKernelInterface {
private $app;
private $prefix;
private $wrappedApp;
public function __construct(HttpKernelInterface $app, $prefix, $spec) {
$this->app = $app;
$this->prefix = $prefix;
$this->wrappedApp = $this->wrapApp($spec);
}
public function handle(Request $request, $type = MASTER, $catch = true) {
$app = $this->requestMatchesPrefix($request) ? $this->wrappedApp : $this->app;
return $app->handle($request, $type, $catch);
}
private function wrapApp($spec) {
if (is_object($spec) && method_exists($spec, '__invoke')) {
return $spec($this->app);
}
list($className, $args) = $this->classSpec($spec);
return (new ReflectionClass($className))
->newInstanceArgs($args);
}
private function classSpec($spec) {
return is_string($spec) ? $this->stringSpec($spec) : $this->arraySpec($spec);
}
private function stringSpec($spec) {
$className = $spec;
$args = [];
return [$className, $args];
}
private function arraySpec($spec) {
$args = $spec;
$className = array_shift($args);
$args = array_merge([$this->app], $args);
return [$className, $args];
}
private function requestMatchesPrefix(Request $request) {
return 0 === strpos($request->getPath(), $this->prefix);
}
}
$app = (new Stack\Builder())
->push('Stack\Conditional', '/foo', function ($app) { return new Ducks\Stack\GeoIp($app); })
->push('Stack\Conditional', '/foo', 'Ducks\Stack\GeoIp')
->push('Stack\Conditional', '/foo', ['Ducks\Stack\GeoIp', ['adapter' => '...']])
->resolve($app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment