learnosity-1.0.x-dev/src/Controller/LearnosityEventController.php
src/Controller/LearnosityEventController.php
<?php
namespace Drupal\learnosity\Controller;
use Drupal\learnosity\Event\LearnosityEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Dispatches Drupal events from Learnosity events.
*/
class LearnosityEventController extends ControllerBase implements ContainerInjectionInterface {
/**
* The request stack service.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $request;
/**
* The event dispatcher service.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* LearnosityEventController constructor.
*
* @param \Symfony\Component\HttpFoundation\RequestStack $request
* The request stack service.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
* The event dispatcher service.
*/
public function __construct(RequestStack $request, EventDispatcherInterface $event_dispatcher) {
$this->request = $request;
$this->eventDispatcher = $event_dispatcher;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack'),
$container->get('event_dispatcher'),
);
}
/**
* Fetch and process the passed query parameters.
*
* @return array
* The associative array of contextual values.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected function processContext() {
// @todo: Make this more robust.
$context = [];
$params = $this->request->getCurrentRequest()->query->all();
if (!empty($params)) {
foreach ($params as $key => $param) {
if ($key != '_wrapper_format') {
$context[$key] = $param;
}
}
}
return $context;
}
/**
* Dispatches an event from Learnosity.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The ajax response.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function dispatchEvent($name) {
// Parse the name. It should only have colons.
$name = str_replace('-', ':', $name);
// We are just dispatching an event, we are not executing anything else.
$context = $this->processContext();
$event = new LearnosityEvent($name, $context);
$dispatch = $this->eventDispatcher->dispatch($event, 'learnosity.' . $name);
// Check to see if any subscribers return a response. If they do then use
// that. Otherwise default to an empty ajax response.
$response = $dispatch->getResponse();
if (empty($response)) {
$response = new AjaxResponse();
}
return $response;
}
}
