TemplateEngineFactory.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View;
  7. use Magento\Framework\ObjectManagerInterface;
  8. /**
  9. * Factory class for Template Engine
  10. */
  11. class TemplateEngineFactory
  12. {
  13. /**
  14. * Object manager
  15. *
  16. * @var ObjectManagerInterface
  17. */
  18. protected $objectManager;
  19. /**
  20. * Engines
  21. *
  22. * @var array
  23. */
  24. protected $engines;
  25. /**
  26. * Constructor
  27. *
  28. * @param ObjectManagerInterface $objectManager
  29. * @param array $engines Format: array('<name>' => 'TemplateEngine\Class', ...)
  30. */
  31. public function __construct(ObjectManagerInterface $objectManager, array $engines)
  32. {
  33. $this->objectManager = $objectManager;
  34. $this->engines = $engines;
  35. }
  36. /**
  37. * Retrieve a template engine instance by its unique name
  38. *
  39. * @param string $name
  40. * @return TemplateEngineInterface
  41. * @throws \UnexpectedValueException If template engine doesn't implement the necessary interface
  42. * @throws \InvalidArgumentException If template engine doesn't exist
  43. */
  44. public function create($name)
  45. {
  46. if (!isset($this->engines[$name])) {
  47. throw new \InvalidArgumentException("Unknown template engine type: '{$name}'.");
  48. }
  49. $engineClass = $this->engines[$name];
  50. $engineInstance = $this->objectManager->create($engineClass);
  51. if (!$engineInstance instanceof \Magento\Framework\View\TemplateEngineInterface) {
  52. throw new \UnexpectedValueException("{$engineClass} has to implement the template engine interface.");
  53. }
  54. return $engineInstance;
  55. }
  56. }