public function run() { $router = Service::get('router'); $route = $router->parseRoute($_SERVER['REQUEST_URI']); try { //Checks if route is empty if (!empty($route)) { //Verifies user role if it needs if (array_key_exists('security', $route)) { if (is_null($user = Service::get('session')->get('user')) || !in_array($user->role, $route['security'])) { throw new SecurityException("Access is denied"); } } //Returns Response object $response = Helper::dispatch($route['controller'], $route['action'], $route['params']); } else { throw new HttpNotFoundException("Route does not found", 404); } } catch (SecurityException $e) { Service::get('session')->set('returnUrl', Registry::getConfig('route')['pattern']); $response = new ResponseRedirect(Service::get('router')->buildRoute('login')); } catch (HttpNotFoundException $e) { $response = new Response(Service::get('renderer')->render(Registry::getConfig('error_400'), array('code' => $e->getCode(), 'message' => $e->getMessage()))); } catch (\Exception $e) { $response = new Response(Service::get('renderer')->render(Registry::getConfig('error_500'), array('code' => $e->getCode(), 'message' => $e->getMessage()))); } $response->send(); }
/** * Registers custom error handler * * @access public * @static * * @return void */ public static function loadErrorHandler() { set_error_handler(function ($errno, $errmsg, $filename, $linenum) { $date = date('Y-m-d H:i:s (T)'); if (!file_exists(__DIR__ . '/../../app/logs/')) { mkdir(__DIR__ . '/../../app/logs/'); } $f = fopen(__DIR__ . '/../../app/logs/errorlog.txt', 'a'); if (!empty($f)) { $error = "____________________________________________________________\n"; $error .= $date . "\n"; $error .= $errno . "\n"; $error .= $errmsg . "\n"; $error .= $filename . "\n"; $error .= $linenum . "\n"; $error .= "____________________________________________________________\n"; fwrite($f, $error); fclose($f); } if (Service::get('config')['mode'] == 'user') { $renderer = new Renderer(Service::get('config')['layouts']); $renderer->set('code', 500); $renderer->set('message', 'Oooops'); $content = $renderer->generatePage('500.html'); $response = new Response($content, array(), 500); $response->send(); } }); }
/** * Функция выполняет роутинг, запуск нужного контроллера, отдает респонс */ public function run() { self::$logger->debug("Running application..."); $this->request = Request::create(); $route_answer = $this->router->route($this->request); $route = $route_answer["route"]; //если роут не найден по данному uri if (empty($route)) { self::$logger->warn("Router was not found"); $response = new Response("Route not found", ResponseType::NOT_FOUND); } else { $controller_class = $route["controller"]; $method_name = $route["action"] . "Action"; if (class_exists($controller_class) && method_exists($controller_class, $method_name)) { $request_params = $route_answer["params"]; $response = $this->getResponseFromController($controller_class, $method_name, $request_params); // TODO добавить оборачивание респонса в шаблон // if("text/html" === $response->getContentType()) { // $content = $response->getContent(); // $response = new Response( include (__DIR__.'/../../src/Blog/views/500.html.php')); // } // $response->setContent($response->getContent()) } else { self::$logger->error("Such controller and method does not exists: " . "{$controller_class} -> {$method_name}()"); $response = new Response("Such controller and method does not exists: " . "{$controller_class} -> {$method_name}()", ResponseType::NOT_FOUND); } } $this->pdo->closeConnection(); $response->send(); }
/** * @throws ServiceException * * solve exception depending from enter message (number or string) * if message is numeric get code from Response class and redirect to 500 html page * if string redirect to $redirectAddress */ public function solveException() { $data = array(); if ($this->getMessage() && is_numeric($this->getMessage())) { $data['code'] = $this->getMessage(); $data['message'] = Response::getMessageByCode($this->getMessage()); if ($this->beforeSolve) { $this->beforeSolveException(); } $renderer = new Renderer(); $responce = new Response($renderer::render(Service::get('config')->get500Layout(), $data), 'text/html', 202); $responce->send(); } else { if ($this->getMessage()) { Service::get('session')->addFlush($this->type, $this->getMessage()); if ($this->beforeSolve) { $this->beforeSolveException(); } echo $this->redirectAddress; $redirect = new ResponseRedirect($this->redirectAddress); $redirect->sendHeaders(); } else { throw new ServiceException(500); } } }
/** * Send Response * * @param $response * @param $flash * @return void */ private function _sendResponse($response, $flash) { try { if ($response instanceof Response) { if ($response->type == 'html') { $view = $this->_config['main_layout']; $renderer = new Renderer($view, array('content' => $response->getContent(), 'flush' => $flash)); $wrapped = $renderer->render(); $response = new Response($wrapped); } $response->send(); } else { throw new BadResponseException('Bad response', 500); } } catch (BadResponseException $e) { new Response($this->renderError($e)); } }
/** * @throws SecurityException */ public function run() { $route = Service::get('route'); $routes = $route->testUri(); if (!empty($routes['security'])) { //check authorization on security pages $session = Service::get('session'); $user = $session->get('user'); if (!empty($user)) { if ($user->role == 'ROLE_ADMIN') { } else { throw new SecurityException('You are not allowed posts adding', Service::get('route')->buildRoute('home')); } } else { throw new SecurityException('Authorization Required', Service::get('route')->buildRoute($this->config['security']['login_route'])); } } try { if (!empty($routes)) { if (class_exists($routes['controller'])) { $controller = $routes['controller']; $response = $this->generateResponseCtrl($controller, $routes['action'], $routes); if ($response instanceof ResponseInterface) { if ($response->type == 'html') { $content['content'] = $response->getContent(); $content['flush'] = Service::get('session')->getFlushMessage(); $renderer = new Renderer(); $response = new Response($renderer->render($this->config['main_layout'], $content)); } } else { throw new HttpNotFoundException('Bad response', 404); } } else { throw new HttpNotFoundException('Controller not found', 404); } } else { throw new HttpNotFoundException('Route not found', 404); } } catch (HttpNotFoundException $e) { $renderer = new Renderer(); $response = new Response($renderer->render($this->config['error_500'], array('message' => $e->getMessage(), 'code' => $e->getCode()))); $response = new Response($renderer->render($this->config['main_layout'], array('content' => $response->getContent(), 'flush' => Service::get('session')->getFlushMessage()))); } catch (DatabaseException $e) { $renderer = new Renderer(); $response = new Response($renderer->render($this->config['error_500'], array('message' => $e->getMessage(), 'code' => $e->getCode()))); } $response->send(); }
public function run() { ServiceContainer::get('security')->generateToken(); try { if (!ServiceContainer::get('security')->checkToken()) { die('Invalid token'); } $map = $this->config['routes']; ServiceContainer::set('route', new Router($map)); $match_route = ServiceContainer::get('route'); $route = $match_route->findRoute(); if (!empty($route['security'])) { $user = ServiceContainer::get('session')->get('authenticated'); if (!empty($user->user_role) != 'ROLE_USER') { $msg = 'Access denied, please login to your account!'; $fsg = ServiceContainer::get('session'); $fsg->setFlush('error', $msg); $redirect = new ResponseRedirect(ServiceContainer::get('route')->buildRoute('security_signin')); $redirect->send(); } } if (class_exists($route['controller'])) { $controller = $route['controller']; $action = $route['action']; $vars = NULL; if (!empty($route['vars'])) { $vars = $route['vars']; } $response = $this->startController($controller, $action, $vars); } else { throw new HttpNotFoundException(); } } catch (HttpNotFoundException $e) { $error_layout = $this->config['not_found']; $renderer = new Renderer($error_layout, array('message' => $e->getMessage(), 'code' => $e->getCode())); $response = new Response($renderer->render()); } $flush = ServiceContainer::get('session')->get('flush') ? ServiceContainer::get('session')->get('flush') : array(); ServiceContainer::get('session')->unsetSession('flush'); if ($response instanceof Response) { if ($response->getType() == 'html') { $view = $this->config['main_layout']; $renderer = new Renderer($view, array('content' => $response->getContent(), 'flush' => $flush)); $wrapped = $renderer->render(); $response = new Response($wrapped); $response->send(); } elseif ($response->getType() == 'json') { $response = new ResponseJson(); $response->send(); } } }
/** * The method starts the app */ public function run() { $router = new Router(Service::get('routes')); $route = $router->parseRoute(); Service::set('currentRoute', $route); try { if (!empty($route)) { /** * Checks the route is allowed for all or not */ if (array_key_exists('security', $route)) { $user = Service::get('security')->getUser(); $allowed = Service::get('security')->checkGrants($user); if (!$allowed) { throw new AccessDenyException(); } } $controllerReflection = new \ReflectionClass($route['controller']); $action = $route['action'] . 'Action'; if ($controllerReflection->hasMethod($action)) { if ($controllerReflection->isInstantiable()) { $controller = $controllerReflection->newInstance(); $actionReflection = $controllerReflection->getMethod($action); $response = $actionReflection->invokeArgs($controller, $route['params']); if (!$response instanceof Response) { throw new BadResponseTypeException('Bad response'); } } else { throw new BadResponseTypeException('Bad response'); } } else { throw new HttpNotFoundException('The page has not found'); } } else { throw new HttpNotFoundException('The page has not found'); } } catch (AccessDenyException $e) { $response = new ResponseRedirect('/login'); } catch (HttpNotFoundException $e) { $renderer = new Renderer(); $params = $e->getParams(); $content = $renderer->render(Service::get('config')['error_500'], $params); $response = new Response($content, 'text/html', '404'); } catch (BadResponseTypeException $e) { $renderer = new Renderer(); $params = $e->getParams(); $content = $renderer->render(Service::get('config')['error_500'], $params); $response = new Response($content, 'text/html', '500'); } catch (\Exception $e) { $response = new Response($e->getMessage(), 'text/html', '200'); } $response->send(); }
/** * @throws BadResponseTypeException * @throws Exception\RendererException */ public function run() { $router = Service::get('router'); $route = $router->parseRoute(); $renderer = Service::get('renderer'); $renderer->assign(array('user' => Service::get('security')->getUser(), 'flush' => Service::get('session')->getFlush())); require_once '../src/Blog/Controller/PostController.php'; try { $response = $this->processRoute(); if (empty($route)) { throw new HttpNotFoundException('Route not found'); } if (isset($route['security'])) { if (!Service::get('security')->isAuthenticated()) { throw new AuthRequiredException('Please. login first!'); } elseif (!Service::get('security')->isGranted($route['security'])) { throw new AccessDeniedException('Access denied!'); } } $controllerReflection = new \ReflectionClass($route['controller']); $action = $route['action'] . 'Action'; if ($controllerReflection->hasMethod($action)) { $controller = $controllerReflection->newInstance(); // var_dump($controller); die; $actionReflection = $controllerReflection->getMethod($action); $response = $actionReflection->invokeArgs($controller, $route['params']); } } catch (HttpNotFoundException $e) { echo $e->getMessage(); } catch (AuthRequiredException $e) { $url = Service::get('router')->buildRoute(Service::get('security')->getLoginRoute()); $response = new ResponseRedirect($url, null, 'Please, login first!'); // var_dump(Service::get('request')->getUri()); die; $response->setReturnUrl(Service::get('request')->getUri()); } catch (AccessDeniedException $e) { echo $e->getMessage(); } catch (\Exception $e) { $renderer = new Renderer(Service::get('config')->error_500); $renderer->assign(array('message' => $e->getMessage(), 'code' => $e->getCode())); $response = new Response($renderer->render(), $e->getCode(), 'Internal Server Error'); echo $e->getMessage(); } $response->send(); }
/** * Run Router class and show resalt of parseRoute() */ public function run() { $router = new Router($this->config['routes']); $routeInfo = $router->parseRoute(); try { if (is_array($routeInfo)) { Service::set('route', $routeInfo); //Security - user Role Verification Service::get('security')->verifyUserRole(); // Security - validation token Service::get('security')->verifyCsrfToken(); $controllerName = $routeInfo['controller']; $actionName = $routeInfo['action'] . 'Action'; $params = $routeInfo['params']; $reflectionClass = new \ReflectionClass($controllerName); if ($reflectionClass->isInstantiable()) { $reflectionObj = $reflectionClass->newInstanceArgs(); if ($reflectionClass->hasMethod($actionName)) { $reflectionMethod = $reflectionClass->getMethod($actionName); $response = $reflectionMethod->invokeArgs($reflectionObj, $params); if (!$response instanceof Response) { throw new \Exception('Method - <b>' . $actionName . '</b> return not instance of class Response'); } } else { throw new \Exception('Can not find Method - ' . $actionName); } } else { throw new \Exception('Can not create Object from Class - ' . $controllerName); } } else { throw new HttpNotFoundException('Page Not Found'); } } catch (RoleException $e) { $response = new ResponseRedirect('/login'); } catch (HttpNotFoundException $e) { $content = $e->getExceptionContent('Error - 404'); $response = new Response($content, 404); } catch (CustomException $e) { $content = $e->getExceptionContent(); $response = new Response($content, 500); } catch (\Exception $e) { $response = new Response('<b>Message:</b> ' . $e->getMessage() . '<br />'); } $response->send(); }
/** * Method starts necessary method of necessary controller with help of Reflection * * @param string $controller * @param string $action * @param array $vars * @throws HttpNotFoundException * @throws \Exception * * @return object */ public function startController($controller, $action, $vars = array()) { $controller = new $controller(); $action = $action . 'Action'; $refl = new \ReflectionClass($controller); try { if ($refl->hasMethod($action)) { $method = new \ReflectionMethod($controller, $action); $params = $method->getParameters(); if (empty($params)) { $response = $method->invoke(new $controller()); } else { foreach ($params as $value) { if (isset($vars[$value->getName()])) { $parameters[$value->getName()] = $vars[$value->getName()]; } else { throw new HttpNotFoundException('parameters for method ' . $method->getName()); } } $response = $method->invokeArgs(new $controller(), $parameters); } if ($response instanceof AResponse) { return $response; } else { throw new ServerErrorException(500, 'Sory, server error', $this->config['error_500']); } } else { throw new HttpNotFoundException('method not found'); } } catch (HttpNotFoundException $e) { throw $e; } catch (ServerErrorException $e) { $renderer = new Renderer($e->layout, array('message' => $e->message, 'code' => $e->code)); $response = new Response($renderer->render()); $response->send(); die; } }
public function run() { Service::get('security')->generateToken(); if (!Service::get('security')->checkToken()) { die('Token not exist'); } $map = $this->config['routes']; Service::set('route', new Router($map)); $match_route = Service::get('route'); $route = $match_route->findRoute(); if (!empty($route['security'])) { $user = Service::get('session')->get('authenticated'); if (is_object($user)) { $user_role = get_object_vars($user); } if (!empty($user_role['role'] !== 'ROLE_ADMIN')) { $msg = 'Access Denied! Only the administrator can create new posts.'; $fsg = Service::get('session'); $fsg->setFlush('error', $msg); $redirect = new ResponseRedirect(Service::get('route')->buildRoute($this->config['security']['login_route'])); $redirect->send(); } } try { if (class_exists($route['controller'])) { $controller = new $route['controller'](); $action = $route['action'] . 'Action'; if (isset($route['vars'])) { $vars = $route['vars']; } $controller_reflection = new \ReflectionClass($route['controller']); if ($controller_reflection->hasMethod($action)) { $method = new \ReflectionMethod($controller, $action); $params = $method->getParameters(); if (empty($params)) { $response = $method->invoke(new $controller()); } else { $response = $method->invokeArgs(new $controller(), $vars); } } } else { throw new HttpNotFoundException('Oops, Not Found', 404); } } catch (HttpNotFoundException $e) { $error_layout = $this->config['error_500']; $renderer = new Renderer($error_layout, array('message' => $e->getMessage(), 'code' => $e->getCode())); $response = new Response($renderer->render()); } $flush = Service::get('session')->get('flush') ? Service::get('session')->get('flush') : array(); Service::get('session')->unsetSession('flush'); Service::get('session')->setReturnUrl(Service::get('request')->getRequestInfo('uri')); try { if ($response instanceof Response) { if ($response->type == 'html') { $view = $this->config['main_layout']; $renderer = new Renderer($view, array('content' => $response->getContent(), 'flush' => $flush)); $wrapped = $renderer->render(); $response = new Response($wrapped); } $response->send(); } else { throw new BadResponseException('Bad response', 500); } } catch (BadResponseException $e) { echo $e->getMessage(); } }