<?php
namespace App\EventSubscriber\cic\Legacy;
use App\Event\DepartmentChangeEvent;
use CIC\DB\envLoader\db;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class DepartmentChangeSubscriber implements EventSubscriberInterface
{
private db $db;
private ParameterBagInterface $params;
private $class;
private $sync = false;
/**
* DepartmentChangeSubscriber constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(db $db, ParameterBagInterface $params)
{
$this->db = $db;
$this->params = $params;
if ($this->params->get('legacy.sync_departments')) {
$className = $this->params->get('legacy.sync_departments');
$this->class = new $className($this->db);
// pass all tests
$this->sync = true;
}
}
public static function getSubscribedEvents()
{
return [
DepartmentChangeEvent::class => [
['onChange'],
['onCreate'],
],
];
}
/**
* @return mixed
*/
public function getEntity(DepartmentChangeEvent $event)
{
return $event->getDepartment();
}
public function onChange(DepartmentChangeEvent $event)
{
if (!$this->sync) {
return;
} // Sync is off
$entity = $this->getEntity($event);
// no ID, not an update
if (!$entity->getId()) {
return;
}
if (method_exists($this->class, 'update')) {
$this->class->update($entity);
}
}
public function onCreate(DepartmentChangeEvent $event)
{
if (!$this->sync) {
return;
} // sync is off
$entity = $this->getEntity($event);
// ID, not an insert
if ($entity->getId()) {
return;
}
if (method_exists($this->class, 'create')) {
$this->class->create($entity);
}
}
}