PhpEngineTheme.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\FrameworkBundle\Form;
  11. use Symfony\Component\Form\Exception\FormException;
  12. use Symfony\Component\Form\Renderer\Theme\FormThemeInterface;
  13. use Symfony\Component\Templating\PhpEngine;
  14. /**
  15. * Renders a Form using the PHP Templating Engine.
  16. *
  17. * Each field is rendered as slot of a template.
  18. *
  19. * @author Benjamin Eberlei <kontakt@beberlei.de>
  20. */
  21. class PhpEngineTheme implements FormThemeInterface
  22. {
  23. /**
  24. * @var array
  25. */
  26. static protected $cache = array();
  27. /**
  28. * @var PhpEngine
  29. */
  30. private $engine;
  31. /**
  32. * @var string
  33. */
  34. private $templateDir;
  35. /**
  36. * @param PhpEngine $engine
  37. */
  38. public function __construct(PhpEngine $engine, $templateDir = null)
  39. {
  40. $this->engine = $engine;
  41. $this->templateDir = $templateDir;
  42. }
  43. public function render($blocks, $section, array $parameters)
  44. {
  45. $blocks = (array)$blocks;
  46. foreach ($blocks as &$block) {
  47. $block = $block.'_'.$section;
  48. if ($template = $this->lookupTemplate($block)) {
  49. return $this->engine->render($template, $parameters);
  50. }
  51. }
  52. throw new FormException(sprintf('The form theme is missing the "%s" template files', implode('", "', $blocks)));
  53. }
  54. protected function lookupTemplate($templateName)
  55. {
  56. if (isset(self::$cache[$templateName])) {
  57. return self::$cache[$templateName];
  58. }
  59. $template = $templateName.'.html.php';
  60. if ($this->templateDir) {
  61. $template = $this->templateDir . ':' . $template;
  62. }
  63. if (!$this->engine->exists($template)) {
  64. $template = false;
  65. }
  66. self::$cache[$templateName] = $template;
  67. return $template;
  68. }
  69. public function attributes(array $attribs)
  70. {
  71. $html = '';
  72. foreach ($attribs as $k => $v) {
  73. $html .= $this->engine->escape($k) . '="' . $this->engine->escape($v) .'" ';
  74. }
  75. return $html;
  76. }
  77. }