Example #1
0
 /**
  * Create view instance.
  * If no events manager provided - events would not be attached.
  *
  * @param DIBehaviour  $di             DI.
  * @param Config       $config         Configuration.
  * @param string       $viewsDirectory Views directory location.
  * @param Manager|null $em             Events manager.
  *
  * @return View
  */
 public static function factory($di, $config, $viewsDirectory, $em = null)
 {
     $view = new PhView();
     $volt = new PhVolt($view, $di);
     $volt->setOptions(["compiledPath" => $config->global->view->compiledPath, "compiledExtension" => $config->global->view->compiledExtension, 'compiledSeparator' => $config->global->view->compiledSeparator, 'compileAlways' => $config->global->view->compileAlways]);
     $compiler = $volt->getCompiler();
     $compiler->addExtension(new EnViewExtension());
     $compiler->addFilter('floor', 'floor');
     $compiler->addFunction('range', 'range');
     $compiler->addFunction('in_array', 'in_array');
     $compiler->addFunction('count', 'count');
     $compiler->addFunction('str_repeat', 'str_repeat');
     $view->registerEngines(['.volt' => $volt])->setRenderLevel(PhView::LEVEL_ACTION_VIEW)->setViewsDir($viewsDirectory);
     // Attach a listener for type "view".
     if ($em) {
         $em->attach("view", function ($event, $view) use($di, $config) {
             if ($config->global->profiler && $di->has('profiler')) {
                 if ($event->getType() == 'beforeRender') {
                     $di->get('profiler')->start();
                 }
                 if ($event->getType() == 'afterRender') {
                     $di->get('profiler')->stop($view->getActiveRenderPath(), 'view');
                 }
             }
             if ($event->getType() == 'notFoundView') {
                 throw new Exception('View not found - "' . $view->getActiveRenderPath() . '"');
             }
         });
         $view->setEventsManager($em);
     }
     $di->set('view', $view);
     return $view;
 }
Example #2
0
 /**
  * Register the services here to make them general
  * or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices(DiInterface $di)
 {
     //Read configuration
     $config = (include __DIR__ . "/config/config.php");
     // The URL component is used to generate all kind of urls in the application
     $di->set('url', function () use($config) {
         $url = new Url();
         $url->setBaseUri($config->application->baseUri);
         return $url;
     });
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         //Create/Get an EventManager
         $eventsManager = new EventsManager();
         //Attach a listener
         $eventsManager->attach('dispatch', function ($event, $dispatcher, $exception) {
             //controller or action doesn't exist
             if ($event->getType() == 'beforeException') {
                 switch ($exception->getCode()) {
                     case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                     case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                         $dispatcher->forward(['module' => 'backend', 'controller' => 'errors', 'action' => 'notFound']);
                         return false;
                 }
             }
         });
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace("Phanbook\\Backend\\Controllers");
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
     /**
      * Setting up the view component
      */
     $di->set('view', function () use($config) {
         $view = new View();
         $view->setViewsDir($config->application->viewsDir);
         $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
         $view->registerEngines(['.volt' => 'volt']);
         // Create an event manager
         $eventsManager = new EventsManager();
         // Attach a listener for type 'view'
         $eventsManager->attach('view', function ($event, $view) {
             if ($event->getType() == 'notFoundView') {
                 throw new \Exception('View not found!!! (' . $view->getActiveRenderPath() . ')');
             }
         });
         // Bind the eventsManager to the view component
         $view->setEventsManager($eventsManager);
         return $view;
     });
     $configMenu = (include __DIR__ . "/config/config.menu.php");
     $di->setShared('menuStruct', function () use($configMenu) {
         // if structure received from db table instead getting from $config
         // we need to store it to cache for reducing db connections
         $struct = $configMenu->get('menuStruct')->toArray();
         return $struct;
     });
 }
Example #3
0
 /**
  * Tests the View::getActiveRenderPath
  *
  * @issue  12139
  * @author Serghei Iakovlev <*****@*****.**>
  * @since  2014-08-14
  */
 public function testGetActiveRenderPath()
 {
     $this->specify('The View::getActiveRenderPath returns unexpected result', function () {
         $view = new View();
         $eventsManager = new Manager();
         $eventsManager->attach('view', new ViewAfterRenderListener());
         $view->setViewsDir(PATH_DATA . 'views');
         $view->setRenderLevel(View::LEVEL_ACTION_VIEW);
         $view->setEventsManager($eventsManager);
         expect($view->getActiveRenderPath())->equals('');
         $view->start();
         $view->render('test15', 'index');
         $view->finish();
         $view->getContent();
         expect($view->getActiveRenderPath())->equals(PATH_DATA . 'views' . DIRECTORY_SEPARATOR . 'test15' . DIRECTORY_SEPARATOR . 'index.phtml');
         $view->setViewsDir([PATH_DATA . 'views', PATH_DATA . 'views2']);
         expect($view->getActiveRenderPath())->equals([PATH_DATA . 'views' . DIRECTORY_SEPARATOR . 'test15' . DIRECTORY_SEPARATOR . 'index.phtml']);
     });
 }
Example #4
0
 /**
  * Register the services here to make them general
  * or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read configuration
      */
     //$config = include __DIR__ . "/config/config.php";
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         $eventsManager = new EventsManager();
         $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) {
             //controller or action doesn't exist
             $object = $event->getData();
             if ($event->getType() == 'beforeException') {
                 switch ($exception->getCode()) {
                     case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                     case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                         $dispatcher->forward(['controller' => 'errors', 'action' => 'index']);
                         return false;
                     case Dispatcher::EXCEPTION_CYCLIC_ROUTING:
                         $dispatcher->forward(['controller' => 'errors', 'action' => 'show404']);
                         return false;
                 }
             }
         });
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace("Phanbook\\Frontend\\Controllers");
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
     /**
      * Setting up the view component
      */
     $di->set('view', function () use($di) {
         $config = $di->get('config');
         $view = new View();
         $view->setViewsDir(ROOT_DIR . 'content/themes/' . $config->theme);
         $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
         $view->registerEngines(['.volt' => 'volt']);
         // Create an event manager
         $eventsManager = new EventsManager();
         $eventsManager->attach('view', function ($event, $view) {
             if ($event->getType() == 'notFoundView') {
                 throw new \Exception('View not found!!! (' . $view->getActiveRenderPath() . ')');
             }
         });
         // Bind the eventsManager to the view component
         $view->setEventsManager($eventsManager);
         return $view;
     });
 }
Example #5
0
 /**
  * Register the services here to make them general
  * or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices(DiInterface $di)
 {
     $di->set('view', function () {
         $view = new View();
         $view->setViewsDir(__DIR__ . '/views/');
         $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
         $view->registerEngines(['.volt' => 'volt']);
         // Create an event manager
         $eventsManager = new EventsManager();
         $eventsManager->attach('view', function ($event, $view) {
             if ($event->getType() == 'notFoundView') {
                 throw new \Exception('View not found!!! (' . $view->getActiveRenderPath() . ')');
             }
         });
         // Bind the eventsManager to the view component
         $view->setEventsManager($eventsManager);
         return $view;
     });
 }
Example #6
0
 /**
  * Register the services here to make them general or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices(\Phalcon\DiInterface $di)
 {
     /**
      * Read configuration
      */
     $config = (include __DIR__ . "/config/config.php");
     /**
      * Setting up the view component
      */
     // The URL component is used to generate all kind of urls in the application
     $di->set('url', function () {
         $url = new Url();
         $url->setBaseUri('/');
         return $url;
     });
     /**
      * Setting up the view component
      */
     $di->set('view', function () use($config) {
         $view = new View();
         $view->setViewsDir($config->application->view->viewsDir);
         $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
         $view->registerEngines(['.volt' => function () use($view, $config) {
             $volt = new Volt($view);
             $volt->setOptions(['compiledPath' => $config->application->view->compiledPath, 'compiledSeparator' => $config->application->view->compiledSeparator, 'compiledExtension' => $config->application->view->compiledExtension, 'compileAlways' => true]);
             return $volt;
         }]);
         // Create an event manager
         $eventsManager = new EventsManager();
         // Attach a listener for type 'view'
         $eventsManager->attach('view', function ($event, $view) {
             if ($event->getType() == 'notFoundView') {
                 throw new \Exception('View not found!!! (' . $view->getActiveRenderPath() . ')');
             }
         });
         // Bind the eventsManager to the view component
         $view->setEventsManager($eventsManager);
         return $view;
     });
 }
Example #7
0
 /**
  * Register the services here to make them general
  * or register in the ModuleDefinition to make them module-specific
  */
 public function registerServices(DiInterface $di)
 {
     //Read configuration
     $config = (include __DIR__ . "/config/config.php");
     $configGlobal = $di->getConfig();
     $di->set('url', function () use($config, $configGlobal) {
         $url = new Url();
         if (APPLICATION_ENV == 'production') {
             $url->setStaticBaseUri($configGlobal->application->production->staticBaseUri);
         } else {
             $url->setStaticBaseUri($configGlobal->application->development->staticBaseUri);
         }
         $url->setBaseUri($config->application->baseUri);
         return $url;
     });
     //Registering a dispatcher
     $di->set('dispatcher', function () {
         $eventsManager = $this->getEventsManager();
         $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) {
             //controller or action doesn't exist
             if ($event->getType() == 'beforeException') {
                 $message = $exception->getMessage();
                 $response = $this->getResponse();
                 switch ($exception->getCode()) {
                     case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                         $response->redirect();
                         return false;
                     case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                         $response->redirect('action-not-found?msg=' . $message);
                         return false;
                     case Dispatcher::EXCEPTION_CYCLIC_ROUTING:
                         $response->redirect('cyclic-routing?msg=' . $message);
                         return false;
                 }
             }
         });
         $dispatcher = new Dispatcher();
         $dispatcher->setDefaultNamespace("Phanbook\\Frontend\\Controllers");
         $dispatcher->setEventsManager($eventsManager);
         return $dispatcher;
     });
     /**
      * Setting up the view component
      */
     $di->set('view', function () use($di) {
         $config = $di->get('config');
         $view = new View();
         $view->setViewsDir(ROOT_DIR . 'content/themes/' . $config->theme);
         $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
         $view->registerEngines(['.volt' => 'volt']);
         // Create an event manager
         $eventsManager = $this->getEventsManager();
         $eventsManager->attach('view', function ($event, $view) {
             if ($event->getType() == 'notFoundView') {
                 throw new \Exception('View not found!!! (' . $view->getActiveRenderPath() . ')');
             }
         });
         // Bind the eventsManager to the view component
         $view->setEventsManager($eventsManager);
         return $view;
     });
 }
Example #8
0
 /**
  * Initialize the View.
  *
  * Setting up the view component.
  *
  *
  * @param DiInterface   $di     Dependency Injector
  * @param Config        $config App config
  * @param EventsManager $em     Events Manager
  *
  * @return Loader
  */
 protected function initView(DiInterface $di, Config $config, EventsManager $em)
 {
     $di->set('view', function () use($di, $config, $em) {
         $view = new View();
         $view->registerEngines(['.volt' => function ($view, $di) use($config) {
             $volt = new VoltEngine($view, $di);
             $voltConfig = $config->get('volt')->toArray();
             $options = ['compiledPath' => $voltConfig['cacheDir'], 'compiledExtension' => $voltConfig['compiledExt'], 'compiledSeparator' => $voltConfig['separator'], 'compileAlways' => ENV_DEVELOPMENT === APPLICATION_ENV && $voltConfig['forceCompile']];
             $volt->setOptions($options);
             $compiler = $volt->getCompiler();
             $compiler->addFunction('number_format', function ($resolvedArgs) {
                 return 'number_format(' . $resolvedArgs . ')';
             });
             $compiler->addFunction('chr', function ($resolvedArgs) {
                 return 'chr(' . $resolvedArgs . ')';
             });
             return $volt;
         }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']);
         $view->setViewsDir($config->get('application')->viewsDir);
         $em->attach('view', function ($event, $view) use($di, $config) {
             /**
              * @var LoggerInterface $logger
              * @var View $view
              * @var Event $event
              * @var DiInterface $di
              */
             $logger = $di->get('logger');
             $logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
             if ('notFoundView' == $event->getType()) {
                 $message = sprintf('View not found: %s', $view->getActiveRenderPath());
                 $logger->error($message);
                 throw new ViewException($message);
             }
         });
         $view->setEventsManager($em);
         return $view;
     });
 }
Example #9
0
        // Cache data for one day by default
        $frontCache = new FrontendOutput(['lifetime' => $config->cache->lifetime]);
        return new FileCache($frontCache, ['cacheDir' => $config->cache->cacheDir, 'prefix' => $config->cache->prefix]);
    }
});
//  Setting up the view component
$di->set('view', function () use($di, $eventsManager) {
    $config = $di->get('config');
    $view = new View($config->toArray());
    $view->setViewsDir($config->application->view->viewsDir);
    $view->disableLevel([View::LEVEL_MAIN_LAYOUT => true, View::LEVEL_LAYOUT => true]);
    $view->registerEngines(['.volt' => 'volt']);
    // Attach a listener for type 'view'
    $eventsManager->attach('view', function ($event, $view) {
        if ($event->getType() == 'notFoundView') {
            throw new \Exception('View not found!!! (' . $view->getActiveRenderPath() . ')');
        }
    });
    // Bind the eventsManager to the view component
    $view->setEventsManager($eventsManager);
    return $view;
});
// Register the flash service with custom CSS classes
$di->set('flashSession', function () {
    $flash = new Session(['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning']);
    return $flash;
});
// Database connection is created based in the parameters defined in the configuration file
$di->set('db', function () use($di) {
    $config = $di->get('config');
    $connection = new Mysql(['host' => $config->database->mysql->host, 'username' => $config->database->mysql->username, 'password' => $config->database->mysql->password, 'dbname' => $config->database->mysql->dbname, 'options' => [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $config->database->mysql->charset]]);
Example #10
0
    $view->registerEngines(['.volt' => function ($view, $di) use($config) {
        $volt = new Volt($view, $di);
        $path = APPLICATION_ENV == APP_TEST ? DOCROOT . 'tests/_cache/' : DOCROOT . $config->get('volt')->cacheDir;
        $options = ['compiledPath' => $path, 'compiledExtension' => $config->get('volt')->compiledExt, 'compiledSeparator' => $config->get('volt')->separator, 'compileAlways' => APPLICATION_ENV !== APP_PRODUCTION];
        $volt->setOptions($options);
        $volt->getCompiler()->addFunction('strtotime', 'strtotime')->addFunction('sprintf', 'sprintf')->addFunction('str_replace', 'str_replace')->addFunction('is_a', 'is_a');
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php']);
    $view->setVar('version', Version::get())->setViewsDir(DOCROOT . $config->get('application')->viewsDir);
    $eventsManager->attach('view', function ($event, $view) use($di, $config) {
        /**
         * @var \Phalcon\Events\Event $event
         * @var \Phalcon\Mvc\View $view
         */
        if ($event->getType() == 'notFoundView') {
            $message = sprintf('View not found - %s', $view->getActiveRenderPath());
            throw new Exception($message);
        }
    });
    $view->setEventsManager($eventsManager);
    return $view;
});
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->setShared('db', function () use($config) {
    $config = $config->get('database')->toArray();
    $dbClass = 'Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter'];
    unset($config['adapter']);
    return new $dbClass($config);
});
 /**
  * Gets/Saves information about views and stores truncated viewParams.
  *
  * @param Event $event
  * @param View  $view
  * @param mixed $file
  */
 public function beforeRenderView($event, $view, $file)
 {
     $params = array();
     $toView = $view->getParamsToView();
     $toView = !$toView ? array() : $toView;
     foreach ($toView as $k => $v) {
         if (is_object($v)) {
             $params[$k] = get_class($v);
         } elseif (is_array($v)) {
             $array = array();
             foreach ($v as $key => $value) {
                 if (is_object($value)) {
                     $array[$key] = get_class($value);
                 } elseif (is_array($value)) {
                     foreach ($value as $k2 => $v2) {
                         if (is_array($v2)) {
                             $array[$key][$k2] = 'Array[...]';
                         } else {
                             $array[$key][$k2] = $v2;
                         }
                     }
                 } else {
                     $array[$key] = $value;
                 }
             }
             $params[$k] = $array;
         } else {
             $params[$k] = (string) $v;
         }
     }
     $this->_viewsRendered[] = array('path' => $view->getActiveRenderPath(), 'params' => $params, 'controller' => $view->getControllerName(), 'action' => $view->getActionName());
 }
Example #12
0
 /**
  * Initialize the View.
  *
  * Setting up the view component.
  */
 protected function initView()
 {
     $this->di->set('view', function () {
         /** @var DiInterface $this */
         $config = $this->getShared('config');
         $em = $this->getShared('eventsManager');
         $view = new View();
         $view->registerEngines(['.volt' => function ($view, $di) {
             /** @var DiInterface $this */
             $config = $this->getShared('config');
             $volt = new VoltEngine($view, $di);
             $options = ['compiledPath' => function ($templatePath) {
                 /** @var DiInterface $this */
                 $config = $this->getShared('config')->get('volt')->toArray();
                 $filename = str_replace(['\\', '/'], $config['separator'], trim(substr($templatePath, strlen(BASE_DIR)), '\\/'));
                 $filename = basename($filename, '.volt') . $config['compiledExt'];
                 $cacheDir = rtrim($config['cacheDir'], '\\/') . DIRECTORY_SEPARATOR;
                 if (!is_dir($cacheDir)) {
                     @mkdir($cacheDir, 0755, true);
                 }
                 return rtrim($config['cacheDir'], '\\/') . DIRECTORY_SEPARATOR . $filename;
             }, 'compileAlways' => boolval($config->get('volt')->forceCompile)];
             $volt->setOptions($options);
             $volt->getCompiler()->addFunction('number_format', function ($resolvedArgs) {
                 return 'number_format(' . $resolvedArgs . ')';
             })->addFunction('chr', function ($resolvedArgs) {
                 return 'chr(' . $resolvedArgs . ')';
             });
             return $volt;
         }, '.phtml' => Php::class]);
         $view->setViewsDir($config->get('application')->viewsDir);
         $that = $this;
         $em->attach('view', function ($event, $view) use($that, $config) {
             /**
              * @var LoggerInterface $logger
              * @var View $view
              * @var Event $event
              * @var DiInterface $that
              */
             $logger = $that->get('logger');
             $logger->debug(sprintf('Event %s. Path: %s', $event->getType(), $view->getActiveRenderPath()));
             if ('notFoundView' == $event->getType()) {
                 $message = sprintf('View not found: %s', $view->getActiveRenderPath());
                 $logger->error($message);
                 throw new ViewException($message);
             }
         });
         $view->setEventsManager($em);
         return $view;
     });
 }