Exemplo n.º 1
0
 /**
  * Check for document from route
  *
  * @param EventInterface $event Mvc Event
  *
  * @return void
  */
 public function onRoute(EventInterface $event)
 {
     $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName();
     if ($matchedRouteName !== 'cms') {
         return;
     }
     $serviceManager = $event->getApplication()->getServiceManager();
     $isAdmin = $serviceManager->get('Auth')->hasIdentity();
     $isPreview = ($isAdmin and $event->getRequest()->getQuery()->get('preview') === 'true');
     $path = ltrim($event->getRouteMatch()->getParam('path'), '/');
     if (empty($path)) {
         $document = Document\Model::fromUrlKey('');
     } else {
         $document = $this->findDocument($path, $isPreview);
     }
     $this->logVisitor($isPreview, $isAdmin);
     if (empty($document) or !$document->isPublished() and !$isPreview) {
         $serviceManager->setService('CurrentDocument', false);
     } else {
         $translator = $serviceManager->get('MvcTranslator');
         $translator->setLocale($this->getLocale($document));
         AbstractValidator::setDefaultTranslator($translator);
         $serviceManager->setService('CurrentDocument', $document);
     }
 }
Exemplo n.º 2
0
 /**
  * Listen to the "route" event and check the user rights
  *
  * @param  MvcEvent $e
  * @return null
  */
 public function checkAcl(EventInterface $e)
 {
     // get route match, params and objects
     $routeMatch = $e->getRouteMatch();
     $controllerParam = $routeMatch->getParam('controller');
     $actionParam = $routeMatch->getParam('action');
     $serviceManager = $e->getApplication()->getServiceManager();
     $controllerLoader = $serviceManager->get('ControllerLoader');
     $acl = $serviceManager->get('User\\Acl\\Service');
     // try to load current controller
     try {
         $controller = $controllerLoader->get($controllerParam);
     } catch (\Exception $exception) {
         return;
     }
     // check acl
     if (!$acl->isAllowed($controllerParam, $actionParam)) {
         // check for guests
         if ($acl->getRole() == 'guest') {
             $routeMatch->setParam('controller', 'user');
             $routeMatch->setParam('action', 'login');
         } else {
             $routeMatch->setParam('controller', 'user');
             $routeMatch->setParam('action', 'forbidden');
         }
     }
 }
Exemplo n.º 3
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $config = $sm->get('Config');
     $acl = new Acl($config);
     $role = Acl::DEFAULT_ROLE;
     if ($auth->hasIdentity()) {
         $user = $auth->getIdentity();
         $role = $user->getUserRole()->getRole();
     }
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if (!$acl->hasResource($controller)) {
         throw new \Exception('Resource ' . $controller . ' not defined');
     }
     if (!$acl->isAllowed($role, $controller, $action)) {
         $url = $e->getRouter()->assemble(array(), array('name' => 'home/login'));
         $response = $e->getResponse();
         $response->getHeaders()->addHeaderLine('Location', $url);
         $response->setStatusCode(302);
         $response->sendHeaders();
         exit;
     }
 }
Exemplo n.º 4
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $config = $sm->get('Config');
     $acl = new Acl($config);
     // everyone is guest until logging in
     $role = Acl::DEFAULT_ROLE;
     // The default role is guest $acl
     if ($auth->hasIdentity()) {
         $user = $auth->getIdentity();
         $role = $user->getRole()->getName();
     }
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if (!$acl->hasResource($controller)) {
         throw new \Exception('Resource ' . $controller . ' not defined');
     }
     if (!$acl->isAllowed($role, $controller, $action)) {
         $url = $e->getRouter()->assemble(array(), array('name' => 'home'));
         $response = $e->getResponse();
         $response->getHeaders()->addHeaderLine('Location', $url);
         // The HTTP response status code 302 Found is a common way of performing a redirection.
         // http://en.wikipedia.org/wiki/HTTP_302
         $response->setStatusCode(302);
         $response->sendHeaders();
         exit;
     }
 }
Exemplo n.º 5
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $config = $sm->get('Config');
     $acl = new Acl($config);
     // everyone is guest untill it gets logged in
     $role = Acl::DEFAULT_ROLE;
     // The default role is guest $acl
     if ($auth->hasIdentity()) {
         $usr = $auth->getIdentity();
         $usrl_id = $usr->role_id;
         // Use a view to get the name of the role
         // TODO we don't need that if the names of the roles are comming from the DB
         switch ($usrl_id) {
             case 1:
                 $role = Acl::ADMIN_ROLE;
                 break;
             case 2:
                 $role = Acl::MANAGE_ROLE;
                 break;
             case 3:
                 $role = Acl::SATFF_ROLE;
                 break;
             case 4:
                 $role = Acl::AGENCY_ROLE;
                 break;
             default:
                 $role = Acl::DEFAULT_ROLE;
                 break;
         }
     }
 }
Exemplo n.º 6
0
 /**
  * @internal
  */
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     // Validate loglevel value. Invalid content will cause the route to fail
     // and trigger the usage message.
     if (!preg_match('/^(emerg|alert|crit|err|warn|notice|info|debug)?$/', $e->getRouteMatch()->getParam('loglevel'))) {
         $e->setError(\Zend\Mvc\Application::ERROR_ROUTER_NO_MATCH);
         $e->getTarget()->getEventManager()->trigger(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, $e);
     }
 }
Exemplo n.º 7
0
 /**
  * @internal
  */
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     // Validate loglevel value. Invalid content will cause the route to fail
     // and trigger the usage message.
     $logLevel = $e->getRouteMatch()->getParam('loglevel');
     if ($logLevel != '' and !\Zend\Validator\StaticValidator::execute($logLevel, 'Library\\LogLevel')) {
         $e->setError(\Zend\Mvc\Application::ERROR_ROUTER_NO_MATCH);
         $e->setName(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR);
         $e->getTarget()->getEventManager()->triggerEvent($e);
     }
 }
Exemplo n.º 8
0
 public function renderSeo(EventInterface $e)
 {
     $sm = $e->getApplication()->getServiceManager();
     $config = $sm->get('config');
     $routes = $config['seo']['seo_routes'];
     $seoRoute = $e->getRouteMatch()->getMatchedRouteName();
     $params = $e->getRouteMatch()->getParams();
     $id = $params['id'];
     $type = $routes[$seoRoute];
     $seo = $this->seoService->getSeoByTypeId($id, $type);
     if ($seo) {
         // get view Model
         $renderer = $sm->get('Zend\\View\\Renderer\\PhpRenderer');
         $renderer->headTitle()->append(ucfirst($seo->getTitle()));
         $renderer->headMeta()->appendName('description', $seo->getDescription());
         $renderer->headMeta()->setName('keywords', $seo->getKeywords());
     }
     // return response
     return $e->getResponse();
 }
Exemplo n.º 9
0
 public function onRoute(EventInterface $poEvent)
 {
     $loApplication = $poEvent->getApplication();
     $loRouteMatch = $poEvent->getRouteMatch();
     $loServiceManager = $loApplication->getServiceManager();
     $loEventManager = $loApplication->getEventManager();
     $loEvents = $loEventManager->getSharedManager();
     $loSession = new Session();
     $loUser = $loSession->getRegister('OnionAuth');
     $laMenu = Config::getAppOptions('menu');
     $lsRole = Acl::DEFAULT_ROLE;
     //guest
     if ($loUser !== null) {
         $lnGroup = $loUser->get('UserGroup_id');
         if (isset($laMenu['groups'][$lnGroup])) {
             $lsRole = $laMenu['groups'][$lnGroup];
         }
     }
     $laMenu = $laMenu[$lsRole];
     $loEvents->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($event) use($laMenu, $loUser) {
         $loController = $event->getTarget();
         $loController->layout()->laMenu = $laMenu;
         $loController->layout()->loUser = $loUser;
         $loController->layout()->loController = $loController;
     }, 100);
     $lsController = $loRouteMatch->getParam('__CONTROLLER__');
     $lsAction = $loRouteMatch->getParam('action');
     if (empty($lsController)) {
         $lsController = 'Index';
     }
     if (empty($lsAction)) {
         $lsAction = 'index';
     }
     $laConfigAcl = Config::getAppOptions('acl');
     $loAcl = new Acl($laConfigAcl);
     if (!$loAcl->hasResource($lsController)) {
         throw new \Exception('Resource ' . $lsController . ' not defined');
     }
     Debug::debug("Route: {$lsController}/{$lsAction}");
     if (!$loAcl->isAllowed($lsRole, $lsController, $lsAction)) {
         if ($lsController != 'Index' && $lsAction != 'index') {
             $loFlashMessenger = new FlashMessenger();
             $loFlashMessenger->addMessage(array('id' => 'Access-' . microtime(true), 'hidden' => false, 'push' => false, 'type' => 'danger', 'msg' => Translator::i18n('Você não tem permissão para executar esta ação!')));
         }
         $lsUrl = $poEvent->getRouter()->assemble(array(), array('name' => 'access', 'query' => array('urlFrom' => base64_encode($_SERVER['REQUEST_URI']))));
         $loResponse = $poEvent->getResponse();
         $loResponse->getHeaders()->addHeaderLine('Location', $lsUrl);
         $loResponse->setStatusCode(302);
         $loResponse->sendHeaders();
         exit;
     }
 }
Exemplo n.º 10
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     // Event manager of the app
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $acl = $sm->get('acl');
     // everyone is guest until logging in
     $role = Acl::DEFAULT_ROLE;
     // The default role is guest $acl
     if ($auth->hasIdentity()) {
         $user = $auth->getIdentity();
         $role = $user->getRole()->getName();
     }
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if (!$acl->hasResource($controller)) {
         throw new \Exception('Resource ' . $controller . ' not defined');
     }
     if (!$acl->isAllowed($role, $controller, $action)) {
         $response = $e->getResponse();
         $config = $sm->get('config');
         $redirect_route = $config['acl']['redirect_route'];
         if (!empty($redirect_route)) {
             $url = $e->getRouter()->assemble($redirect_route['params'], $redirect_route['options']);
             $response->getHeaders()->addHeaderLine('Location', $url);
             // The HTTP response status code 302 Found is a common way of performing a redirection.
             // http://en.wikipedia.org/wiki/HTTP_302
             $response->setStatusCode(302);
             $response->sendHeaders();
             exit;
         } else {
             //Status code 403 responses are the result of the web server being configured to deny access,
             //for some reason, to the requested resource by the client.
             //http://en.wikipedia.org/wiki/HTTP_403
             $response->setStatusCode(403);
             $response->setContent('
                 <html>
                     <head>
                         <title>403 Forbidden</title>
                     </head>
                     <body>
                         <h1>403 Forbidden</h1>
                     </body>
                 </html>');
             return $response;
         }
     }
 }
Exemplo n.º 11
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $config = $sm->get('Config');
     $acl = new Acl($config);
     // everyone is guest untill it gets logged in
     $role = Acl::DEFAULT_ROLE;
     // The default role is guest $acl
     // with Doctrine
     if ($auth->hasIdentity()) {
         $user = $auth->getIdentity();
         $usrlId = $user->getUsrlId();
         // Use a view to get the name of the role
         // TODO we don't need that if the names of the roles are comming from the DB
         switch ($usrlId) {
             case 1:
                 $role = Acl::DEFAULT_ROLE;
                 // guest
                 break;
             case 2:
                 $role = 'member';
                 break;
             case 3:
                 $role = 'admin';
                 break;
             default:
                 $role = Acl::DEFAULT_ROLE;
                 // guest
                 break;
         }
     }
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if (!$acl->hasResource($controller)) {
         throw new \Exception('Resource ' . $controller . ' not defined');
     }
     if (!$acl->isAllowed($role, $controller, $action)) {
         $url = $e->getRouter()->assemble(array(), array('name' => 'home'));
         $response = $e->getResponse();
         $response->getHeaders()->addHeaderLine('Location', $url);
         // The HTTP response status code 302 Found is a common way of performing a redirection.
         // http://en.wikipedia.org/wiki/HTTP_302
         $response->setStatusCode(302);
         $response->sendHeaders();
         exit;
     }
 }
Exemplo n.º 12
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     // Event manager of the app
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $translator = $sm->get('translator');
     // $routeMatch->getParam('lang');
     // By default, the translator will get the locale to use from the Intl extension’s Locale class. If you want to set an alternative locale explicitly, you can do so by passing it to the setLocale() method.
     // $translator->setLocale('bg_BG');
     // echo $_SERVER["HTTP_ACCEPT_LANGUAGE"];
     // allow intl extension
     $translator->setLocale(\Locale::acceptFromHttp($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
     //-		echo '<h1>On Route</h1>';
     // echo $translator->getLocale();
 }
Exemplo n.º 13
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     // Event manager of the app
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $acl = $sm->get('acl');
     // everyone is guest until logging in
     $role = Acl::DEFAULT_ROLE;
     // The default role is guest $acl
     if ($auth->hasIdentity()) {
         $user = $auth->getIdentity();
         $role = $user->getRole()->getName();
     }
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if (!$acl->hasResource($controller)) {
         throw new \Exception('Resource ' . $controller . ' not defined');
     }
     if (!$acl->isAllowed($role, $controller, $action)) {
         $response = $e->getResponse();
         $config = $sm->get('config');
         $redirect_route = $config['acl']['redirect_route'];
         if (!empty($redirect_route['options']['params'])) {
             $url = $e->getRouter()->assemble($redirect_route['params'], $redirect_route['options']);
             $response->getHeaders()->addHeaderLine('Location', $url);
             $response->setStatusCode(302);
             $response->sendHeaders();
             exit;
         } else {
             $response->setStatusCode(403);
             $response->setContent('
                 <html>
                     <head>
                         <title>403 Forbidden</title>
                     </head>
                     <body>
                         <h1>403 Forbidden</h1>
                     </body>
                 </html>');
             return $response;
         }
     }
 }
Exemplo n.º 14
0
 /**
  * @see \Usermanager\Guard\AbstractGuard::isGranted()
  */
 public function isGranted(EventInterface $e)
 {
     $route = $e->getRouteMatch()->getMatchedRouteName();
     $allowed = array();
     foreach ($this->options->getGuards() as $pattern => $roles) {
         if (fnmatch($pattern, $route, FNM_CASEFOLD)) {
             $allowed = $roles;
             break;
         }
     }
     if (empty($allowed)) {
         return $this->options->getPolicy() === \Usermanager\Policy\Allow::class;
     }
     if (in_array('*', $allowed)) {
         return true;
     }
     return $this->identityService->hasRoles($allowed);
 }
Exemplo n.º 15
0
 /**
  * Check if ssl is forced or not
  *
  * @param EventInterface $event Mvc event
  *
  * @return null|Zend\Http\PhpEnvironment\Response
  */
 public function check(EventInterface $event)
 {
     $coreConfig = $event->getApplication()->getServiceManager()->get('CoreConfig');
     $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName();
     $request = $event->getRequest();
     $uri = $request->getUri();
     if ($matchedRouteName === 'cms') {
         if ($uri->getScheme() === 'https' or $coreConfig->getValue('force_frontend_ssl')) {
             $newUri = new Uri($coreConfig->getValue('secure_frontend_base_path'));
             $newUri->setScheme('https');
         } else {
             $newUri = new Uri($coreConfig->getValue('unsecure_frontend_base_path'));
         }
     } else {
         if ($uri->getScheme() === 'https' or $coreConfig->getValue('force_backend_ssl')) {
             $newUri = new Uri($coreConfig->getValue('secure_backend_base_path'));
             $newUri->setScheme('https');
         } else {
             $newUri = new Uri($coreConfig->getValue('unsecure_backend_base_path'));
         }
     }
     if (!empty($newUri) and $newUri->isValid() and ($newUri->getHost() != '' and $uri->getHost() != $newUri->getHost()) or $newUri->getScheme() != '' and $uri->getScheme() != $newUri->getScheme()) {
         $uri->setPort($newUri->getPort());
         if ($newUri->getHost() != '') {
             $uri->setHost($newUri->getHost());
         }
         if ($newUri->getScheme() != '') {
             $uri->setScheme($newUri->getScheme());
         }
         $response = $event->getResponse();
         $response->setStatusCode(302);
         $response->getHeaders()->addHeaderLine('Location', $request->getUri());
         $event->stopPropagation();
         return $response;
     }
 }
Exemplo n.º 16
0
 public function onRoute(EventInterface $e)
 {
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     // Authentication
     //        $auth = $sm->get('Zend\Authentication\AuthenticationService');
     /**
      * @Todo check if session container 'User' still exists
      */
     $UserContainer = new Container('User');
     //Authorization with database (check module.config.php)
     $acl = $sm->get('acl');
     // everyone is guest until it gets logged in
     $role = AclDb::DEFAULT_ROLE;
     if ($UserContainer->id) {
         $role = $UserContainer->activeRole;
     }
     $resource = $routeMatch->getParam('controller');
     $privilege = $routeMatch->getParam('action');
     if (!$acl->hasResource($resource)) {
         throw new \Exception('Resource ' . $resource . ' not defined');
     }
     if (!$acl->isAllowed($role, $resource, $privilege)) {
         // Get acl configuration to redirect route
         $response = $e->getResponse();
         $config = $sm->get('config');
         $redirect_route = $config['acl']['redirect_route'];
         $url = $e->getRouter()->assemble($redirect_route['params'], $redirect_route['options']);
         $response->getHeaders()->addHeaderLine('Location', $url);
         // The HTTP response status code 302 Found is a common way of performing a redirection.
         $response->setStatusCode(302);
         $response->sendHeaders();
         exit;
     }
 }
Exemplo n.º 17
0
 public function onRoute(\Zend\EventManager\EventInterface $e)
 {
     $application = $e->getApplication();
     $routeMatch = $e->getRouteMatch();
     $sm = $application->getServiceManager();
     $auth = $sm->get('Zend\\Authentication\\AuthenticationService');
     $config = $sm->get('Config');
     $acl = new Acl($config);
     $role = Acl::DEFAULT_ROLE;
     if ($auth->hasIdentity()) {
         $user = $auth->getIdentity();
         switch ($user->role_id) {
             case 1:
                 $role = Acl::ADMIN_ROLE;
                 break;
             case 2:
                 $role = Acl::TEACHER_ROLE;
                 break;
             case 3:
                 $role = Acl::STUDENT_ROLE;
                 break;
             default:
                 $role = Acl::DEFAULT_ROLE;
                 break;
         }
     }
     $controller = $routeMatch->getParam('controller');
     $action = $routeMatch->getParam('action');
     if (!$acl->hasResource($controller)) {
         throw new \Exception('Resource ' . $controller . ' not defined');
     }
     if (!$acl->isAllowed($role, $controller, $action)) {
         $url = $e->getRouter()->assemble(array(), array('name' => 'errors/no-permission'));
         $response = $e->getResponse();
         $response->getHeaders()->addHeaderLine('Location', $url);
         $response->setStatusCode(403);
         $response->sendHeaders();
         exit;
     }
 }
Exemplo n.º 18
0
 /**
  * Load menu if module has view with name "menu.phtml"
  *
  * @param EventInterface $event Event
  *
  * @return void
  */
 public function loadMenu(EventInterface $event)
 {
     if ($route = $event->getRouter()->getRoute('module')->match($event->getRequest())) {
         if ($route->getParam('module') === 'module') {
             return;
         }
         $filter = new Filter\Word\CamelCaseToSeparator();
         $filter->setSeparator('-');
         $filterChain = new Filter\FilterChain();
         $filterChain->attach($filter)->attach(new Filter\StringToLower());
         $template = $filterChain->filter($route->getParam('module')) . '/menu';
         $target = $event->getTarget();
         $resolver = $event->getApplication()->getServiceManager()->get('Zend\\View\\Resolver\\TemplatePathStack');
         $navigation = $target->getServiceLocator()->get('navigation');
         $navigation->findByRoute('module')->addPage(array('label' => $route->getParam('module'), 'route' => $event->getRouteMatch()->getMatchedRouteName(), 'active' => true));
         if (false !== $resolver->resolve($template)) {
             $target->layout()->setVariable('moduleMenu', $template);
         }
     }
 }
Exemplo n.º 19
0
 /**
  * Retrieve the action handles from the matched route.
  *
  * @param EventInterface $event
  * @return array
  */
 protected function getActionHandles(EventInterface $event)
 {
     /* @var $routeMatch MvcEvent */
     $routeMatch = $event->getRouteMatch();
     $controller = $event->getTarget();
     if (is_object($controller)) {
         $controller = get_class($controller);
     }
     $routeMatchController = $routeMatch->getParam('controller', '');
     if (!$controller || $this->preferRouteMatchController && $routeMatchController) {
         $controller = $routeMatchController;
     }
     $template = $this->mapController($controller);
     if (!$template) {
         $module = $this->deriveModuleNamespace($controller);
         if ($namespace = $routeMatch->getParam(ModuleRouteListener::MODULE_NAMESPACE)) {
             $controllerSubNs = $this->deriveControllerSubNamespace($namespace);
             if (!empty($controllerSubNs)) {
                 if (!empty($module)) {
                     $module .= self::TEMPLATE_SEPARATOR . $controllerSubNs;
                 } else {
                     $module = $controllerSubNs;
                 }
             }
         }
         $controller = $this->deriveControllerClass($controller);
         $template = $this->inflectName($module);
         if (!empty($template)) {
             $template .= self::TEMPLATE_SEPARATOR;
         }
         $template .= $this->inflectName($controller);
     }
     $action = $routeMatch->getParam('action');
     if (null !== $action) {
         $template .= self::TEMPLATE_SEPARATOR . $this->inflectName($action);
     }
     $priority = 0;
     $actionHandles = [];
     $previousHandle = '';
     $templateParts = explode(self::TEMPLATE_SEPARATOR, $template);
     foreach ($templateParts as $index => $name) {
         $actionHandles[] = new Handle($previousHandle . $name, $priority);
         $priority += 10;
         $previousHandle .= $name . self::TEMPLATE_SEPARATOR;
     }
     return $actionHandles;
 }
Exemplo n.º 20
0
 /**
  * @param EventInterface $e
  */
 public function onBootstrap(EventInterface $e)
 {
     /* @var $application Application */
     $application = $e->getApplication();
     $serviceManager = $application->getServiceManager();
     $config = $serviceManager->get('config');
     $request = $application->getRequest();
     $debugbarConfig = $config['php-debug-bar'];
     if ($debugbarConfig['enabled'] !== true || !$request instanceof Request) {
         return;
     }
     $applicationEventManager = $application->getEventManager();
     $viewEventManager = $serviceManager->get('View')->getEventManager();
     $viewRenderer = $serviceManager->get('ViewRenderer');
     $debugbar = $serviceManager->get('debugbar');
     $timeCollector = $debugbar['time'];
     $exceptionCollector = $debugbar['exceptions'];
     self::$messageCollector = $debugbar['messages'];
     $lastMeasure = null;
     $applicationEventManager->attach(MvcEvent::EVENT_FINISH, function (MvcEvent $event) use($debugbar) {
         $response = $event->getResponse();
         if (!$response instanceof Response) {
             return;
         }
         $contentTypeHeader = $response->getHeaders()->get('Content-type');
         if ($contentTypeHeader && $contentTypeHeader->getFieldValue() !== 'text/html') {
             return;
         }
         $renderer = $debugbar->getJavascriptRenderer();
         $renderer->renderOnShutdown(false);
     });
     // Enable messages function
     require __DIR__ . '/Functions.php';
     // Auto enable assets
     if ($debugbarConfig['auto-append-assets']) {
         $viewRenderer->plugin('DebugBar')->appendAssets();
     }
     // Timeline
     $measureListener = function (EventInterface $e) use($timeCollector, &$lastMeasure) {
         if ($lastMeasure !== null && $timeCollector->hasStartedMeasure($lastMeasure)) {
             $timeCollector->stopMeasure($lastMeasure);
         }
         $lastMeasure = $e->getName();
         if ($e instanceof ViewEvent) {
             $model = $e->getParam('model');
             if ($model instanceof ModelInterface) {
                 $lastMeasure .= ' (' . $model->getTemplate() . ')';
             }
         }
         $timeCollector->startMeasure($lastMeasure, $lastMeasure);
     };
     $applicationEventManager->attach('*', $measureListener);
     $viewEventManager->attach('*', $measureListener);
     // Exceptions
     $exceptionListener = function (EventInterface $event) use($exceptionCollector) {
         $exception = $event->getParam('exception');
         if ($exception instanceof \Exception) {
             $exceptionCollector->addException($exception);
         }
     };
     $applicationEventManager->attach('*', $exceptionListener);
     $viewEventManager->attach('*', $exceptionListener);
     // Route
     $applicationEventManager->attach(MvcEvent::EVENT_ROUTE, function (EventInterface $e) use($debugbar) {
         $route = $e->getRouteMatch();
         $data = array('route_name' => $route->getMatchedRouteName(), 'params' => $route->getParams());
         $debugbar->addCollector(new ConfigCollector($data, 'Route'));
     });
 }