<?php
namespace Klikensteen\ThemeCustomChanges\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Framework\Event\DataMappingEvent;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
/**
* Class AllVariantDetailPage
*
* Used to collect the information of the variants
*/
class AddressChangedSubscriber implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var Connection
*/
private $connection;
/**
* @var RequestStack
*/
protected RequestStack $requestStack;
/**
* @var EntityRepository
*/
private EntityRepository $customerRepo;
public function __construct(
ContainerInterface $container,
RequestStack $requestStack,
EntityRepository $customerRepo
) {
$this->container = $container;
$this->requestStack = $requestStack;
$this->connection = $this->container->get(Connection::class);
$this->customerRepo = $customerRepo;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
CustomerEvents::MAPPING_ADDRESS_CREATE => 'onAddessSave',
// CustomerEvents::CUSTOMER_ADDRESS_WRITTEN_EVENT => 'onAddessSave',
// ProductListingCriteriaEvent::class => 'onProductListingCriteria'
];
}
public function onAddessSave(DataMappingEvent $event)
{
$request = $this->requestStack->getMainRequest();
$customFields = $request->request->get('custom_fields');
$vatIds = $request->request->get('vatIds');
$customer = $request->attributes->get('sw-sales-channel-context')->getCustomer();
$kvkNumber = $customFields['kvk_number'];
$orderReference = $customFields['order_reference'];
if ($customFields) {
try {
$this->connection->executeStatement(
'UPDATE customer
SET custom_fields = JSON_SET(
custom_fields,
"$.kvk_number",
' . $kvkNumber . '
) WHERE id = :customer_id',
['customer_id' => Uuid::fromHexToBytes($customer->id)]
);
$this->connection->executeStatement(
'UPDATE customer
SET custom_fields = JSON_SET(
custom_fields,
"$.order_reference",
' . $orderReference . '
) WHERE id = :customer_id',
['customer_id' => Uuid::fromHexToBytes($customer->id)]
);
} catch (\Exception $e) {
dump($e);
}
if ($vatIds[0] != "") {
$this->customerRepo->update([
[
'id' => $customer->id,
'vatIds' => $vatIds
]
], Context::createDefaultContext());
}
}
}
public function onProductListingCriteria(ProductListingCriteriaEvent $event)
{
$criteria = $event->getCriteria();
$event->getCriteria()->addAssociation('properties');
$event->getCriteria()->addAssociation('properties.group');
}
}