Using the Media class, you can globally configure input and output of different types of
content, i.e.:
{{{ embed:lithium\tests\cases\net\http\MediaTest::testCustomEncodeHandler(4-12) }}}
You may then render CSV content from anywhere in your application. For example, in a controller
you may do the following:
{{{
$this->render(array('csv' => Post::find('all')));
}}}
/** * Deliver a message with Mailgun's HTTP REST API via curl. * * _NOTE: Uses the `messages.mime` API endpoint, not the * `messages` API endpoint (because a, if embedded attachments * were used Mailgun would alter the `Content-ID` for them, and * b, cURL needs to have a local file to send as file, but * not all attachments have a path), see `_parameters()`._ * * @see li3_mailer\net\mail\transport\adapter\Mailgun::_parameters() * @see http://documentation.mailgun.net/api-sending.html * @see http://php.net/curl * @param object $message The message to deliver. * @param array $options Options (see `_parameters()`). * @return string The message id on success; `false` on error. */ public function deliver($message, array $options = array()) { list($url, $auth, $parameters) = $this->_parameters($message, $options); $curl = curl_init($url); curl_setopt_array($curl, array(CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => "{$auth['username']}:{$auth['password']}", CURLOPT_RETURNTRANSFER => 1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $parameters)); $result = curl_exec($curl); $info = curl_getinfo($curl); if ($info['http_code'] != '200') { $result = false; } curl_close($curl); $result = Media::decode('json', $result); return $result['id']; }
/** * This tests that setting custom paths and disabling layout * via `\lithium\net\http\Media::type()` is handled properly * by the default `\lithium\template\View` class and `File` * rendered adapter. */ public function testMediaTypeViewRender() { Media::type('view-integration-test', 'lithium/viewtest', array('view' => 'lithium\\template\\View', 'paths' => array('layout' => false, 'template' => array('{:library}/tests/mocks/template/view/adapters/{:template}.{:type}.php', '{:library}/tests/mocks/template/view/adapters/{:template}.html.php')))); // testing no layout with a custom type template $response = new Response(); $response->type('view-integration-test'); Media::render($response, array(), array('layout' => true, 'library' => 'lithium', 'template' => 'testTypeFile')); $this->assertEqual('This is a type test.', $response->body()); // testing the template falls back to the html template $response = new Response(); $response->type('view-integration-test'); Media::render($response, array(), array('layout' => true, 'library' => 'lithium', 'template' => 'testFile')); $this->assertEqual('This is a test.', $response->body()); // testing with a layout Media::type('view-integration-test', 'lithium/viewtest', array('view' => 'lithium\\template\\View', 'paths' => array('layout' => '{:library}/tests/mocks/template/view/adapters/testLayoutFile.html.php', 'template' => array('{:library}/tests/mocks/template/view/adapters/{:template}.{:type}.php', '{:library}/tests/mocks/template/view/adapters/{:template}.html.php')))); $response = new Response(); $response->type('view-integration-test'); Media::render($response, array(), array('layout' => true, 'library' => 'lithium', 'template' => 'testTypeFile')); $this->assertEqual("Layout top.\nThis is a type test.Layout bottom.", $response->body()); }
* the following: * {{{ * $posts = Post::find('all'); * return $posts->to('json'); * }}} */ use lithium\util\Collection; Collection::formats('lithium\\net\\http\\Media'); // Mount assets directory as DOMAIN/assets // Stamp assets with version. use lithium\net\http\Media; Media::attach('app', array('path' => dirname(LITHIUM_APP_PATH) . '/assets', 'prefix' => 'assets/v:' . PROJECT_VERSION_BUILD)); // Set default scope. Media::scope('app'); // Render libary views in the app's layout only. Media::type('default', null, array('view' => 'lithium\\template\\View', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => LITHIUM_APP_PATH . '/views/layouts/{:layout}.{:type}.php', 'element' => '{:library}/views/elements/{:template}.{:type}.php'))); /** * This filter is a convenience method which allows you to automatically route requests for static * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js` * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem. * In production, it is recommended that you disable this filter in favor of symlinking each * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing * rules in your web server's configuration. */ // use lithium\action\Dispatcher; // use lithium\action\Response; // use lithium\net\http\Media; // // Dispatcher::applyFilter('_callable', function($self, $params, $chain) { // $url = ltrim($params['request']->url, '/');
<?php use lithium\core\Libraries; use lithium\core\ConfigException; use lithium\template\View; use lithium\net\http\Media; // Define path to plugin and other constants defined('LI3_HIERARCHY_PATH') or define('LI3_HIERARCHY_PATH', dirname(__DIR__)); /** * Map to the new renderer */ Media::type('default', null, array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_hierarchy\\template\\view\\adapter\\Hierarchy', 'paths' => array('template' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php', '{:library}/views/{:controller}/{:template}.{:type}.php'), 'layout' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:layout}.{:type}.php', '{:library}/views/{:controller}/{:layout}.{:type}.php')))); Media::applyFilter('view', function ($self, $params, $chain) { if (isset($params['handler']['renderer']) && array_slice(explode('\\', $params['handler']['renderer']), -1, 1) == array('Hierarchy')) { $params['handler']['processes'] = array('all' => array('template'), 'template' => array('template'), 'element' => array('element')); } return $chain->next($self, $params, $chain); });
public function testContentNegotiationByUserAgent() { Media::type('iphone', 'application/xhtml+xml', array('conditions' => array('mobile' => true))); $request = new Request(array('env' => array('HTTP_USER_AGENT' => 'Safari', 'HTTP_ACCEPT' => 'application/xhtml+xml,text/html'))); $this->assertEqual('html', Media::negotiate($request)); $request = new Request(array('env' => array('HTTP_USER_AGENT' => 'iPhone', 'HTTP_ACCEPT' => 'application/xhtml+xml,text/html'))); $this->assertEqual('iphone', Media::negotiate($request)); }
public function setUp() { Media::reset(); }
public function testScopeBase() { $result = Media::asset('style.css', 'css'); $this->assertEqual('/css/style.css', $result); Media::attach(false, array('base' => 'lithium/app/webroot')); $result = Media::asset('style.css', 'css'); $this->assertEqual('/lithium/app/webroot/css/style.css', $result); }
/** * Instantiates a request object (usually an instance of `http\Request`) and tests its * properties based on the request type and data to be sent. * * @param string $method The HTTP method of the request, i.e. `'GET'`, `'HEAD'`, `'OPTIONS'`, * etc. Can be passed in upper- or lower-case. * @param string $path The * @param string $data * @param string $options * @return object Returns an instance of `http\Request`, configured with an HTTP method, query * string or POST/PUT data, and URL. */ protected function _request($method, $path, $data, $options) { $defaults = array('type' => 'form'); $options += $defaults + $this->_config; $request = $this->_instance('request', $options); $request->path = str_replace('//', '/', "{$request->path}{$path}"); $request->method = $method = strtoupper($method); $media = $this->_classes['media']; $type = null; if (in_array($options['type'], $media::types()) && $data && !is_string($data)) { $type = $media::type($options['type']); $contentType = (array) $type['content']; $request->headers(array('Content-Type' => current($contentType))); $data = Media::encode($options['type'], $data, $options); } in_array($method, array('POST', 'PUT')) ? $request->body($data) : ($request->params = $data); return $request; }
/** * Run the Lexer and gather the block objects * @param blob $source template contents * @param string $template path to template * @return object|string BlockSet object or path to cached template */ public static function run($template, $data = array(), array $options = array()) { /** * Lets check for cache, if exists then we'll return the cache file name * @var Cache */ $options += array('type' => 'html'); $_cache = new Cache(); $file = static::_template($template); $_cacheFile = sha1($file . $options['type']); if ($_isCached = $_cache->file($_cacheFile) and $_cache->cache()) { return $_isCached; } /** * Guess there was no cache file, lets lex this mother. */ $source = self::_read($template); $_blockSet = static::$_blockSet; $template = self::_template($template); // Set the final template, this gets reset on every iteration to the current template // landing, finally, on the last. static::$_blockSet->templates($template); foreach (static::$_terminals as $pattern => $terminal) { // attempt to match block/parent regex $_preg = $terminal == "T_BLOCK" ? preg_match_all($pattern, $source, $matches) : preg_match($pattern, $source, $matches); if ($_preg) { // Blocks, load them in the BlockSet if ($terminal == "T_BLOCK") { foreach ($matches[2] as $index => $name) { /** * Block parameters * Options that can be set to modify how the block is rendered * @var [type] */ $params = explode(',', $matches[3][$index]); $params = array_map(function ($param) { return trim($param); }, $params); static::$_blockSet->push($name, $matches[4][$index], $template, $params); } // Parent templates, read these and throw them back to the lexer. } else { if (!empty(static::$_hierarchy)) { list($type, $file) = array_slice($matches, 2); if (empty($type)) { $type = 'template'; } else { $type = trim($type); } // override the controller if more than simple file name is passed in. First directory becomes controller $file = explode('/', ltrim($file, '/')); if (count($file) > 1) { $options['controller'] = array_shift($file); } // set filename to template/layout $file = implode('/', $file); preg_match('/(' . implode('|', Media::types()) . ')\\.php$/', $file, $extensions); if (count($extensions) == 2) { // remove .{:type}.php $file = substr($file, 0, strlen($file) - strlen($extensions[0]) - 1); // set type to render as extension specified $options['type'] = $extensions[1]; } $options[$type] = $file; // template path from \lithium\template\view\adapter\File $_template = static::$_hierarchy->template($type, $options); // if $_hierarchy not passed in, use template as is } else { $_template = $matches[3]; } static::run($_template, $data, $options); } } } return static::$_blockSet; }
<?php /** * li3_markdown: lithium port to PHP Markdown for parsing markdown markup into HTML. * * @copyright Copyright 2011, Tobias Sandelius (http://sandelius.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ use lithium\util\String; use lithium\core\Libraries; use lithium\net\http\Media; /** * Include PHP Markdown class file */ if (!class_exists('Markdown_Parser', false)) { require_once dirname(__DIR__) . '/vendors/PHPMarkdown/markdown.php'; } Media::type('md', 'text/html', array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_markdown\\template\\view\\adapter\\Markdown', 'loader' => '\\li3_markdown\\template\\view\\adapter\\Markdown', 'paths' => array('template' => array('{:library}/views/{:controller}/{:template}.{:type}.php', LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php'), 'layout' => array('{:library}/views/layouts/{:layout}.{:type}.php', LITHIUM_APP_PATH . '/views/layouts/{:layout}.{:type}.php'))));
<?php use lithium\core\Libraries; use lithium\net\http\Media; /** * This is the path to the li3_twig plugin, used for Libraries path resolution. */ define('LI3_TWIG_PATH', dirname(__DIR__)); /** * Add the Twig libraries */ Libraries::add('Twig', array('path' => LI3_TWIG_PATH . '/libraries/Twig/lib/Twig', 'prefix' => 'Twig_', 'loader' => 'Twig_Autoloader::autoload')); /** * Add Twig to recognized media types. */ Media::type('default', null, array('view' => 'lithium\\template\\View', 'loader' => 'li3_twig\\template\\Loader', 'renderer' => 'li3_twig\\template\\view\\adapter\\Twig', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}.twig', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.twig')));
$code = Inspector::lines($frame['file'], $lines); if ($code) { foreach ($code as $num => &$content) { $numPad = str_pad($num, 3, ' '); $content = str_ireplace(array('<?php', '?>'), '', $content); $content = highlight_string("<?php {$numPad}{$content} ?>", true); $content = str_replace($replace, '', $content); } } $frame += compact('location', 'lines', 'code'); } $code = $exception->getCode(); $class = get_class($exception); $message = $exception->getMessage(); $data = compact('info', 'params', 'class', 'stack', 'code', 'exception'); Media::render($response, $data, array('controller' => '_errors', 'type' => 'html', 'template' => 'development', 'layout' => 'error', 'request' => $params['request'])); return $response; }); /** * If you use regular lithium templates you should use this handler as the view * itself contains all the formatting setup that is taken care of here for * twig templates */ /* ErrorHandler::apply('lithium\action\Dispatcher::run', array(), function($info, $params) { $response = new Response(array('request' => $params['request'])); Media::render($response, compact('info', 'params'), array( 'controller' => '_errors', 'template' => 'development', 'layout' => 'error',
protected function _scaffoldPaths($field = null) { Media::type('default', null, array('view' => 'lithium\\template\\View', 'paths' => array('template' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php', RADIUM_PATH . '/views/{:controller}/{:template}.{:type}.php', '{:library}/views/scaffold/{:template}.{:type}.php', RADIUM_PATH . '/views/scaffold/{:template}.{:type}.php', '{:library}/views/{:controller}/{:template}.{:type}.php'), 'layout' => array(LITHIUM_APP_PATH . '/views/layouts/{:layout}.{:type}.php', RADIUM_PATH . '/views/layouts/{:layout}.{:type}.php', '{:library}/views/layouts/{:layout}.{:type}.php'), 'element' => array(LITHIUM_APP_PATH . '/views/elements/{:template}.{:type}.php', RADIUM_PATH . '/views/elements/{:template}.{:type}.php', '{:library}/views/elements/{:template}.{:type}.php'), 'widget' => array(LITHIUM_APP_PATH . '/views/widgets/{:template}.{:type}.php', RADIUM_PATH . '/views/widgets/{:template}.{:type}.php', '{:library}/views/widgets/{:template}.{:type}.php')))); }
<?php use lithium\core\Libraries; use lithium\net\http\Media; /** * This is the path to the li3_twig plugin, used for Libraries path resolution. */ define('LI3_TWIG_PATH', dirname(__DIR__)); /** * Register the Twig media type. * The default renderer is still accessible if needed. (default exception handling for example). */ Media::type('twig', array('text/html', 'application/xhtml+xml', '*/*'), array('view' => 'li3_twig\\template\\View', 'loader' => 'li3_twig\\template\\Loader', 'renderer' => 'li3_twig\\template\\view\\adapter\\Twig', 'paths' => array('template' => array('{:library}/views/{:controller}/{:template}.html.twig', '{:library}/views/layouts'))));
$base = isset($config['url']) ? $config['url'] : '/docs'; /** * Handles broken URL parsers by matching method URLs with no closing ) and redirecting. */ Router::connect("{$base}/{:args}\\(", array(), function ($request) { return new Response(array('location' => "{$request->url})")); }); Router::connect($base, array('controller' => 'li3_docs.ApiBrowser', 'action' => 'index')); Router::connect("{$base}/{:lib}/{:args}", array('controller' => 'li3_docs.ApiBrowser', 'action' => 'view')); Router::connect('/li3_docs/{:path:js|css}/{:file}.{:type}', array(), function ($request) { $req = $request->params; $file = dirname(__DIR__) . "/webroot/{$req['path']}/{$req['file']}.{$req['type']}"; if (!file_exists($file)) { return; } return new Response(array('body' => file_get_contents($file), 'headers' => array('Content-type' => str_replace(array('css', 'js'), array('text/css', 'text/javascript'), $req['type'])))); }); Router::connect('/li3_docs/{:path:img}/{:args}.{:type}', array(), function ($request) { $req = $request->params; $path = implode('/', $req['args']); $file = dirname(__DIR__) . "/webroot/{$req['path']}/{$path}.{$req['type']}"; if (!file_exists($file)) { return; } $media = Media::type($req['type']); $content = (array) $media['content']; return new Response(array('body' => file_get_contents($file), 'headers' => array('Content-type' => reset($content)))); }); Router::connect('/li3_docs/search/{:query}', array('controller' => 'li3_docs.ApiSearch', 'action' => 'query')); Router::connect(new Locale(array('template' => $base, 'params' => array('controller' => 'li3_docs.ApiBrowser')))); Router::connect(new Locale(array('template' => "{$base}/{:lib}/{:args}", 'params' => array('controller' => 'li3_docs.ApiBrowser', 'action' => 'view'))));
<?php use lithium\core\Libraries; use lithium\net\http\Media; /** * This is the path to the CMS plugin, used for Libraries path resolution. */ define('CMS_PATH', dirname(__DIR__)); /** * Give CMS access to the media types. */ Media::type('default', null, array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_partials\\template\\view\\adapter\\Parser', 'paths' => array('template' => array('{:library}/views/{:controller}/{:template}.{:type}.php', LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.php'), 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php')));
* @license http://opensource.org/licenses/bsd-license.php The BSD License */ use lithium\core\ErrorHandler; use lithium\action\Response; use lithium\net\http\Media; use lithium\core\Environment; use lithium\core\Libraries; ErrorHandler::apply('lithium\\action\\Dispatcher::run', array(), function ($info, $params) { $response = new Response(array('request' => $params['request'], 'status' => $info['exception']->getCode())); // Production error templates should follow the design of the site. $error_layout = 'default'; $error_template = 'production'; $appCfg = Libraries::get(); $defaultApp = false; $defaultLibrary = null; foreach ($appCfg as $k => $library) { if ($library['default'] === true) { $defaultApp = $library; $defaultLibrary = $k; } } // Development error templates can look different. if (Environment::is('development')) { $error_layout = file_exists($defaultApp['path'] . '/views/layouts/error.html.php') ? 'error' : $error_layout; $error_template = 'development'; } // If the error templates don't exist use li3b_core's. $error_library = file_exists($defaultApp['path'] . '/views/layouts/' . $error_layout . '.html.php') && file_exists($defaultApp['path'] . '/views/_errors/' . $error_template . '.html.php') ? $defaultLibrary : 'li3b_core'; Media::render($response, compact('info', 'params'), array('library' => $error_library, 'controller' => '_errors', 'template' => $error_template, 'layout' => $error_layout, 'request' => $params['request'])); return $response; });
<?php use lithium\action\Dispatcher; use lithium\net\http\Media; Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { Media::type('default', null, array('theme' => 'default', 'view' => 'li3_themes\\template\\View', 'paths' => array('layout' => '{:library}/webroot/themes/{:theme}/views/layouts/{:layout}.{:type}.php', 'template' => '{:library}/webroot/themes/{:theme}/views/{:controller}/{:template}.{:type}.php', 'element' => '{:library}/webroot/themes/{:theme}/views/elements/{:template}.{:type}.php'), 'webroot' => '{:library}/webroot/themes/{:theme}')); Media::assets('img', array('paths' => array('{:base}/themes/{:theme}/img/{:path}' => array('base', 'theme', 'path')), 'theme' => 'default')); Media::assets('js', array('paths' => array('{:base}/themes/{:theme}/js/{:path}' => array('base', 'theme', 'path')), 'theme' => 'default')); Media::assets('css', array('paths' => array('{:base}/themes/{:theme}/css/{:path}' => array('base', 'theme', 'path')), 'theme' => 'default')); return $chain->next($self, $params, $chain); });
/** * Tests that empty asset paths correctly return the base path for the asset type, and don't * generate notices or errors. */ public function testEmptyAssetPaths() { $this->assertEqual('/img/', Media::asset('', 'image')); $this->assertEqual('/css/.css', Media::asset('', 'css')); $this->assertEqual('/js/.js', Media::asset('', 'js')); $this->assertEqual('/', Media::asset('', 'generic')); }
$cacheKey = $params['request']->params['controller'] . 'Controller::' . $params['request']->params['action']; if (isset($response->varnish) && !empty($response->varnish)) { $cache = Varnish::cache($cacheKey, true); if (is_array($response->varnish)) { $cache += $response->varnish; } } else { $cache = Varnish::cache($cacheKey); } if (!empty($cache)) { $varnishHeaders = Varnish::headers($cache); foreach ($varnishHeaders as $key => $val) { $response->headers($key, $val); } } return $response; }); // filter to set esi includes around partials Media::applyFilter('view', function ($self, $params, $chain) { $view = $chain->next($self, $params, $chain); $view->applyFilter('_step', function ($self, $params, $chain) { $content = $chain->next($self, $params, $chain); if (isset($params['options']['esi']) && $params['options']['esi'] == true) { if (!empty($content)) { $content = \lithium\util\String::insert(Varnish::config('template'), array('url' => Router::match(array('controller' => 'Esi', 'action' => 'show', 'type' => $params['step']['path'], 'name' => $params['options']['template'])), 'content' => $content)); } } return $content; }); return $view; });
<?php use lithium\core\Libraries; use lithium\action\Dispatcher; use lithium\net\http\Media; use li3_amf\extensions\media\Amf; /* * Load Zend Framework Libraries (for AMF encoding and decoding). * http://rad-dev.org/lithium/wiki/guides/using/zend * * 'path' should be set to the location of the Zend folder. * 'includePath' should be set to the loation of folder containing the Zend folder. * */ if (!Libraries::get('Zend')) { Libraries::add("Zend", array("prefix" => "Zend_", 'path' => '/Library/Webserver/Documents/lithium/libraries/Zend', "includePath" => '/Library/Webserver/Documents/lithium/libraries', "bootstrap" => "Loader/Autoloader.php", "loader" => array("Zend_Loader_Autoloader", "autoload"), "transform" => function ($class) { return str_replace("_", "/", $class) . ".php"; })); } /** * Declare AMF media type. */ Media::type('amf', 'application/x-amf', array('decode' => function ($data) { $amf = new Amf(); $response = $amf->processResponseBodies(); $response->finalize(); die(print_r(debug_backtrace(), 1)); return $response; }, 'encode' => function ($data) { return $data; }, 'view' => false));
* return $posts->to('json'); * }}} */ use lithium\util\Collection; Collection::formats('lithium\\net\\http\\Media'); /** * This filter is a convenience method which allows you to automatically route requests for static * assets stored within active plugins. For example, given a JavaScript file `bar.js` inside the * `li3_foo` plugin installed in an application, requests to `http://app/path/li3_foo/js/bar.js` * will be routed to `/path/to/app/libraries/plugins/li3_foo/webroot/js/bar.js` on the filesystem. * In production, it is recommended that you disable this filter in favor of symlinking each * plugin's `webroot` directory into your main application's `webroot` directory, or adding routing * rules in your web server's configuration. */ use lithium\action\Dispatcher; use lithium\action\Response; use lithium\net\http\Media; Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { list($library, $asset) = explode('/', $params['request']->url, 2) + array("", ""); if ($asset && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) { return function () use($file) { $info = pathinfo($file); $media = Media::type($info['extension']); $content = (array) $media['content']; return new Response(array('headers' => array('Content-type' => reset($content)), 'body' => file_get_contents($file))); }; } return $chain->next($self, $params, $chain); }); Media::type('js', array('application/javascript', 'text/javascript'), array('view' => 'lithium\\template\\View', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}.php', 'layout' => '{:library}/views/layouts/{:layout}.{:type}.php', 'element' => array('{:library}/views/elements/{:template}.{:type}.php', '{:library}/views/elements/{:template}.html.php'))));
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ use lithium\core\ErrorHandler; use lithium\action\Response; use lithium\net\http\Media; ErrorHandler::apply('lithium\\action\\Dispatcher::run', array(), function ($info, $params) { $response = new Response(array('request' => $params['request'], 'status' => $info['exception']->getCode())); Media::render($response, compact('info', 'params'), array('library' => true, 'controller' => '_errors', 'template' => 'development', 'layout' => 'error', 'request' => $params['request'])); return $response; });
use lithium\core\Libraries; use lithium\action\Dispatcher; use lithium\action\Response; use lithium\net\http\Media; use li3_less\core\Less; define('LI3_BOOTSTRAP_PATH', dirname(__DIR__)); /* * this filter allows automatic linking and loading of assets from `webroot` folder */ Dispatcher::applyFilter('_callable', function ($self, $params, $chain) { list($library, $asset) = explode('/', ltrim($params['request']->url, '/'), 2) + array("", ""); if ($asset && $library == 'li3_bootstrap' && ($path = Media::webroot($library)) && file_exists($file = "{$path}/{$asset}")) { return function () use($file) { $info = pathinfo($file); $media = Media::type($info['extension']); $content = (array) $media['content']; return new Response(array('headers' => array('Content-type' => reset($content)), 'body' => file_get_contents($file))); }; } return $chain->next($self, $params, $chain); }); /** * Here we check, if there is a library called `li3_less` * * If that is the case, we can directly work with the * less files, that is much more flexible. To get this * up and running, you need to add li3_less as a library * and load it _before_ the li3_bootstrap library like this: * * Libraries::add('li3_less');
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2011, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ use lithium\core\ErrorHandler; use lithium\action\Response; use lithium\net\http\Media; use lithium\analysis\Debugger; ErrorHandler::apply('lithium\\action\\Dispatcher::run', array(), function ($info, $params) { $stack = Debugger::trace(array('format' => 'array', 'trace' => $info['exception']->getTrace())); $exception_class = get_class($info['exception']); array_unshift($stack, array('functionRef' => '[exception]', 'file' => $info['exception']->getFile(), 'line' => $info['exception']->getLine())); $response = new Response(array('request' => $params['request'], 'status' => $info['exception']->getCode())); Media::render($response, compact('info', 'params', 'stack', 'exception_class'), array('controller' => 'errors', 'template' => 'development', 'layout' => 'error', 'request' => $params['request'])); return $response; });
<?php use lithium\net\http\Media; use li3_perf\extensions\util\Data; // Apply a filter that will gather all the variables available to the view template. Media::applyFilter('render', function ($self, $params, $chain) { $filter_start = microtime(true); $view_vars = array(); foreach ($params['data'] as $k => $v) { if (is_object($v) && method_exists($v, 'data')) { $view_vars[$k] = $v->data(); } else { $view_vars[$k] = $v; } } Data::append('view_vars', $view_vars); Data::append('timers', array('_filter_for_variables' => microtime(true) - $filter_start)); return $chain->next($self, $params, $chain); });
<?php use lithium\core\Libraries; use lithium\core\ConfigException; use lithium\template\View; use lithium\net\http\Media; use lithium\util\Set; // Define path to plugin and other constants defined('SMARTY_VERSION') or define('SMARTY_VERSION', '3.1.10'); // Allows us to test different versions without breaking things defined('LI3_SMARTY_PATH') or define('LI3_SMARTY_PATH', dirname(__DIR__)); defined('LI3_SMARTY_LIB') or define('LI3_SMARTY_LIB', dirname(__DIR__) . "/libraries/Smarty/" . SMARTY_VERSION . "/libs/"); Libraries::add('Smarty', array("path" => LI3_SMARTY_LIB, "bootstrap" => "Smarty.class.php")); $defaults = array('view' => '\\lithium\\template\\View', 'renderer' => '\\li3_smarty\\template\\view\\adapter\\Smarty', 'paths' => array('template' => array(LITHIUM_APP_PATH . '/views/{:controller}/{:template}.{:type}.tpl', '{:library}/views/{:controller}/{:template}.{:type}.tpl'), 'element' => array(LITHIUM_APP_PATH . '/views/elements/{:template}.html.tpl', '{:library}/views/elements/{:template}.html.tpl'), 'layout' => false), 'compile_dir' => LITHIUM_APP_PATH . '/resources/templates_c', 'cache_dir' => LITHIUM_APP_PATH . '/resources/cache', 'template_dir' => array(LITHIUM_APP_PATH . "/views", LITHIUM_APP_PATH . "/views/pages"), 'plugin_dir' => array(LI3_SMARTY_PATH . "/plugins", LITHIUM_APP_PATH . "/extensions/plugins")); $keys = array_intersect_key($config, $defaults); foreach ($keys as $key => $val) { if (is_array($defaults[$key])) { $defaults[$key] = Set::merge($defaults[$key], $config[$key]); } else { $defaults[$key] = $val; } } /** * Map to the new renderer */ Media::type('default', null, $defaults);
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ use lithium\core\Libraries; use lithium\core\ErrorHandler; use lithium\action\Response; use lithium\net\http\Media; use lithium\analysis\Logger; ErrorHandler::apply('lithium\\action\\Dispatcher::run', array(), function ($info, $params) { if (preg_match('/not found/i', $info['exception']->getMessage())) { $code = 404; } else { $code = $info['exception']->getCode() == 404 ? 404 : 500; } $response = new Response(array('request' => $params['request'], 'status' => $code)); Media::render($response, compact('info', 'params'), array('library' => true, 'controller' => '_errors', 'template' => $code == 404 ? 'fourohfour' : 'fiveohoh', 'layout' => 'default', 'request' => $params['request'])); return $response; }); Logger::config(['default' => ['adapter' => 'File', 'path' => dirname(Libraries::get(true, 'path')) . '/log', 'timestamp' => '[Y-m-d H:i:s]', 'file' => function ($data, $config) { return 'app.log'; }, 'priority' => ['debug', 'error', 'notice', 'warning']]]);
// // Inflector::rules('plural', array('rules' => array('/rata/' => '\1ratum'))); // Inflector::rules('plural', array('irregular' => array('bar' => 'foo'))); // // Inflector::rules('transliteration', array('/É|Ê/' => 'E')); // // Inflector::rules('uninflected', 'bord'); // Inflector::rules('uninflected', array('bord', 'baird')); /** * Integration with `View`. Embeds message translation aliases into the `View` * class (or other content handler, if specified) when content is rendered. This * enables translation functions, i.e. `<?=$t("Translated content"); ?>`. */ Media::applyFilter('_handle', function ($self, $params, $chain) { $params['handler'] += array('outputFilters' => array()); $params['handler']['outputFilters'] += Message::aliases(); return $chain->next($self, $params, $chain); }); /** * Integration with `Validator`. You can load locale dependent rules into the `Validator` * by specifying them manually or retrieving them with the `Catalog` class. */ foreach (array('phone', 'postalCode', 'ssn') as $name) { Validator::add($name, Catalog::read(true, "validation.{$name}", 'en_US')); } /** * Intercepts dispatching processes in order to set the effective locale by using * the locale of the request or if that is not available retrieving a locale preferred * by the client. */ ActionDispatcher::applyFilter('_callable', function ($self, $params, $chain) {
<?php use lithium\net\http\Media; require dirname(__DIR__) . '/libraries/mustache/Mustache.php'; Media::type('mustache', 'text/x-mustache', array('view' => 'lithium\\template\\View', 'loader' => 'Mustache', 'renderer' => 'Mustache', 'paths' => array('template' => '{:library}/views/{:controller}/{:template}.{:type}', 'layout' => '{:library}/views/layouts/{:layout}.{:type}', 'element' => '{:library}/views/elements/{:template}.{:type}')));