Compare.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Quote\Model\Quote\Item;
  7. use Magento\Quote\Model\Quote\Item;
  8. use Magento\Framework\Serialize\Serializer\Json;
  9. use Magento\Framework\App\ObjectManager;
  10. use Magento\Framework\Serialize\JsonValidator;
  11. /**
  12. * Compare quote items
  13. */
  14. class Compare
  15. {
  16. /**
  17. * @var Json
  18. */
  19. private $serializer;
  20. /**
  21. * @var JsonValidator
  22. */
  23. private $jsonValidator;
  24. /**
  25. * Constructor
  26. *
  27. * @param Json|null $serializer
  28. * @param JsonValidator|null $jsonValidator
  29. */
  30. public function __construct(
  31. Json $serializer = null,
  32. JsonValidator $jsonValidator = null
  33. ) {
  34. $this->serializer = $serializer ?: ObjectManager::getInstance()->get(Json::class);
  35. $this->jsonValidator = $jsonValidator ?: ObjectManager::getInstance()->get(JsonValidator::class);
  36. }
  37. /**
  38. * Returns option values adopted to compare
  39. *
  40. * @param mixed $value
  41. * @return mixed
  42. */
  43. protected function getOptionValues($value)
  44. {
  45. if (is_string($value) && $this->jsonValidator->isValid($value)) {
  46. $value = $this->serializer->unserialize($value);
  47. if (is_array($value)) {
  48. unset($value['qty'], $value['uenc']);
  49. $value = array_filter($value, function ($optionValue) {
  50. return !empty($optionValue);
  51. });
  52. }
  53. }
  54. return $value;
  55. }
  56. /**
  57. * Compare two quote items
  58. *
  59. * @param Item $target
  60. * @param Item $compared
  61. * @return bool
  62. */
  63. public function compare(Item $target, Item $compared)
  64. {
  65. if ($target->getProductId() != $compared->getProductId()) {
  66. return false;
  67. }
  68. $targetOptions = $this->getOptions($target);
  69. $comparedOptions = $this->getOptions($compared);
  70. if (array_diff_key($targetOptions, $comparedOptions) != array_diff_key($comparedOptions, $targetOptions)
  71. ) {
  72. return false;
  73. }
  74. foreach ($targetOptions as $name => $value) {
  75. if ($comparedOptions[$name] != $value) {
  76. return false;
  77. }
  78. }
  79. return true;
  80. }
  81. /**
  82. * Returns options adopted to compare
  83. *
  84. * @param Item $item
  85. * @return array
  86. */
  87. public function getOptions(Item $item)
  88. {
  89. $options = [];
  90. foreach ($item->getOptions() as $option) {
  91. $options[$option->getCode()] = $this->getOptionValues($option->getValue());
  92. }
  93. return $options;
  94. }
  95. }