TwigThemeFactory.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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\Component\Form\Renderer\Theme;
  11. use Symfony\Component\Form\Exception\FormException;
  12. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  13. /**
  14. * Creates TwigTheme instances
  15. *
  16. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  17. */
  18. class TwigThemeFactory implements FormThemeFactoryInterface
  19. {
  20. /**
  21. * @var Twig_Environment
  22. */
  23. private $environment;
  24. /**
  25. * @var array
  26. */
  27. private $fallbackTemplates;
  28. public function __construct(\Twig_Environment $environment, $fallbackTemplates = null)
  29. {
  30. if (empty($fallbackTemplates)) {
  31. $fallbackTemplates = array();
  32. } else if (!is_array($fallbackTemplates)) {
  33. // Don't use type casting, because then objects (Twig_Template)
  34. // are converted to arrays
  35. $fallbackTemplates = array($fallbackTemplates);
  36. }
  37. $this->environment = $environment;
  38. $this->fallbackTemplates = $fallbackTemplates;
  39. }
  40. /**
  41. * @see Symfony\Component\Form\Renderer\Theme\FormThemeFactoryInterface::create()
  42. */
  43. public function create($template = null)
  44. {
  45. if (null !== $template && !is_string($template) && !$template instanceof \Twig_Template) {
  46. throw new UnexpectedTypeException($template, 'string or Twig_Template');
  47. }
  48. $templates = $template
  49. ? array_merge($this->fallbackTemplates, array($template))
  50. : $this->fallbackTemplates;
  51. if (count($templates) === 0) {
  52. throw new FormException('Twig themes either need default templates or templates passed during creation');
  53. }
  54. return new TwigTheme($this->environment, $templates);
  55. }
  56. }