contacts_events-8.x-1.x-dev/src/EventSubscriber/TicketUserCancelConfirmationSubscriber.php

src/EventSubscriber/TicketUserCancelConfirmationSubscriber.php
<?php

namespace Drupal\contacts_events\EventSubscriber;

use Drupal\contacts\Event\UserCancelConfirmationEvent;
use Drupal\Core\Database\Connection;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber invoked on user cancel confirmation form.
 *
 * Provides additional information, confirmations and errors about the
 * cancellation based on Contacts tickets.
 */
class TicketUserCancelConfirmationSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The database connection for the Contacts tickets table.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * TicketUserCancelConfirmationSubscriber constructor.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * Invoked when a user cancel form is created.
   *
   * @param \Drupal\contacts\Event\UserCancelConfirmationEvent $event
   *   The event representing the user cancel confirmation.
   */
  public function onCancelConfirm(UserCancelConfirmationEvent $event) {
    $user = $event->getUser();

    // Check if the user has any tickets.
    $query = $this->database->select('contacts_ticket', 'ct');
    $query->fields('ct', ['id']);
    $query->condition('ct.contact', $user->id());
    $user_bookings = $query->execute()->fetchAll();
    if (count($user_bookings)) {
      $error = $this->formatPlural(
        count($user_bookings),
        '%user has a ticket',
        '%user has %count tickets',
        ['%count' => count($user_bookings), '%user' => $user->label()]
      );
      $event->addError($error);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[UserCancelConfirmationEvent::NAME][] = ['onCancelConfirm'];
    return $events;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc