/** * Triggers when the object is called as a string * * @access public * @return string */ public function __toString() { if (!empty($this->viewPath) && !empty($this->viewFile)) { return $this->view->render($this->viewFile, $this->attributes); } return ''; }
protected function registerViewService() { $this->di['console.view'] = function () { $view = new View(); $view->setViewsDir($this->di['console.config']->viewsDir); return $view; }; }
public function testRenderWithCache(IntegrationTester $I) { $I->wantToTest('Render by using simple view with cache'); if (PHP_MAJOR_VERSION == 7) { throw new \PHPUnit_Framework_SkippedTestError('Skipped in view of the experimental support for PHP 7.'); } // Create cache at first run $view = new Simple(); codecept_debug(gettype($view->getParamsToView())); $view->setViewsDir(PATH_DATA . 'views/'); // No cache before DI is set $I->assertFalse($view->getCache()); $view->setDI($this->getDi()); $I->assertEquals($view, $view->cache(['key' => 'view_simple_cache'])); $cache = $view->getCache(); $I->assertInstanceOf('Phalcon\\Cache\\BackendInterface', $cache); $timeNow = time(); $view->setParamToView('a_cool_var', $timeNow); $I->assertEquals("<p>{$timeNow}</p>", rtrim($view->render('test3/coolVar'))); $I->amInPath(PATH_CACHE); $I->seeFileFound('view_simple_cache'); $I->seeInThisFile("<p>{$timeNow}</p>"); unset($view, $cache); // Re-use the cached contents $view = new Simple(); $view->setViewsDir(PATH_DATA . 'views/'); $view->setDI($this->getDi()); $view->cache(['key' => 'view_simple_cache']); $I->assertEmpty($view->getContent()); $I->assertEquals("<p>{$timeNow}</p>", rtrim($view->render('test3/coolVar'))); $I->assertNotEmpty($view->getContent()); $I->assertEquals("<p></p>", rtrim($view->render('test3/coolVar'))); $I->deleteFile('view_simple_cache'); }
/** * Constructor * Initializes simple view * * @param null $options */ public function __construct($options = null) { parent::__construct($options); $this->registerEngines(array('.volt' => function ($this, $di) use($options) { $volt = new PhalconView\Engine\Volt($this, $di); $volt->setOptions(array('compiledPath' => $options['cacheDir'], 'compiledSeparator' => '_')); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); }
/** * * @param \Phalcon\DI $di */ public function registerServices($di) { Admin::instance(); require __DIR__ . '/../../../../phad/phad.php'; $di['phadConfig'] = function () { $config = (require __DIR__ . '/../../../../phad-config.php'); return new Config($config); }; $di['view'] = function () { $view = new ViewEngine(); $view->setViewsDir(__DIR__ . '/Views/'); $view->setLayoutsDir('Layouts/'); $view->setPartialsDir('Partials/'); return $view; }; $di['viewSimple'] = function () { $view = new Simple(); $view->setViewsDir(__DIR__ . '/Views/'); return $view; }; $di['flashSession'] = function () { $flashClasses = ['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning']; return new FlashSession($flashClasses); }; $di['session'] = function () { $session = new Session(); $session->start(); return $session; }; $di['phadAuth'] = function () { return new Auth(); }; $di['assets'] = function () use($di) { $options = ['sourceBasePath' => __DIR__ . '/Assets/', 'targetBasePath' => __DIR__ . '/../../../../public/backend-assets/']; $assets = new AssetsManager($options); $assets->collection('backend_css')->setTargetPath('final.css')->setTargetUri('backend-assets/final.css')->addCss('bootstrap/css/bootstrap.min.css')->addCss('css/styles.css')->join(true)->addFilter(new AssetsNullFilter()); $assets->collection('backend_js')->setTargetPath('final.js')->setTargetUri('backend-assets/final.js')->addJs('bootstrap/js/bootstrap.min.js')->addJs('js/custom.js')->join(true)->addFilter(new AssetsNullFilter()); return $assets; }; }
<?php use Phalcon\Mvc\View\Simple as SimpleView; use Phalcon\Di\FactoryDefault; use Phalcon\Config\Adapter\Php as PhpConfig; $di = new FactoryDefault(); $di->set('config', function () { $config = new PhpConfig(__DIR__ . '/app.php'); if (is_readable(__DIR__ . '/app.development.php') && getenv('APPLICATION_ENV') == 'development') { $development = new PhpConfig(__DIR__ . '/app.development.php'); $config->merge($development); } return $config; }, true); $di->set('view', function () use($di) { $config = $di->get('config')['view']; $view = new SimpleView(); $view->setViewsDir($config['dir']); $view->setVar('appConfig', $di->get('config')['app']); $view->setVar('flashSession', $di->get('flashSession')); $engine = new $config['engine']($view); $engine->setOptions([$config['options']]); $view->registerEngines([$config['prefix'] => $engine]); return $view; }, true); $di->set('connection', function () use($di) { $config = $di->get('config')['database']; $adapter = new $config->adapter(["host" => $config->host, "username" => $config->username, "password" => $config->password, "dbname" => $config->db]); return $adapter; }, true);
/** * Register the Simple View instance */ protected function registerView() { if ($this->di->has('view')) { $this->di['mailer.view'] = function () { return $this->di->get('view'); }; } else { $this->di['mailer.view'] = function () { $view = new SimpleView(); $view->setViewsDir($this->config->application->viewsDir); return $view; }; } }
}, true); /** * Load the url resolver * */ $container->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }, true); /** * The Views component * */ $container->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $container) use($config) { $volt = new VoltEngine($view, $container); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeperator' => '_')); return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }, true); /** * The database component * */ $container->set('db', function () use($config) { return new DbAdapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname)); });
public function testRenderWithCache() { // Create cache at first run $view = new View(); $view->setViewsDir('unit-tests/views/'); $this->assertFalse($view->getCache()); // No cache before DI is set $view->setDI($this->_getDI()); $this->assertEquals($view, $view->cache(array('key' => 'view_simple_cache'))); $cache = $view->getCache(); $this->assertInstanceOf('Phalcon\\Cache\\BackendInterface', $cache); if ($cache instanceof BackendInterface == false) { $this->fail('Expected BackendInterface'); } $timeNow = time(); $view->setParamToView('a_cool_var', $timeNow); $this->assertEquals("<p>{$timeNow}</p>", $view->render('test3/coolVar')); unset($view, $cache); // Re-use the cached contents $view = new View(); $view->setViewsDir('unit-tests/views/'); $view->setDI($this->_getDI()); $view->cache(array('key' => 'view_simple_cache')); $this->assertEquals("<p>{$timeNow}</p>", $view->render('test3/coolVar')); // Cache should expire $this->assertEquals("<p></p>", @$view->render('test3/coolVar')); }
<?php use Phalcon\DI\FactoryDefault, Phalcon\Assets\Manager as AssetsManager, Phalcon\Mvc\Collection\Manager as CollectionManager, Phalcon\Mvc\View\Simple as View, Phalcon\Mvc\View\Engine\Volt, Phalcon\Mvc\Url as UrlResolver, Phalcon\Flash\Session as Flash, Phalcon\Flash\Direct as FlashDirect, Phalcon\Session\Adapter\Files as Session; $di = new FactoryDefault(); //View service $di['view'] = function () { $view = new View(); $view->setViewsDir(APP_PATH . '/views/'); $view->registerEngines(array('.volt' => function ($view, $di) { $volt = new Volt($view, $di); $volt->setOptions(array('compiledPath' => APP_PATH . '/cache/volt/', 'compiledSeparator' => '_')); return $volt; })); return $view; }; $di['url'] = function () { $url = new UrlResolver(); $url->setBaseUri('/dasshy/'); return $url; }; $di['assets'] = function () { $assets = new AssetsManager(); $assets->addJs('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', false)->addJs('//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js', false); return $assets; }; /** * Flash service with custom CSS classes */ $di['flash'] = function () { return new Flash(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info')); };
public function run(Api $api, DiInterface $di, Config $config) { /** * @description Config - \Phalcon\Config */ $di->setShared(Services::CONFIG, $config); /** * @description Phalcon - \Phalcon\Db\Adapter\Pdo\Mysql */ $di->set(Services::DB, function () use($config, $di) { $config = $config->get('database')->toArray(); $adapter = $config['adapter']; unset($config['adapter']); $class = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; $connection = new $class($config); // Assign the eventsManager to the db adapter instance $connection->setEventsManager($di->get(Services::EVENTS_MANAGER)); return $connection; }); /** * @description Phalcon - \Phalcon\Mvc\Url */ $di->set(Services::URL, function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->get('application')->baseUri); return $url; }); /** * @description Phalcon - \Phalcon\Mvc\View\Simple */ $di->set(Services::VIEW, function () use($config) { $view = new View(); $view->setViewsDir($config->get('application')->viewsDir); return $view; }); /** * @description Phalcon - EventsManager */ $di->setShared(Services::EVENTS_MANAGER, function () use($di, $config) { return new EventsManager(); }); /** * @description Phalcon - TokenParsers */ $di->setShared(Services::TOKEN_PARSER, function () use($di, $config) { return new JWTTokenParser($config->get('authentication')->secret, JWTTokenParser::ALGORITHM_HS256); }); /** * @description Phalcon - AuthManager */ $di->setShared(Services::AUTH_MANAGER, function () use($di, $config) { $authManager = new AuthManager($config->get('authentication')->expirationTime); $authManager->registerAccountType(UsernameAccountType::NAME, new UsernameAccountType()); return $authManager; }); /** * @description Phalcon - \Phalcon\Mvc\Model\Manager */ $di->setShared(Services::MODELS_MANAGER, function () use($di) { $modelsManager = new ModelsManager(); return $modelsManager->setEventsManager($di->get(Services::EVENTS_MANAGER)); }); /** * @description PhalconRest - \League\Fractal\Manager */ $di->setShared(Services::FRACTAL_MANAGER, function () { $fractal = new FractalManager(); $fractal->setSerializer(new CustomSerializer()); return $fractal; }); /** * @description PhalconRest - \PhalconRest\User\Service */ $di->setShared(Services::USER_SERVICE, new UserService()); }
public function testRenderWithFilenameWithEngineWithoutEngineRegistered() { $this->setExpectedException('Phalcon\\Mvc\\View\\Exception'); $view = new View(); $view->setDI(new Di()); $view->setViewsDir('unit-tests/views/'); $view->setParamToView('name', 'FooBar'); $this->assertEquals('Hello FooBar', $view->render('test4/index.mhtml')); }
public function testGetRegisteredEngines() { $expected = array('.mhtml' => 'My_Mustache_Engine', '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php', '.twig' => 'My_Twig_Engine', '.volt' => 'Phalcon\\Mvc\\View\\Engine\\Volt'); $di = new Phalcon\DI(); $view = new Phalcon\Mvc\View\Simple(); $view->setDI($di); $view->setViewsDir('unit-tests/views/'); $view->registerEngines($expected); $this->assertEquals($expected, $view->getRegisteredEngines()); }
/** * @codeCoverageIgnore * @param \Exception $exception */ public function exceptionHandler(\Exception $exception) { if (count(ob_list_handlers())) { ob_clean(); } $view = new ViewSimple(); $view->setViewsDir($this->viewsDir . DIRECTORY_SEPARATOR); $statusCode = 500; $message = 'Internal Server Error'; $template = $this->options['template_500']; if ($exception instanceof DispatchException) { $template = $this->options['template_404']; $statusCode = 404; $message = 'Not Found'; } $content = $view->render($template, ['message' => $exception->getMessage(), 'file' => $exception->getFile(), 'code' => $exception->getCode(), 'line' => $exception->getLine(), 'trace' => $exception->getTrace(), 'traceStr' => $exception->getTraceAsString()]); (new Response())->setContent($content)->setStatusCode($statusCode, $message)->send(); exit; }
/** * Register the Simple View instance */ protected function registerView() { if ($this->di->has('view')) { $this->di['mailer.view'] = function () { return $this->di->get('view'); }; } else { $this->di['mailer.view'] = function () { if (!isset($this->config['viewsDir'])) { throw new \InvalidArgumentException('Invalid views dir!'); } $view = new SimpleView(); $view->setViewsDir($this->config['viewsDir']); return $view; }; } }
/** * Tests render with partials * * @author Kamil Skowron <*****@*****.**> * @since 2014-05-28 */ public function testRenderWithPartials() { $this->specify('Render with partials does not work as expected', function () { $view = new Simple(); $view->setViewsDir(PATH_DATA . 'views' . DIRECTORY_SEPARATOR); $expectedParams = ['cool_var' => 'FooBar']; $this->renderPartialBuffered($view, 'partials/_partial1', $expectedParams); expect($view->getContent())->equals('Hey, this is a partial, also FooBar'); $view->setVars($expectedParams); expect($view->render('test5/index'))->equals('Hey, this is a partial, also FooBar'); expect($view->render('test9/index'))->equals('Hey, this is a partial, also FooBar<br />Hey, this is a second partial, also FooBar'); }); }
/** * Register the Simple View instance */ protected function registerView() { $this->di['mailer.view'] = function () { $view = new SimpleView(); $view->setViewsDir($this->_config['templateDir']); return $view; }; }
protected static function phSimpleView() { static $view; if (!$view) { $view = new SimpleView(); $view->setViewsDir(static::$viewsdir); } return $view; }
$manager->collection('css')->setPrefix('/public/vendor')->setLocal(true); return $manager; }); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }, true); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); if (!isset($_SERVER['CLEARDB_DATABASE_URL'])) { $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_')); } return $volt; }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }, true); /** * Database connection is created based in the parameters defined in the configuration file */ $di->set('db', function () use($config) { return new DbAdapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname));
public function run(DiInterface $diContainer, array $options = []) { $memoryUsage = memory_get_usage(); $currentTime = microtime(true); $this->diContainer = $diContainer; /** * The app path */ if (!defined('K_PATH')) { define('K_PATH', dirname(dirname(dirname(__FILE__)))); } /** * We will need the Utils class */ require_once K_PATH . '/library/Kitsune/Utils.php'; /** * Utils class */ $utils = new Utils(); $this->diContainer->set('utils', $utils, true); /** * Check if this is a CLI app or not */ $cli = $utils->fetch($options, 'cli', false); if (!defined('K_CLI')) { define('K_CLI', $cli); } $tests = $utils->fetch($options, 'tests', false); if (!defined('K_TESTS')) { define('K_TESTS', $tests); } /********************************************************************** * CONFIG **********************************************************************/ /** * The configuration is split into two different files. The first one * is the base configuration. The second one is machine/installation * specific. */ if (!file_exists(K_PATH . '/var/config/base.php')) { throw new \Exception('Base configuration files are missing'); } if (!file_exists(K_PATH . '/var/config/config.php')) { throw new \Exception('Configuration files are missing'); } /** * Get the config files and merge them */ $base = (require K_PATH . '/var/config/base.php'); $specific = (require K_PATH . '/var/config/config.php'); $combined = array_replace_recursive($base, $specific); $config = new Config($combined); $this->diContainer->set('config', $config, true); /** * Check if we are in debug/dev mode */ if (!defined('K_DEBUG')) { $debugMode = boolval($utils->fetch($config, 'debugMode', false)); define('K_DEBUG', $debugMode); } /** * Access to the debug/dev helper functions */ if (K_DEBUG) { require_once K_PATH . '/library/Kitsune/Debug.php'; } /********************************************************************** * LOADER **********************************************************************/ /** * We're a registering a set of directories taken from the * configuration file */ $loader = new Loader(); $loader->registerNamespaces($config->namespaces->toArray()); $loader->register(); require K_PATH . '/vendor/autoload.php'; /********************************************************************** * LOGGER **********************************************************************/ /** * The essential logging service */ $format = '[%date%][%type%] %message%'; $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log'; $logger = new LoggerFile($name); $formatter = new LoggerFormatter($format); $logger->setFormatter($formatter); $this->diContainer->set('logger', $logger, true); /********************************************************************** * ERROR HANDLING **********************************************************************/ ini_set('display_errors', boolval(K_DEBUG)); error_reporting(E_ALL); set_error_handler(function ($exception) use($logger) { if ($exception instanceof \Exception) { $logger->error($exception->__toString()); } else { $logger->error(json_encode(debug_backtrace())); } }); set_exception_handler(function (\Exception $exception) use($logger) { $logger->error($exception->getMessage()); }); register_shutdown_function(function () use($logger, $utils, $memoryUsage, $currentTime) { $memoryUsed = memory_get_usage() - $memoryUsage; $executionTime = microtime(true) - $currentTime; if (K_DEBUG) { $logger->info(sprintf('Shutdown completed [%s]s - [%s]', round($executionTime, 3), $utils->bytesToHuman($memoryUsed))); } }); $timezone = $config->get('app_timezone', 'US/Eastern'); date_default_timezone_set($timezone); /********************************************************************** * ROUTES **********************************************************************/ if (false === K_CLI) { $router = new Router(false); $router->removeExtraSlashes(true); $routes = $config->routes->toArray(); foreach ($routes as $pattern => $options) { $router->add($pattern, $options); } $this->diContainer->set('router', $router, true); } /********************************************************************** * DISPATCHER **********************************************************************/ if (false === K_CLI) { /** * We register the events manager */ $eventsManager = new EventsManager(); /** * Handle exceptions and not-found exceptions using NotFoundPlugin */ $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin()); $dispatcher = new Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace('Kitsune\\Controllers'); } else { $dispatcher = new PhCliDispatcher(); $dispatcher->setDefaultNamespace('Kitsune\\Cli\\Tasks'); } $this->diContainer->set('dispatcher', $dispatcher); /********************************************************************** * URL **********************************************************************/ /** * The URL component is used to generate all kind of urls in the application */ $url = new UrlProvider(); $url->setBaseUri($config->baseUri); $this->diContainer->set('url', $url); /********************************************************************** * VIEW **********************************************************************/ $view = new View(); $view->setViewsDir(K_PATH . '/app/views/'); $view->registerEngines([".volt" => function ($view) { return $this->setVoltOptions($view); }]); $this->diContainer->set('view', $view); /********************************************************************** * VIEW SIMPLE **********************************************************************/ $viewSimple = new ViewSimple(); $viewSimple->setViewsDir(K_PATH . '/app/views/'); $viewSimple->registerEngines([".volt" => function ($view) { return $this->setVoltOptions($view); }]); $this->diContainer->set('viewSimple', $viewSimple); /********************************************************************** * CACHE **********************************************************************/ $frontConfig = $config->cache_data->front->toArray(); $backConfig = $config->cache_data->back->toArray(); $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter']; $frontCache = new $class($frontConfig['params']); $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter']; $cache = new $class($frontCache, $backConfig['params']); $this->diContainer->set('cache', $cache, true); /********************************************************************** * POSTS FINDER **********************************************************************/ $this->diContainer->set('finder', new PostFinder(), true); /********************************************************************** * DISPATCH 17.5s **********************************************************************/ if (K_CLI) { return new PhCliConsole($this->diContainer); } else { $application = new Application($this->diContainer); if (K_TESTS) { return $application; } else { return $application->handle()->getContent(); } } }
public function render($path, $params = null) { $config = $this->getDI()->get('config'); $this->setVars(['DEV' => DEV, 'TEST' => TEST_ENV === ENV, 'DIST' => DIST_ENV === ENV, 'domain' => $config->server->domain, 'link' => $config->site->link]); return parent::render($path, $params); }
/** * Render the template using the Simple View * @return string */ public function render() { return $this->view->render($this->name, $this->variables); }
/** * Returns the html-form widget * * @return View */ public function getForm() { $view = new View(); return $view->render(__DIR__ . '/../views/ulogin', ['widget' => $this->widget, 'fields' => $this->requiredFields, 'optional' => $this->optionalFields, 'providers' => $this->requiredProviders, 'hidden' => $this->hiddenProviders, 'url' => $this->url]); }
try { $loader = new Loader(); $loader->registerDirs(array(APP_DIR . 'controllers/', APP_DIR . 'lib/', APP_DIR . 'models/'))->register(); require VENDOR_DIR . 'autoload.php'; $di = new DI(); /** * Setting up the credentials config */ $di->set('config', function () { return new Ini(APP_DIR . 'config/config.ini'); }, true); /** * Setting up the view component */ $di->set('view', function () { $view = new View(); $view->setViewsDir(APP_DIR . 'views/'); $view->registerEngines(array('.volt' => function ($view, $di) { $env = $di->get('config')->get('environment'); /** @var ViewInterface|View $view */ $volt = new Volt($view, $di); $volt->setOptions(array('compiledPath' => function ($templatePath) use($view) { $dir = rtrim(sys_get_temp_dir(), '/') . '/volt-cache'; if (!is_dir($dir)) { mkdir($dir); } return $dir . '/hunter-light%' . str_replace('/', '%', str_replace($view->getViewsDir(), '', $templatePath)) . '.php'; }, 'compileAlways' => $env->realm != 'prod')); return $volt; })); return $view;
/** * Sends the digest */ public function send() { $lastMonths = new \DateTime(); $lastMonths->modify('-6 month'); $parameters = ['modified_at >= ?0 AND digest = "Y" AND notifications <> "N"', 'bind' => [$lastMonths->getTimestamp()]]; $users = []; foreach (Users::find($parameters) as $user) { if ($user->email && strpos($user->email, '@') !== false && strpos($user->email, '@users.noreply.github.com') === false) { $users[trim($user->email)] = $user->name; } } $view = new View(); $view->setViewsDir($this->config->application->viewsDir); $fromName = $this->config->mail->fromName; $fromEmail = $this->config->mail->fromEmail; $url = rtrim($this->config->site->url, '/'); $subject = sprintf('Top Stories from Phosphorum %s', date('d/m/y')); $view->setVar('title', $subject); $lastWeek = new \DateTime(); $lastWeek->modify('-1 week'); $order = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - ' . 'IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies + IF(accepted_answer = "Y", 10, 0) DESC'; $parameters = ['created_at >= ?0 AND deleted != 1 AND categories_id <> 4', 'bind' => [$lastWeek->getTimestamp()], 'order' => $order, 'limit' => 10]; $e = $this->escaper; /** @var \Phalcon\Logger\AdapterInterface $logger */ $logger = $this->getDI()->get('logger', ['mail']); $stories = []; foreach (Posts::find($parameters) as $i => $post) { $user = $post->user; if ($user == false) { continue; } $this->gravatar->setSize(32); $stories[$i]['user_name'] = $user->name; $stories[$i]['user_avatar'] = $this->gravatar->getAvatar($user->email); $stories[$i]['user_url'] = "{$url}/user/{$user->id}/{$user->login}"; $stories[$i]['user_karma'] = $user->getHumanKarma(); $stories[$i]['post_title'] = $e->escapeHtml($post->title); $stories[$i]['post_created'] = $post->getHumanCreatedAt(); $stories[$i]['post_replies'] = (int) $post->number_replies; $stories[$i]['post_views'] = (int) $post->number_views; $stories[$i]['post_votes'] = $post->votes_up - $post->votes_down; $stories[$i]['post_content'] = $this->markdown->render($e->escapeHtml($post->content)); $stories[$i]['post_url'] = "{$url}/discussion/{$post->id}/{$post->slug}"; } if (empty($stories)) { return; } $view->setVar('stories', $stories); $view->setVar('notice', sprintf('This email was sent by %s mail sender. Change your e-mail preferences <a href="%s/settings">here</a>', $this->config->site->name, $url)); $content = $view->render('mail/digest.phtml'); $textContent = preg_replace('#<a[^>]+href="([^"]+)"[^>]*>([^<]+)<\\/a>#', '$2:' . "\n" . '$1', $content); $textContent = str_replace('<span class="foot-line"></span>', "--\n", $textContent); $textContent = trim(strip_tags($textContent)); $textContent = str_replace(' ', ' ', $textContent); $textContent = preg_replace('#\\t+#', '', $textContent); $textContent = preg_replace('# {2,}#', ' ', $textContent); $textContent = preg_split('#(\\r|\\n)#', $textContent); $textContent = join("\n\n", array_filter($textContent, function ($line) { return '' !== trim($line); })); $textContent = preg_replace('#^[ \\t]+#m', '', $textContent); foreach ($users as $email => $name) { try { $message = new \Swift_Message("[{$this->config->site->name} Forum] " . $subject); $message->setTo([$email => $name]); $message->setFrom([$fromEmail => $fromName]); $bodyMessage = new \Swift_MimePart($content, 'text/html'); $bodyMessage->setCharset('UTF-8'); $message->attach($bodyMessage); $bodyMessage = new \Swift_MimePart($textContent, 'text/plain'); $bodyMessage->setCharset('UTF-8'); $message->attach($bodyMessage); if (!$this->transport) { $this->transport = \Swift_SmtpTransport::newInstance($this->config->smtp->host, $this->config->smtp->port, $this->config->smtp->security); $this->transport->setUsername($this->config->smtp->username); $this->transport->setPassword($this->config->smtp->password); } if (!$this->mailer) { $this->mailer = \Swift_Mailer::newInstance($this->transport); } $failedRecipients = []; $this->mailer->send($message, $failedRecipients); if (empty($failedRecipients)) { $logger->info("Sent an email to {$email}"); } else { $logger->error("Unable to sent an email to " . join(', ', $failedRecipients)); } } catch (\Exception $e) { $logger->error($e->getMessage()); throw new \Exception($e->getMessage(), $e->getCode(), $e); } } }
/** * @return string */ public function render() { $view = new PhalconView(); $template = $this->getTemplate(); $view->setViewsDir(dirname($template) . '/'); $filename = basename($template); $file = explode('.', $filename); array_pop($file); $file = implode('.', $file); return $view->render($file, $this->getParameters()); }
<?php use Phalcon\DI\FactoryDefault, Phalcon\Mvc\View\Simple as View, Phalcon\Mvc\Url as UrlResolver, Phalcon\Mvc\View\Engine\Volt as VoltEngine; /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new FactoryDefault(); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }, true); /** * Setting up the view component */ $di->set('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array('.volt' => function ($view, $di) use($config) { $volt = new VoltEngine($view, $di); $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_')); return $volt; })); return $view; }, true);
/** * Render the given view. * * @param string $view * @param array $data * * @return string */ protected function getView($template, $data) { return $this->view->render($template, $data); }
<?php use Phalcon\Mvc\View\Simple as View; use Phalcon\Mvc\Url as UrlResolver; use Phalcon\DI\FactoryDefault; use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter; use Phalcon\Http\Response; use Phalcon\Filter; $di = new FactoryDefault(); $filter = new Filter(); /** * Sets the view component */ $di['view'] = function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); return $view; }; /** * The URL component is used to generate all kind of urls in the application */ $di['url'] = function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }; /** * Database connection is created based in the parameters defined in the configuration file */ $di['db'] = function () use($config) { return new DbAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "charset" => $config->database->charset));
$di = new FactoryDefault(); $di->set('flash', function () { $base = 'alert alert-'; return new Flash(array('error' => $base . 'danger', 'success' => $base . 'success', 'notice' => $base . 'info', 'warning' => $base . 'warning')); }); $di->setShared('session', function () use($config) { $conn = new DbAdapter($config->database->toArray()); $session = new Database(array('db' => $conn, 'table' => 'session_data')); $session->start(); return $session; }); /** * Sets the view component */ $di->setShared('view', function () use($config) { $view = new View(); $view->setViewsDir($config->application->viewsDir); $view->registerEngines(array(".volt" => 'Phalcon\\Mvc\\View\\Engine\\Volt', ".phtml" => 'Phalcon\\Mvc\\View\\Engine\\Php')); return $view; }); /** * The URL component is used to generate all kind of urls in the application */ $di->set('url', function () use($config) { $url = new UrlResolver(); $url->setBaseUri($config->application->baseUri); return $url; }); /** * Database connection is created based in the parameters defined in the configuration file */