<?php
namespace App\EventSubscriber;
use Exception;
use Pimcore\Event\DataObjectEvents;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Model\DataObject\PropertyIdentification;
use Pimcore\Model\DataObject\RefrigerantGas;
use Pimcore\Model\DataObject\Service;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class RefrigerantGasSubscriber implements EventSubscriberInterface
{
const REFRIGERANT_GAS_FOLDER = '1 – Property Description/1.7 Refrigerant Gas';
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
DataObjectEvents::PRE_ADD => ['onPreAdd', 10],
DataObjectEvents::PRE_UPDATE => ['onPreUpdate', 10],
];
}
/**
* @throws Exception
*/
public function onPreAdd(DataObjectEvent $event): void
{
$refrigerantGas = $event->getObject();
if (!($refrigerantGas instanceof RefrigerantGas)) {
return;
}
$refrigerantGas->setRFGAS_LocationName($refrigerantGas->getKey());
$propertyIdentification = $this->getPropertyIdentification($refrigerantGas);
if (!empty($propertyIdentification)) {
$refrigerantGas->setRFGAS_RelatedProperty([$propertyIdentification]);
}
}
/**
* @throws Exception
*/
public function onPreUpdate(DataObjectEvent $event): void
{
$refrigerantGas = $event->getObject();
if (!($refrigerantGas instanceof RefrigerantGas)) {
return;
}
$refrigerantGas->setKey($refrigerantGas->getRFGAS_LocationName());
if (!empty($refrigerantGas->getRFGAS_RelatedProperty())) {
$propertyIdentification = $refrigerantGas->getRFGAS_RelatedProperty()[0];
$parentFolder = Service::createFolderByPath(
$propertyIdentification->getFullPath() . DIRECTORY_SEPARATOR . static::REFRIGERANT_GAS_FOLDER
);
if (!empty($parentFolder)) {
$refrigerantGas->setParent($parentFolder);
}
}
}
/**
* Go up the tree to find the center
* @param RefrigerantGas $refrigerantGas
* @return PropertyIdentification|null
*/
private function getPropertyIdentification(RefrigerantGas $refrigerantGas): ?PropertyIdentification
{
$propertyIdentification = $refrigerantGas->getParent();
$count = 0;
while ($propertyIdentification && $count < 7) {
/**
* Condition $count < 7 : guard to avoid infinite loop
*/
if ($propertyIdentification instanceof PropertyIdentification) {
break;
}
$propertyIdentification = $propertyIdentification->getParent();
$count++;
}
return $propertyIdentification;
}
}