Renderer.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\template\view;
  9. use RuntimeException;
  10. use lithium\core\Libraries;
  11. use lithium\core\ClassNotFoundException;
  12. /**
  13. * The `Renderer` abstract class serves as a base for all concrete `Renderer` adapters.
  14. *
  15. * When in a view, the local scope is that of an instance of `Renderer` - meaning that
  16. * `$this` in views is an instance of the current renderer adapter.
  17. *
  18. * For more information about implementing your own template loaders or renderers, see the
  19. * `lithium\template\View` class.
  20. *
  21. * @see lithium\template\View
  22. * @see lithium\template\adapter\File
  23. * @see lithium\template\adapter\Simple
  24. */
  25. abstract class Renderer extends \lithium\core\Object {
  26. /**
  27. * These configuration variables will automatically be assigned to their corresponding protected
  28. * properties when the object is initialized.
  29. *
  30. * @var array
  31. */
  32. protected $_autoConfig = array(
  33. 'request', 'response', 'context', 'strings', 'handlers', 'view', 'classes' => 'merge'
  34. );
  35. /**
  36. * Holds an instance of the `View` object that created this rendering context. See the `view()`
  37. * method for more details.
  38. *
  39. * @see lithium\template\view\Renderer::view()
  40. * @var object
  41. */
  42. protected $_view = null;
  43. /**
  44. * Context values that exist across all templates rendered in this context. These values
  45. * are usually rendered in the layout template after all other values have rendered.
  46. *
  47. * @var array
  48. */
  49. protected $_context = array(
  50. 'content' => '', 'title' => '', 'scripts' => array(), 'styles' => array(), 'head' => array()
  51. );
  52. /**
  53. * `Renderer`'s dependencies. These classes are used by the output handlers to generate URLs
  54. * for dynamic resources and static assets.
  55. *
  56. * @see Renderer::$_handlers
  57. * @var array
  58. */
  59. protected $_classes = array(
  60. 'router' => 'lithium\net\http\Router',
  61. 'media' => 'lithium\net\http\Media'
  62. );
  63. /**
  64. * Contains the list of helpers currently in use by this rendering context. Helpers are loaded
  65. * via the `helper()` method, which is called by `Renderer::__get()`, allowing for on-demand
  66. * loading of helpers.
  67. *
  68. * @var array
  69. */
  70. protected $_helpers = array();
  71. /**
  72. * Aggregates named string templates used by helpers. Can be overridden to change the default
  73. * strings a helper uses.
  74. *
  75. * @var array
  76. */
  77. protected $_strings = array();
  78. /**
  79. * The `Request` object instance, if applicable.
  80. *
  81. * @var object The request object.
  82. */
  83. protected $_request = null;
  84. /**
  85. * The `Response` object instance, if applicable.
  86. *
  87. * @var object The response object.
  88. */
  89. protected $_response = null;
  90. /**
  91. * Automatically matches up template strings by name to output handlers. A handler can either
  92. * be a string, which represents a method name of the helper, or it can be a closure or callable
  93. * object. A handler takes 3 parameters: the value to be filtered, the name of the helper
  94. * method that triggered the handler, and the array of options passed to the `_render()`. These
  95. * handlers are shared among all helper objects, and are automatically triggered whenever a
  96. * helper method renders a template string (using `_render()`) and a key which is to be embedded
  97. * in the template string matches an array key of a corresponding handler.
  98. *
  99. * @see lithium\template\view\Renderer::applyHandler()
  100. * @see lithium\template\view\Renderer::handlers()
  101. * @var array
  102. */
  103. protected $_handlers = array();
  104. /**
  105. * An array containing any additional variables to be injected into view templates. This allows
  106. * local variables to be communicated between multiple templates (i.e. an element and a layout)
  107. * which are using the same rendering context.
  108. *
  109. * @see lithium\template\view\Renderer::set()
  110. * @var array
  111. */
  112. protected $_data = array();
  113. /**
  114. * Variables that have been set from a view/element/layout/etc. that should be available to the
  115. * same rendering context.
  116. *
  117. * @var array Key/value pairs of variables
  118. */
  119. protected $_vars = array();
  120. /**
  121. * Available options accepted by `template\View::render()`, used when rendering.
  122. *
  123. * @see lithium\template\View::render()
  124. * @var array
  125. */
  126. protected $_options = array();
  127. /**
  128. * Render the template with given data. Abstract; must be added to subclasses.
  129. *
  130. * @param string $template
  131. * @param array|string $data
  132. * @param array $options
  133. * @return string Returns the result of the rendered template.
  134. */
  135. abstract public function render($template, $data = array(), array $options = array());
  136. /**
  137. * Renderer constructor.
  138. *
  139. * Accepts these following configuration parameters:
  140. * - `view`: The `View` object associated with this renderer.
  141. * - `strings`: String templates used by helpers.
  142. * - `handlers`: An array of output handlers for string template inputs.
  143. * - `request`: The `Request` object associated with this renderer and passed to the
  144. * defined handlers.
  145. * - `response`: The `Response` object associated with this renderer.
  146. * - `context`: An array of the current rendering context data, including `content`,
  147. * `title`, `scripts`, `head` and `styles`.
  148. * @param array $config
  149. */
  150. public function __construct(array $config = array()) {
  151. $defaults = array(
  152. 'view' => null,
  153. 'strings' => array(),
  154. 'handlers' => array(),
  155. 'request' => null,
  156. 'response' => null,
  157. 'context' => array(
  158. 'content' => '', 'title' => '', 'scripts' => array(),
  159. 'styles' => array(), 'head' => array()
  160. )
  161. );
  162. parent::__construct((array) $config + $defaults);
  163. }
  164. /**
  165. * Sets the default output handlers for string template inputs.
  166. *
  167. * @return void
  168. */
  169. protected function _init() {
  170. parent::_init();
  171. $request =& $this->_request;
  172. $context =& $this->_context;
  173. $classes =& $this->_classes;
  174. $h = $this->_view ? $this->_view->outputFilters['h'] : null;
  175. $this->_handlers += array(
  176. 'url' => function($url, $ref, array $options = array()) use (&$classes, &$request, $h) {
  177. $url = $classes['router']::match($url ?: '', $request, $options);
  178. return $h ? str_replace('&amp;', '&', $h($url)) : $url;
  179. },
  180. 'path' => function($path, $ref, array $options = array()) use (&$classes, &$request) {
  181. $defaults = array('base' => $request ? $request->env('base') : '');
  182. $type = 'generic';
  183. if (is_array($ref) && $ref[0] && $ref[1]) {
  184. list($helper, $methodRef) = $ref;
  185. list($class, $method) = explode('::', $methodRef);
  186. $type = $helper->contentMap[$method];
  187. }
  188. return $classes['media']::asset($path, $type, $options + $defaults);
  189. },
  190. 'options' => '_attributes',
  191. 'title' => 'escape',
  192. 'value' => 'escape',
  193. 'scripts' => function($scripts) use (&$context) {
  194. return "\n\t" . join("\n\t", $context['scripts']) . "\n";
  195. },
  196. 'styles' => function($styles) use (&$context) {
  197. return "\n\t" . join("\n\t", $context['styles']) . "\n";
  198. },
  199. 'head' => function($head) use (&$context) {
  200. return "\n\t" . join("\n\t", $context['head']) . "\n";
  201. }
  202. );
  203. unset($this->_config['view']);
  204. }
  205. /**
  206. * Magic `__isset` method.
  207. *
  208. * Is triggered by calling isset() or empty() on inaccessible properties, and performs
  209. * an `isset()` check on for keys in the current `context`.
  210. *
  211. * @param string $property The accessed property.
  212. * @return boolean True if set, false otherwise.
  213. */
  214. public function __isset($property) {
  215. return isset($this->_context[$property]);
  216. }
  217. /**
  218. * Returns a helper object or context value by name.
  219. *
  220. * @param string $property The name of the helper or context value to return.
  221. * @return mixed
  222. * @filter
  223. */
  224. public function __get($property) {
  225. $context = $this->_context;
  226. $helpers = $this->_helpers;
  227. $filter = function($self, $params, $chain) use ($context, $helpers) {
  228. $property = $params['property'];
  229. foreach (array('context', 'helpers') as $key) {
  230. if (isset(${$key}[$property])) {
  231. return ${$key}[$property];
  232. }
  233. }
  234. return $self->helper($property);
  235. };
  236. return $this->_filter(__METHOD__, compact('property'), $filter);
  237. }
  238. /**
  239. * Dispatches method calls for (a) rendering context values or (b) applying handlers to pieces
  240. * of content. If `$method` is a key in `Renderer::$_context`, the corresponding context value
  241. * will be returned (with the value run through a matching handler if one is available). If
  242. * `$method` is a key in `Renderer::$_handlers`, the value passed as the first parameter in the
  243. * method call will be passed through the handler and returned.
  244. *
  245. * @see lithium\template\view\Renderer::$_context
  246. * @see lithium\template\view\Renderer::$_handlers
  247. * @see lithium\template\view\Renderer::applyHandler()
  248. * @param string $method The method name to call, usually either a rendering context value or a
  249. * content handler.
  250. * @param array $params
  251. * @return mixed
  252. */
  253. public function __call($method, $params) {
  254. if (!isset($this->_context[$method]) && !isset($this->_handlers[$method])) {
  255. return isset($params[0]) ? $params[0] : null;
  256. }
  257. if (!isset($this->_handlers[$method]) && !$params) {
  258. return $this->_context[$method];
  259. }
  260. if (isset($this->_context[$method]) && $params) {
  261. if (is_array($this->_context[$method])) {
  262. $this->_context[$method][] = $params[0];
  263. } else {
  264. $this->_context[$method] = $params[0];
  265. }
  266. }
  267. if (!isset($this->_context[$method])) {
  268. $params += array(null, array());
  269. return $this->applyHandler(null, null, $method, $params[0], $params[1]);
  270. }
  271. return $this->applyHandler(null, null, $method, $this->_context[$method]);
  272. }
  273. /**
  274. * Custom check to determine if our given magic methods can be responded to.
  275. *
  276. * @param string $method Method name.
  277. * @param bool $internal Interal call or not.
  278. * @return bool
  279. */
  280. public function respondsTo($method, $internal = false) {
  281. return is_callable(array($this, $method), true);
  282. }
  283. /**
  284. * Brokers access to helpers attached to this rendering context, and loads helpers on-demand if
  285. * they are not available.
  286. *
  287. * @param string $name Helper name
  288. * @param array $config
  289. * @return object
  290. */
  291. public function helper($name, array $config = array()) {
  292. if (isset($this->_helpers[$name])) {
  293. return $this->_helpers[$name];
  294. }
  295. try {
  296. $config += array('context' => $this);
  297. return $this->_helpers[$name] = Libraries::instance('helper', ucfirst($name), $config);
  298. } catch (ClassNotFoundException $e) {
  299. if (ob_get_length()) {
  300. ob_end_clean();
  301. }
  302. throw new RuntimeException("Helper `{$name}` not found.");
  303. }
  304. }
  305. /**
  306. * Manages template strings.
  307. *
  308. * @param mixed $strings
  309. * @return mixed
  310. */
  311. public function strings($strings = null) {
  312. if (is_array($strings)) {
  313. return $this->_strings = $this->_strings + $strings;
  314. }
  315. if (is_string($strings)) {
  316. return isset($this->_strings[$strings]) ? $this->_strings[$strings] : null;
  317. }
  318. return $this->_strings;
  319. }
  320. /**
  321. * Returns either one or all context values for this rendering context. Context values persist
  322. * across all templates rendered in the current context, and are usually outputted in a layout
  323. * template.
  324. *
  325. * @see lithium\template\view\Renderer::$_context
  326. * @param string $property If unspecified, an associative array of all context values is
  327. * returned. If a string is specified, the context value matching the name given
  328. * will be returned, or `null` if that name does not exist.
  329. * @return mixed A string or array, depending on whether `$property` is specified.
  330. */
  331. public function context($property = null) {
  332. if ($property) {
  333. return isset($this->_context[$property]) ? $this->_context[$property] : null;
  334. }
  335. return $this->_context;
  336. }
  337. /**
  338. * Gets or adds content handlers from/to this rendering context, depending on the value of
  339. * `$handlers`. For more on how to implement handlers and the various types, see
  340. * `applyHandler()`.
  341. *
  342. * @see lithium\template\view\Renderer::applyHandler()
  343. * @see lithium\template\view\Renderer::$_handlers
  344. * @param mixed $handlers If `$handlers` is empty or no value is provided, the current list
  345. * of handlers is returned. If `$handlers` is a string, the handler with the name
  346. * matching the string will be returned, or null if one does not exist. If
  347. * `$handlers` is an array, the handlers named in the array will be merged into
  348. * the list of handlers in this rendering context, with the pre-existing handlers
  349. * taking precedence over those newly added.
  350. * @return mixed Returns an array of handlers or a single handler reference, depending on the
  351. * value of `$handlers`.
  352. */
  353. public function handlers($handlers = null) {
  354. if (is_array($handlers)) {
  355. return $this->_handlers += $handlers;
  356. }
  357. if (is_string($handlers)) {
  358. return isset($this->_handlers[$handlers]) ? $this->_handlers[$handlers] : null;
  359. }
  360. return $this->_handlers;
  361. }
  362. /**
  363. * Filters a piece of content through a content handler. A handler can be:
  364. * - a string containing the name of a method defined in `$helper`. The method is called with 3
  365. * parameters: the value to be handled, the helper method called (`$method`) and the
  366. * `$options` that were passed into `applyHandler`.
  367. * - an array where the first element is an object reference, and the second element is a method
  368. * name. The method name given will be called on the object with the same parameters as
  369. * above.
  370. * - a closure, which takes the value as the first parameter, an array containing an instance of
  371. * the calling helper and the calling method name as the second, and `$options` as the third.
  372. * In all cases, handlers should return the transformed version of `$value`.
  373. *
  374. * @see lithium\template\view\Renderer::handlers()
  375. * @see lithium\template\view\Renderer::$_handlers
  376. * @param object $helper The instance of the object (usually a helper) that is invoking
  377. * @param string $method The object (helper) method which is applying the handler to the content
  378. * @param string $name The name of the value to which the handler is applied, i.e. `'url'`,
  379. * `'path'` or `'title'`.
  380. * @param mixed $value The value to be transformed by the handler, which is ultimately returned.
  381. * @param array $options Any options which should be passed to the handler used in this call.
  382. * @return mixed The transformed value of `$value`, after it has been processed by a handler.
  383. */
  384. public function applyHandler($helper, $method, $name, $value, array $options = array()) {
  385. if (!(isset($this->_handlers[$name]) && $handler = $this->_handlers[$name])) {
  386. return $value;
  387. }
  388. switch (true) {
  389. case is_string($handler) && !$helper:
  390. $helper = $this->helper('html');
  391. case is_string($handler) && is_object($helper):
  392. return $helper->invokeMethod($handler, array($value, $method, $options));
  393. case is_array($handler) && is_object($handler[0]):
  394. list($object, $func) = $handler;
  395. return $object->invokeMethod($func, array($value, $method, $options));
  396. case is_callable($handler):
  397. return $handler($value, array($helper, $method), $options);
  398. default:
  399. return $value;
  400. }
  401. }
  402. /**
  403. * Returns the `Request` object associated with this rendering context.
  404. *
  405. * @return object Returns an instance of `lithium\action\Request`, which provides the context
  406. * for URLs, etc. which are generated in any templates rendered by this context.
  407. */
  408. public function request() {
  409. return $this->_request;
  410. }
  411. /**
  412. * Returns the `Response` object associated with this rendering context.
  413. *
  414. * @return object Returns an instance of `lithium\action\Response`, which provides the i.e.
  415. * the encoding for the document being the result of templates rendered by this context.
  416. */
  417. public function response() {
  418. return $this->_response;
  419. }
  420. /**
  421. * Retuns the `View` object that controls this rendering context's instance. This can be used,
  422. * for example, to render view elements, i.e. `<?=$this->view()->render('element' $name); ?>`.
  423. *
  424. * @return void
  425. */
  426. public function view() {
  427. return $this->_view;
  428. }
  429. /**
  430. * Returns all variables and their values that have been set.
  431. *
  432. * @return array Key/value pairs of data that has been set.
  433. */
  434. public function data() {
  435. return $this->_data + $this->_vars;
  436. }
  437. /**
  438. * Allows variables to be set by one template and used in subsequent templates rendered using
  439. * the same context. For example, a variable can be set in a template and used in an element
  440. * rendered within a template, or an element or template could set a variable which would be
  441. * made available in the layout.
  442. *
  443. * @param array $data An array of key/value pairs representing local variables that should be
  444. * made available to all other templates rendered in this rendering context.
  445. * @return void
  446. */
  447. public function set(array $data = array()) {
  448. $this->_data = $data + $this->_data;
  449. $this->_vars = $data + $this->_vars;
  450. }
  451. /**
  452. * Shortcut method used to render elements and other nested templates from inside the templating
  453. * layer.
  454. *
  455. * @see lithium\template\View::$_processes
  456. * @see lithium\template\View::render()
  457. * @param string $type The type of template to render, usually either `'element'` or
  458. * `'template'`. Indicates the process used to render the content. See
  459. * `lithium\template\View::$_processes` for more info.
  460. * @param string $template The template file name. For example, if `'header'` is passed, and
  461. * `$type` is set to `'element'`, then the template rendered will be
  462. * `views/elements/header.html.php` (assuming the default configuration).
  463. * @param array $data An array of any other local variables that should be injected into the
  464. * template. By default, only the values used to render the current template will
  465. * be sent. If `$data` is non-empty, both sets of variables will be merged.
  466. * @param array $options Any options accepted by `template\View::render()`.
  467. * @return string Returns a the rendered template content as a string.
  468. */
  469. protected function _render($type, $template, array $data = array(), array $options = array()) {
  470. $options += $this->_options;
  471. return $this->_view->render($type, $data + $this->_data, compact('template') + $options);
  472. }
  473. }
  474. ?>