Beispiel #1
0
 /**
  * Rendering method
  *
  * @param   string  Layout file name
  * @param   mixed   Data
  *
  * @return  Response
  */
 public function render($layout, $data = array())
 {
     $fullpath = realpath($this->getViewPath() . $layout . '.php');
     $renderer = new Renderer(Service::get('config')['main_layout']);
     $content = $renderer->render($fullpath, $data);
     return new Response($content);
 }
 /**
  * Rendering method
  *
  * @param   string  $layout file name
  * @param   mixed   $data
  *
  * @return  Response
  */
 public function render($layout, $data = array())
 {
     $fullpath = realpath(\Loader::get_path_views() . $layout . '.php');
     $renderer = new Renderer(realpath(Service::get('config')->get('main_layout')));
     $content = $renderer->render($fullpath, $data);
     return new Response($content);
 }
Beispiel #3
0
 public function editAction($id)
 {
     $route = Service::get('route');
     $post = Post::find((int) $id);
     $session = Service::get('session');
     $user = $session->get('user');
     if (Service::get('security')->isAuthenticated()) {
         if ($user->role == 'ROLE_ADMIN') {
             if ($this->getRequest()->isPost()) {
                 try {
                     $post = new Post();
                     $date = new \DateTime();
                     $post->title = $this->getRequest()->post('title');
                     $post->content = trim($this->getRequest()->post('content'));
                     $post->date = $date->format('Y-m-d H:i:s');
                     $validator = new Validator($post);
                     if ($validator->isValid()) {
                         $post->update('id', $id);
                         return $this->redirect($this->generateRoute('home'), 'The data has been update successfully');
                     } else {
                         $error = $validator->getErrors();
                     }
                 } catch (DatabaseException $e) {
                     $error = $e->getMessage();
                 }
             }
         } else {
             throw new SecurityException('You are not allowed posts updating', $this->getRequest()->getReferrer());
         }
     } else {
         throw new SecurityException('Please, login', $route->buildRoute('login'));
     }
     $renderer = new Renderer();
     return new Response($renderer->render(__DIR__ . '/../../Blog/views/Post/add.html.php', array('action' => $this->generateRoute('edit'), 'post' => isset($post) ? $post : null, 'show' => 'check', 'errors' => isset($error) ? $error : null)));
 }
Beispiel #4
0
 /**
  * Render full path to $layout
  *
  * @param $layout
  * @param null $data
  * @return Response
  */
 public function render($layout, $data = null)
 {
     $layout_full_path = $this->getLayoutPath($layout);
     $renderer = new Renderer($layout_full_path, $data);
     $response = new Response($renderer->render());
     return $response;
 }
Beispiel #5
0
 /**
  * remake of the name name to full path for this views
  * @param $layout
  * @param array $data
  * @return Response
  */
 public function render($layout, $data = array())
 {
     $ctrl_class = get_class($this);
     $ctrl_namespace = explode('\\', $ctrl_class);
     $bundle = array_shift($ctrl_namespace);
     $ctrl_name = str_replace('Controller', '', array_pop($ctrl_namespace));
     $path_to_layout = __DIR__ . '/../../src/' . $bundle . '/views/' . $ctrl_name . '/' . $layout . '.php';
     $renderer = new Renderer();
     $resp = new Response($renderer->render($path_to_layout, $data));
     return $resp;
 }
Beispiel #6
0
 /**
  * For rendering
  *
  * @param $template
  * @param $date
  * @return Response
  */
 public function render($template, $date)
 {
     $calledClassName = get_called_class();
     $segments = explode('\\', $calledClassName);
     $bundleName = $segments[0];
     $controllerName = $segments[2];
     $controllerName = str_replace('Controller', '', $controllerName);
     $template = realpath(__DIR__ . '/../../src/' . $bundleName . '/views/' . $controllerName . '/' . $template . '.php');
     $renderer = new Renderer();
     $content = $renderer->render($template, $date);
     return new Response($content);
 }
Beispiel #7
0
 /**
  * Render full path to $layout. Finally '/var/www/mindkblog.com/src/Blog/views/Post/index.html.php'.
  *
  * @param $layout
  * @param null $data
  * @return Response
  */
 public function render($layout, $data = null)
 {
     $controller_class = get_class($this);
     $segments = explode('\\', $controller_class);
     $root_namespace = array_shift($segments);
     $path_to_pkg = \Loader::getPath($root_namespace);
     $ctrl = array_pop($segments);
     $view_dir_name = str_replace('Controller', '', $ctrl);
     $layout_full_path = realpath($path_to_pkg . '/views/' . $view_dir_name . '/' . $layout . '.php');
     $renderer = new Renderer($layout_full_path, $data);
     $response = new Response($renderer->render());
     return $response;
 }
Beispiel #8
0
 /**
  * Метод получает имя view, преобразует его в абсолютный путь, получает от рендерера сформированный контент и возвращает респонс. Так же, при необходимости, оборачивает в шаблон
  * @param string $view имя вью
  * @param array $params параметры, которые необходимо передать рендереру
  * @param bool $with_layout указывает, нужно ли оборачивать контент в шаблон (по умолчанию - да)
  * @return Response ответ
  * @throws HttpNotFoundException если вью не найдена
  */
 public function render($view, $params, $with_layout = true)
 {
     $view_path = $this->generatePathToView($view);
     self::$logger->debug("Rendering view {$view} " . ($with_layout == true ? "with" : "without") . " layout");
     if (file_exists($view_path)) {
         $response = Renderer::render($view_path, $params);
         //рендерим шаблон, если необходимо
         if ($with_layout == true && file_exists($layout_path = Service::get("config")["main_layout"])) {
             //создаем и передаем в шаблон массив с сообщениями
             $flush = array();
             $mess = $this->request->get("redirectmessage");
             if (isset($mess)) {
                 $flush["info"] = array($mess);
             }
             $response_with_layout = Renderer::render($layout_path, array("content" => $response, "flush" => $flush, "user" => null));
             $response = $response_with_layout;
         }
         return new Response($response);
     } else {
         self::$logger->error("View {$view_path} does not exists");
         throw new HttpNotFoundException('Page Not Found!');
     }
 }
Beispiel #9
0
 /**
  * @param $e
  * @return Response
  */
 public function renderError($e)
 {
     $error_layout = $this->_config['error_500'];
     $renderer = new Renderer($error_layout, array('message' => $e->getMessage(), 'code' => $e->getCode()));
     $response = new Response($renderer->render());
     $result = $response;
     return $result;
 }
Beispiel #10
0
 /**
  * @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();
         }
     }
 }
Beispiel #12
0
 /**
  *  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();
 }
Beispiel #14
0
 protected function render($layout, $content){
     $renderer = new Renderer($layout, $content);
     return new Response($renderer->render());
 }
Beispiel #15
0
 /**
  * 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;
     }
 }
Beispiel #16
0
 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();
     }
 }