Created
June 30, 2013 12:11
-
-
Save igorw/5894929 to your computer and use it in GitHub Desktop.
Conditional Strategy Stack Middleware.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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