Composite.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Ui\Config\Converter;
  7. use Magento\Ui\Config\ConverterInterface;
  8. /**
  9. * Composite converter
  10. *
  11. * Identify required converter
  12. */
  13. class Composite implements ConverterInterface
  14. {
  15. /**
  16. * Format: array('<name>' => <instance>, ...)
  17. *
  18. * @var ConverterInterface[]
  19. */
  20. private $converters;
  21. /**
  22. * Data key that holds name of an converter to be used for that data
  23. *
  24. * @var string
  25. */
  26. private $discriminator;
  27. /**
  28. * @param ConverterInterface[] $converters
  29. * @param string $discriminator
  30. * @throws \InvalidArgumentException
  31. */
  32. public function __construct(array $converters, $discriminator)
  33. {
  34. foreach ($converters as $converterName => $converterInstance) {
  35. if (!$converterInstance instanceof ConverterInterface) {
  36. throw new \InvalidArgumentException(
  37. "Converter named '{$converterName}' is expected to be an argument converter instance."
  38. );
  39. }
  40. }
  41. $this->converters = $converters;
  42. $this->discriminator = $discriminator;
  43. }
  44. /**
  45. * @inheritdoc
  46. * @throws \InvalidArgumentException
  47. */
  48. public function convert(\DOMNode $node, array $data)
  49. {
  50. if (!isset($data[$this->discriminator])) {
  51. throw new \InvalidArgumentException(
  52. sprintf('Value for key "%s" is missing in the argument data.', $this->discriminator)
  53. );
  54. }
  55. $converterName = $data[$this->discriminator];
  56. unset($data[$this->discriminator]);
  57. $converter = $this->getConverter($converterName);
  58. return $converter->convert($node, $data);
  59. }
  60. /**
  61. * Register parser instance under a given unique name
  62. *
  63. * @param string $name
  64. * @param ConverterInterface $instance
  65. * @return void
  66. * @throws \InvalidArgumentException
  67. */
  68. public function addConverter($name, ConverterInterface $instance)
  69. {
  70. if (isset($this->converters[$name])) {
  71. throw new \InvalidArgumentException("Argument converter named '{$name}' has already been defined.");
  72. }
  73. $this->converters[$name] = $instance;
  74. }
  75. /**
  76. * Retrieve parser instance by its unique name
  77. *
  78. * @param string $name
  79. * @return ConverterInterface
  80. * @throws \InvalidArgumentException
  81. */
  82. private function getConverter($name)
  83. {
  84. if (!isset($this->converters[$name])) {
  85. throw new \InvalidArgumentException("Argument converter named '{$name}' has not been defined.");
  86. }
  87. return $this->converters[$name];
  88. }
  89. }