/** * * @param type $config */ public function __construct($config = null) { \Loader::addNamespacePath('CMS\\', __DIR__ . '/../src/CMS'); Service::set('configuration', function () { return new \Framework\Configuration(); }); Service::get('configuration')->loadFile($config); Service::set('db', function () { return new \Framework\Connection(Service::get('configuration')->get('pdo')); }); Service::set('router', function () { return new \Framework\Router\Router(Service::get('configuration')->get('routes')); }); Service::set('request', function () { return new \Framework\Request\Request(); }); Service::set('security', function () { return new \Framework\Security\Security(); }); Service::set('session', function () { return new \Framework\Session\Session(); }); Service::set('renderer', function () { return new \Framework\Renderer\Renderer(Service::get('configuration')->get('main_layout')); }); Service::get('session'); }
/** * Execute MVC application. * * @return \Framework\Http\Response object. * @throws HttpException * @throws \Framework\Exception\DIException */ public function run() { try { $tmp = Service::get('router')->execute(); //var_dump($tmp); Service::set('sub_view', new \Framework\View()); Service::set('view', new \Framework\View()); if (class_exists($tmp['controller'])) { $controller = new $tmp['controller'](); $tmp['action'] .= 'Action'; if (method_exists($controller, $tmp['action'])) { $action = $tmp['action']; unset($tmp['controller'], $tmp['action']); $response = $controller->{$action}($tmp); if (is_string($response)) { return Service::get('response')->setContent($response); } elseif (null === $response) { return Service::get('response'); } else { throw new \Exception('All is bad', 404); } } else { throw new HttpException('Action isn\'t found!', 404); } } else { throw new HttpException('Controller isn\'t found!', 404); } } catch (\Exception $e) { return Service::get('response')->setContent(Service::get('view')->set('content', Service::get('sub_view')->render($this->config['error_500'], array('code' => $e->getCode(), 'message' => $e->getMessage())))->set('flush', array())->render(Service::get('application')->config['main_layout'])); } }
/** * Inits Services at Application */ public function init() { Service::set('routes', Service::get('config')['routes']); Service::set('session', new Session()); Service::set('security', new Security()); $pdoFromConfig = Service::get('config')['pdo']; $db = new \PDO($pdoFromConfig['dns'], $pdoFromConfig['user'], $pdoFromConfig['password']); Service::set('db', $db); }
/** * Application constructor. * @param string $config_path */ public function __construct($config_path) { $this->config = (include $config_path); ini_set('display_errors', $this->config == 'dev' ? '1' : '0'); Service::set('app', $this); Service::set('router', new Router($this->config['routes'])); Service::set('renderer', new Renderer($this->config['main_layout'])); Service::set('db', new \PDO($this->config['pdo']['dsn'], $this->config['pdo']['user'], $this->config['pdo']['password'])); Service::set('session', new Session()); Service::set('security', new Security()); }
/** * 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(); }
public function __construct($config_path) { $this->config = (include_once $config_path); $this->router = new Router($this->config["routes"]); Service::set('config', $this->config); // Setup database connetion... $db = new \PDO($this->config['pdo']['dns'], $this->config['pdo']['user'], $this->config['pdo']['password']); Service::set('pdo', $db); //Main variables Service::set('security', new Security()); Service::set('session', new Session()); }
public function __construct($configPath) { self::$config = (include $configPath); Service::set('request', 'Framework\\Request\\Request'); Service::set('router', function () { $object = new Router(self::$config['routes']); return $object; }); /* Service::set('response', 'Framework\Response\Response'); Service::set('security', 'Framework\Security\Security'); Service::set('session', 'Framework\Session\SessionManager'); Service::set('localization', 'Framework\Localization\LocalizationManager', array(self::$config['localization'])); */ }
public function __construct($config) { $config = new \ArrayObject(include $config, \ArrayObject::ARRAY_AS_PROPS); $session = new Session(); ini_set('xdebug.var_display_max_depth', -1); ini_set('xdebug.var_display_max_children', -1); ini_set('xdebug.var_display_max_data', -1); Service::set('session', $session); Service::set('renderer', new Renderer('../src/Blog/views/layout.html.php')); Service::set('db', new \PDO($config->pdo['dns'], $config->pdo['user'], $config->pdo['password'])); Service::set('request', new Request()); Service::set('config', $config); Service::set('router', new Router($config->routes)); Service::set('application', $this); Service::set('security', new Security($config->security, $session)); }
/** * Конструктор фронт контроллера * @param $config_path string к конфигурационному файлу */ public function __construct($config_path) { $config = (include_once $config_path); $run_mode = $config["mode"]; self::$logger = Logger::getLogger($this->configureLogParams($run_mode, $config["log"])); Service::set("logger", self::$logger); self::$logger->debug("Run mode set to " . $run_mode); $this->setErrorReportingLevel($run_mode); $this->router = new Router($config["routes"]); $this->pdo = Database::getInstance($config["pdo"]); Service::setAll($config["di"]); Service::set("router", $this->router); Service::set("pdo", $this->pdo->getConnection()); Service::set("config", $config); $this->config = $config; //TODO добавить обработку остальных параметров конфига, когда понядобятся }
/** * 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(); }
public function __construct($configFile) { $this->config = (include $configFile); Service::set('request', new Request()); Service::set('security', new Security()); $req = Service::get('request'); $this->request = $req->getUri(); Service::set('route', new Router($this->request, $this->config['routes'])); $this->pdo = $this->config['pdo']; try { Service::set('db', new \PDO($this->pdo['dns'], $this->pdo['user'], $this->pdo['password'])); } catch (\PDOException $e) { echo 'Connection error' . $e->getMessage(); } Service::set('app', $this); Service::set('session', new Session()); Service::set('csrf', new Csrf()); }
/** * Create new object of current service * Write values in array of services * Always create new Security object * * @param $service_name * @return mixed * @throws InvalidArgumentException * @throws InvalidTypeException */ public static function factory($service_name) { $service_data = self::getConfig()[$service_name]; if (!empty($service_data)) { $regexp = '~.*class.*~'; foreach ($service_data as $namespace => $path) { if (preg_match($regexp, $namespace)) { $object = new $path(); if ($service_name == 'security') { return $object; } Service::set($service_name, $object); return $object; } } throw new InvalidTypeException("There are no objects in service {$service_name}!"); } else { throw new InvalidArgumentException("Service {$service_name} not found!"); } }
/** * Application constructor. */ public function __construct($configPath) { //Registration all configuration vars in the config container Registry::setConfigsArr(include $configPath); Service::set('router', new Router(Registry::getConfig('routes'))); Service::set('dbConnection', Connection::get(Registry::getConfig('pdo'))); Service::set('request', new Request()); Service::set('security', new Security()); Service::set('session', Session::getInstance()); Service::set('renderer', new Renderer(Registry::getConfig('main_layout'))); Service::set('eventManager', EventManager::getInstance()); //Registers the events Service::get('eventManager')->registerEvent('applicationInit')->registerEvent('parseRoute')->registerEvent('dispatchAction')->registerEvent('controllerRender')->registerEvent('controllerGenerateRoute')->registerEvent('controllerRedirect')->registerEvent('sendAction')->registerEvent('renderAction'); //Attaches a new listener Service::get('eventManager')->addListener('Framework\\Logger\\Logger'); //Sets the error display mode Helper::errorReporting(); //Launches the appropriate event Service::get('eventManager')->trigger('applicationInit', "The start of application"); }
/** * Parse URL * * @param $url */ public function parseRoute($url = '') { $url = empty($url) ? $_SERVER['REQUEST_URI'] : $url; $route_found = null; foreach (self::$map as $route) { $pattern = $this->prepare($route); if (preg_match($pattern, $url, $params)) { // Get assoc array of params: preg_match($pattern, str_replace(array('{', '}'), '', $route['pattern']), $param_names); $params = array_map('urldecode', $params); $params = array_combine($param_names, $params); array_shift($params); // Get rid of 0 element $route_found = $route; $route_found['params'] = $params; break; } } Service::set('route_controller', $route_found); return $route_found; }
/** * Application constructor * * @access public * * @param $config */ public function __construct($config) { try { Service::setSimple('config', $this->config = (require_once $config)); Service::set('request', 'Framework\\Request\\Request'); Service::setSingleton('router', $this->router = new Router()); Service::setSingleton('session', Sessions::getInstance()); Service::setSingleton('dataBase', DataBase::getInstance()); Service::set('security', 'Framework\\Security\\Security'); Service::setSingleton('flushMessenger', 'Framework\\FlushMessenger\\FlushMessenger'); Service::set('app', $this); } catch (ServiceException $e) { } catch (\Exception $e) { } finally { if (isset($e)) { $code = isset($code) ? $code : 500; $errorMessage = isset($errorMessage) ? $errorMessage : 'Sorry for the inconvenience. We are working to resolve this issue. Thank you for your patience.'; $responce = MainException::handleForUser($e, array('code' => $code, 'message' => $errorMessage)); $responce->send(); } } }
/** * Run app * * @throws \Exception * @return void */ public function run() { Service::set('router', new Router($this->_config['routes'])); $route = Service::get('router')->find(); $this->_checkSecurity($route); $response = $this->_runControllerActionByRoute($route); $flash = $this->_sendFlash(); $this->_sendResponse($response, $flash); }
/** * Set required services */ private function _setServices() { Service::set('router', ObjectPool::get('Framework\\Router\\Router', include __DIR__ . '/../app/config/routes.php')); Service::set('loader', ObjectPool::get('Loader')); Service::set('renderer', ObjectPool::get('Framework\\Renderer\\Renderer', include __DIR__ . '/../app/config/config.php')); }
/** * Closes DB connection */ public function closeDB() { Service::set('db', null); }
private function _initComponents() { $components = Service::getConfig('components'); foreach ($components as $component) { \Loader::addNamespacePath($component['namespace'], $component['path']); if (isset($component['bootstrap']) && $component['bootstrap'] === 'on') { $class = $component['class']; Service::set($component['name'], new $class()); } } }
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(); } }