<?php
namespace App\Subscriber\OneRoster;
use App\Entity\System\School;
use Cms\CoreBundle\Entity\AbstractOneRosterEntity;
use Cms\CoreBundle\Entity\OneRoster\OneRosterOrg;
use Cms\CoreBundle\Entity\OneRosterSync;
use Cms\CoreBundle\Events\OneRosterProcessEvent;
use Cms\CoreBundle\Model\Interfaces\OneRosterable\AbstractOneRosterableSubscriber;
use Doctrine\Common\Util\ClassUtils;
/**
*/
final class OneRosterOrgProcessSubscriber extends AbstractOneRosterableSubscriber
{
/**
* {@inheritdoc}
*/
static public function getSubscribedEvents(): array
{
return [
OneRosterProcessEvent::EVENT__ORG => [
['populateSchools', 100],
],
];
}
/**
* @param OneRosterProcessEvent $event
*/
public function populateSchools(OneRosterProcessEvent $event): void
{
// ensure we are meant to process this
if ( ! $this->checkTypes($event->getSync(), [
OneRosterSync::STRATEGIES__SCHOOLS,
])) {
return;
}
// get the org
$org = $event->getEntity();
if ( ! $org instanceof OneRosterOrg) {
throw new \Exception(sprintf(
'Org is not of proper type, got "%s".',
ClassUtils::getClass($org)
));
}
// branch on the org type
switch (true) {
case $this->checkTypes($event->getSync(), [OneRosterSync::STRATEGIES__SCHOOLS]) && $org->isType(AbstractOneRosterEntity::ENUMS__ORG_TYPE__DISTRICT):
case $this->checkTypes($event->getSync(), [OneRosterSync::STRATEGIES__SCHOOLS])
&& $org->isType(AbstractOneRosterEntity::ENUMS__ORG_TYPE__SCHOOL)
&& ! $event->getSync()->hasFlag(OneRosterSync::FLAGS__SINGLE_SCHOOL):
break;
default:
// DEBUGGING
$event->getOutput()->writeln(sprintf(
'Org type for #%s is "%s", skipping...',
$org->getSourcedId(),
$org->getType()
));
return;
}
// try to find an existing school for the org based on the oneroster id
$school = $this->em->getRepository(School::class)->findOneBy([
'oneRosterOrg' => $org->getSourcedId(),
]);
// if we don't have one, attempt to find one based on the name
if ( ! $school) {
$school = $this->em->getRepository(School::class)->findOneBy([
'name' => $org->getName(),
]);
}
// if we still don't have one, make one
if ( ! $school) {
$school = (new School())
->setType(
$org->isType(AbstractOneRosterEntity::ENUMS__ORG_TYPE__DISTRICT)
? School::TYPES__DISTRICT
: School::TYPES__OTHER
)
;
}
// set stuff
$school
->setName($school->getName() ?: $org->getName())
->setOneRosterOrg($org->getSourcedId())
;
// TODO: schools should now be a onerosterable object...
// save the school
$this->em->save($school);
}
}