ConditionFactory.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Rule\Model;
  7. use Magento\Framework\ObjectManagerInterface;
  8. use Magento\Rule\Model\Condition\ConditionInterface;
  9. class ConditionFactory
  10. {
  11. /**
  12. * @var ObjectManagerInterface
  13. */
  14. private $objectManager;
  15. /**
  16. * Store all used condition models
  17. *
  18. * @var array
  19. */
  20. private $conditionModels = [];
  21. /**
  22. * @param ObjectManagerInterface $objectManager
  23. */
  24. public function __construct(ObjectManagerInterface $objectManager)
  25. {
  26. $this->objectManager = $objectManager;
  27. }
  28. /**
  29. * Create new object for each requested model.
  30. * If model is requested first time, store it at array.
  31. * It's made by performance reasons to avoid initialization of same models each time when rules are being processed.
  32. *
  33. * @param string $type
  34. *
  35. * @return \Magento\Rule\Model\Condition\ConditionInterface
  36. *
  37. * @throws \LogicException
  38. * @throws \BadMethodCallException
  39. * @throws \InvalidArgumentException
  40. */
  41. public function create($type)
  42. {
  43. if (!array_key_exists($type, $this->conditionModels)) {
  44. if (!class_exists($type)) {
  45. throw new \InvalidArgumentException('Class does not exist');
  46. }
  47. if (!in_array(ConditionInterface::class, class_implements($type))) {
  48. throw new \InvalidArgumentException('Class does not implement condition interface');
  49. }
  50. $this->conditionModels[$type] = $this->objectManager->create($type);
  51. }
  52. return clone $this->conditionModels[$type];
  53. }
  54. }