o365-2.0.3/modules/o365_outlook_calendar/src/Controller/OutlookCalendarSaveAjaxController.php
modules/o365_outlook_calendar/src/Controller/OutlookCalendarSaveAjaxController.php
<?php
namespace Drupal\o365_outlook_calendar\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\o365_outlook_calendar\OutlookCalendarSaveEventService;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for Microsoft 365 - Outlook Calendar routes.
*/
final class OutlookCalendarSaveAjaxController extends ControllerBase {
/**
* The event service.
*
* @var \Drupal\o365_outlook_calendar\OutlookCalendarSaveEventService
*/
protected OutlookCalendarSaveEventService $eventService;
/**
* The drupal messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The controller constructor.
*
* @param \Drupal\o365_outlook_calendar\OutlookCalendarSaveEventService $eventService
* The event service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The Drupal messenger.
*/
public function __construct(OutlookCalendarSaveEventService $eventService, MessengerInterface $messenger) {
$this->eventService = $eventService;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('o365_outlook_calendar.save_event'), $container->get('messenger'));
}
/**
* The ajax callback function.
*
* @param mixed $nid
* The node ID of the node to use.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The response.
*
* @throws \Drupal\Core\TempStore\TempStoreException
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
*/
public function ajaxLinkCallback($nid = FALSE): AjaxResponse {
$response = new AjaxResponse();
$output = 'Something went wrong. Please try again.';
if ($nid) {
$node = Node::load($nid);
if ($node) {
$webLink = $this->eventService->addEvent($node, '', TRUE);
if ($webLink) {
$url = Url::fromUri($webLink, ['attributes' => ['target' => '_blank']]);
$link = Link::fromTextAndUrl('Outlook Calendar', $url);
$output = $this->t('This event has been created in your @link', ['@link' => $link->toString()]);
}
}
}
$response->addCommand(new ReplaceCommand('#o365-calendar-ajax-link', $output));
return $response;
}
}
