public function testModelsMysql()
 {
     require 'unit-tests/config.db.php';
     if (empty($configMysql)) {
         $this->markTestSkipped('Test skipped');
         return;
     }
     $di = $this->_getDI();
     $tracer = array();
     $di->set('db', function () use(&$tracer) {
         require 'unit-tests/config.db.php';
         $eventsManager = new Phalcon\Events\Manager();
         $connection = new Phalcon\Db\Adapter\Pdo\Mysql($configMysql);
         $eventsManager->attach('db', function ($event, $connection) use(&$tracer) {
             if ($event->getType() == 'beforeQuery') {
                 $tracer[] = $connection->getSqlStatement();
             }
         });
         $connection->setEventsManager($eventsManager);
         return $connection;
     }, true);
     $this->_executeTestsNormal($di, $tracer);
     $tracer = array();
     $this->_executeTestsRenamed($di, $tracer);
 }
Exemplo n.º 2
0
 public function registerServices(DiInterface $di)
 {
     $di['dispatcher'] = function () {
         $eventsManager = new \Phalcon\Events\Manager();
         //Attach a listener
         $eventsManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
             //controller or action doesn't exist
             if ($exception instanceof \Phalcon\Mvc\Dispatcher\Exception) {
                 $dispatcher->forward(array('controller' => 'error', 'action' => 'error404'));
                 return false;
             }
             switch ($exception->getCode()) {
                 case \Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                 case \Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                     $dispatcher->forward(array('controller' => 'error', 'action' => 'error404'));
                     return false;
             }
         });
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace("Modules\\Frontend\\Controllers");
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     };
     $di['view'] = function () {
         $view = new View();
         $view->setViewsDir(__DIR__ . '/views/');
         $view->setLayoutsDir('../../common/layout_frontend/');
         return $view;
     };
 }
Exemplo n.º 3
0
 public function _executeTests($connection)
 {
     $eventsManager = new Phalcon\Events\Manager();
     $listener = new DbProfilerListener();
     $eventsManager->attach('db', $listener);
     $connection->setEventsManager($eventsManager);
     $connection->query("SELECT TOP 3 * FROM personas");
     $profiler = $listener->getProfiler();
     $this->assertEquals($profiler->getNumberTotalStatements(), 1);
     $profile = $profiler->getLastProfile();
     $this->assertEquals(get_class($profile), 'Phalcon\\Db\\Profiler\\Item');
     $this->assertEquals("SELECT TOP 3 * FROM personas", $profile->getSQLStatement());
     $this->assertEquals(gettype($profile->getInitialTime()), "double");
     $this->assertEquals(gettype($profile->getFinalTime()), "double");
     $this->assertEquals(gettype($profile->getTotalElapsedSeconds()), "double");
     $this->assertTrue($profile->getFinalTime() > $profile->getInitialTime());
     $connection->query("SELECT TOP 100 * FROM personas");
     $this->assertEquals($profiler->getNumberTotalStatements(), 2);
     $profile = $profiler->getLastProfile();
     $this->assertEquals(get_class($profile), 'Phalcon\\Db\\Profiler\\Item');
     $this->assertEquals($profile->getSQLStatement(), "SELECT TOP 100 * FROM personas");
     $this->assertTrue($profile->getFinalTime() > $profile->getInitialTime());
     $connection->query("SELECT TOP 5 * FROM personas");
     $connection->query("SELECT TOP 10 * FROM personas");
     $connection->query("SELECT TOP 15 * FROM personas");
     $this->assertEquals(count($profiler->getProfiles()), 5);
     $this->assertEquals($profiler->getNumberTotalStatements(), 5);
     $this->assertEquals(gettype($profiler->getTotalElapsedSeconds()), "double");
     $this->assertEquals($profiler->getPoints(), 0);
     $profiler->reset();
     $this->assertEquals(count($profiler->getProfiles()), 0);
     $this->assertEquals($profiler->getNumberTotalStatements(), 0);
 }
Exemplo n.º 4
0
 protected function _prepareDI(&$trace)
 {
     Phalcon\DI::reset();
     $eventsManager = new Phalcon\Events\Manager();
     $eventsManager->attach('model', function ($event, $model) use(&$trace) {
         if (!isset($trace[$event->getType()][get_class($model)])) {
             $trace[$event->getType()][get_class($model)] = 1;
         } else {
             $trace[$event->getType()][get_class($model)]++;
         }
     });
     $di = new Phalcon\DI();
     $di->set('modelsManager', function () use($eventsManager) {
         $modelsManager = new Phalcon\Mvc\Model\Manager();
         $modelsManager->setEventsManager($eventsManager);
         return $modelsManager;
     }, true);
     $di->set('modelsMetadata', function () {
         return new Phalcon\Mvc\Model\Metadata\Memory();
     }, true);
     $di->set('db', function () {
         require 'unit-tests/config.db.php';
         //return new Phalcon\Db\Adapter\Pdo\Mysql($configMysql);
         return new Twm\Db\Adapter\Pdo\Mssql($configMssql);
     }, true);
 }
Exemplo n.º 5
0
 /**
  * Register specific services for the module
  *
  * @package     base-app
  * @version     2.0
  *
  * @param object $di dependency Injector
  *
  * @return void
  */
 public function registerServices(\Phalcon\DiInterface $di)
 {
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         //Create/Get an EventManager
         $eventsManager = new \Phalcon\Events\Manager();
         //Attach a listener
         $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) {
             //controller or action doesn't exist
             if ($event->getType() == 'beforeException') {
                 switch ($exception->getCode()) {
                     case \Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                     case \Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                         $dispatcher->forward(array('controller' => 'index', 'action' => 'notFound'));
                         return false;
                 }
             }
         });
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         //Set default namespace to documentation module
         $dispatcher->setDefaultNamespace("Baseapp\\Documentation\\Controllers");
         //Bind the EventsManager to the dispatcher
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
     //Registering the view component
     $di->set('view', function () use($di) {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir(__DIR__ . '/views/');
         $view->registerEngines(\Baseapp\Library\Tool::registerEngines($view, $di));
         return $view;
     });
 }
Exemplo n.º 6
0
 /**
  * @param \Phalcon\DiInterface $di
  */
 public function registerServices(\Phalcon\DiInterface $di = null)
 {
     // Set up MVC dispatcher.
     $controller_class = 'Modules\\' . $this->_module_class_name . '\\Controllers';
     $di['dispatcher'] = function () use($controller_class) {
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) {
             // Set odd/even pairs as the key and value of parameters, respectively.
             $keyParams = array();
             $params = $dispatcher->getParams();
             foreach ($params as $position => $value) {
                 if (is_int($position)) {
                     if ($position & 1) {
                         $keyParams[$params[$position - 1]] = urldecode($value);
                     }
                 } else {
                     // The "name" parameter is internal to routes.
                     if ($position != 'name') {
                         $keyParams[$position] = urldecode($value);
                     }
                 }
             }
             $dispatcher->setParams($keyParams);
             // Detect filename in controller and convert to "format" parameter.
             $controller_name = $dispatcher->getControllerName();
             if (strstr($controller_name, '.') !== false) {
                 list($controller_clean, $format) = explode('.', $controller_name, 2);
                 $dispatcher->setControllerName($controller_clean);
                 $dispatcher->setParam('format', $format);
             }
             // Detect filename in action and convert to "format" parameter.
             $action_name = $dispatcher->getActionName();
             if (strstr($action_name, '.') !== false) {
                 list($action_clean, $format) = explode('.', $action_name, 2);
                 $dispatcher->setActionName($action_clean);
                 $dispatcher->setParam('format', $format);
             }
         });
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setDefaultNamespace($controller_class);
         return $dispatcher;
     };
     // Set up module-specific configuration.
     $module_base_name = strtolower($this->_module_class_name);
     $module_config = $di->get('module_config');
     $di->setShared('current_module_config', function () use($module_base_name, $module_config) {
         if (isset($module_config[$module_base_name])) {
             return $module_config[$module_base_name];
         } else {
             return null;
         }
     });
     // Set up the view component and shared templates.
     $views_dir = 'modules/' . $module_base_name . '/views/scripts/';
     $di['view'] = function () use($views_dir) {
         return \FA\Phalcon\View::getView(array('views_dir' => $views_dir));
     };
 }
Exemplo n.º 7
0
 public function initialize()
 {
     $eventsManager = new \Phalcon\Events\Manager();
     $eventsManager->attach('model', function ($event, $robot) {
         return true;
     });
     $this->setEventsManager($eventsManager);
     $this->setSource('parts');
 }
Exemplo n.º 8
0
 protected function _registerListeners()
 {
     $eventsManager = new \Phalcon\Events\Manager();
     $eventsManager->attach('application', new Engine\Listener());
     $this->setEventsManager($eventsManager);
     $eventsManager = new \Phalcon\Events\Manager();
     $eventsManager->attach('dispatch', new Dispatcher\Listener());
     $this->di->get(Service::DISPATCHER)->setEventsManager($eventsManager);
 }
 protected function registerDispatcher()
 {
     $this->di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace('Cronmonitor\\Controllers');
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach('dispatch:beforeExecuteRoute', new Security());
         $eventsManager->attach('dispatch:beforeException', new NotFound());
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
 }
Exemplo n.º 10
0
 /**
  * Registers an autoloader related to the module
  *
  * @param DiInterface $di
  */
 public function registerAutoloaders(DiInterface $di = null)
 {
     $eventsManager = new \Phalcon\Events\Manager();
     $loader = new Loader();
     $loader->registerNamespaces(array('Phlame\\Core\\Controllers' => __DIR__ . '/controllers/', 'Phlame\\Core\\Models' => __DIR__ . '/models/', 'Phlame\\Core\\Components' => __DIR__ . '/components/'));
     // Listen all the loader events
     $eventsManager->attach('loader', function ($event, $loader) {
         if ($event->getType() == 'beforeCheckPath') {
             echo 'beforeCheckPath:' . $loader->getCheckedPath() . '<br/>';
         }
     });
     $loader->setEventsManager($eventsManager);
     $loader->register();
 }
Exemplo n.º 11
0
 public function testMicroEvents()
 {
     $trace = array();
     $eventsManager = new Phalcon\Events\Manager();
     $eventsManager->attach('micro', function ($event) use(&$trace) {
         $trace[$event->getType()] = true;
     });
     $app = new Phalcon\Mvc\Micro();
     $app->setEventsManager($eventsManager);
     $app->map('/blog', function () {
     });
     $app->handle('/blog');
     $this->assertEquals($trace, array('beforeHandleRoute' => true, 'beforeExecuteRoute' => true, 'afterExecuteRoute' => true, 'afterHandleRoute' => true));
 }
Exemplo n.º 12
0
 public function initialize()
 {
     $eventsManager = new \Phalcon\Events\Manager();
     //Attach an anonymous function as a listener for "model" events
     $eventsManager->attach('model', function ($event, $robot) {
         if ($event->getType() == 'beforeSave') {
             if ($robot->name == 'Scooby Doo') {
                 echo "Scooby Doo isn't a robot!";
                 return false;
             }
         }
         return true;
     });
 }
Exemplo n.º 13
0
 public static function initDb()
 {
     $config = \Phalcon\DI::getDefault()->get('config');
     $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config->database->toArray());
     if (getenv('APPLICATION_ENV') == 'devel') {
         $eventsManager = new \Phalcon\Events\Manager();
         $eventsManager->attach('db', function ($event, $connection) {
             if ($event->getType() == 'beforeQuery') {
                 //Start a profile with the active connection
                 error_log($connection->getSQLStatement() . "\n" . json_encode($connection->getSQLVariables()));
             }
         });
         $connection->setEventsManager($eventsManager);
     }
     return $connection;
 }
Exemplo n.º 14
0
 /**
  * Prepares component
  *
  * @param stdClass $database
  */
 public static function setup($database)
 {
     $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $database->adapter;
     self::$_connection = new $adapter(array('host' => $database->host, 'username' => $database->username, 'password' => $database->password, 'dbname' => $database->name));
     $profiler = new \Phalcon\Mvc\Model\Migration\Profiler();
     $eventsManager = new \Phalcon\Events\Manager();
     $eventsManager->attach('db', function ($event, $connection) use($profiler) {
         if ($event->getType() == 'beforeQuery') {
             $profiler->startProfile($connection->getSQLStatement());
         }
         if ($event->getType() == 'afterQuery') {
             $profiler->stopProfile();
         }
     });
     self::$_connection->setEventsManager($eventsManager);
 }
Exemplo n.º 15
0
 /**
  * Registra os serviços específicos para este módulo
  */
 public function registerServices($di)
 {
     //Registra o dispatcher
     $di->set('dispatcher', function () {
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         $eventManager = new \Phalcon\Events\Manager();
         $eventManager->attach('dispatch', new \Acl('backend'));
         $dispatcher->setEventsManager($eventManager);
         $dispatcher->setDefaultNamespace("Multiple\\Backend\\Controllers\\");
         return $dispatcher;
     });
     //Registra os diretórios das views
     $di->set('view', function () {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir('../apps/backend/views/');
         return $view;
     });
 }
Exemplo n.º 16
0
 public static function enableDbProfiling($di, $connection)
 {
     $eventsManager = new \Phalcon\Events\Manager();
     //从di中获取共享的profiler实例
     $profiler = $di->getProfiler();
     //监听所有的db事件
     $eventsManager->attach('db', function ($event, $connection) use($profiler) {
         //一条语句查询之前事件,profiler开始记录sql语句
         if ($event->getType() == 'beforeQuery') {
             $profiler->startProfile($connection->getSQLStatement());
         }
         //一条语句查询结束,结束本次记录,记录结果会保存在profiler对象中
         if ($event->getType() == 'afterQuery') {
             $profiler->stopProfile();
         }
     });
     $connection->setEventsManager($eventsManager);
 }
Exemplo n.º 17
0
 /**
  * Register the services here to make them general or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices($di)
 {
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         $dispatcher = new \Phalcon\Mvc\Dispatcher();
         //Attach a event listener to the dispatcher
         $eventManager = new \Phalcon\Events\Manager();
         $eventManager->attach('dispatch', new \Acl('frontend'));
         $dispatcher->setEventsManager($eventManager);
         $dispatcher->setDefaultNamespace("Multiple\\Frontend\\Controllers\\");
         return $dispatcher;
     });
     //Registering the view component
     $di->set('view', function () {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir('../apps/frontend/views/');
         return $view;
     });
 }
/**
 * view register function for tests
 *
 * @param \Phalcon\Mvc\ViewBaseInterface $view new class instance
 * @return \Phalcon\Mvc\ViewBaseInterface
 */
function testViewRegister(\Phalcon\Mvc\ViewBaseInterface $view)
{
    $view->setViewsDir('views/');
    $eventsManager = new \Phalcon\Events\Manager();
    //
    // For XML debug
    //
    if ($_GET['debug'] == 1) {
        $eventsManager->attach('view:beforeRender', function ($event, \Phalcon\Mvc\ViewBaseInterface $view) {
            header('Content-Type: text/plain;charset=utf-8');
            echo XSLT::createXmlFromArray((array) $view->getParamsToView(), 'variables')->saveXML();
            exit;
        });
    }
    $view->setEventsManager($eventsManager);
    $view->registerEngines(array('.xsl' => '\\Z\\Phalcon\\Mvc\\View\\Engine\\XSLT', '.xsl' => function ($view, $di) {
        $engine = new XSLT($view, $di);
        $engine->setOptions(array('phpFunctions' => array('ucfirst')));
        return $engine;
    }));
    return $view;
}
Exemplo n.º 19
0
 /**
  * Register the services here to make them general or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices($di)
 {
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         $dispatcher = new Dispatcher();
         //Attach a event listener to the dispatcher
         $eventManager = new \Phalcon\Events\Manager();
         $eventManager->attach('dispatch', new \Acl('frontend'));
         $dispatcher->setEventsManager($eventManager);
         $dispatcher->setDefaultNamespace("Multiple\\Frontend\\Controllers\\");
         return $dispatcher;
     });
     //Registering the view component
     $di->set('view', function () {
         $view = new \Phalcon\Mvc\View();
         $view->setViewsDir('../apps/frontend/views/');
         return $view;
     });
     $di->set('db', function () {
         return new Database(array("host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "invo"));
     });
 }
Exemplo n.º 20
0
 public function testShouldFireEvents()
 {
     $firedEventsCounter = 0;
     $eventsManager = new \Phalcon\Events\Manager();
     $eventsManager->attach('generator:beforeBuild', function (Event $event, Generator $generator) use(&$firedEventsCounter) {
         $firedEventsCounter++;
     });
     $eventsManager->attach('generator:afterBuild', function (Event $event, Generator $generator) use(&$firedEventsCounter) {
         $firedEventsCounter++;
     });
     $eventsManager->attach('generator:beforeRender', function (Event $event, Generator $generator) use(&$firedEventsCounter) {
         $firedEventsCounter++;
     });
     $eventsManager->attach('generator:afterRender', function (Event $event, Generator $generator) use(&$firedEventsCounter) {
         $firedEventsCounter++;
     });
     $generator = new \Vegas\ApiDoc\Generator(APP_ROOT . '/app/modules', ['match' => '/(.*)Controller(.*)\\.php/i', 'verbose' => false]);
     $generator->setEventsManager($eventsManager);
     $generator->build();
     $generator->setRenderer(new FakeRenderer());
     $generator->render();
     $this->assertInstanceOf('\\Phalcon\\Events\\Manager', $generator->getEventsManager());
     $this->assertSame(4, $firedEventsCounter);
 }
Exemplo n.º 21
0
 /**
  * Mount the module specific routes before the module is loaded.
  * Add ModuleRoutes Group and annotated controllers for parsing their routing information.
  *
  * @param \Phalcon\DiInterface  $di
  */
 public static function initRoutes(DiInterface $di)
 {
     $loader = new Loader();
     $loader->registerNamespaces(['App\\Modules\\Backend\\Controllers' => __DIR__ . '/Controllers/', 'App\\Modules\\Backend\\Controllers\\API' => __DIR__ . '/Controllers/api/', 'App\\Modules\\Backend\\Models' => __DIR__ . '/Models/', 'App\\Modules\\Backend\\Library' => __DIR__ . '/Lib/', 'App\\Modules\\Frontend\\Controllers' => __DIR__ . '/../Frontend/Controllers/', 'App\\Modules\\Frontend\\Models' => __DIR__ . '/../Frontend/Models/'], TRUE)->register();
     /**
      * Read application wide and module only configurations
      */
     $appConfig = $di->get('config');
     $moduleConfig = (include __DIR__ . '/config/config.php');
     $di->setShared('moduleConfig', $moduleConfig);
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->setShared('url', function () use($appConfig) {
         $url = new UrlResolver();
         $url->setBaseUri($appConfig->application->baseUri);
         return $url;
     });
     $di->setShared('request', function () use($appConfig) {
         return new \Phalcon\Http\Request();
     });
     /**
      * Read configuration
      */
     include __DIR__ . "/../../config/env/" . $appConfig->application->environment . ".php";
     $database = $di->getConfig()->application->site . $di->get('request')->getQuery("countryCode");
     /**
      * Module specific database connection
      */
     $di->set('db', function () use($config, $database) {
         $eventsManager = new \Phalcon\Events\Manager();
         //Create a database listener
         $dbListener = new MyDBListener();
         //Listen all the database events
         $eventsManager->attach('db', $dbListener);
         $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(['host' => $config->{$database}->host, 'username' => $config->{$database}->username, 'password' => $config->{$database}->password, 'dbname' => $config->{$database}->dbname, 'options' => array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'")]);
         //Assign the eventsManager to the db adapter instance
         $connection->setEventsManager($eventsManager);
         return $connection;
     });
     /**
      * Simple database connection to localhost
      */
     $di->set('mongo', function () use($config, $database) {
         $mongo = new \MongoClient();
         return $mongo->selectDb($config->{$database}->dbname);
     }, true);
     $di->set('collectionManager', function () {
         return new \Phalcon\Mvc\Collection\Manager();
     }, true);
     /**
      * Include composer autoloader
      */
     require __DIR__ . "/../../../vendor/autoload.php";
     /**
      * Module specific dispatcher
      */
     $di->set('dispatcher', function () use($di) {
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace('App\\Modules\\Backend\\Controllers\\');
         return $dispatcher;
     });
     $di->set('utils', function () {
         require __DIR__ . "/../../Common/Lib/Application/Plugins/Utils.php";
         $utils = new Utils();
         return $utils;
     });
     /**
      * If our request contains a body, it has to be valid JSON.  This parses the
      * body into a standard Object and makes that available from the DI.  If this service
      * is called from a function, and the request body is not valid JSON or is empty,
      * the program will throw an Exception.
      */
     $di->setShared('requestBody', function () {
         parse_str(file_get_contents("php://input"), $in);
         // JSON body could not be parsed, throw exception
         if ($in === null) {
             throw new HTTPException('There was a problem understanding the data sent to the server by the application.', 409, array('dev' => 'The JSON body sent to the server was unable to be parsed.', 'internalCode' => 'REQ1000', 'more' => ''));
         }
         return $in;
     });
     /**
      * This means we can create listeners that run when an event is triggered.
      */
     $di->setShared('modelsManager', function () use($di, $config, $database) {
         $eventsManager = new \Phalcon\Events\Manager();
         $customModelsManager = new CustomModelsManager();
         /**
          * Attach an anonymous function as a listener for "model" events
          */
         $eventsManager->attach('model', $customModelsManager);
         /**
          * Setting a default EventsManager
          */
         $customModelsManager->setEventsManager($eventsManager);
         return $customModelsManager;
     });
 }
Exemplo n.º 22
0
 public function testEvents()
 {
     $dispatcher = $this->_getDispatcher();
     $listener = new DispatcherListener($this);
     $eventsManager = new Phalcon\Events\Manager();
     $eventsManager->attach('dispatch', $listener);
     $dispatcher->setEventsManager($eventsManager);
     //Normal flow events
     $listener->setControllerName('test2');
     $listener->setActionName('index');
     $dispatcher->setControllerName('test2');
     $dispatcher->setActionName('index');
     $dispatcher->setParams(array());
     $dispatcher->dispatch();
     $trace = join('-', $listener->getTrace());
     $this->assertEquals($trace, 'beforeDispatch-beforeExecuteRoute-afterInitialize-afterExecuteRoute-afterDispatch');
     //Stop at beforeDispatch event
     $listener->stopAt('beforeDispatch');
     $dispatcher->dispatch();
     $trace = join('-', $listener->getTrace());
     $this->assertEquals($trace, 'beforeDispatch');
     //Stop at beforeExecuteRoute event
     $listener->stopAt('beforeExecuteRoute');
     $dispatcher->dispatch();
     $trace = join('-', $listener->getTrace());
     $this->assertEquals($trace, 'beforeDispatch-beforeExecuteRoute');
     $listener->clearTrace();
     //Dispatch a not existing action
     $listener->setActionName('notExists');
     $dispatcher->setControllerName('test2');
     $dispatcher->setActionName('notExists');
     $dispatcher->setParams(array());
     $dispatcher->dispatch();
     $trace = join('-', $listener->getTrace());
     $this->assertEquals($trace, 'beforeDispatch-beforeNotFoundAction');
     $listener->clearTrace();
     //Dispatching exceptions
     $listener->setControllerName('nonController');
     $listener->setActionName('index');
     $listener->setExceptionMessage('NoncontrollerController handler class cannot be loaded');
     $listener->setExceptionType('Phalcon\\Mvc\\Dispatcher\\Exception');
     $dispatcher->setControllerName('nonController');
     $dispatcher->setActionName('index');
     $dispatcher->setParams(array());
     $dispatcher->dispatch();
     $trace = join('-', $listener->getTrace());
     $this->assertEquals($trace, 'beforeDispatch-beforeException');
     //Still we can't completely stop exceptions
     $listener->clearTrace();
     $listener->resetStop();
     //Uncaught exception
     $listener->setControllerName('test8');
     $listener->setActionName('buggy');
     $listener->setExceptionMessage("This is an uncaught exception");
     $listener->setExceptionType("Exception");
     $dispatcher->setControllerName('test8');
     $dispatcher->setActionName('buggy');
     $dispatcher->setParams(array());
     $dispatcher->dispatch();
     $trace = join('-', $listener->getTrace());
     $this->assertEquals($trace, 'beforeDispatch-beforeExecuteRoute-afterInitialize-beforeException-afterExecuteRoute-afterDispatch');
 }
Exemplo n.º 23
0
<?php

//Registering the collectionManager service
$di->set('collectionManager', function () {
    $eventsManager = new Phalcon\Events\Manager();
    // Attach an anonymous function as a listener for "model" events
    $eventsManager->attach('collection', function ($event, $model) {
        if (get_class($model) == 'Robots') {
            if ($event->getType() == 'beforeSave') {
                if ($model->name == 'Scooby Doo') {
                    echo "Scooby Doo isn't a robot!";
                    return false;
                }
            }
        }
        return true;
    });
    // Setting a default EventsManager
    $modelsManager = new Phalcon\Mvc\Collection\Manager();
    $modelsManager->setEventsManager($eventsManager);
    return $modelsManager;
}, true);
Exemplo n.º 24
0
<?php

$di->set('view', function () {
    //Create an events manager
    $eventsManager = new Phalcon\Events\Manager();
    //Attach a listener for type "view"
    $eventsManager->attach("view", function ($event, $view) {
        echo $event->getType(), ' - ', $view->getActiveRenderPath(), PHP_EOL;
    });
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir("../app/views/");
    //Bind the eventsManager to the view component
    $view->setEventsManager($eventsManager);
    return $view;
}, true);
Exemplo n.º 25
0
 * meant to be public.                                                       *
 *                                                                           *
 * Identification of peers is done via SSL client certificates               *
 *                                                                           *
 * Required:                                                                 *
 * Phalcon PHP extension - http://phalconphp.com                             *
 *****************************************************************************/
require_once 'libs/db.inc.php';
// =================================================
// Authenticate the remote peer (Before the Routing)
// =================================================
// Done via the EventManager and beforeHandleRoute event
// By default peer is not authenticated:
$authinfo = false;
// Create a events manager
$eventManager = new Phalcon\Events\Manager();
// Attach the anonymous function to handle the authentication of the peer
$eventManager->attach('micro', function ($event, $app) use($mysqli) {
    global $authinfo;
    if ($event->getType() == 'beforeHandleRoute') {
        // The server should have the TLS client certificate information and the remote peer address
        // If not, just fail early
        if (!array_key_exists("VERIFIED", $_SERVER) || $_SERVER['VERIFIED'] != "SUCCESS" || !array_key_exists("DN", $_SERVER) || strlen($_SERVER['DN']) == 0 || !array_key_exists("REMOTE_ADDR", $_SERVER) || strlen($_SERVER['REMOTE_ADDR']) == 0) {
            $response = new Phalcon\Http\Response();
            $response->setStatusCode(401, "Unauthorized");
            //Send errors to the client
            $response->setJsonContent(array('status' => 'ERROR', 'messages' => array('Missing/Wrong TLS client certificate')));
            $response->send();
            return false;
        } elseif ($mysqli->connect_errno != 0) {
            $response = new Phalcon\Http\Response();
Exemplo n.º 26
0
        //vraiment utile?
        $view->metadonneesViewsDir = $config->application->pilotage->viewsDir;
    }
    $view->viewsDir = $config->application->navigateur->viewsDir;
    // $view->mapserver_path=$config->mapserver->url;
    $view->setViewsDir($config->application->navigateur->viewsDir);
    $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
        $volt = new VoltEngine($view, $di);
        $volt->setOptions(array('compiledPath' => $config->application->navigateur->cacheDir, 'compiledSeparator' => '_', 'compileAlways' => isset($config->application->debug) && $config->application->debug ? true : false));
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
    return $view;
}, true);
$di->set('dispatcher', function () use($di) {
    //Create/Get an EventManager
    $eventsManager = new Phalcon\Events\Manager();
    //Attach a listener
    $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) {
        //The controller exists but the action not
        if ($event->getType() == 'beforeNotFoundAction') {
            $dispatcher->forward(array('controller' => 'error', 'action' => 'error404'));
            return false;
        }
        //Alternative way, controller or action doesn't exist
        if ($event->getType() == 'beforeException') {
            switch ($exception->getCode()) {
                case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $dispatcher->forward(array('controller' => 'error', 'action' => 'error404'));
                    return false;
            }
Exemplo n.º 27
0
<?php

$eventsManager = new Phalcon\Events\Manager();
//Attach an anonymous function as a listener for "model" events
$eventsManager->attach('collection', function ($event, $robot) {
    if ($event->getType() == 'beforeSave') {
        if ($robot->name == 'Scooby Doo') {
            echo "Scooby Doo isn't a robot!";
            return false;
        }
    }
    return true;
});
$robot = new Robots();
$robot->setEventsManager($eventsManager);
$robot->name = 'Scooby Doo';
$robot->year = 1969;
$robot->save();
Exemplo n.º 28
0
<?php

//Create an event manager
$eventsManager = new Phalcon\Events\Manager();
//Attach a listener for type "acl"
$eventsManager->attach("acl", function ($event, $acl) {
    if ($event->getType() == 'beforeCheckAccess') {
        echo $acl->getActiveRole(), $acl->getActiveResource(), $acl->getActiveAccess();
    }
});
$acl = new \Phalcon\Acl\Adapter\Memory();
//Setup the $acl
//...
//Bind the eventsManager to the acl component
$acl->setEventsManager($eventManagers);
Exemplo n.º 29
0
 /**
  * "Attaching event listeners by event name fails if preceded by
  * detachment of all listeners for that type."
  *
  * Test contains 4 steps:
  * - assigning event manager to dummy service with single log event
  *   listener attached
  * - attaching second log listener
  * - detaching all log listeners
  * - attaching different listener
  *
  * NOTE: This test looks the same as above but it checks detachAll()
  * instead of detachAll() method. To be DELETED when detachAll()
  * will not supported any more.
  *
  * @see https://github.com/phalcon/cphalcon/issues/1331
  */
 public function testBug1331BackwardCompatibility()
 {
     $di = new Phalcon\Di();
     $di->set('componentX', function () use($di) {
         $component = new LeDummyComponent();
         $eventsManager = new Phalcon\Events\Manager();
         $eventsManager->attach('log', $di->get('MyFirstWeakrefListener'));
         $component->setEventsManager($eventsManager);
         return $component;
     });
     $di->set('firstListener', 'MyFirstWeakrefListener');
     $di->set('secondListener', 'MySecondWeakrefListener');
     // ----- TESTING STEP 1 - SIGNLE 'LOG' LISTENER ATTACHED
     $component = $di->get('componentX');
     $logListeners = $component->getEventsManager()->getListeners('log');
     $this->assertCount(1, $logListeners);
     $this->assertInstanceOf('MyFirstWeakrefListener', $logListeners[0]);
     // ----- TESTING STEP 2 - SECOND 'LOG' LISTENER ATTACHED
     $component->getEventsManager()->attach('log', $di->get('MySecondWeakrefListener'));
     $logListeners = $component->getEventsManager()->getListeners('log');
     $this->assertCount(2, $logListeners);
     $firstLister = array_shift($logListeners);
     $secondLister = array_shift($logListeners);
     $this->assertInstanceOf('MyFirstWeakrefListener', $firstLister);
     $this->assertInstanceOf('MySecondWeakrefListener', $secondLister);
     // ----- TESTING STEP 3 - ALL 'LOG' LISTENER DETACHED
     $component->getEventsManager()->detachAll('log');
     $logListeners = $component->getEventsManager()->getListeners('log');
     $this->assertEmpty($logListeners);
     // ----- TESTING STEP 4 - SINGLE 'LOG' LISTENER ATTACHED SECOND TIME
     $component->getEventsManager()->attach('log', $di->get('MySecondWeakrefListener'));
     $logListeners = $component->getEventsManager()->getListeners('log');
     $this->assertCount(1, $logListeners);
     $this->assertInstanceOf('MySecondWeakrefListener', $logListeners[0]);
 }
Exemplo n.º 30
-1
 protected function _getDI()
 {
     Phalcon\DI::reset();
     $di = new Phalcon\DI();
     $di->set('modelsManager', function () {
         return new Phalcon\Mvc\Model\Manager();
     });
     $di->set('modelsMetadata', function () {
         return new Phalcon\Mvc\Model\Metadata\Memory();
     });
     $di->set('db', function () {
         require 'unit-tests/config.db.php';
         //return new Twm\Db\Adapter\Pdo\Mssql($configMssql);
         $connection = new Phalcon\Db\Adapter\Pdo\Mysql($configMysql);
         $eventsManager = new Phalcon\Events\Manager();
         //Listen all the database events
         $eventsManager->attach('db', function ($event, $connection) {
             if ($event->getType() == 'beforeQuery') {
                 echo $connection->getSQLStatement();
             }
         });
         //Assign the eventsManager to the db adapter instance
         $connection->setEventsManager($eventsManager);
         return $connection;
     });
     return $di;
 }