TotalsReader.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Quote\Model\Quote;
  7. use Magento\Quote\Model\Quote\Address\Total;
  8. use Magento\Quote\Model\Quote\Address\Total\ReaderInterface;
  9. class TotalsReader
  10. {
  11. /**
  12. * @var \Magento\Quote\Model\Quote\Address\TotalFactory
  13. */
  14. protected $totalFactory;
  15. /**
  16. * @var \Magento\Quote\Model\Quote\TotalsCollectorList
  17. */
  18. protected $collectorList;
  19. /**
  20. * @param Address\TotalFactory $totalFactory
  21. * @param TotalsCollectorList $collectorList
  22. */
  23. public function __construct(
  24. \Magento\Quote\Model\Quote\Address\TotalFactory $totalFactory,
  25. \Magento\Quote\Model\Quote\TotalsCollectorList $collectorList
  26. ) {
  27. $this->totalFactory = $totalFactory;
  28. $this->collectorList = $collectorList;
  29. }
  30. /**
  31. * @param \Magento\Quote\Model\Quote $quote
  32. * @param array $total
  33. * @return Total[]
  34. */
  35. public function fetch(\Magento\Quote\Model\Quote $quote, array $total)
  36. {
  37. $output = [];
  38. $total = $this->totalFactory->create()->setData($total);
  39. /** @var ReaderInterface $reader */
  40. foreach ($this->collectorList->getCollectors($quote->getStoreId()) as $reader) {
  41. $data = $reader->fetch($quote, $total);
  42. if ($data === null || empty($data)) {
  43. continue;
  44. }
  45. $totalInstance = $this->convert($data);
  46. if (is_array($totalInstance)) {
  47. foreach ($totalInstance as $item) {
  48. $output = $this->merge($item, $output);
  49. }
  50. } else {
  51. $output = $this->merge($totalInstance, $output);
  52. }
  53. }
  54. return $output;
  55. }
  56. /**
  57. * @param array $total
  58. * @return Total|Total[]
  59. */
  60. protected function convert($total)
  61. {
  62. if ($total instanceof Total) {
  63. return $total;
  64. }
  65. if (count(array_column($total, 'code')) > 0) {
  66. $totals = [];
  67. foreach ($total as $item) {
  68. $totals[] = $this->totalFactory->create()->setData($item);
  69. }
  70. return $totals;
  71. }
  72. return $this->totalFactory->create()->setData($total);
  73. }
  74. /**
  75. * @param Total $totalInstance
  76. * @param Total[] $output
  77. * @return Total[]
  78. */
  79. protected function merge(Total $totalInstance, $output)
  80. {
  81. if (array_key_exists($totalInstance->getCode(), $output)) {
  82. $output[$totalInstance->getCode()] = $output[$totalInstance->getCode()]->addData(
  83. $totalInstance->getData()
  84. );
  85. } else {
  86. $output[$totalInstance->getCode()] = $totalInstance;
  87. }
  88. return $output;
  89. }
  90. }