Simple.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\adapter;
  9. use Closure;
  10. use Exception;
  11. use lithium\util\Set;
  12. use lithium\util\String;
  13. /**
  14. * This view adapter renders content using simple string substitution, and is only useful for very
  15. * simple templates (no conditionals or looping) or testing.
  16. *
  17. */
  18. class Simple extends \lithium\template\view\Renderer {
  19. /**
  20. * Renders content from a template file provided by `template()`.
  21. *
  22. * @param string $template
  23. * @param array $data
  24. * @param array $options
  25. * @return string
  26. */
  27. public function render($template, $data = array(), array $options = array()) {
  28. $defaults = array('context' => array());
  29. $options += $defaults;
  30. $context = array();
  31. $this->_context = $options['context'] + $this->_context;
  32. foreach (array_keys($this->_context) as $key) {
  33. $context[$key] = $this->__get($key);
  34. }
  35. $data = array_merge($this->_toString($context), $this->_toString($data));
  36. return String::insert($template, $data, $options);
  37. }
  38. /**
  39. * Returns a template string
  40. *
  41. * @param string $type
  42. * @param array $options
  43. * @return string
  44. */
  45. public function template($type, $options) {
  46. if (isset($options[$type])) {
  47. return $options[$type];
  48. }
  49. return isset($options['template']) ? $options['template'] : '';
  50. }
  51. protected function _toString($data) {
  52. foreach ($data as $key => $val) {
  53. switch (true) {
  54. case is_object($val) && !$val instanceof Closure:
  55. try {
  56. $data[$key] = (string) $val;
  57. } catch (Exception $e) {
  58. $data[$key] = '';
  59. }
  60. break;
  61. case is_array($val):
  62. $data = array_merge($data, Set::flatten($val));
  63. break;
  64. }
  65. }
  66. return $data;
  67. }
  68. }
  69. ?>