Template.class.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * hold PMA\Template class
  5. *
  6. * @package PMA
  7. */
  8. namespace PMA;
  9. if (! defined('PHPMYADMIN')) {
  10. exit;
  11. }
  12. /**
  13. * Class Template
  14. *
  15. * Handle front end templating
  16. *
  17. * @package PMA
  18. */
  19. class Template
  20. {
  21. protected $name = null;
  22. const BASE_PATH = 'templates/';
  23. /**
  24. * Template constructor
  25. *
  26. * @param string $name Template name
  27. */
  28. protected function __construct($name)
  29. {
  30. $this->name = $name;
  31. }
  32. /**
  33. * Template getter
  34. *
  35. * @param string $name Template name
  36. *
  37. * @return Template
  38. */
  39. public static function get($name)
  40. {
  41. return new Template($name);
  42. }
  43. /**
  44. * Remove whitespaces between tags and innerHTML
  45. *
  46. * @param string $content HTML to perform the trim method
  47. *
  48. * @return string
  49. */
  50. public static function trim($content)
  51. {
  52. $regexp = '/(<[^\/][^>]+>)\s+|\s+(<\/)/';
  53. return preg_replace($regexp, "$1$2", $content);
  54. }
  55. /**
  56. * Render template
  57. *
  58. * @param array $data Variables to provides for template
  59. * @param bool $trim Trim content
  60. *
  61. * @return string
  62. */
  63. public function render($data = array(), $trim = true)
  64. {
  65. $template = static::BASE_PATH . $this->name . '.phtml';
  66. try {
  67. extract($data);
  68. ob_start();
  69. if (file_exists($template)) {
  70. include $template;
  71. } else {
  72. throw new \LogicException(
  73. 'The template "' . $template . '" not found.'
  74. );
  75. }
  76. if ($trim) {
  77. $content = Template::trim(ob_get_clean());
  78. } else {
  79. $content = ob_get_clean();
  80. }
  81. return $content;
  82. } catch (\LogicException $e) {
  83. ob_end_clean();
  84. throw new \LogicException($e->getMessage());
  85. }
  86. }
  87. }