<?php
namespace B2bOffer\Subscriber;
use B2bOffer\Components\Offer\Aggregate\OfferCustomer\OfferCustomerEntity;
use B2bOffer\Components\Offer\OfferEntity;
use B2bSellersCore\Components\Customer\CustomerDisplayName;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerDisplayNameSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
'b2b_offer.loaded' => 'onOfferLoadedAddDisplayName',
'b2b_offer_customer.loaded' => 'onOfferCustomerLoadedAddDisplayName'
];
}
public function onOfferLoadedAddDisplayName(EntityLoadedEvent $event): void
{
/** @var OfferEntity $offerEntity */
foreach ($event->getEntities() as $offerEntity) {
if ($offerEntity->getOfferCustomer()) {
$this->addDisplayNameExtension($offerEntity->getOfferCustomer());
if ($offerEntity->getOfferCustomer()->getCustomer()) {
$this->addDisplayNameExtension($offerEntity->getOfferCustomer()->getCustomer());
}
}
}
}
public function onOfferCustomerLoadedAddDisplayName(EntityLoadedEvent $event): void
{
/** @var OfferCustomerEntity $offerCustomerEntity */
foreach ($event->getEntities() as $offerCustomerEntity) {
$this->addDisplayNameExtension($offerCustomerEntity);
if ($offerCustomerEntity->getCustomer()) {
$this->addDisplayNameExtension($offerCustomerEntity->getCustomer());
}
}
}
private function addDisplayNameExtension($entity): void
{
$shortName = $entity->getFirstName() . ' ' . $entity->getLastName();
$name = $shortName;
$longName = $shortName;
if (!empty($entity->getTitle())) {
$longName = $entity->getTitle() . ' ' . $shortName;
}
if ($entity->getSalutation() && $entity->getSalutation()->getSalutationKey() !== 'not_specified') {
$name = $entity->getSalutation()->getTranslation('displayName') . ' ' . $name;
$longName = $entity->getSalutation()->getTranslation('displayName') . ' ' . $longName;
}
if (!empty($entity->getCompany())) {
$longName = $entity->getCompany() . ' - ' . $shortName;
$shortName = $entity->getCompany();
$name = $entity->getCompany();
if ((empty($entity->getFirstName()) || empty($entity->getLastName()))) {
$longName = $entity->getCompany();
}
}
if($entity instanceof OfferCustomerEntity) {
$entity->setDisplayName(new CustomerDisplayName($shortName, $name, $longName));
return;
}
$entity->addExtension('displayName', new CustomerDisplayName($shortName, $name, $longName));
}
}