zaya-1.0.x-dev/modules/zaya_events/src/EventSubscriber/ItineraryCompletionSubscriber.php
modules/zaya_events/src/EventSubscriber/ItineraryCompletionSubscriber.php
<?php
declare(strict_types=1);
namespace Drupal\zaya_events\EventSubscriber;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\Entity\Node;
use Drupal\zaya\Entity\Node\ZayaProgress;
use Drupal\zaya_events\Event\ItineraryCompletionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* The subscriber to the event itinerary completion.
*/
final class ItineraryCompletionSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
/**
* Chapter completion event handler.
*/
public function onItineraryCompletion(ItineraryCompletionEvent $event): void {
$itinerary = $event->itinerary;
$progress_values = [
"title" => "completion of itinerary: {$itinerary->label()}",
"type" => 'zaya_progress',
"uid" => $event->account->id(),
"zaya_learning_entity_bundle" => "zaya_itinerary",
"zaya_learning_entity_type" => "group",
"zaya_event" => $event->completionAction,
"zaya_progress_status" => ZayaProgress::COMPLETED,
];
if ($itinerary) {
$progress_values['zaya_itinerary'] = ['entity' => $itinerary];
$progress_values['zaya_itinerary_uuid'] = $itinerary->uuid();
}
if ($event->groupLastRelationshipAutocomplete) {
$last_relationship_plugin = $event->groupLastRelationshipAutocomplete->getPluginId();
if ($last_relationship_plugin === 'group_node:zaya_chapter') {
$chapter = $event->groupLastRelationshipAutocomplete->getEntity();
$progress_values['zaya_chapter'] = ['entity' => $chapter];
$progress_values['zaya_chapter_uuid'] = $chapter->uuid();
$progress_values["title"] .= " when ending chapter: {$chapter->label()}";
}
if ($last_relationship_plugin === 'group_node:zaya_resource') {
$resource = $event->groupLastRelationshipAutocomplete->getEntity();
$progress_values['zaya_resource'] = ['entity' => $resource];
$progress_values['zaya_resource_uuid'] = $resource->uuid();
$progress_values["title"] .= " when completing resource: {$resource->label()}";
}
}
$progress_node = Node::create($progress_values);
$progress_node->save();
$account = $event->account;
// Add skill content belonging to user entity.
foreach ($itinerary->zaya_skills->referencedEntities() as $skill) {
$skill_values = [
"title" => $skill->label(),
"type" => "zaya_skill",
"zaya_skill_terms" => $skill->id(),
"uid" => $account->id(),
"body" => $this->t("User @user_name has earned the skill @skill as result of completing the itinerary @itinerary", [
"@user_name" => $account->getDisplayName(),
"@skill" => $skill->label(),
"@itinerary" => $itinerary->label(),
]),
];
$skill_acquired = Node::create($skill_values);
$skill_acquired->save();
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [
ItineraryCompletionEvent::EVENT_NAME => ['onItineraryCompletion'],
];
}
}
