<?php
declare(strict_types=1);
namespace Wbfk\ITScope\Subscriber;
use Doctrine\DBAL\Connection;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSavedSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
EntityWrittenContainerEvent::class => 'onProductWritten',
];
}
public function __construct(
protected Connection $connection,
protected EntityRepository $wbfkItScopeProductExtRepo
)
{
}
public function onProductWritten(EntityWrittenContainerEvent $event): void
{
if (!$event = $event->getEventByEntityName(ProductDefinition::ENTITY_NAME)) {
return;
}
if (!$this->hasProductWbfkItScopeEntityExtention($event->getWriteResults())) {
$this->createWbfkItScopeEntityExtension($event->getWriteResults());
}
}
protected function hasProductWbfkItScopeEntityExtention(array $writeResults): bool
{
return $this->executeFunctionForProductWriteResult($writeResults, function ($writeResult) {
$stmt = $this->connection->prepare('SELECT id FROM wbfk_it_scope_product_extension WHERE product_id = UNHEX(?)');
$stmt->executeQuery([$writeResult->getPrimaryKey()]);
return $stmt->rowCount() > 0;
});
}
protected function createWbfkItScopeEntityExtension(array $writeResults): void
{
$this->executeFunctionForProductWriteResult($writeResults, function ($writeResult) {
$payload = $writeResult->getPayload();
if (array_key_exists('id', $payload) && array_key_exists('versionId', $payload)) {
$this->wbfkItScopeProductExtRepo->create([
[
'productId' => $payload['id'],
'productVersionId' => $payload['versionId'],
]
], Context::createDefaultContext());
return true;
}
return false;
});
}
protected function executeFunctionForProductWriteResult(array $writeResults, callable $callback): bool
{
foreach ($writeResults as $writeResult) {
if (
$writeResult->getEntityName() === ProductDefinition::ENTITY_NAME &&
($writeResult->getOperation() === EntityWriteResult::OPERATION_INSERT || $writeResult->getOperation() === EntityWriteResult::OPERATION_UPDATE)) {
return $callback($writeResult);
}
}
return false;
}
}