<?php
namespace Jabber\DataEnrichmentBundle\EventListener;
use Carbon\Carbon;
use Jabber\DataEnrichmentBundle\Model\Request;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Model\DataObject\DataEnrichmentModel;
use Pimcore\Model\DataObject\Product;
use Pimcore\Model\User;
class PostUpdateListener {
public function __construct(public int $systemUser = 2) {
}
public function onPostUpdate(ElementEventInterface $e) {
$foo = $e->getArguments();
if (!$e->hasArgument('isAutoSave')) {
if ($e instanceof DataObjectEvent) {
// do something with the object
$dataObject = $e->getObject();
if ($dataObject instanceof Product) {
if ($dataObject->getUserModification() != (int) $this->systemUser) {
$enrichmentProfiles = $this->getEnrichmentProfiles();
foreach ($enrichmentProfiles as $enrichmentProfile) {
if (strtoupper($enrichmentProfile->getLevel()) == $dataObject->getProductLevel()) {
if ($enrichmentProfile->getUpdates() == false) {
$isEmpty = $this->checkForEmptyValues($enrichmentProfile);
if ($isEmpty) {
$this->createRequest($enrichmentProfile->getId(), $dataObject->getId());
}
} else {
$this->createRequest($enrichmentProfile->getId(), $dataObject->getId(), $enrichmentProfile->getDuration());
}
}
}
}
}
}
}
}
public function createRequest($profileId, $productId, $duration = null) {
$listing = new Request\Listing();
$existingRequests = $listing->getByProductId($productId, $profileId);
if ($profileId == 366349) {
$foo = "bar";
}
if (empty($existingRequests)) {
$request = new Request();
$request->setEnrichmentId($profileId);
$request->setObjectId($productId);
$request->save();
} else {
foreach ($existingRequests as $existingRequest) {
if ($duration != null) {
$date = Carbon::parse($existingRequest->getCreatedAt());
$now = Carbon::now();
$diff = $date->diffInDays($now);
if ($diff >= $duration) {
$newRequest = new Request();
$newRequest->setEnrichmentId($profileId);
$newRequest->setObjectId($productId);
$newRequest->save();
}
}
break;
}
}
}
public function getEnrichmentProfiles() {
$dataEnrichmentModels = DataEnrichmentModel::getList();
return $dataEnrichmentModels;
}
/**
* Checks the handler class for the function isEmpty
*
* If it exists it'll run the check based on the rules set by the handler
*
* @param DataEnrichmentModel $enrichmentProfile
* @return bool
*/
public function checkForEmptyValues(DataEnrichmentModel $enrichmentProfile) {
if (!empty($enrichmentProfile->getHandler())) {
$handlerClass= $enrichmentProfile->getHandler();
if (class_exists($handlerClass)) {
$handler = new $handlerClass();
if (method_exists($handler, 'isEmpty')) {
return $handler->isEmpty();
}
}
}
return false;
}
}