|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Zend Framework (http://framework.zend.com/) |
| 4 | + * |
| 5 | + * @link http://github.com/zendframework/zf2 for the canonical source repository |
| 6 | + * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) |
| 7 | + * @license http://framework.zend.com/license/new-bsd New BSD License |
| 8 | + */ |
| 9 | + |
| 10 | +namespace Zend\Mvc\Controller; |
| 11 | + |
| 12 | +use Zend\EventManager\EventManager; |
| 13 | +use Zend\Http\Request; |
| 14 | +use Zend\Http\Response; |
| 15 | +use Zend\Mvc\Exception\RuntimeException; |
| 16 | +use Zend\Mvc\MvcEvent; |
| 17 | +use Zend\Psr7Bridge\Psr7Response; |
| 18 | +use Zend\Psr7Bridge\Psr7ServerRequest; |
| 19 | +use Zend\Router\RouteMatch; |
| 20 | + |
| 21 | +/** |
| 22 | + * Note: I'm a terrible person |
| 23 | + * |
| 24 | + * @internal don't use this in your codebase, or else @ocramius will hunt you down. This is just an internal |
| 25 | + * @internal hack to make middleware trigger 'dispatch' events attached to the DispatchableInterface identifier. |
| 26 | + */ |
| 27 | +final class MiddlewareController extends AbstractController |
| 28 | +{ |
| 29 | + /** |
| 30 | + * @var callable |
| 31 | + */ |
| 32 | + private $middleware; |
| 33 | + |
| 34 | + public function __construct(callable $middleware, EventManager $eventManager, MvcEvent $event) |
| 35 | + { |
| 36 | + $this->eventIdentifier = __CLASS__; |
| 37 | + $this->middleware = $middleware; |
| 38 | + |
| 39 | + $this->setEventManager($eventManager); |
| 40 | + $this->setEvent($event); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * {@inheritDoc} |
| 45 | + * @throws \Zend\Mvc\Exception\RuntimeException |
| 46 | + */ |
| 47 | + public function onDispatch(MvcEvent $e) |
| 48 | + { |
| 49 | + $request = $this->request; |
| 50 | + $response = $this->response; |
| 51 | + |
| 52 | + if (! $request instanceof Request) { |
| 53 | + throw new RuntimeException(sprintf( |
| 54 | + 'Expected request to be a %s, %s given', |
| 55 | + Request::class, |
| 56 | + get_class($request) |
| 57 | + )); |
| 58 | + } |
| 59 | + |
| 60 | + if (! $response instanceof Response) { |
| 61 | + throw new RuntimeException(sprintf( |
| 62 | + 'Expected response to be a %s, %s given', |
| 63 | + Response::class, |
| 64 | + get_class($response) |
| 65 | + )); |
| 66 | + } |
| 67 | + |
| 68 | + $routeMatch = $e->getRouteMatch(); |
| 69 | + $psr7Request = Psr7ServerRequest::fromZend($request)->withAttribute(RouteMatch::class, $routeMatch); |
| 70 | + |
| 71 | + if ($routeMatch) { |
| 72 | + foreach ($routeMatch->getParams() as $key => $value) { |
| 73 | + $psr7Request = $psr7Request->withAttribute($key, $value); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + $result = \call_user_func($this->middleware, $psr7Request, Psr7Response::fromZend($response)); |
| 78 | + |
| 79 | + $e->setResult($result); |
| 80 | + |
| 81 | + return $result; |
| 82 | + } |
| 83 | +} |
0 commit comments