Commit | Line | Data |
---|---|---|
44d399bc S |
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; | |
11 | ||
12 | use Zend\EventManager\AbstractListenerAggregate; | |
13 | use Zend\EventManager\EventManagerInterface; | |
14 | ||
15 | class RouteListener extends AbstractListenerAggregate | |
16 | { | |
17 | /** | |
18 | * Attach to an event manager | |
19 | * | |
20 | * @param EventManagerInterface $events | |
21 | * @param int $priority | |
22 | * @return void | |
23 | */ | |
24 | public function attach(EventManagerInterface $events, $priority = 1) | |
25 | { | |
26 | $this->listeners[] = $events->attach(MvcEvent::EVENT_ROUTE, [$this, 'onRoute']); | |
27 | } | |
28 | ||
29 | /** | |
30 | * Listen to the "route" event and attempt to route the request | |
31 | * | |
32 | * If no matches are returned, triggers "dispatch.error" in order to | |
33 | * create a 404 response. | |
34 | * | |
35 | * Seeds the event with the route match on completion. | |
36 | * | |
37 | * @param MvcEvent $e | |
38 | * @return null|Router\RouteMatch | |
39 | */ | |
40 | public function onRoute($e) | |
41 | { | |
42 | $target = $e->getTarget(); | |
43 | $request = $e->getRequest(); | |
44 | $router = $e->getRouter(); | |
45 | $routeMatch = $router->match($request); | |
46 | ||
47 | if (!$routeMatch instanceof Router\RouteMatch) { | |
48 | $e->setName(MvcEvent::EVENT_DISPATCH_ERROR); | |
49 | $e->setError(Application::ERROR_ROUTER_NO_MATCH); | |
50 | ||
51 | $results = $target->getEventManager()->triggerEvent($e); | |
52 | if (count($results)) { | |
53 | return $results->last(); | |
54 | } | |
55 | ||
56 | return $e->getParams(); | |
57 | } | |
58 | ||
59 | $e->setRouteMatch($routeMatch); | |
60 | return $routeMatch; | |
61 | } | |
62 | } |