Collection.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Pricing\Adjustment;
  7. /**
  8. * Adjustment collection model
  9. *
  10. * @api
  11. * @since 100.0.2
  12. */
  13. class Collection
  14. {
  15. /**
  16. * @var Pool
  17. */
  18. protected $adjustmentPool;
  19. /**
  20. * @var string[]
  21. */
  22. protected $adjustments;
  23. /**
  24. * @var AdjustmentInterface[]
  25. */
  26. protected $adjustmentInstances;
  27. /**
  28. * @param Pool $adjustmentPool
  29. * @param string[] $adjustments
  30. */
  31. public function __construct(
  32. Pool $adjustmentPool,
  33. array $adjustments
  34. ) {
  35. $this->adjustmentPool = $adjustmentPool;
  36. $this->adjustments = $adjustments;
  37. }
  38. /**
  39. * @return AdjustmentInterface[]
  40. */
  41. public function getItems()
  42. {
  43. if ($this->adjustmentInstances === null) {
  44. $this->adjustmentInstances = $this->fetchAdjustments($this->adjustments);
  45. }
  46. return $this->adjustmentInstances;
  47. }
  48. /**
  49. * Get adjustment by code
  50. *
  51. * @param string $adjustmentCode
  52. * @throws \InvalidArgumentException
  53. * @return AdjustmentInterface
  54. */
  55. public function getItemByCode($adjustmentCode)
  56. {
  57. if ($this->adjustmentInstances === null) {
  58. $this->adjustmentInstances = $this->fetchAdjustments($this->adjustments);
  59. }
  60. if (!isset($this->adjustmentInstances[$adjustmentCode])) {
  61. throw new \InvalidArgumentException(sprintf('Price adjustment "%s" is not found', $adjustmentCode));
  62. }
  63. return $this->adjustmentInstances[$adjustmentCode];
  64. }
  65. /**
  66. * @param string[] $adjustments
  67. * @return AdjustmentInterface[]
  68. */
  69. protected function fetchAdjustments($adjustments)
  70. {
  71. $instances = [];
  72. foreach ($adjustments as $code) {
  73. $instances[$code] = $this->adjustmentPool->getAdjustmentByCode($code);
  74. }
  75. uasort($instances, [$this, 'sortAdjustments']);
  76. return $instances;
  77. }
  78. /**
  79. * Sort adjustments
  80. *
  81. * @param AdjustmentInterface $firstAdjustment
  82. * @param AdjustmentInterface $secondAdjustment
  83. * @return int
  84. */
  85. protected function sortAdjustments(AdjustmentInterface $firstAdjustment, AdjustmentInterface $secondAdjustment)
  86. {
  87. if ($firstAdjustment->getSortOrder() === \Magento\Framework\Pricing\Adjustment\Pool::DEFAULT_SORT_ORDER) {
  88. return 1;
  89. }
  90. return $firstAdjustment->getSortOrder() > $secondAdjustment->getSortOrder() ? 1 : -1;
  91. }
  92. }