DataObject.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View\Layout\Argument\Interpreter;
  7. use Magento\Framework\Data\Argument\InterpreterInterface;
  8. use Magento\Framework\ObjectManagerInterface;
  9. /**
  10. * Interpreter that instantiates object by a class name
  11. */
  12. class DataObject implements InterpreterInterface
  13. {
  14. /**
  15. * @var ObjectManagerInterface
  16. */
  17. private $objectManager;
  18. /**
  19. * @var string|null
  20. */
  21. private $expectedClass;
  22. /**
  23. * @param ObjectManagerInterface $objectManager
  24. * @param string|null $expectedClass
  25. */
  26. public function __construct(ObjectManagerInterface $objectManager, $expectedClass = null)
  27. {
  28. $this->objectManager = $objectManager;
  29. $this->expectedClass = $expectedClass;
  30. }
  31. /**
  32. * {@inheritdoc}
  33. * @return object
  34. * @throws \InvalidArgumentException
  35. * @throws \UnexpectedValueException
  36. */
  37. public function evaluate(array $data)
  38. {
  39. if (!isset($data['value'])) {
  40. throw new \InvalidArgumentException('Object class name is missing.');
  41. }
  42. $className = $data['value'];
  43. $result = $this->objectManager->create($className);
  44. if ($this->expectedClass && !$result instanceof $this->expectedClass) {
  45. throw new \UnexpectedValueException(
  46. sprintf("Instance of %s is expected, got %s instead.", $this->expectedClass, get_class($result))
  47. );
  48. }
  49. return $result;
  50. }
  51. }