SwitchPriceAttributeScopeOnConfigChange.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Catalog\Observer;
  7. use Magento\Framework\Event\Observer as EventObserver;
  8. use Magento\Framework\Event\ObserverInterface;
  9. use Magento\Catalog\Api\Data\ProductAttributeInterface;
  10. use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
  11. use Magento\Store\Model\Store;
  12. use Magento\Framework\App\Config\ReinitableConfigInterface;
  13. use Magento\Framework\Api\SearchCriteriaBuilder;
  14. /**
  15. * Observer is responsible for changing scope for all price attributes in system
  16. * depending on 'Catalog Price Scope' configuration parameter
  17. */
  18. class SwitchPriceAttributeScopeOnConfigChange implements ObserverInterface
  19. {
  20. /**
  21. * @var ReinitableConfigInterface
  22. */
  23. private $config;
  24. /**
  25. * @var ProductAttributeRepositoryInterface
  26. */
  27. private $productAttributeRepository;
  28. /**
  29. * @var SearchCriteriaBuilder
  30. */
  31. private $searchCriteriaBuilder;
  32. /**
  33. * @param ReinitableConfigInterface $config
  34. * @param ProductAttributeRepositoryInterface $productAttributeRepository
  35. * @param SearchCriteriaBuilder $searchCriteriaBuilder
  36. */
  37. public function __construct(
  38. ReinitableConfigInterface $config,
  39. ProductAttributeRepositoryInterface $productAttributeRepository,
  40. SearchCriteriaBuilder $searchCriteriaBuilder
  41. ) {
  42. $this->config = $config;
  43. $this->productAttributeRepository = $productAttributeRepository;
  44. $this->searchCriteriaBuilder = $searchCriteriaBuilder;
  45. }
  46. /**
  47. * Change scope for all price attributes according to
  48. * 'Catalog Price Scope' configuration parameter value
  49. *
  50. * @param EventObserver $observer
  51. * @return void
  52. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  53. */
  54. public function execute(EventObserver $observer)
  55. {
  56. $this->searchCriteriaBuilder->addFilter('frontend_input', 'price');
  57. $criteria = $this->searchCriteriaBuilder->create();
  58. $scope = $this->config->getValue(Store::XML_PATH_PRICE_SCOPE);
  59. $scope = ($scope == Store::PRICE_SCOPE_WEBSITE)
  60. ? ProductAttributeInterface::SCOPE_WEBSITE_TEXT
  61. : ProductAttributeInterface::SCOPE_GLOBAL_TEXT;
  62. $priceAttributes = $this->productAttributeRepository->getList($criteria)->getItems();
  63. /** @var ProductAttributeInterface $priceAttribute */
  64. foreach ($priceAttributes as $priceAttribute) {
  65. $priceAttribute->setScope($scope);
  66. $this->productAttributeRepository->save($priceAttribute);
  67. }
  68. }
  69. }