custom/plugins/SelfdelveCms/src/Subscriber/CustomerWrittenSubscriber.php line 68

Open in your IDE?
  1. <?php
  2.     namespace Selfdelve\Cms\Subscriber;
  3.     use Psr\Log\LoggerInterface;
  4.     use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5.     use Shopware\Core\Checkout\Customer\CustomerEvents;
  6.     use Shopware\Core\Checkout\Customer\CustomerEntity;
  7.     use Shopware\Core\Content\Mail\Service\AbstractMailService;
  8.     use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  9.     use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  10.     use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
  11.     use Shopware\Core\Framework\Api\Context\AdminApiSource;
  12.     use Shopware\Core\Framework\Validation\DataBag\DataBag;
  13.     use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  14.     use Shopware\Core\Content\MailTemplate\MailTemplateEntity;
  15.     use Shopware\Core\System\SystemConfig\SystemConfigService;
  16.     class CustomerWrittenSubscriber implements EventSubscriberInterface
  17.     {
  18.         private LoggerInterface $logger;
  19.         private EntityRepositoryInterface $customerRepository;
  20.         private EntityRepositoryInterface $mailTemplateRepository;
  21.         private AbstractMailService $mailService;
  22.         private SystemConfigService $systemConfigService;
  23.         /**
  24.          * CustomerWrittenSubscriber constructor.
  25.          *
  26.          * @param LoggerInterface $logger
  27.          * @param EntityRepositoryInterface $customerRepository
  28.          * @param EntityRepositoryInterface $mailTemplateRepository
  29.          * @param AbstractMailService $mailService
  30.          * @param SystemConfigService $systemConfigService
  31.          */
  32.         public function __construct(
  33.             LoggerInterface $logger,
  34.             EntityRepositoryInterface $customerRepository,
  35.             EntityRepositoryInterface $mailTemplateRepository,
  36.             AbstractMailService $mailService,
  37.             SystemConfigService $systemConfigService
  38.         ) {
  39.             $this->logger $logger;
  40.             $this->customerRepository $customerRepository;
  41.             $this->mailTemplateRepository $mailTemplateRepository;
  42.             $this->mailService $mailService;
  43.             $this->systemConfigService $systemConfigService;
  44.         }
  45.         /**
  46.          * @return array
  47.          */
  48.         public static function getSubscribedEvents(): array
  49.         {
  50.             return [
  51.                 CustomerEvents::CUSTOMER_WRITTEN_EVENT => 'onCustomerWritten',
  52.             ];
  53.         }
  54.         /**
  55.          * Send an email with user credentials if an user creates a customer in the backend.
  56.          *
  57.          * @param EntityWrittenEvent $event
  58.          */
  59.         public function onCustomerWritten(EntityWrittenEvent $event): void
  60.         {
  61.             // Check backend context
  62.             if (!$event->getContext()->getSource() instanceof AdminApiSource) {
  63.                 return;
  64.             }
  65.             // Check insert
  66.             $insertWriteResult null;
  67.             foreach ($event->getWriteResults() as $res) {
  68.                 if ($res->getOperation() === EntityWriteResult::OPERATION_INSERT) {
  69.                     $insertWriteResult $res;
  70.                     break;
  71.                 }
  72.             }
  73.             if (!$insertWriteResult instanceof EntityWriteResult) {
  74.                 return;
  75.             }
  76.             $id $insertWriteResult->getProperty('id');
  77.             /** @var CustomerEntity $customer */
  78.             $customer $this->customerRepository->search(
  79.                 new Criteria([$id]),
  80.                 $event->getContext()
  81.             )->first();
  82.             if (!$customer instanceof CustomerEntity) {
  83.                 return;
  84.             }
  85.             // Only accounts, no guests
  86.             if ($customer->getGuest() === true) {
  87.                 return;
  88.             }
  89.             // Initial password
  90.             $pass $this->generateRandomString();
  91.             $this->customerRepository->update([
  92.                 [
  93.                     'id' => $id,
  94.                     'password' => $pass
  95.                 ]
  96.             ], $event->getContext());
  97.             $mailTemplateId $this->systemConfigService->get('SelfdelveCms.config.creationTemplateId');
  98.             /** @var MailTemplateEntity $mailTemplate */
  99.             $mailTemplate $this->mailTemplateRepository->search(
  100.                 new Criteria([
  101.                     $mailTemplateId
  102.                 ]),
  103.                 $event->getContext()
  104.             )->first();
  105.             if (!$mailTemplate) {
  106.                 $this->logger->error(
  107.                     sprintf('Could not find email template for id %s.'$mailTemplateId)
  108.                 );
  109.                 return;
  110.             }
  111.             $data = new DataBag();
  112.             $data->set('salesChannelId'$customer->getSalesChannelId());
  113.             $data->set('templateId'$mailTemplate->getId());
  114.             $data->set('recipients', [
  115.                 $customer->getEmail() => trim($customer->__toString())
  116.             ]);
  117.             $data->set('senderName'$mailTemplate->getTranslation('senderName'));
  118.             $data->set('subject'$mailTemplate->getTranslation('subject'));
  119.             $data->set('contentHtml'$mailTemplate->getTranslation('contentHtml'));
  120.             $data->set('contentPlain'$mailTemplate->getTranslation('contentPlain'));
  121.             if (!$this->mailService->send(
  122.                 $data->all(),
  123.                 $event->getContext(),
  124.                 [
  125.                     'customer' => $customer,
  126.                     'pass' => $pass
  127.                 ]
  128.             )) {
  129.                 $this->logger->error(
  130.                     sprintf('Could not send customer creation email to %s.'$customer->getEmail())
  131.                 );
  132.                 return;
  133.             }
  134.             $this->logger->info(
  135.                 sprintf('Customer with email %s was informed about its new account.'$customer->getEmail())
  136.             );
  137.         }
  138.         /**
  139.          * Generates a random string for the intial password.
  140.          *
  141.          * @param int $length
  142.          * @return string
  143.          */
  144.         private function generateRandomString($length 15) {
  145.             $characters '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ_=.-';
  146.             $charactersLength strlen($characters);
  147.             $randomString '';
  148.             for ($i 0$i $length$i++) {
  149.                 $randomString .= $characters[rand(0$charactersLength 1)];
  150.             }
  151.             return $randomString;
  152.         }
  153.     }