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\Link;
  7. use Magento\Downloadable\Api\LinkRepositoryInterface as LinkRepository;
  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 LinkRepository
  17. */
  18. protected $linkRepository;
  19. /**
  20. * @param LinkRepository $linkRepository
  21. */
  22. public function __construct(LinkRepository $linkRepository)
  23. {
  24. $this->linkRepository = $linkRepository;
  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\LinkInterface[] $links */
  39. $links = $entity->getExtensionAttributes()->getDownloadableProductLinks() ?: [];
  40. $updatedLinks = [];
  41. $oldLinks = $this->linkRepository->getList($entity->getSku());
  42. foreach ($links as $link) {
  43. if ($link->getId()) {
  44. $updatedLinks[$link->getId()] = true;
  45. }
  46. $this->linkRepository->save($entity->getSku(), $link, !(bool)$entity->getStoreId());
  47. }
  48. /** @var \Magento\Catalog\Api\Data\ProductInterface $entity */
  49. foreach ($oldLinks as $link) {
  50. if (!isset($updatedLinks[$link->getId()])) {
  51. $this->linkRepository->delete($link->getId());
  52. }
  53. }
  54. return $entity;
  55. }
  56. }