<?php
declare(strict_types=1);
namespace VioB2BLogin\Entity\Employee\Subscriber;
use Shopware\Core\Content\ImportExport\Event\ImportExportBeforeImportRecordEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ImportSubscriber implements EventSubscriberInterface
{
private EntityRepository $employeeRepository;
public function __construct(
EntityRepository $employeeRepository
) {
$this->employeeRepository = $employeeRepository;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
ImportExportBeforeImportRecordEvent::class => 'onImportExportBeforeImportRecord'
];
}
public function onImportExportBeforeImportRecord(ImportExportBeforeImportRecordEvent $event): void
{
// check if the row is new or updated
$isNew = false;
$record = $event->getRecord();
$id = $record['id'] ?? null;
if (!empty($id)) {
// updated record
$id = $this->employeeRepository->searchIds(new Criteria([$id]), $event->getContext())->firstId();
}
if (empty($id)) {
// new record
$isNew = true;
}
if(!array_key_exists('password', $record) && $isNew ){
// generate password
$record['password'] = $this->generatePassword();
$event->setRecord($record);
}
}
private function generatePassword(): string
{
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass);
}
}