UpdateHandler.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Downloadable\Model\Sample;
  7. use Magento\Downloadable\Api\SampleRepositoryInterface as SampleRepository;
  8. use Magento\Downloadable\Model\Product\Type;
  9. use Magento\Framework\EntityManager\Operation\ExtensionInterface;
  10. /**
  11. * Class UpdateHandler
  12. */
  13. class UpdateHandler implements ExtensionInterface
  14. {
  15. /**
  16. * @var SampleRepository
  17. */
  18. protected $sampleRepository;
  19. /**
  20. * @param SampleRepository $sampleRepository
  21. */
  22. public function __construct(SampleRepository $sampleRepository)
  23. {
  24. $this->sampleRepository = $sampleRepository;
  25. }
  26. /**
  27. * @param object $entity
  28. * @param array $arguments
  29. * @return \Magento\Catalog\Api\Data\ProductInterface|object
  30. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  31. */
  32. public function execute($entity, $arguments = [])
  33. {
  34. /** @var $entity \Magento\Catalog\Api\Data\ProductInterface */
  35. if ($entity->getTypeId() != Type::TYPE_DOWNLOADABLE) {
  36. return $entity;
  37. }
  38. /** @var \Magento\Downloadable\Api\Data\SampleInterface[] $samples */
  39. $samples = $entity->getExtensionAttributes()->getDownloadableProductSamples() ?: [];
  40. $updatedSamples = [];
  41. $oldSamples = $this->sampleRepository->getList($entity->getSku());
  42. foreach ($samples as $sample) {
  43. if ($sample->getId()) {
  44. $updatedSamples[$sample->getId()] = true;
  45. }
  46. $this->sampleRepository->save($entity->getSku(), $sample, !(bool)$entity->getStoreId());
  47. }
  48. /** @var \Magento\Catalog\Api\Data\ProductInterface $entity */
  49. foreach ($oldSamples as $sample) {
  50. if (!isset($updatedSamples[$sample->getId()])) {
  51. $this->sampleRepository->delete($sample->getId());
  52. }
  53. }
  54. return $entity;
  55. }
  56. }