| #2 | Phalcon\Mvc\Application->handle()
/var/www/sites/tla/config/bootstrap.php (175) <?php
namespace Blazy;
use Blazy\Library\Mvc\Url as UrlResolver;
use Blazy\Library\Mvc\View\PhpFunctionExtension;
use Intervention\Image\ImageManager;
use Lamvh\Phalcon\Translate\Translate;
use Phalcon\Assets\Manager as AssetsManager;
use Phalcon\Cache\BackendInterface;
use Phalcon\Cache\Frontend\Output as FrontOutput;
use Phalcon\Config;
use Phalcon\Di;
use Phalcon\DiInterface;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Flash\Session as FlashSession;
use Phalcon\Http\Response\Cookies;
use Phalcon\Loader;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Logger\AdapterInterface as LoggerInterface;
use Phalcon\Logger\Formatter\Line as FormatterLine;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Exception as ViewException;
use Phalcon\Mvc\View\Simple as SimpleView;
use Phalcon\Queue\Beanstalk;
use Phalcon\Utils\Slug;
use RuntimeException;
class Bootstrap extends Application
{
private $app;
private $loaders = [
'cache',
'session',
'view',
'database',
'router',
'url',
'dispatcher',
'flash',
'timezones',
'assets',
'cookie',
'translate',
'media',
];
private $activeModules = ['frontend', 'backend', 'skeleton', 'auth', 'category', 'widget', 'mobile', 'article', 'shop'];
/**
* Bootstrap constructor.
*
* @param DiInterface $di
*/
public function __construct(DiInterface $di)
{
$em = new EventsManager;
$em->enablePriorities(true);
$config = $this->initConfig();
// Register the configuration itself as a service
$di->setShared('eventsManager', $em);
$this->app = new Application;
$this->initLogger($di, $config, $em);
$this->registerActiveModules($this->activeModules);
$this->initLoader($di, $config, $em);
foreach ($this->loaders as $service) {
$serviceName = ucfirst($service);
$this->{'init' . $serviceName}($di, $config, $em);
}
$this->initBackground();
$this->setEventsManager($em);
$this->setDI($di);
}
/**
* Runs the Application
*
* @return $this|string
*/
public function run()
{
if (ENV_TESTING === APPLICATION_ENV) {
return $this;
}
return $this->getOutput();
}
/**
* Get application output.
*
* @return string
*/
public function getOutput()
{
if ($this instanceof Application) {
/**
* @var BackendInterface $viewCache
*/
if (!empty($this->config->viewCache->cacheHtml)) {
$viewCache = $this->viewCache;
$prefix = $this->config->viewCache->htmlPrefix;
$key = $prefix . Slug::generate($this->router->getRewriteUri(), '_');
$output = $viewCache->get($key);
if (empty($output)) {
$output = $this->handle()->getContent();
$isMinify = false;
if (!empty($this->config->minify->mode)) {
if (empty($this->config->minify->condition)) {
$isMinify = true;
} else {
$strCondition = $this->dispatcher->getModuleName() . '_' .
$this->dispatcher->getControllerName() . '_' .
$this->dispatcher->getActionName();
if (stripos($strCondition, $this->config->minify->condition) !== false) {
$isMinify = true;
}
}
}
if (!empty($isMinify)) {
$output = preg_replace('/<!--(.|\s)*?-->/', '', $output);
$search = [
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\</s', //strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/>(\s)+</',
'/\n/',
'/\r/',
'/\t/',
];
$replace = [
'>',
'<',
'\\1',
'><',
'',
'',
'',
];
$output = preg_replace($search, $replace, $output);
}
$viewCache->save($key, $output);
}
} else {
$output = $this->handle()->getContent();
}
return $output;
}
return $this->handle();
}
/**
* Initialize the Logger.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initLogger(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('logger', function ($filename = null, $format = null) use ($config) {
$format = $format ?: $config->get('logger')->format;
$filename = trim($filename ?: $config->get('logger')->filename, '\\/');
$path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
$formatter = new FormatterLine($format, $config->get('logger')->date);
$logger = new FileLogger($path . $filename);
$logger->setFormatter($formatter);
$logger->setLogLevel($config->get('logger')->logLevel);
return $logger;
});
}
/**
* Initialize the Loader.
*
* Adds all required namespaces.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initLoader(DiInterface $di, Config $config, EventsManager $em)
{
$loader = new Loader;
$loader->registerNamespaces(
[
'Blazy\Library' => $config->get('application')->libraryDir,
'Blazy\Helper' => $config->get('application')->helpersDir,
'Blazy\Models' => $config->get('application')->modelsDir,
'Blazy\Plugin' => $config->get('application')->pluginsDir,
'Blazy\Constant' => $config->get('application')->constantDir,
//module
'Blazy\Library\Mvc' => $config->get('application')->libraryDir . '/mvc/',
'Blazy\Library\Mvc\View' => $config->get('application')->libraryDir . '/mvc/view',
'Blazy\Util' => $config->get('application')->utilModuleDir,
]
);
$loader->setEventsManager($em);
$loader->register();
$di->setShared('loader', $loader);
return $loader;
}
/**
* Initialize the Cache.
*
* The frontend must always be Phalcon\Cache\Frontend\Output and the service 'viewCache'
* must be registered as always open (not shared) in the services container (DI).
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initCache(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('viewCache', function () use ($config) {
$frontend = new FrontOutput(['lifetime' => $config->get('viewCache')->lifetime]);
$config = $config->get('viewCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime']);
return new $backend($frontend, $config);
});
$di->setShared('modelsCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('modelsCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('modelsCache')->lifetime]);
$config = $config->get('modelsCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
$di->setShared('dataCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('dataCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('dataCache')->lifetime]);
$config = $config->get('dataCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
}
/**
* Initialize the Session Service.
*
* Start the session the first time some component request the session service.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initSession(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('session', function () use ($config) {
$adapter = '\Phalcon\Session\Adapter\\' . $config->get('session')->adapter;
/** @var \Phalcon\Session\AdapterInterface $session */
$session = new $adapter;
$session->start();
return $session;
});
}
/**
* 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->setShared('view', function () use ($di, $config, $em) {
$view = new View;
$view->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($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->addExtension(new PhpFunctionExtension());
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
$compiler->addFunction('truncate', 'Lamvh\Phalcon\Utils\Str::truncateSafe');
$compiler->addFunction('in_array', 'in_array');
$compiler->addFunction('blockRender', function ($resolvedArgs, $exprArgs) {
return sprintf('$this->block->render(%s)', $resolvedArgs);
});
$compiler->addFunction(
'repeat',
function ($resolvedArgs, $exprArgs) use ($compiler) {
// Resolve the first argument
$firstArgument = $compiler->expression($exprArgs[0]['expr']);
// Checks if the second argument was passed
if (isset($exprArgs[1])) {
$secondArgument = $compiler->expression($exprArgs[1]['expr']);
} else {
// Use '10' as default
$secondArgument = '10';
}
return 'str_repeat(' . $firstArgument . ', ' . $secondArgument . ')';
}
);
return $volt;
},
]);
$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;
});
$di->setShared('simpleView', function () use ($di, $config, $em) {
$simpleView = new SimpleView();
$simpleView->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($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 . ')';
});
return $volt;
},
// Setting up Php Engine
'.phtml' => 'Phalcon\Mvc\View\Engine\Php',
]);
$simpleView->setViewsDir($config->get('application')->viewsDir);
$em->attach('simpleView', 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);
}
});
$simpleView->setEventsManager($em);
return $simpleView;
});
}
/**
* Initialize the Database connection.
*
* Database connection is created based in the parameters defined in the configuration file.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDatabase(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('db', function () use ($config, $em, $di) {
$config = $config->database->toArray();
$adapter = '\Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
unset($config['adapter']);
/** @var \Phalcon\Db\Adapter\Pdo $connection */
$connection = new $adapter($config);
// Listen all the database events
$em->attach(
'db',
function ($event, $connection) use ($di) {
/**
* @var \Phalcon\Events\Event $event
* @var \Phalcon\Db\AdapterInterface $connection
* @var \Phalcon\DiInterface $di
*/
if ($event->getType() == 'beforeQuery') {
$variables = $connection->getSQLVariables();
$string = $connection->getSQLStatement();
if ($variables) {
$string .= "\n" . print_r($variables, true);;
}
// To disable logging change logLevel in config
$di->get('logger', ['db.log'])->debug($string);
}
}
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($em);
return $connection;
});
$di->setShared('modelsManager', function () use ($em) {
$modelsManager = new ModelsManager;
$modelsManager->setEventsManager($em);
return $modelsManager;
});
$di->setShared('modelsMetadata', function () use ($config, $em) {
$config = $config->get('metadata')->toArray();
$adapter = '\Phalcon\Mvc\Model\Metadata\\' . $config['adapter'];
unset($config['adapter']);
$metaData = new $adapter($config);
return $metaData;
});
}
/**
* Initialize the Queue Service.
* TODO: Not yet implement
*
* Queue to deliver e-mails in real-time and other tasks.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initQueue(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('queue', function () use ($config) {
$config = $config->get('beanstalk');
$config->get('disabled', true);
if ($config->get('disabled', true)) {
return new DummyServer();
}
if (!$host = $config->get('host', false)) {
$error = 'Beanstalk is not configured';
if (class_exists('\Phalcon\Queue\Beanstalk\Exception')) {
$exception = '\Phalcon\Queue\Beanstalk\Exception';
} else {
$exception = '\Phalcon\Exception';
}
throw new $exception($error);
}
return new Beanstalk(['host' => $host]);
});
}
/**
* Initialize the Router.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initRouter(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('router', function () use ($config, $em) {
/** @var \Phalcon\Mvc\Router $router */
$router = include BASE_DIR . 'config/routes.php';
if (!isset($_GET['_url'])) {
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
}
if (preg_match('/(.jpg|.jpge|.png|.gif|.ico|.css|.js)$/', $router->getRewriteUri())) {
exit;
}
$router->removeExtraSlashes(true);
$router->setEventsManager($em);
$router->setDefaultNamespace('Blazy\Frontend\Controllers');
$router->setDefaultModule('frontend');
$router->notFound(['controller' => 'error', 'action' => 'route404']);
return $router;
});
}
/**
* Initialize the Url service.
*
* The URL component is used to generate all kind of urls in the application.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initUrl(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('url', function () use ($config) {
$url = new UrlResolver;
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri(STATIC_BASE_URL . $config->application->baseUri);
return $url;
});
}
/**
* Initialize the Dispatcher.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDispatcher(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('dispatcher', function () use ($em) {
$dispatcher = new Dispatcher;
$dispatcher->setDefaultNamespace('Blazy\Frontend\Controllers');
$em->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) {
if (!class_exists('Blazy\Backend\Module')) {
include_once BASE_DIR . '/app/modules/backend/module.php';
$module = new Backend\Module();
$module->registerServices($this->getDI());
$module->registerAutoloaders($this->getDI());
$dispatcher->setNamespaceName('Blazy\Backend\Controllers');
}
});
$dispatcher->setEventsManager($em);
return $dispatcher;
});
}
/**
* Initialize the Flash Service.
*
* Register the Flash Service with the Twitter Bootstrap classes
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initFlash(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('flash', function () {
$flash = new Flash(
[
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]
);
return $flash;
});
$di->setShared('flashInline', function () use ($di) {
$flash = $di->getShared('flash');
$flash->setCssClasses([
'error' => 'custom-message error',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
return $flash;
});
$di->setShared(
'flashSession',
function () {
return new FlashSession([
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in alert-hightlight',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
}
);
}
/**
* Initialize time zones.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initTimezones(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('timezones', function () use ($config) {
return require_once BASE_DIR . 'config/timezones.php';
});
}
/**
* Load module's configuration file, prepare and return the Config.
*
* @param string $path Config path [Optional]
*
* @return Config
* @throws RuntimeException
*/
protected function initConfig($path = null)
{
$path = $path ?: BASE_DIR . 'config/';
if (!is_readable($path . 'config.php')) {
throw new RuntimeException(
'Unable to read config from ' . $path . 'config.php'
);
}
$di = Di::getDefault();
/**
* Load default configuration and run module background job
*
* @var \Phalcon\Config $config
*/
$config = include_once $path . 'config.php';
$di->setShared('config', $config);
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.php'))
$config->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.php');
}
/**
* Load environment configuration
*
* @var \Phalcon\Config $envConfig
*/
$envConfig = include_once $path . 'config.' . APPLICATION_ENV . '.php';
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php'))
$envConfig->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php');
}
if ($envConfig instanceof Config) {
$config->merge($envConfig);
}
return $config;
}
protected function initBackground()
{
$di = Di::getDefault();
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/Background.php')) {
include_once BASE_DIR . 'app/modules/' . $module . '/Background.php';
$background = 'Blazy\\' . $module . '\Background';
new $background($di);
}
}
}
/**
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initAssets(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('assets', function () use ($config, $em) {
return new AssetsManager();
});
}
/*protected function initViewSimple(DiInterface $di, Config $config, EventsManager $em) {
$di->setShared('viewSimple', function() {
$view = new ViewSimple();
$view->setViewsDir($config->application->viewsDir);
return new ViewSimple();
});
}*/
/**
* starts the cookie the first time some component requests the cookie service
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initCookie(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('cookies', function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
});
}
/**
* Multi language
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initTranslate(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('translate', function () use ($di, $config) {
$translate = new Translate($config->application->messagesDir, $config->application->defaultLanguage);
$dispatcher = $di->getShared('dispatcher');
$lang = $dispatcher->getParam('lang');
if (!empty($lang)) {
$translate->setCurrentLanguage($lang);
}
return $translate;
});
$di->setShared('t', function () use ($di, $config) {
return $di->getShared('translate')->getTranslation();
});
}
/**
* media manager: image, video ..
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initMedia(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('image', new ImageManager(['driver' => 'gd']));
}
public function registerActiveModules($modules, $merge = false)
{
$preparedModules = [];
foreach ($modules as $module) {
$preparedModules[$module] = [
'className' => 'Blazy\\' . ucfirst($module) . '\\Module',
'path' => BASE_DIR . 'app/modules/' . $module . '/Module.php',
];
}
parent::registerModules($preparedModules, $merge);
}
}
|
| #3 | Blazy\Bootstrap->getOutput()
/var/www/sites/tla/config/bootstrap.php (99) <?php
namespace Blazy;
use Blazy\Library\Mvc\Url as UrlResolver;
use Blazy\Library\Mvc\View\PhpFunctionExtension;
use Intervention\Image\ImageManager;
use Lamvh\Phalcon\Translate\Translate;
use Phalcon\Assets\Manager as AssetsManager;
use Phalcon\Cache\BackendInterface;
use Phalcon\Cache\Frontend\Output as FrontOutput;
use Phalcon\Config;
use Phalcon\Di;
use Phalcon\DiInterface;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Flash\Session as FlashSession;
use Phalcon\Http\Response\Cookies;
use Phalcon\Loader;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Logger\AdapterInterface as LoggerInterface;
use Phalcon\Logger\Formatter\Line as FormatterLine;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Exception as ViewException;
use Phalcon\Mvc\View\Simple as SimpleView;
use Phalcon\Queue\Beanstalk;
use Phalcon\Utils\Slug;
use RuntimeException;
class Bootstrap extends Application
{
private $app;
private $loaders = [
'cache',
'session',
'view',
'database',
'router',
'url',
'dispatcher',
'flash',
'timezones',
'assets',
'cookie',
'translate',
'media',
];
private $activeModules = ['frontend', 'backend', 'skeleton', 'auth', 'category', 'widget', 'mobile', 'article', 'shop'];
/**
* Bootstrap constructor.
*
* @param DiInterface $di
*/
public function __construct(DiInterface $di)
{
$em = new EventsManager;
$em->enablePriorities(true);
$config = $this->initConfig();
// Register the configuration itself as a service
$di->setShared('eventsManager', $em);
$this->app = new Application;
$this->initLogger($di, $config, $em);
$this->registerActiveModules($this->activeModules);
$this->initLoader($di, $config, $em);
foreach ($this->loaders as $service) {
$serviceName = ucfirst($service);
$this->{'init' . $serviceName}($di, $config, $em);
}
$this->initBackground();
$this->setEventsManager($em);
$this->setDI($di);
}
/**
* Runs the Application
*
* @return $this|string
*/
public function run()
{
if (ENV_TESTING === APPLICATION_ENV) {
return $this;
}
return $this->getOutput();
}
/**
* Get application output.
*
* @return string
*/
public function getOutput()
{
if ($this instanceof Application) {
/**
* @var BackendInterface $viewCache
*/
if (!empty($this->config->viewCache->cacheHtml)) {
$viewCache = $this->viewCache;
$prefix = $this->config->viewCache->htmlPrefix;
$key = $prefix . Slug::generate($this->router->getRewriteUri(), '_');
$output = $viewCache->get($key);
if (empty($output)) {
$output = $this->handle()->getContent();
$isMinify = false;
if (!empty($this->config->minify->mode)) {
if (empty($this->config->minify->condition)) {
$isMinify = true;
} else {
$strCondition = $this->dispatcher->getModuleName() . '_' .
$this->dispatcher->getControllerName() . '_' .
$this->dispatcher->getActionName();
if (stripos($strCondition, $this->config->minify->condition) !== false) {
$isMinify = true;
}
}
}
if (!empty($isMinify)) {
$output = preg_replace('/<!--(.|\s)*?-->/', '', $output);
$search = [
'/\>[^\S ]+/s', //strip whitespaces after tags, except space
'/[^\S ]+\</s', //strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/>(\s)+</',
'/\n/',
'/\r/',
'/\t/',
];
$replace = [
'>',
'<',
'\\1',
'><',
'',
'',
'',
];
$output = preg_replace($search, $replace, $output);
}
$viewCache->save($key, $output);
}
} else {
$output = $this->handle()->getContent();
}
return $output;
}
return $this->handle();
}
/**
* Initialize the Logger.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initLogger(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('logger', function ($filename = null, $format = null) use ($config) {
$format = $format ?: $config->get('logger')->format;
$filename = trim($filename ?: $config->get('logger')->filename, '\\/');
$path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
$formatter = new FormatterLine($format, $config->get('logger')->date);
$logger = new FileLogger($path . $filename);
$logger->setFormatter($formatter);
$logger->setLogLevel($config->get('logger')->logLevel);
return $logger;
});
}
/**
* Initialize the Loader.
*
* Adds all required namespaces.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return Loader
*/
protected function initLoader(DiInterface $di, Config $config, EventsManager $em)
{
$loader = new Loader;
$loader->registerNamespaces(
[
'Blazy\Library' => $config->get('application')->libraryDir,
'Blazy\Helper' => $config->get('application')->helpersDir,
'Blazy\Models' => $config->get('application')->modelsDir,
'Blazy\Plugin' => $config->get('application')->pluginsDir,
'Blazy\Constant' => $config->get('application')->constantDir,
//module
'Blazy\Library\Mvc' => $config->get('application')->libraryDir . '/mvc/',
'Blazy\Library\Mvc\View' => $config->get('application')->libraryDir . '/mvc/view',
'Blazy\Util' => $config->get('application')->utilModuleDir,
]
);
$loader->setEventsManager($em);
$loader->register();
$di->setShared('loader', $loader);
return $loader;
}
/**
* Initialize the Cache.
*
* The frontend must always be Phalcon\Cache\Frontend\Output and the service 'viewCache'
* must be registered as always open (not shared) in the services container (DI).
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initCache(DiInterface $di, Config $config, EventsManager $em)
{
$di->set('viewCache', function () use ($config) {
$frontend = new FrontOutput(['lifetime' => $config->get('viewCache')->lifetime]);
$config = $config->get('viewCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime']);
return new $backend($frontend, $config);
});
$di->setShared('modelsCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('modelsCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('modelsCache')->lifetime]);
$config = $config->get('modelsCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
$di->setShared('dataCache', function () use ($config) {
$frontend = '\Phalcon\Cache\Frontend\\' . $config->get('dataCache')->frontend;
$frontend = new $frontend(['lifetime' => $config->get('dataCache')->lifetime]);
$config = $config->get('dataCache')->toArray();
$backend = '\Phalcon\Cache\Backend\\' . $config['backend'];
unset($config['backend'], $config['lifetime'], $config['frontend'], $config['useCache'], $config['isFresh']);
return new $backend($frontend, $config);
});
}
/**
* Initialize the Session Service.
*
* Start the session the first time some component request the session service.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initSession(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('session', function () use ($config) {
$adapter = '\Phalcon\Session\Adapter\\' . $config->get('session')->adapter;
/** @var \Phalcon\Session\AdapterInterface $session */
$session = new $adapter;
$session->start();
return $session;
});
}
/**
* 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->setShared('view', function () use ($di, $config, $em) {
$view = new View;
$view->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($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->addExtension(new PhpFunctionExtension());
$compiler->addFunction('number_format', function ($resolvedArgs) {
return 'number_format(' . $resolvedArgs . ')';
});
$compiler->addFunction('truncate', 'Lamvh\Phalcon\Utils\Str::truncateSafe');
$compiler->addFunction('in_array', 'in_array');
$compiler->addFunction('blockRender', function ($resolvedArgs, $exprArgs) {
return sprintf('$this->block->render(%s)', $resolvedArgs);
});
$compiler->addFunction(
'repeat',
function ($resolvedArgs, $exprArgs) use ($compiler) {
// Resolve the first argument
$firstArgument = $compiler->expression($exprArgs[0]['expr']);
// Checks if the second argument was passed
if (isset($exprArgs[1])) {
$secondArgument = $compiler->expression($exprArgs[1]['expr']);
} else {
// Use '10' as default
$secondArgument = '10';
}
return 'str_repeat(' . $firstArgument . ', ' . $secondArgument . ')';
}
);
return $volt;
},
]);
$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;
});
$di->setShared('simpleView', function () use ($di, $config, $em) {
$simpleView = new SimpleView();
$simpleView->registerEngines([
// Setting up Volt Engine
'.volt' => function ($view, $di) use ($config) {
$volt = new \Phalcon\Mvc\View\Engine\Volt($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 . ')';
});
return $volt;
},
// Setting up Php Engine
'.phtml' => 'Phalcon\Mvc\View\Engine\Php',
]);
$simpleView->setViewsDir($config->get('application')->viewsDir);
$em->attach('simpleView', 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);
}
});
$simpleView->setEventsManager($em);
return $simpleView;
});
}
/**
* Initialize the Database connection.
*
* Database connection is created based in the parameters defined in the configuration file.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDatabase(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('db', function () use ($config, $em, $di) {
$config = $config->database->toArray();
$adapter = '\Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
unset($config['adapter']);
/** @var \Phalcon\Db\Adapter\Pdo $connection */
$connection = new $adapter($config);
// Listen all the database events
$em->attach(
'db',
function ($event, $connection) use ($di) {
/**
* @var \Phalcon\Events\Event $event
* @var \Phalcon\Db\AdapterInterface $connection
* @var \Phalcon\DiInterface $di
*/
if ($event->getType() == 'beforeQuery') {
$variables = $connection->getSQLVariables();
$string = $connection->getSQLStatement();
if ($variables) {
$string .= "\n" . print_r($variables, true);;
}
// To disable logging change logLevel in config
$di->get('logger', ['db.log'])->debug($string);
}
}
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($em);
return $connection;
});
$di->setShared('modelsManager', function () use ($em) {
$modelsManager = new ModelsManager;
$modelsManager->setEventsManager($em);
return $modelsManager;
});
$di->setShared('modelsMetadata', function () use ($config, $em) {
$config = $config->get('metadata')->toArray();
$adapter = '\Phalcon\Mvc\Model\Metadata\\' . $config['adapter'];
unset($config['adapter']);
$metaData = new $adapter($config);
return $metaData;
});
}
/**
* Initialize the Queue Service.
* TODO: Not yet implement
*
* Queue to deliver e-mails in real-time and other tasks.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initQueue(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('queue', function () use ($config) {
$config = $config->get('beanstalk');
$config->get('disabled', true);
if ($config->get('disabled', true)) {
return new DummyServer();
}
if (!$host = $config->get('host', false)) {
$error = 'Beanstalk is not configured';
if (class_exists('\Phalcon\Queue\Beanstalk\Exception')) {
$exception = '\Phalcon\Queue\Beanstalk\Exception';
} else {
$exception = '\Phalcon\Exception';
}
throw new $exception($error);
}
return new Beanstalk(['host' => $host]);
});
}
/**
* Initialize the Router.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initRouter(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('router', function () use ($config, $em) {
/** @var \Phalcon\Mvc\Router $router */
$router = include BASE_DIR . 'config/routes.php';
if (!isset($_GET['_url'])) {
$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
}
if (preg_match('/(.jpg|.jpge|.png|.gif|.ico|.css|.js)$/', $router->getRewriteUri())) {
exit;
}
$router->removeExtraSlashes(true);
$router->setEventsManager($em);
$router->setDefaultNamespace('Blazy\Frontend\Controllers');
$router->setDefaultModule('frontend');
$router->notFound(['controller' => 'error', 'action' => 'route404']);
return $router;
});
}
/**
* Initialize the Url service.
*
* The URL component is used to generate all kind of urls in the application.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initUrl(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('url', function () use ($config) {
$url = new UrlResolver;
$url->setBaseUri($config->application->baseUri);
$url->setStaticBaseUri(STATIC_BASE_URL . $config->application->baseUri);
return $url;
});
}
/**
* Initialize the Dispatcher.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initDispatcher(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('dispatcher', function () use ($em) {
$dispatcher = new Dispatcher;
$dispatcher->setDefaultNamespace('Blazy\Frontend\Controllers');
$em->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) {
if (!class_exists('Blazy\Backend\Module')) {
include_once BASE_DIR . '/app/modules/backend/module.php';
$module = new Backend\Module();
$module->registerServices($this->getDI());
$module->registerAutoloaders($this->getDI());
$dispatcher->setNamespaceName('Blazy\Backend\Controllers');
}
});
$dispatcher->setEventsManager($em);
return $dispatcher;
});
}
/**
* Initialize the Flash Service.
*
* Register the Flash Service with the Twitter Bootstrap classes
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initFlash(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('flash', function () {
$flash = new Flash(
[
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]
);
return $flash;
});
$di->setShared('flashInline', function () use ($di) {
$flash = $di->getShared('flash');
$flash->setCssClasses([
'error' => 'custom-message error',
'success' => 'alert alert-success fade in',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
return $flash;
});
$di->setShared(
'flashSession',
function () {
return new FlashSession([
'error' => 'alert alert-danger fade in',
'success' => 'alert alert-success fade in alert-hightlight',
'notice' => 'alert alert-info fade in',
'warning' => 'alert alert-warning fade in',
]);
}
);
}
/**
* Initialize time zones.
*
* @param DiInterface $di Dependency Injector
* @param Config $config App config
* @param EventsManager $em Events Manager
*
* @return void
*/
protected function initTimezones(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('timezones', function () use ($config) {
return require_once BASE_DIR . 'config/timezones.php';
});
}
/**
* Load module's configuration file, prepare and return the Config.
*
* @param string $path Config path [Optional]
*
* @return Config
* @throws RuntimeException
*/
protected function initConfig($path = null)
{
$path = $path ?: BASE_DIR . 'config/';
if (!is_readable($path . 'config.php')) {
throw new RuntimeException(
'Unable to read config from ' . $path . 'config.php'
);
}
$di = Di::getDefault();
/**
* Load default configuration and run module background job
*
* @var \Phalcon\Config $config
*/
$config = include_once $path . 'config.php';
$di->setShared('config', $config);
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.php'))
$config->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.php');
}
/**
* Load environment configuration
*
* @var \Phalcon\Config $envConfig
*/
$envConfig = include_once $path . 'config.' . APPLICATION_ENV . '.php';
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php'))
$envConfig->offsetSet($module, include_once BASE_DIR . 'app/modules/' . $module . '/config.' . APPLICATION_ENV . '.php');
}
if ($envConfig instanceof Config) {
$config->merge($envConfig);
}
return $config;
}
protected function initBackground()
{
$di = Di::getDefault();
foreach ($this->activeModules as $module) {
if (is_readable(BASE_DIR . 'app/modules/' . $module . '/Background.php')) {
include_once BASE_DIR . 'app/modules/' . $module . '/Background.php';
$background = 'Blazy\\' . $module . '\Background';
new $background($di);
}
}
}
/**
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initAssets(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('assets', function () use ($config, $em) {
return new AssetsManager();
});
}
/*protected function initViewSimple(DiInterface $di, Config $config, EventsManager $em) {
$di->setShared('viewSimple', function() {
$view = new ViewSimple();
$view->setViewsDir($config->application->viewsDir);
return new ViewSimple();
});
}*/
/**
* starts the cookie the first time some component requests the cookie service
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initCookie(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('cookies', function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
});
}
/**
* Multi language
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initTranslate(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('translate', function () use ($di, $config) {
$translate = new Translate($config->application->messagesDir, $config->application->defaultLanguage);
$dispatcher = $di->getShared('dispatcher');
$lang = $dispatcher->getParam('lang');
if (!empty($lang)) {
$translate->setCurrentLanguage($lang);
}
return $translate;
});
$di->setShared('t', function () use ($di, $config) {
return $di->getShared('translate')->getTranslation();
});
}
/**
* media manager: image, video ..
*
* @param DiInterface $di
* @param Config $config
* @param EventsManager $em
*/
protected function initMedia(DiInterface $di, Config $config, EventsManager $em)
{
$di->setShared('image', new ImageManager(['driver' => 'gd']));
}
public function registerActiveModules($modules, $merge = false)
{
$preparedModules = [];
foreach ($modules as $module) {
$preparedModules[$module] = [
'className' => 'Blazy\\' . ucfirst($module) . '\\Module',
'path' => BASE_DIR . 'app/modules/' . $module . '/Module.php',
];
}
parent::registerModules($preparedModules, $merge);
}
}
|