BuilderFactory.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View\Layout;
  7. use Magento\Framework\ObjectManagerInterface;
  8. use Magento\Framework\View;
  9. /**
  10. * Class BuilderFactory
  11. */
  12. class BuilderFactory
  13. {
  14. /**#@+
  15. * Allowed builder types
  16. */
  17. const TYPE_LAYOUT = 'layout';
  18. const TYPE_PAGE = 'page';
  19. /**#@-*/
  20. /**#@-*/
  21. protected $typeMap = [
  22. self::TYPE_LAYOUT => \Magento\Framework\View\Layout\Builder::class,
  23. self::TYPE_PAGE => \Magento\Framework\View\Page\Builder::class,
  24. ];
  25. /**
  26. * @var ObjectManagerInterface
  27. */
  28. protected $objectManager;
  29. /**
  30. * Constructor
  31. *
  32. * @param ObjectManagerInterface $objectManager
  33. * @param array $typeMap
  34. */
  35. public function __construct(
  36. ObjectManagerInterface $objectManager,
  37. array $typeMap = []
  38. ) {
  39. $this->objectManager = $objectManager;
  40. $this->mergeTypes($typeMap);
  41. }
  42. /**
  43. * Add or override builder types
  44. *
  45. * @param array $typeMap
  46. * @return void
  47. */
  48. protected function mergeTypes(array $typeMap)
  49. {
  50. foreach ($typeMap as $typeInfo) {
  51. if (isset($typeInfo['type']) && isset($typeInfo['class'])) {
  52. $this->typeMap[$typeInfo['type']] = $typeInfo['class'];
  53. }
  54. }
  55. }
  56. /**
  57. * Create builder instance
  58. *
  59. * @param string $type
  60. * @param array $arguments
  61. * @throws \InvalidArgumentException
  62. * @return BuilderInterface
  63. */
  64. public function create($type, array $arguments)
  65. {
  66. if (empty($this->typeMap[$type])) {
  67. throw new \InvalidArgumentException('"' . $type . ': isn\'t allowed');
  68. }
  69. $builderInstance = $this->objectManager->create($this->typeMap[$type], $arguments);
  70. if (!$builderInstance instanceof BuilderInterface) {
  71. throw new \InvalidArgumentException(get_class($builderInstance) . ' isn\'t instance of BuilderInterface');
  72. }
  73. return $builderInstance;
  74. }
  75. }