MassSubscribe.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Controller\Adminhtml\Index;
  7. use Magento\Backend\App\Action\Context;
  8. use Magento\Ui\Component\MassAction\Filter;
  9. use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
  10. use Magento\Customer\Api\CustomerRepositoryInterface;
  11. use Magento\Newsletter\Model\SubscriberFactory;
  12. use Magento\Eav\Model\Entity\Collection\AbstractCollection;
  13. use Magento\Framework\Controller\ResultFactory;
  14. /**
  15. * Class MassSubscribe
  16. */
  17. class MassSubscribe extends AbstractMassAction
  18. {
  19. /**
  20. * @var CustomerRepositoryInterface
  21. */
  22. protected $customerRepository;
  23. /**
  24. * @var SubscriberFactory
  25. */
  26. protected $subscriberFactory;
  27. /**
  28. * @param Context $context
  29. * @param Filter $filter
  30. * @param CollectionFactory $collectionFactory
  31. * @param CustomerRepositoryInterface $customerRepository
  32. * @param SubscriberFactory $subscriberFactory
  33. */
  34. public function __construct(
  35. Context $context,
  36. Filter $filter,
  37. CollectionFactory $collectionFactory,
  38. CustomerRepositoryInterface $customerRepository,
  39. SubscriberFactory $subscriberFactory
  40. ) {
  41. parent::__construct($context, $filter, $collectionFactory);
  42. $this->customerRepository = $customerRepository;
  43. $this->subscriberFactory = $subscriberFactory;
  44. }
  45. /**
  46. * Customer mass subscribe action
  47. *
  48. * @param AbstractCollection $collection
  49. * @return \Magento\Backend\Model\View\Result\Redirect
  50. */
  51. protected function massAction(AbstractCollection $collection)
  52. {
  53. $customersUpdated = 0;
  54. foreach ($collection->getAllIds() as $customerId) {
  55. // Verify customer exists
  56. $this->customerRepository->getById($customerId);
  57. $this->subscriberFactory->create()->subscribeCustomerById($customerId);
  58. $customersUpdated++;
  59. }
  60. if ($customersUpdated) {
  61. $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', $customersUpdated));
  62. }
  63. /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
  64. $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
  65. $resultRedirect->setPath($this->getComponentRefererUrl());
  66. return $resultRedirect;
  67. }
  68. }