TemplateManager.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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\WebProfilerBundle\Profiler;
  11. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  12. use Symfony\Component\HttpKernel\Profiler\Profile;
  13. use Symfony\Component\HttpKernel\Profiler\Profiler;
  14. use Twig\Environment;
  15. /**
  16. * Profiler Templates Manager.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. * @author Artur Wielogórski <wodor@wodor.net>
  20. *
  21. * @internal
  22. */
  23. class TemplateManager
  24. {
  25. protected $twig;
  26. protected $templates;
  27. protected $profiler;
  28. public function __construct(Profiler $profiler, Environment $twig, array $templates)
  29. {
  30. $this->profiler = $profiler;
  31. $this->twig = $twig;
  32. $this->templates = $templates;
  33. }
  34. /**
  35. * Gets the template name for a given panel.
  36. *
  37. * @return mixed
  38. *
  39. * @throws NotFoundHttpException
  40. */
  41. public function getName(Profile $profile, string $panel)
  42. {
  43. $templates = $this->getNames($profile);
  44. if (!isset($templates[$panel])) {
  45. throw new NotFoundHttpException(sprintf('Panel "%s" is not registered in profiler or is not present in viewed profile.', $panel));
  46. }
  47. return $templates[$panel];
  48. }
  49. /**
  50. * Gets template names of templates that are present in the viewed profile.
  51. *
  52. * @return array
  53. *
  54. * @throws \UnexpectedValueException
  55. */
  56. public function getNames(Profile $profile)
  57. {
  58. $loader = $this->twig->getLoader();
  59. $templates = [];
  60. foreach ($this->templates as $arguments) {
  61. if (null === $arguments) {
  62. continue;
  63. }
  64. [$name, $template] = $arguments;
  65. if (!$this->profiler->has($name) || !$profile->hasCollector($name)) {
  66. continue;
  67. }
  68. if ('.html.twig' === substr($template, -10)) {
  69. $template = substr($template, 0, -10);
  70. }
  71. if (!$loader->exists($template.'.html.twig')) {
  72. throw new \UnexpectedValueException(sprintf('The profiler template "%s.html.twig" for data collector "%s" does not exist.', $template, $name));
  73. }
  74. $templates[$name] = $template.'.html.twig';
  75. }
  76. return $templates;
  77. }
  78. }