TemplateNameParser.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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\Templating;
  11. use Symfony\Component\HttpKernel\KernelInterface;
  12. use Symfony\Component\Templating\TemplateNameParser as BaseTemplateNameParser;
  13. use Symfony\Component\Templating\TemplateReferenceInterface;
  14. /**
  15. * TemplateNameParser converts template names from the short notation
  16. * "bundle:section:template.format.engine" to TemplateReferenceInterface
  17. * instances.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class TemplateNameParser extends BaseTemplateNameParser
  22. {
  23. protected $kernel;
  24. protected $cache = array();
  25. public function __construct(KernelInterface $kernel)
  26. {
  27. $this->kernel = $kernel;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function parse($name)
  33. {
  34. if ($name instanceof TemplateReferenceInterface) {
  35. return $name;
  36. } elseif (isset($this->cache[$name])) {
  37. return $this->cache[$name];
  38. }
  39. // normalize name
  40. $name = str_replace(':/', ':', preg_replace('#/{2,}#', '/', str_replace('\\', '/', $name)));
  41. if (false !== strpos($name, '..')) {
  42. throw new \RuntimeException(sprintf('Template name "%s" contains invalid characters.', $name));
  43. }
  44. if (!preg_match('/^(?:([^:]*):([^:]*):)?(.+)\.([^\.]+)\.([^\.]+)$/', $name, $matches) || $this->isAbsolutePath($name) || 0 === strpos($name, '@')) {
  45. return parent::parse($name);
  46. }
  47. $template = new TemplateReference($matches[1], $matches[2], $matches[3], $matches[4], $matches[5]);
  48. if ($template->get('bundle')) {
  49. try {
  50. $this->kernel->getBundle($template->get('bundle'));
  51. } catch (\Exception $e) {
  52. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid.', $name), 0, $e);
  53. }
  54. }
  55. return $this->cache[$name] = $template;
  56. }
  57. private function isAbsolutePath($file)
  58. {
  59. return (bool) preg_match('#^(?:/|[a-zA-Z]:)#', $file);
  60. }
  61. }