custom/plugins/VioB2BLogin/src/Entity/Employee/Subscriber/ImportSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace VioB2BLogin\Entity\Employee\Subscriber;
  4. use Shopware\Core\Content\ImportExport\Event\ImportExportBeforeImportRecordEvent;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class ImportSubscriber implements EventSubscriberInterface
  9. {
  10.     private EntityRepository $employeeRepository;
  11.     public function __construct(
  12.         EntityRepository $employeeRepository
  13.     ) {
  14.         $this->employeeRepository $employeeRepository;
  15.     }
  16.     /**
  17.      * @inheritDoc
  18.      */
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             ImportExportBeforeImportRecordEvent::class => 'onImportExportBeforeImportRecord'
  23.         ];
  24.     }
  25.     public function onImportExportBeforeImportRecord(ImportExportBeforeImportRecordEvent $event): void
  26.     {
  27.         // check if the row is new or updated
  28.         $isNew false;
  29.         $record $event->getRecord();
  30.         $id $record['id'] ?? null;
  31.         if (!empty($id)) {
  32.             // updated record
  33.             $id $this->employeeRepository->searchIds(new Criteria([$id]), $event->getContext())->firstId();
  34.         }
  35.         if (empty($id)) {
  36.             // new record
  37.             $isNew true;
  38.         }
  39.         if(!array_key_exists('password'$record) && $isNew ){
  40.             // generate password
  41.             $record['password'] = $this->generatePassword();
  42.             $event->setRecord($record);
  43.         }
  44.     }
  45.     private function generatePassword(): string
  46.     {
  47.         $alphabet 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  48.         $pass = array();
  49.         $alphaLength strlen($alphabet) - 1;
  50.         for ($i 0$i 8$i++) {
  51.             $n rand(0$alphaLength);
  52.             $pass[] = $alphabet[$n];
  53.         }
  54.         return implode($pass);
  55.     }
  56. }