Exemple #1
0
 /**
  * Register specific services for the module
  */
 function registerServices(\Phalcon\DiInterface $di)
 {
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace('Modules\\Frontend\\Controllers');
         return $dispatcher;
     });
     $config = $di->getShared('config');
     $di->set('view', function () use($config, $di) {
         $view = new View();
         $router = $di->getShared('router');
         /*
          * @todo 给layouts等目录统一变量
          * */
         $view->setViewsDir(__DIR__ . '/views/');
         $view->setLayoutsDir('/../../../layouts/');
         // 多模块的话, 可能会有多个风格,所以需要切换layout,这里的Path是根据当前module的Path向上走的
         $view->setLayout('index');
         $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
             $volt = new VoltEngine($view, $di);
             $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_'));
             return $volt;
         }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
         return $view;
     }, true);
 }
Exemple #2
0
 /**
  * Registers the module-only services
  *
  * @param \Phalcon\DiInterface $di
  */
 public function registerServices($di)
 {
     /**
      * Read application wide and module only configurations
      */
     $appConfig = $di->get('config');
     $moduleConfig = (include __DIR__ . '/config/config.php');
     $di->set('moduleConfig', $moduleConfig);
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($appConfig) {
         $url = new UrlResolver();
         $url->setBaseUri($appConfig->application->baseUri);
         return $url;
     });
     /**
      * Module specific dispatcher
      */
     $di->set('dispatcher', function () use($di) {
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($di->getShared('eventsManager'));
         $dispatcher->setDefaultNamespace('App\\Modules\\Oauth\\');
         return $dispatcher;
     });
     /**
      * Module specific database connection
      */
     $di->set('db', function () use($appConfig) {
         return new DbAdapter(['host' => $moduleConfig->database->host, 'username' => $moduleConfig->database->username, 'password' => $moduleConfig->database->password, 'dbname' => $moduleConfig->database->name]);
     });
 }
Exemple #3
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read common configuration
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * Try to load local configuration
      */
     if (file_exists(__DIR__ . '/config/config.php')) {
         $override = new Config(include __DIR__ . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     /**
      * Setting up the view component
      */
     $view = $di->get('view');
     $view->setViewsDir($config->get('application')->viewsDir);
     $di->set('view', $view);
     // add default namespace
     $dispatcher = $di->get('dispatcher');
     $dispatcher->setDefaultNamespace("Application\\Frontend\\Controllers");
     $di->set('dispatcher', $dispatcher);
 }
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * 获取全局配置
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * 各模块可自定义config文件并替换全局的config配置
      */
     if (file_exists($this->modulePath . '/config/config.php')) {
         $override = new Config(include $this->modulePath . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     //重置全局配置
     $di->setShared('config', $config);
     /**
      * 设置各个模块的视图目录
      */
     $view = new View();
     //$view->setViewsDir($this->modulePath . '/views/default/');
     $view->setViewsDir(FRONTEND_PUBLIC_PATH . 'views/default/');
     $view->registerEngines(['.volt' => 'volt', '.php' => 'volt', '.html' => 'volt']);
     $di->set('view', $view);
 }
Exemple #5
0
 /**
  * Initialize the Loader.
  *
  * Adds all required namespaces.
  */
 protected function initLoader()
 {
     $config = $this->di->getShared('config');
     $loader = new Loader();
     $loader->registerNamespaces(['Phosphorum\\Models' => $config->get('application')->modelsDir, 'Phosphorum\\Controllers' => $config->get('application')->controllersDir, 'Phosphorum' => $config->get('application')->libraryDir]);
     $loader->register();
     $this->di->setShared('loader', $loader);
 }
 public function registerAutoloaders(DiInterface $di = null)
 {
     $path = $di->getShared('config')->modules->poll->path;
     $path = str_replace('Module.php', '', $path);
     $loader = new Loader();
     $loader->registerNamespaces(array('Socialveo\\Poll\\Models' => $path . 'models/', 'Socialveo\\Poll\\Controllers' => $path . 'controllers/', 'Socialveo\\Poll\\Plugins' => $path . 'plugins/'));
     $loader->register();
 }
 /**
  * {@inheritdoc}
  */
 public function register(DiInterface $di)
 {
     $di->set(self::SERVICE_NAME, function () use($di) {
         $arrayConfig = (array) $di->get('config')->{self::SERVICE_NAME};
         $db = new \Phalcon\Db\Adapter\Pdo\Sqlite($arrayConfig);
         $db->setEventsManager($di->getShared('eventsManager'));
         return $db;
     }, true);
 }
Exemple #8
0
 /**
  * Returns the value of the CSRF token in session
  *
  * @return string
  * @throws FlashException
  */
 public function getSessionToken()
 {
     if (is_object($this->_dependencyInjector) === false) {
         throw new FlashException('A dependency injection container is required to access the \'session\' service');
     }
     $session = $this->_dependencyInjector->getShared('session');
     if (is_object($session) === false || $session instanceof SessionAdapterInterface === false) {
         throw new FlashException('Session service is unavailable.');
     }
     return $session->get('$PHALCON/CSRF$');
 }
Exemple #9
0
 /**
  * Deletes the cookie by setting an expire time in the past
  *
  * @throws Exception
  */
 public function delete()
 {
     if (is_object($this->_dependencyInjector) === true) {
         $session = $this->_dependencyInjector->getShared('session');
         if ($session instanceof SessionInterface === false) {
             throw new Exception('Wrong session service.');
         }
         $session->remove('_PHCOOKIE_' . $this->_name);
     }
     $this->_value = null;
     //@note use the type 'boolean' for the last two parameters
     setcookie((string) $this->_name, null, time() - 691200, (string) $this->_path, (string) $this->_domain, (bool) $this->_secure, (bool) $this->_httpOnly);
 }
Exemple #10
0
 /**
  * @param array       $config
  * @param DiInterface $di
  * @return MvcView
  */
 public static function createFrom(array $config, DiInterface $di) : MvcView
 {
     $view = new MvcView();
     if (isset($config['templatePath'])) {
         $view->setViewsDir($config['templatePath']);
         /** @var MvcDispatcher $dispatcher */
         $dispatcher = $di->getShared('dispatcher');
         $dispatcher->getEventsManager()->attach('dispatch', new self());
     } else {
         $view->disable();
     }
     return $view;
 }
Exemple #11
0
 /**
  * Registers default dispatcher
  */
 public function initDispatcher()
 {
     $this->di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         /**
          * @var \Phalcon\Events\Manager $eventsManager
          */
         $eventsManager = $this->di->getShared('eventsManager');
         $eventsManager->attach('dispatch:beforeException', (new ExceptionListener())->beforeException());
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
 }
Exemple #12
0
 /**
  * Register the services here to make them general or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices(DiInterface $di)
 {
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace(__NAMESPACE__ . '\\Controllers\\');
         return $dispatcher;
     });
     //Registering the view component
     $view = $di->getShared('view');
     $view->setViewsDir(APP_PATH . '/modules/' . __NAMESPACE__ . '/view');
     $view->setLayoutsDir('layout/');
     $view->setTemplateAfter('main');
     $view->setVar('menu', new MenuHelper($di));
 }
Exemple #13
0
 /**
  * Stores the messages in session
  *
  * @param array $messages
  * @throws Exception
  * @return array
  */
 protected function _setSessionMessages($messages)
 {
     if (is_array($messages) === false) {
         throw new Exception('Invalid parameter type.');
     }
     if (is_object($this->_dependencyInjector) === false) {
         throw new Exception('A dependency injection container is required to access the \'session\' service');
     }
     $session = $this->_dependencyInjector->getShared('session');
     if (is_object($session) === false || $session instanceof SessionAdapterInterface === false) {
         throw new Exception('Session service is unavailable.');
     }
     $session->set('_flashMessages', $messages);
     return $messages;
 }
Exemple #14
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read common configuration
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * Try to load local configuration
      */
     if (file_exists(__DIR__ . '/config/config.php')) {
         $override = new Config(include __DIR__ . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     /**
      * Setting up the view component
      */
     $view = $di->get('view');
     $view->setViewsDir($config->get('application')->viewsDir);
     $di->set('view', $view);
     // register helper
     $di->setShared('adminHelper', function () {
         return new \Application\Admin\Librarys\voltHelper();
     });
     /**
      * Database connection is created based in the parameters defined in the configuration file
      */
     $di['db'] = function () use($config) {
         $config = $config->database->toArray();
         $dbAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter'];
         unset($config['adapter']);
         return new $dbAdapter($config);
     };
     // add default namespace
     $dispatcher = $di->get('dispatcher');
     $dispatcher->setDefaultNamespace("Application\\Admin\\Controllers");
     $di->set('dispatcher', $dispatcher);
     // register menu
     $di->set('AdminMenus', function () {
         return require __DIR__ . '/config/menus.php';
     });
 }
Exemple #15
0
 /**
  * Generates a pseudo random token value to be used as input's value in a CSRF check
  *
  * @param int|null $numberBytes
  * @return string
  * @throws Exception
  */
 public function getToken($numberBytes = null)
 {
     if (is_null($numberBytes)) {
         $numberBytes = 12;
     } elseif (!is_int($numberBytes)) {
         throw new Exception('Invalid parameter type.');
     }
     if (!function_exists('openssl_random_pseudo_bytes')) {
         throw new SecException('Openssl extension must be loaded');
     }
     $token = self::filterAlnum(base64_encode(openssl_random_pseudo_bytes($numberBytes)));
     if (!is_object($this->_dependencyInjector)) {
         throw new Exception('A dependency injection container is required to access the \'session\' service');
     }
     $session = $this->_dependencyInjector->getShared('session');
     $session->set($this->_tokenValueSessionID, $token);
     return $token;
 }
Exemple #16
0
 /**
  * Registers the module-only services
  *
  * @param \Phalcon\DiInterface $di
  */
 public function registerServices($di)
 {
     /**
      * Read application wide and module only configurations
      */
     $appConfig = $di->get('config');
     $moduleConfig = (include __DIR__ . '/config/config.php');
     $di->set('moduleConfig', $moduleConfig);
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($appConfig) {
         $url = new UrlResolver();
         $url->setBaseUri($appConfig->application->baseUri);
         return $url;
     });
     /**
      * Module specific dispatcher
      */
     $di->set('dispatcher', function () use($di) {
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($di->getShared('eventsManager'));
         $dispatcher->setDefaultNamespace('App\\Modules\\Frontend\\');
         return $dispatcher;
     });
     $di->setShared('request', function () use($appConfig) {
         return new \Phalcon\Http\Request();
     });
     /**
      * Include config per environment
      */
     include __DIR__ . '/config/config_' . $appConfig->application->environment . '.php';
     $database = $di->getConfig()->application->site . $di->get('request')->getQuery("country_code");
     /**
      * Simple database connection to localhost
      */
     $di->setShared('mongo', function ($config, $database) {
         $mongo = new \Mongo();
         return $mongo->selectDb($config->{$database}->dbname);
     }, true);
     $di->setShared('collectionManager', function () {
         return new \Phalcon\Mvc\Collection\Manager();
     }, true);
 }
Exemple #17
0
 /**
  * Registers the module-only services
  *
  * @param \Phalcon\DiInterface $di
  */
 public function registerServices($di)
 {
     /**
      * Read application wide and module only configurations
      */
     $appConfig = $di->get('config');
     $moduleConfig = (include __DIR__ . '/config/config.php');
     $di->set('moduleConfig', $moduleConfig);
     /**
      * Setting up the view component
      */
     $di->set('view', function () {
         $view = new View();
         $view->setViewsDir(__DIR__ . '/../../../public/src/app/modules/leads/views/')->setLayoutsDir('../../../layouts/')->setPartialsDir('../../../partials/')->setTemplateAfter('main')->registerEngines(['.html' => 'Phalcon\\Mvc\\View\\Engine\\Php']);
         return $view;
     });
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($appConfig) {
         $url = new UrlResolver();
         $url->setBaseUri($appConfig->application->baseUri);
         return $url;
     });
     /**
      * Module specific dispatcher
      */
     $di->set('dispatcher', function () use($di) {
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($di->getShared('eventsManager'));
         $dispatcher->setDefaultNamespace('App\\Modules\\Leads\\');
         return $dispatcher;
     });
     /**
      * Module specific database connection
      */
     $di->set('db', function () use($appConfig) {
         return new DbAdapter(['host' => $moduleConfig->database->host, 'username' => $moduleConfig->database->username, 'password' => $moduleConfig->database->password, 'dbname' => $moduleConfig->database->name]);
     });
 }
Exemple #18
0
 public function registerServices(\Phalcon\DiInterface $di = NULL)
 {
     $config = $di->get('config');
     $di->set('dispatcher', function () use($di) {
         $eventsManager = $di->getShared('eventsManager');
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setDefaultNamespace($this->namespace . '\\Controllers\\');
         return $dispatcher;
     });
     if (file_exists('../' . $config->app->apps . $this->moduleName . '/config/routers.ini')) {
         $router = $di->get('router');
         $routers = new \Phalcon\Config\Adapter\Ini('../' . $config->app->apps . $this->moduleName . '/config/routers.ini');
         if (!empty($routers)) {
             foreach ($routers as $name => $rule) {
                 $rule->module = $this->moduleName;
                 $pattern = $rule->pattern;
                 unset($rule->pattern);
                 $router->add($pattern, $rule->toArray())->setName($name);
             }
         }
         $router->handle();
     }
     $di->set('view', function () use($config) {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir('../' . $config->app->apps . $this->moduleName . '/' . $config->app->views);
         $view->registerEngines(array('.html' => function ($view, $di) use($config) {
             $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
             $volt->setOptions(array('compiledPath' => '../' . $config->app->apps . $this->moduleName . '/cache/volt/', 'compiledExtension' => '.php', 'compileAlways' => true, 'compiledSeparator' => '_'));
             return $volt;
         }));
         return $view;
     });
     $di->set('flashSession', function () {
         return new \Phalcon\Flash\Session(array('error' => 'alert alert-warning alert-small', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
     });
     $di->set('flash', function () {
         return new \Phalcon\Flash\Direct(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
     });
 }
Exemple #19
0
 /**
  * Returns the connection to read data related to a model
  *
  * @param \Phalcon\Mvc\ModelInterface $model
  * @return \Phalcon\Db\AdapterInterface
  * @throws Exception
  */
 public function getReadConnection($model)
 {
     if (is_object($model) === false || $model instanceof ModelInterface === false) {
         throw new Exception('Invalid parameter type.');
     }
     $service = 'db';
     if (is_array($this->_readConnectionServices) === true) {
         $entityName = strtolower(get_class($model));
         //Check if the model has a custom connection service
         if (isset($this->_readConnectionServices[$entityName]) === true) {
             $service = $this->_readConnectionServices[$entityName];
         }
     }
     if (is_object($this->_dependencyInjector) === false) {
         throw new Exception('A dependency injector container is required to obtain the services related to the ORM');
     }
     //Request the connection service from the DI
     $connection = $this->_dependencyInjector->getShared($service);
     if (is_object($connection) === false) {
         throw new Exception('Invalid injected connection service');
     }
     return $connection;
 }
Exemple #20
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read common configuration
      */
     $config = $di->has('config') ? $di->getShared('config') : null;
     /**
      * Try to load local configuration
      */
     if (file_exists(__DIR__ . '/config/config.php')) {
         $override = new Config(include __DIR__ . '/config/config.php');
         if ($config instanceof Config) {
             $config->merge($override);
         } else {
             $config = $override;
         }
     }
     $di->setShared('config', $config);
     /**
      * Setting up the view component
      */
     $view = $di->get('view');
     $view->setViewsDir($config->get('application')->viewsDir);
     $di->set('view', $view);
     // register helper
     $di->setShared('adminHelper', function () {
         return new \Application\Admin\Librarys\voltHelper();
     });
     // add default namespace
     $dispatcher = $di->get('dispatcher');
     $dispatcher->setDefaultNamespace("Application\\Admin\\Controllers");
     $di->set('dispatcher', $dispatcher);
     // register menu
     $di->set('AdminMenus', function () {
         return require __DIR__ . '/config/menus.php';
     });
 }
Exemple #21
0
 /**
  * Handle the command-line arguments.
  *
  *
  * <code>
  *  $arguments = array(
  *      'task' => 'taskname',
  *      'action' => 'action',
  *      'params' => array('parameter1', 'parameter2')
  *  );
  *  $console->handle($arguments);
  * </code>
  *
  * @param array $arguments
  * @return mixed
  * @throws Exception
  */
 public function handle($arguments = null)
 {
     /* Type check */
     if (is_null($arguments) === true) {
         $arguments = array();
     } elseif (is_array($arguments) === false) {
         throw new Exception('Invalid parameter type.');
     }
     if (is_object($this->_dependencyInjector) === false) {
         throw new Exception('A dependency injection object is required to access internal services');
     }
     $router = $this->_dependencyInjector->getShared('router');
     $router->handle($arguments);
     $moduleName = $router->getModuleName();
     if (isset($moduleName) === true) {
         //Event: console:beforeStartModule
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('console:beforeStartModule', $this, $moduleName) === false) {
                 return false;
             }
         }
         //Validate module structure
         if (is_array($this->_modules) === false || isset($this->_modules[$moduleName]) === false) {
             throw new Exception('Module \'' . $moduleName . '\' isn\'t registered in the console container');
         }
         if (is_array($this->_modules[$moduleName]) === false) {
             throw new Exception('Invalid module definition path');
         }
         //Require ['path']
         if (isset($this->_modules[$moduleName]['path']) === true) {
             if (file_exists($this->_modules[$moduleName]['path']) === true) {
                 require $this->_modules[$moduleName]['path'];
             } else {
                 throw new Exception('Module definition path \'' . $this->_modules[$moduleName]['path'] . '" doesn\'t exist');
             }
         }
         //Get class name
         if (isset($this->_modules[$moduleName]['className']) === true) {
             $className = $this->_modules[$moduleName]['className'];
         } else {
             $className = 'Module';
         }
         //Prepare $moduleObject
         $moduleObject = $this->_dependencyInjector->get($className);
         $moduleObject->registerAutoloaders();
         $moduleObject->registerServices($this->_dependencyInjector);
         //Event: console:afterStartModule
         if (is_object($this->_eventsManager) === true) {
             $this->_moduleObject = $moduleObject;
             if ($this->_eventsManager->fire('console:afterStartModule', $this, $moduleName) === false) {
                 return false;
             }
         }
     }
     //Get route
     $taskName = $router->getTaskName();
     $actionName = $router->getActionName();
     $params = $router->getParams();
     //Get dispatcher
     $dispatcher = $this->_dependencyInjector->getShared('dispatcher');
     if (is_object($dispatcher) === false || $dispatcher instanceof DispatcherInterface === false) {
         throw new Exception('Dispatcher service is not available.');
     }
     //Set route
     $dispatcher->setTaskName($taskName);
     $dispatcher->setActionName($actionName);
     $dispatcher->setParams($params);
     //Event: console:beforeHandleTask
     if (is_object($this->_eventsManager) === true) {
         if ($this->_eventsManager->fire('console:beforeHandleTask', $this, $dispatcher) === false) {
             return false;
         }
     }
     //Dispatch
     $task = $dispatcher->dispatch();
     if (is_object($this->_eventsManager) === true) {
         $this->_eventsManager->fire('console:afterHandleTask', $this, $task);
     }
     return $task;
 }
Exemple #22
0
 /**
  * Executes a parsed PHQL statement
  *
  * @param array|null $bindParams
  * @param array|null $bindTypes
  * @return mixed
  * @throws Exception
  */
 public function execute($bindParams = null, $bindTypes = null)
 {
     if (is_array($bindParams) === false && is_null($bindParams) === false || is_array($bindTypes) === false && is_null($bindTypes) === false) {
         throw new Exception('Invalid parameter type.');
     }
     /* GET THE CACHE */
     $cacheOptions = $this->_cacheOptions;
     if (is_null($cacheOptions) === false) {
         if (is_array($cacheOptions) === false) {
             throw new Exception('Invalid caching options');
         }
         //The user must set a cache key
         if (isset($cacheOptions['key']) === true) {
             $key = $cacheOptions['key'];
         } else {
             throw new Exception('A cache key must be provided to identify the cached resultset in the cache backend');
         }
         //By default use 3600 seconds (1 hour) as cache lifetime
         if (isset($cacheOptions['lifetime']) === true) {
             $lifetime = $cacheOptions['lifetime'];
         } else {
             $lifetime = 3600;
         }
         //'modelsCache' is the default name for the models cache service
         if (isset($cacheOptions['service']) === true) {
             $cacheService = $cacheOptions['service'];
         } else {
             $cacheService = 'modelsCache';
         }
         $cache = $this->_dependencyInjector->getShared($cacheService);
         if (is_object($cache) === false) {
             //@note no interface validation
             throw new Exception('The cache service must be an object');
         }
         $result = $cache->get($key, $lifetime);
         if (is_null($result) === false) {
             if (is_object($result) === false) {
                 throw new Exception("The cache didn't return a valid resultset");
                 //@note (sic!)
             }
             $result->setIsFresh(false);
             //Check if only the first two rows must be returned
             if ($this->_uniqueRow == true) {
                 $preparedResult = $result->getFirst();
             } else {
                 $preparedResult = $result;
             }
             return $preparedResult;
         }
         $this->_cache = $cache;
     }
     //The statement is parsed from its PHQL string or a previously processed IR
     $intermediate = $this->parse();
     //Check for default bind parameters and merge them with the passed ones
     $defaultBindParams = $this->_bindParams;
     if (is_array($defaultBindParams) === true) {
         if (is_array($bindParams) === true) {
             $mergedParams = array_merge($defaultBindParams, $bindParams);
         } else {
             $mergedParams = $defaultBindParams;
         }
     } else {
         $mergedParams = $bindParams;
     }
     //Check for default bind types and merge them with the passed onees
     $defaultBindTypes = $this->_bindTypes;
     if (is_array($defaultBindTypes) === true) {
         if (is_array($bindTypes) === true) {
             $mergedTypes = array_merge($defaultBindTypes, $bindTypes);
         } else {
             $mergedTypes = $defaultBindTypes;
         }
     } else {
         $mergedTypes = $bindTypes;
     }
     switch ((int) $this->_type) {
         case 309:
             $result = $this->_executeSelect($intermediate, $mergedParams, $mergedTypes);
             break;
         case 306:
             $result = $this->_executeInsert($intermediate, $mergedParams, $mergedTypes);
             break;
         case 300:
             $result = $this->_executeUpdate($intermediate, $mergedParams, $mergedTypes);
             break;
         case 303:
             $result = $this->_executeDelete($intermediate, $mergedParams, $mergedTypes);
             break;
         default:
             throw new Exception('Unknown statement ' . $this->_type);
             break;
     }
     //We store the resultset in the cache if any
     if (is_null($cacheOptions) === false) {
         //Only PHQL SELECTs can be cached
         if ($this->_type !== 309) {
             throw new Exception('Only PHQL statements return resultsets can be cached');
         }
         $cache->save($key, $result, $lifetime);
     }
     //Check if only the first row must be returned
     if ($this->_uniqueRow == true) {
         return $result->getFirst();
     } else {
         return $result;
     }
 }
Exemple #23
0
 /**
  * Checks that current url matches route
  *
  * ``` php
  * <?php
  * $I->seeCurrentRouteIs('posts.index');
  * ?>
  * ```
  * @param string $routeName
  */
 public function seeCurrentRouteIs($routeName)
 {
     if (!$this->di->has('url')) {
         $this->fail('Unable to resolve "url" service.');
     }
     /** @var Url $url */
     $url = $this->di->getShared('url');
     try {
         $this->seeCurrentUrlEquals($url->get(['for' => $routeName], null, true));
     } catch (Exception $e) {
         $this->fail($e->getMessage());
     }
 }
Exemple #24
0
 /**
  * Dispatches a handle action taking into account the routing parameters
  *
  * @return object|boolean
  */
 public function dispatch()
 {
     if (is_object($this->_dependencyInjector) === false) {
         $this->_throwDispatchException('A dependency injection container is required to access related dispatching services', self::EXCEPTION_NO_DI);
         return false;
     }
     if (is_object($this->_eventsManager) === true) {
         if ($this->_eventsManager->fire('dispatch:beforeDispatchLoop', $this) === false) {
             return false;
         }
     }
     $numberDispatches = 0;
     $this->_finished = false;
     $handler = null;
     while (true) {
         //Loop until finished is false
         if ($this->_finished === true) {
             break;
         }
         ++$numberDispatches;
         //Throw an exception after 256 consecutive forwards
         if ($numberDispatches >= 256) {
             $this->_throwDispatchException('Dispatcher has detected a cyclic routing causing stability problems', self::EXCEPTION_CYCLIC_ROUTING);
             break;
         }
         $this->_finished = true;
         //If the current namespace is null we use the set in $this->_defaultNamespace
         if (is_null($this->_namespaceName) === true) {
             $this->_namespaceName = $this->_defaultNamespace;
         }
         //If the handler is null we use the set in $this->_defaultHandler
         if (is_null($this->_handlerName) === true) {
             $this->_handlerName = $this->_defaultHandler;
         }
         //If the action is null we use the set in $this->_defaultAction
         if (is_null($this->_actionName) === true) {
             $this->_actionName = $this->_defaultAction;
         }
         //Calling beforeDispatch
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('dispatch:beforeDispatch', $this) === false) {
                 continue;
             }
             //Check if the user made a forward in the listener
             if ($this->_finished === false) {
                 continue;
             }
         }
         //We don't camelize the classes if they are in namespaces
         $p = strpos($this->_handlerName, '\\');
         if ($p === false) {
             $camelizedClass = Text::camelize($this->_handlerName);
         } elseif ($p === 0) {
             //@note this only handles one leading slash
             $camelizedClass = substr($this->_handlerName, strlen($this->_handlerName) + 1);
         } else {
             $camelizedClass = $this->_handlerName;
         }
         //Create the complete controller class name prepending the namespace
         if (is_null($this->_namespaceName) === false) {
             if (strrpos($this->_namespaceName, '\\') === strlen($this->_namespaceName) - 1) {
                 $handlerClass = $this->_namespaceName . $camelizedClass . $this->_handlerSuffix;
             } else {
                 $handlerClass = $this->_namespaceName . '\\' . $camelizedClass . $this->_handlerSuffix;
             }
         } else {
             $handlerClass = $camelizedClass . $this->_handlerSuffix;
         }
         //Handlers are retrieved as shared instances from the Service Container
         if ($this->_dependencyInjector->has($handlerClass) === false) {
             //Check using autoloading
             if (class_exists($handlerClass) === false) {
                 if ($this->_throwDispatchException($handlerClass . ' handler class cannot be loaded', self::EXCEPTION_HANDLER_NOT_FOUND) === false) {
                     if ($this->_finished === false) {
                         continue;
                     }
                 }
                 break;
             }
         }
         //Handlers must be only objects
         $handler = $this->_dependencyInjector->getShared($handlerClass);
         if (is_object($handler) === false) {
             if ($this->_throwDispatchException('Invalid handler returned from the services container', self::EXCEPTION_INVALID_HANDLER) === false) {
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             break;
         }
         //If the object was recently created in the DI we initialize it
         $wasFresh = $this->_dependencyInjector->wasFreshInstance();
         $this->_activeHandler = $handler;
         //Check if the method exists in the handler
         $actionMethod = $this->_actionName . $this->_actionSuffix;
         if (method_exists($handler, $actionMethod) === false) {
             //Call beforeNotFoundAction
             if (is_object($this->_eventsManager) === true) {
                 if ($this->_eventsManager->fire('dispatch:beforeNotFoundAction', $this) === false) {
                     continue;
                 }
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             if ($this->_throwDispatchException('Action \'' . $this->_actionName . '\' was not found on handler \'' . $this->_handlerName . '\'', self::EXCEPTION_ACTION_NOT_FOUND) === false) {
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             break;
         }
         //Calling beforeExecuteRoute
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('dispatch:beforeExecuteRoute', $this) === false) {
                 continue;
             }
             //Check if the user made a forward in the listener
             if ($this->_finished === false) {
                 continue;
             }
         }
         //Calling beforeExecuteRoute as callback and event
         if (method_exists($handler, 'beforeExecuteRoute') === true) {
             if ($handler->beforeExecuteRoute($this) === false) {
                 continue;
             }
             //Check if the user made a forward in the listener
             if ($this->_finished === false) {
                 continue;
             }
         }
         //Check if params is an array
         if (is_array($this->_params) === false) {
             if ($this->_throwDispatchException('Action parameters must be an Array', self::EXCEPTION_INVALID_PARAMS) === false) {
                 if ($this->_finished === false) {
                     continue;
                 }
             }
             break;
         }
         //Call the 'initialize' method just once per request
         if ($wasFresh === true) {
             if (method_exists($handler, 'initialize') === true) {
                 $handler->initialize();
             }
         }
         //Call the method with/without exceptions if an events manager is present
         if (is_object($this->_eventsManager) === true) {
             try {
                 //Call the method allowing exceptions
                 $m = new ReflectionMethod($handler, $actionMethod);
                 $value = $m->invokeArgs($handler, $this->_params);
             } catch (\Exception $exception) {
                 //Copy the exception to rethrow it later if needed
                 //Try to handle the exception
                 if ($this->_handleException($exception) === false) {
                     if ($this->_finished === false) {
                         continue;
                     }
                 } else {
                     //Exception wasn't handled, rethrow it
                     throw new Exception($exception);
                 }
             }
             //Update the latest value produced by the latest handler
             $this->_returnedValue = $value;
         } else {
             //Call the method handling exceptions as normal
             $this->_returnedValue = call_user_func_array(array($handler, $actionMethod), $this->_params);
         }
         $this->_lastHandler = $handler;
         //Calling afterExecuteRoute
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('dispatch:afterExecuteRoute', $this) === false) {
                 continue;
             }
             if ($this->_finished === false) {
                 continue;
             }
             //Calling afetDispatch
             $this->_eventsManager->fire('dispatch:afterDispatch', $this);
         }
         //Calling afterExecuteRoute as callback and event
         if (method_exists($handler, 'afterExecuteRoute') === true) {
             if ($handler->afterExecuteRoute($this, $this->_returnedValue) === false) {
                 continue;
             }
             if ($this->_finished === false) {
                 continue;
             }
         }
     }
     //Call afterDispatchLoop
     if (is_object($this->_eventsManager) === true) {
         $this->_eventsManager->fire('dispatch:afterDispatchLoop', $this);
     }
     return $handler;
 }
Exemple #25
0
 /**
  * Регистрация сервисов модуля
  */
 public function registerServices(\Phalcon\DiInterface $di)
 {
     $config = new \Phalcon\Config\Adapter\Ini(__DIR__ . '/config/config.ini');
     // Set site config
     $di->set('config', $config);
     // Setting up mongo
     $di->set('mongo', function () use($config) {
         $mongo = new \MongoClient($config->database->host);
         return $mongo->selectDb($config->database->name);
     }, true);
     // Registering the collectionManager service
     $di->set('collectionManager', function () {
         $modelsManager = new \Phalcon\Mvc\Collection\Manager();
         return $modelsManager;
     }, true);
     // Start the session the first time when some component request the session service
     $di->set('session', function () use($config) {
         if (isset($config->session->adapter)) {
             switch ($config->session->adapter) {
                 case 'mongo':
                     $mongo = new \Mongo($config->session->mongoHost);
                     $session = new \Phalcon\Session\Adapter\Mongo(array('collection' => $mongo->kladrapiSession->data));
                     break;
                 case 'file':
                     $session = new \Phalcon\Session\Adapter\Files();
                     break;
             }
         } else {
             $session = new \Phalcon\Session\Adapter\Files();
         }
         $session->start();
         return $session;
     });
     // Setting up dispatcher
     $di->set('dispatcher', function () use($di) {
         $evManager = $di->getShared('eventsManager');
         $evManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
             switch ($exception->getCode()) {
                 case \Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                 case \Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                     $dispatcher->forward(array('controller' => 'index', 'action' => 'show404'));
                     return false;
             }
         });
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         $dispatcher->setDefaultNamespace("Kladr\\Frontend\\Controllers");
         $dispatcher->setEventsManager($evManager);
         return $dispatcher;
     });
     // Register an user component
     $di->set('elements', function () {
         return new Library\Elements();
     });
     // Register key tools
     $di->set('keyTools', function () {
         return new Plugins\KeyTools();
     });
     // Register the flash service with custom CSS classes
     $di->set('flash', function () {
         $flash = new \Phalcon\Flash\Direct();
         return $flash;
     });
     // Setting up the view component
     $di->set('view', function () {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir('../apps/frontend/views/');
         return $view;
     });
 }
Exemple #26
0
 /**
  * Handle the whole request
  *
  * @param string|null $uri
  * @return mixed
  * @throws Exception
  */
 public function handle($uri = null)
 {
     if (is_string($uri) === false && is_null($uri) === false) {
         throw new Exception('Invalid parameter type.');
     }
     if (is_object($this->_dependencyInjector) === false) {
         throw new Exception('A dependency injection container is required to access related dispatching services');
     }
     //Calling beforeHandle routing
     if (is_object($this->_eventsManager) === true) {
         if ($this->_eventsManager->fire('micro:beforeHandleRoute', $this) === false) {
             return false;
         }
     }
     //Handling route information
     $router = $this->_dependencyInjector->getShared('router');
     //Handle the URI as normal
     $router->handle($uri);
     //Check if one route was matched
     $matchedRoute = $router->getMatchedRoute();
     if (is_object($matchedRoute) === true) {
         $routeId = $matchedRoute->getRouteId();
         if (isset($this->_handlers[$routeId]) === false) {
             throw new Exception("Matched route doesn't have an associate handler");
         }
         //Updating active handler
         $handler = $this->_handlers[$routeId];
         $this->_activeHandler = $handler;
         //Calling beforeExecuteRoute event
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('micro:beforeExecuteRoute', $this) === false) {
                 return false;
             } else {
                 $handler = $this->_activeHandler;
             }
         }
         if (is_array($this->_beforeHandlers) === true) {
             $this->_stopped = false;
             //Call the before handlers
             foreach ($this->_beforeHandlers as $before) {
                 if (is_object($before) === true) {
                     if ($before instanceof MiddlewareInterface === true) {
                         //Call the middleware
                         $status = $before->call($this);
                         //break the execution if the middleware was stopped
                         if ($this->_stopped === true) {
                             break;
                         }
                         continue;
                     }
                 }
                 if (is_callable($before) === false) {
                     throw new Exception('The before handler is not callable');
                 }
                 //Call the before handler, if it return false exit
                 $status = call_user_func($before);
                 if ($status === false) {
                     return false;
                 }
                 //Reload the stopped status
                 if ($this->_stopped === true) {
                     return $status;
                 }
             }
         }
         //Update the returned value
         $params = $router->getParams();
         $this->_returnedValue = call_user_func_array($handler, $params);
         //Calling afterExecuteRoute event
         if (is_object($this->_eventsManager) === true) {
             $this->_eventsManager->fire('micro:afterExecuteRoute', $this);
         }
         if (is_array($this->_afterHandlers) === true) {
             $this->_stopped = false;
             //Call the after handlers
             foreach ($this->_afterHandlers as $after) {
                 if (is_object($after) === true && $after instanceof MiddlewareInterface === true) {
                     //Call the middleware
                     $status = $after->call($this);
                     //Reload the status
                     if ($this->_stopped === true) {
                         break;
                     }
                     continue;
                 }
                 if (is_callable($after) === false) {
                     throw new Exception("One of the 'after' handlers is not callable");
                 }
                 $status = call_user_func($after);
             }
         }
     } else {
         //Calling beforeNotFound event
         if (is_object($this->_eventsManager) === true) {
             if ($this->_eventsManager->fire('micro:beforeNotFound', $this) === false) {
                 return false;
             }
         }
         //Check if a notfound handler is defined and is callable
         if (is_callable($this->_notFoundHandler) === false) {
             throw new Exception('The Not-Found handler is not callable or is not defined');
         }
         //Call the notfound handler
         $this->_returnedValue = call_user_func($this->_notFoundHandler);
         return $this->_returnedValue;
     }
     //Calling afterHandleRoute event
     if (is_object($this->_eventsManager) === true) {
         $this->_eventsManager->fire('micro:afterHandleRoute', $this);
     }
     if (is_array($this->_finishHandlers) === true) {
         $this->_stopped = false;
         $params = null;
         foreach ($this->_finishHandlers as $finish) {
             //Try to execute middleware as plugins
             if (is_object($finish) === true && $finish instanceof MiddlewareInterface === true) {
                 //Call the middleware
                 $status = $finish->call($this);
                 //Reload the status
                 if ($this->_stopped === true) {
                     break;
                 }
                 continue;
             }
             if (is_callable($finish) === false) {
                 throw new Exception('One of finish handlers is not callable');
             }
             if (is_null($params) === true) {
                 //@note see #719
                 $params = array($this);
             }
             //Call the 'finish' middleware
             $status = $finish($params);
             //Reload the status
             if ($this->_stopped === true) {
                 break;
             }
         }
     }
     //Check if the returned object is already a response
     if (is_object($this->_returnedValue) === true && $this->_returnedValue instanceof ResponseInterface === true) {
         //Automatically send the responses
         $this->_returnedValue->send();
     }
     return $this->_returnedValue;
 }
Exemple #27
0
 /**
  * Handles routing information received from the rewrite engine
  *
  *<code>
  * //Read the info from the rewrite engine
  * $router->handle();
  *
  * //Manually passing an URL
  * $router->handle('/posts/edit/1');
  *</code>
  *
  * @param string|null $uri
  * @throws Exception
  */
 public function handle($uri = null)
 {
     if (is_null($uri) === true) {
         $uri = $this->getRewriteUri();
     } elseif (is_string($uri) === false) {
         throw new Exception('Invalid parameter type.');
     }
     //Remove extra slashes in the route
     if ($this->_removeExtraSlashes === true) {
         $uri = self::phalconRemoveExtraSlashes($uri);
     }
     //Runtime variables
     $request = null;
     $currentHostName = null;
     $routeFound = false;
     $matches = null;
     $parts = array();
     $params = array();
     //Set status properties
     $this->_wasMatched = false;
     $this->_matchedRoute = null;
     $routes = is_array($this->_routes) === true ? $this->_routes : array();
     //Routes are traversed in reversed order
     foreach ($routes as $route) {
         //Look for HTTP method constraints
         $methods = $route->getHttpMethods();
         if (is_null($methods) === false) {
             //Retrieve the request service from the container
             if (is_null($request) === true) {
                 if (is_object($this->_dependencyInjector) === false) {
                     throw new Exception("A dependency injection container is required to access the 'request' service");
                 }
                 $request = $this->_dependencyInjector->getShared('request');
                 //@note no interface or object validation
             }
             //Check if the current method is allowed by the route
             if ($request->isMethod($methods) === false) {
                 continue;
             }
         }
         //Look for hostname constraints
         $hostname = $route->getHostname();
         if (is_null($hostname) === false) {
             //Retrieve the request service from the container
             if (is_null($request) === true) {
                 if (is_object($this->_dependencyInjector) === false) {
                     throw new Exception("A dependency injection container is required to access the 'request' service");
                 }
                 $request = $this->_dependencyInjector->getShared('request');
             }
             //Check if the current hostname is the same as the route
             if (is_null($currentHostName) === true) {
                 $currentHostName = $request->getHttpHost();
             }
             //No HTTP_HOST, maybe in CLI mode?
             if (is_null($currentHostName) === true) {
                 continue;
             }
             //Check if the hostname restriction is the same as the current in the route
             if (strpos($hostname, '(') !== false) {
                 if (strpos($hostname, '#') === false) {
                     $hostname = '#^' . $hostname . '$#';
                 }
                 $matched = preg_match($hostname, $currentHostName) == 0 ? false : true;
             } else {
                 $matched = $currentHostName === $hostname ? true : false;
             }
             if ($matched === false) {
                 continue;
             }
         }
         //If the route has parentheses use preg_match
         $pattern = $route->getCompiledPattern();
         if (strpos($pattern, '^') !== false) {
             $routeFound = preg_match($pattern, $uri, $matches) == 0 ? false : true;
         } else {
             $routeFound = $pattern === $uri ? true : false;
         }
         //Check for beforeMatch conditions
         if ($routeFound === true) {
             $beforeMatch = $route->getBeforeMatch();
             if (is_null($beforeMatch) === false) {
                 //Check first if the callback is callable
                 if (is_callable($beforeMatch) === false) {
                     throw new Exception('Before-Match callback is not callable in matched route');
                 }
                 //Call the function
                 $routeFound = call_user_func_array($beforeMatch, array($uri, $route, $this));
             }
         }
         //Apply converters
         if ($routeFound === true) {
             //Start from the default paths
             $paths = $route->getPaths();
             $parts = $paths;
             //Check if the matches has variables
             if (is_array($matches) === true) {
                 //Get the route converters if any
                 $converters = $route->getConverters();
                 foreach ($paths as $part => $position) {
                     if (is_string($part) === false || $part[0] !== chr(0)) {
                         if (isset($matches[$position]) === true) {
                             $matchPosition = $matches[$position];
                             //Check if the part has a converter
                             if (isset($converters[$part]) === true) {
                                 $converter = $converters[$part];
                                 $parts[$part] = call_user_func_array($converter, $matchPosition);
                                 continue;
                             }
                             //Update the parts if there is no coverter
                             $parts[$part] = $matchPosition;
                         } else {
                             //Apply the converters anyway
                             if (isset($converters[$part]) === true) {
                                 $converter = $converters[$part];
                                 $parts[$part] = call_user_func_array($converter, array($position));
                             }
                         }
                     }
                 }
                 //Update the matches generated by preg_match
                 $this->_matches = $matches;
             }
             $this->_matchedRoute = $route;
             break;
         }
     }
     //Update the wasMatched property indicating if the route was matched
     $this->_wasMatched = $routeFound === true ? true : false;
     //The route wasn't found, try to use the not-found paths
     if ($routeFound !== true) {
         if (is_null($this->_notFoundPaths) === false) {
             $parts = $this->_notFoundPaths;
             $routeFound = true;
         }
     }
     //Check route
     if ($routeFound === true) {
         //Check for a namespace
         if (isset($parts['namespace']) === true) {
             if (is_numeric($parts['namespace']) === false) {
                 $this->_namespace = $parts['namespace'];
             }
             unset($parts['namespace']);
         } else {
             $this->_namespace = $this->_defaultNamespace;
         }
         //Check for a module
         if (isset($parts['module']) === true) {
             if (is_numeric($parts['module']) === false) {
                 $this->_module = $parts['module'];
                 unset($parts['module']);
             } else {
                 $this->_module = $this->_defaultModule;
             }
         }
         //Check for exact controller name
         $exactStrIdentifer = chr(0) . 'exact';
         if (isset($parts[$exactStrIdentifer]) === true) {
             $this->_isExactControllerName = $parts[$exactStrIdentifer];
             unset($parts[$exactStrIdentifer]);
         } else {
             $this->_isExactControllerName = false;
         }
         //Check for a controller
         if (isset($parts['controller']) === true) {
             if (is_numeric($parts['controller']) === false) {
                 $this->_controller = $parts['controller'];
             }
             unset($parts['controller']);
         } else {
             $this->_controller = $this->_defaultController;
         }
         //Check for an action
         if (isset($parts['action']) === true) {
             if (is_numeric($parts['action']) === false) {
                 $this->_action = $parts['action'];
             }
             unset($parts['action']);
         } else {
             $this->_action = $this->_defaultAction;
         }
         //Check for parameters
         $params = array();
         if (isset($parts['params']) === true) {
             $paramStr = (string) substr($parts['params'], 1, 0);
             if (empty($paramStr) === false) {
                 $params = explode($paramStr, '/');
             }
             unset($parts['params']);
         }
         if (empty($params) === false) {
             $params = array_merge($params, $parts);
         } else {
             $params = $parts;
         }
         $this->_params = $params;
     } else {
         //Use default values if the route hasn't matched
         $this->_namespace = $this->_defaultNamespace;
         $this->_module = $this->_defaultModule;
         $this->_controller = $this->_defaultController;
         $this->_action = $this->_defaultAction;
         $this->_params = $this->_defaultParams;
     }
 }
Exemple #28
0
 /**
  * Register services
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     $module = $this->module;
     $baseControllers = $this->baseControllers;
     //Registering a dispatcher
     $di->set('dispatcher', function () use($di, &$module, &$baseControllers) {
         /**
          * @var \Phalcon\Events\ManagerInterface $eventsManager
          */
         $eventsManager = $di->getShared('eventsManager');
         $eventsManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
             /**
              * @var Dispatcher $dispatcher
              * @var \Phalcon\Mvc\Dispatcher\Exception $exception
              */
             switch ($exception->getCode()) {
                 case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                 case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                     $dispatcher->forward(['module' => 'index', 'controller' => 'error', 'action' => 'notFound404']);
                     return false;
             }
             return true;
         });
         $dispatcher = new Dispatcher();
         //Set default namespace to this module
         $dispatcher->setDefaultNamespace($baseControllers);
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setModuleName($module);
         return $dispatcher;
     });
     //Registering the view component
     $di->set('view', function () use($di, &$module) {
         $view = new View();
         $view->setViewsDir(APP_DIR . '/frontend/' . $module . '/views/');
         /**
          * @var \Phalcon\Events\Manager $eventsManager
          */
         $eventsManager = $di->getShared('eventsManager');
         $eventsManager->attach('view:beforeRender', new ZFrontTemplate($this->module));
         $eventsManager->attach('view:afterRender', new ZFrontTemplate($this->module));
         //Set view Event
         $view->setEventsManager($eventsManager);
         $view->registerEngines(['.volt' => function ($view, $di) {
             $volt = new Volt($view, $di);
             $volt->setOptions(['compiledPath' => function ($templatePath) {
                 $templatePath = strstr($templatePath, '/app');
                 $dirName = dirname($templatePath);
                 if (!is_dir(ROOT_PATH . '/cache/volt' . $dirName)) {
                     mkdir(ROOT_PATH . '/cache/volt' . $dirName, 0755, true);
                 }
                 return ROOT_PATH . '/cache/volt' . $dirName . '/' . basename($templatePath, '.volt') . '.php';
             }, 'compileAlways' => method_exists($di, 'get') ? (bool) $di->get('config')->frontendTemplate->compileTemplate : false, 'stat' => false]);
             $compiler = $volt->getCompiler();
             $compiler->addFunction('get_sidebar', 'get_sidebar');
             $compiler->addFunction('__', '__');
             $compiler->addFilter('t', function ($resolvedArgs) {
                 return '__(' . $resolvedArgs . ')';
             });
             $compiler->addFunction('strtotime', 'strtotime');
             $compiler->addFunction('human_timing', 'human_timing');
             $compiler->addFunction('moneyFormat', 'moneyFormat');
             $compiler->addFunction('number_format', 'number_format');
             $compiler->addFunction('zcms_header', 'zcms_header');
             $compiler->addFunction('zcms_header_prefix', 'zcms_header_prefix');
             $compiler->addFunction('change_date_format', 'change_date_format');
             $compiler->addFunction('in_array', 'in_array');
             return $volt;
         }]);
         return $view;
     });
 }
Exemple #29
0
 /**
  * Register services
  *
  * @param DiInterface $di
  */
 public final function registerServices(DiInterface $di)
 {
     $module = $this->module;
     $baseControllers = $this->baseControllers;
     //Registering a dispatcher
     $di->set('dispatcher', function () use($di, &$module, &$baseControllers) {
         //Create new Dispatcher
         $dispatcher = new PDispatcher();
         //Set default namespace to this module
         $dispatcher->setModuleName($this->module);
         //Set default namespace
         $dispatcher->setDefaultNamespace($baseControllers);
         //Set default controller
         $dispatcher->setDefaultController($this->defaultController);
         /**
          * Get Event Manager
          *
          * @var \Phalcon\Events\Manager $eventsManager
          */
         $eventsManager = $di->getShared('eventsManager');
         //Attach acl in dispatcher
         $eventsManager->attach('dispatch', $di->get('acl'));
         //Set event manager
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
     //Register the view component
     $di->set('view', function () use($di, &$module) {
         //Create Phalcon\Mvc\View
         $view = new ZView();
         $template = new ZTemplate($this->module);
         //Attach event
         $eventsManager = $di->getShared('eventsManager');
         if (method_exists($eventsManager, 'attach')) {
             $eventsManager->attach('view:beforeRender', $template);
             $eventsManager->attach('view:afterRender', $template);
             $eventsManager->attach('view:beforeRenderView', $template);
         } else {
             die(__FILE__ . ' Error: ZCMS cannot render template');
         }
         //Set view Event
         $view->setEventsManager($eventsManager);
         //Set view dir
         $view->setViewsDir(APP_DIR . '/backend/' . $module . '/views/');
         //Register engines
         $view->registerEngines(['.volt' => function ($view, $di) {
             $volt = new Volt($view, $di);
             $volt->setOptions(['compiledPath' => function ($templatePath) {
                 $templatePath = strstr($templatePath, '/app');
                 $dirName = dirname($templatePath);
                 if (!is_dir(ROOT_PATH . '/cache/volt' . $dirName)) {
                     mkdir(ROOT_PATH . '/cache/volt' . $dirName, 0755, TRUE);
                 }
                 return ROOT_PATH . '/cache/volt' . $dirName . '/' . basename($templatePath, '.volt') . '.php';
             }, 'compileAlways' => method_exists($di, 'get') ? (bool) $di->get('config')->backendTemplate->compileTemplate : false]);
             $compiler = $volt->getCompiler();
             $compiler->addFunction('get_sidebar', 'get_sidebar');
             $compiler->addFunction('__', '__');
             $compiler->addFunction('strtotime', 'strtotime');
             $compiler->addFunction('human_timing', 'human_timing');
             $compiler->addFunction('moneyFormat', 'moneyFormat');
             $compiler->addFunction('number_format', 'number_format');
             $compiler->addFunction('change_date_format', 'change_date_format');
             $compiler->addFunction('in_array', 'in_array');
             return $volt;
         }]);
         return $view;
     }, true);
 }
Exemple #30
0
 /**
  * Returns the models meta-data service related to the entity instance
  *
  * @return \Phalcon\Mvc\Model\MetaDataInterface
  * @throws Exception
  */
 public function getModelsMetaData()
 {
     if (is_object($this->_modelsMetaData) === false) {
         /*
         @see __construct
         
         if(is_object($this->_dependencyInjector) === false) {
             throw new Exception('A dependency injector container is required to obtain the services related to the ORM');
         }
         */
         $metaData = $this->_dependencyInjector->getShared('modelsMetadata');
         if (is_object($metaData) === false) {
             //@note no interface validation
             throw new Exception("The injected service 'modelsMetadata' is not valid");
         }
         $this->_modelsMetaData = $metaData;
     }
     return $this->_modelsMetaData;
 }