<?php
namespace AppBundle\EventListener;
use AppBundle\EventListener\Validator\PromotionsEventListenerValidator;
use AppBundle\Service\TrimSpacesService;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Model\DataObject\Promotions;
use Symfony\Component\Messenger\MessageBusInterface;
class PromotionsEventListener extends DataObjectEventListener
{
const PIMCORE_DATA_OBJECT_CLASS_PATH = Promotions::class;
protected $object;
private $trimSpacesService;
public function __construct(MessageBusInterface $messageBus){
parent::__construct($messageBus);
$this->trimSpacesService = new TrimSpacesService();
}
/**
* @param ElementEventInterface $event
* @return void
* @throws \Doctrine\DBAL\DBALException
*/
public function onObjectPreAdd(ElementEventInterface $event): void {
// Not Promotions DataObject?
if(!$this->eventBelongsToThisClass($event)){
return;
}
$validator = new PromotionsEventListenerValidator();
$validator->validatePreAdd($this->object);
$this->onObjectPrePersist($event);
}
/**
* @param ElementEventInterface $event
* @return void
* @throws \Doctrine\DBAL\DBALException
*/
public function onObjectPreUpdate(ElementEventInterface $event): void {
// Not Promotions DataObject?
if(!$this->eventBelongsToThisClass($event)){
return;
}
$validator = new PromotionsEventListenerValidator();
$validator->validatePreUpdate($this->object);
$this->onObjectPrePersist($event);
$this->forceUpdateCategoryAndBrandTimestamps();
}
/**
* @param ElementEventInterface $event
* @return void
*/
public function onObjectPrePersist(ElementEventInterface $event): void {
$promotion = $this->trimSpacesService->trimSpaces($this->object->getPromotion());
$this->object->setPromotion($promotion);
}
/**
* @return void
* @throws \Doctrine\DBAL\DBALException
*/
private function forceUpdateCategoryAndBrandTimestamps(): void {
$db = \Pimcore\Db::get();
// Get list of all Marken assigned to this object:
$marken = $this->object->getMarken();
$markenIdsArr = [];
// Iterate through them and fetch the ids
foreach($marken as $marke){
$markenIdsArr[] = $marke->getObjectId();
}
$markenIdsStr = implode(",", $markenIdsArr);
// Update it in the DB
$markenQuery = "UPDATE objects
SET o_modificationDate = UNIX_TIMESTAMP()
WHERE o_id IN ({$markenIdsStr})";
$kategorien = $this->object->getKategorien();
$kategorienIdsArr = [];
// Iterate through them and fetch the ids
foreach($kategorien as $category){
$kategorienIdsArr[] = $category->getObjectId();
}
$kategorienIdsStr = implode(",", $kategorienIdsArr);
// Update it in the DB
$kategorienQuery = "UPDATE objects
SET o_modificationDate = UNIX_TIMESTAMP()
WHERE o_id IN ({$kategorienIdsStr})";
try{
$db->beginTransaction();
if(count($markenIdsArr) > 0){
$db->executeQuery($markenQuery);
}
if(count($kategorienIdsArr) > 0){
$db->executeQuery($kategorienQuery);
}
$db->commit();
}catch(\Throwable $throwable){
$db->rollBack();
throw new \Exception("Failed to update timestamps for Brands and Categories, please try saving again!");
}
}
}