Example #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);
 }
Example #2
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)));
 }
Example #3
0
 /**
  * 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);
 }
 /**
  * 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();
         }
     });
 }
Example #5
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;
 }
Example #6
0
 /**
  * Return Response object with contents
  * 
  * @param string $template
  * @param array $data
  * 
  * @return Response
  */
 public function render($template, $data = array())
 {
     $calledClassName = get_called_class();
     $renderer = new Renderer($template, $data, $calledClassName);
     $content = $renderer->renderContent();
     return new Response($content);
 }
Example #7
0
 public function render($view, $data = [])
 {
     $viewPath = $this->getViewPath($view);
     //Service::get('logger')->log($viewPath);
     $renderer = new Renderer($viewPath, $data);
     $content = $renderer->getContentBuffer();
     return new Response($content);
 }
Example #8
0
 /**
  * Content rendering method
  *
  * @access protected
  *
  * @param string $template
  * @param array  $args
  *
  * @return Response
  */
 protected function render($template, $args = array())
 {
     $renderer = new Renderer($this->generatePath());
     $keys = array();
     foreach ($args as $arg => $value) {
         $renderer->set($arg, $value);
         $keys[] = $arg;
     }
     return new Response($renderer->generatePage($template, $keys));
 }
Example #9
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;
 }
Example #10
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);
 }
Example #11
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;
 }
 /**
  * Handles exception for user
  *
  * @access public
  * @static
  *
  * @param \Exception $exception
  * @param array      $messages
  *
  * @return Response
  * @throws ServiceException
  */
 public static function handleForUser(\Exception $exception, $messages = array())
 {
     if ($exception == null) {
         $exception = new \Exception('Sorry for the inconvenience. We are working to resolve this issue.
         Thank you for your patience.');
     }
     $renderer = new Renderer(Service::get('config')['error_500'], true);
     foreach ($messages as $message => $m) {
         $renderer->set($message, $m);
     }
     $content = $renderer->generatePage();
     $response = new Response($content, array(), 500);
     $exception->saveExceptionLog();
     return $response;
 }
Example #13
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!');
     }
 }
Example #14
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();
     }
 }
Example #15
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;
 }
Example #16
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();
 }
Example #17
0
 function getExceptionContent($title = 'Error')
 {
     $renderer = new Renderer('show.html', array('title' => $title, 'message' => $this->getMessage()), 'Blog\\Controller\\ExceptionController');
     $result = $renderer->renderContent();
     return $result;
 }
 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();
         }
     }
 }
Example #19
0
 protected function render($layout, $content){
     $renderer = new Renderer($layout, $content);
     return new Response($renderer->render());
 }
 /**
  * @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();
 }
Example #21
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();
 }
Example #22
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;
     }
 }