/src/Propel/Generator/Builder/Util/PropelTemplate.php

https://github.com/fabienpomerol/Propel2 · PHP · 99 lines · 36 code · 11 blank · 52 comment · 4 complexity · c6e40ab5eb2bd159aa97ebd2ff4a9e6a MD5 · raw file

  1. <?php
  2. /**
  3. * This file is part of the Propel package.
  4. * For the full copyright and license information, please view the LICENSE
  5. * file that was distributed with this source code.
  6. *
  7. * @license MIT License
  8. */
  9. namespace Propel\Generator\Builder\Util;
  10. use Propel\Generator\Exception\InvalidArgumentException;
  11. /**
  12. * Simple templating system to ease behavior writing
  13. *
  14. * @author François Zaninotto
  15. */
  16. class PropelTemplate
  17. {
  18. /**
  19. * @var string
  20. */
  21. protected $template;
  22. /**
  23. * @var string
  24. */
  25. protected $templateFile;
  26. /**
  27. * Sets a string as a template.
  28. * The string doesn't need closing php tags.
  29. *
  30. * <code>
  31. * $template->setTemplate('This is <?php echo $name ?>');
  32. * </code>
  33. *
  34. * @param string $template the template string
  35. */
  36. public function setTemplate($template)
  37. {
  38. $this->template = $template;
  39. }
  40. /**
  41. * Set a file as a template. The file can be any regular PHP file.
  42. *
  43. * <code>
  44. * $template->setTemplateFile(dirname(__FILE__) . '/template/foo.php');
  45. * </code>
  46. *
  47. * @param string $filePath The (absolute or relative to the include path) file path
  48. */
  49. public function setTemplateFile($filePath)
  50. {
  51. $this->templateFile = $filePath;
  52. }
  53. /**
  54. * Render the template using the variable provided as arguments.
  55. *
  56. * <code>
  57. * $template = new PropelTemplate();
  58. * $template->setTemplate('This is <?php echo $name ?>');
  59. * echo $template->render(array('name' => 'Mike'));
  60. * // This is Mike
  61. * </code>
  62. *
  63. * @param array $vars An associative array of argumens to be rendered
  64. *
  65. * @return string The rendered template
  66. */
  67. public function render($vars = array())
  68. {
  69. if (null === $this->templateFile && null === $this->template) {
  70. throw new InvalidArgumentException('You must set a template or a template file before rendering');
  71. }
  72. extract($vars);
  73. ob_start();
  74. ob_implicit_flush(0);
  75. try {
  76. if (null !== $this->templateFile) {
  77. require $this->templateFile;
  78. } else {
  79. eval('?>' . $this->template . '<?php ');
  80. }
  81. } catch (\Exception $e) {
  82. // need to end output buffering before throwing the exception #7596
  83. ob_end_clean();
  84. throw $e;
  85. }
  86. return ob_get_clean();
  87. }
  88. }