livre-1.0.0-beta6/book/src/BookUninstallValidator.php

book/src/BookUninstallValidator.php
<?php

namespace Drupal\book;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;

/**
 * Prevents book module from being uninstalled under certain conditions.
 *
 * These conditions are when any book nodes exist or there are any book outline
 * stored.
 */
class BookUninstallValidator implements ModuleUninstallValidatorInterface {

  use StringTranslationTrait;

  /**
   * Constructs a new BookUninstallValidator.
   *
   * @param \Drupal\book\BookOutlineStorageInterface $bookOutlineStorage
   *   The book outline storage.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   */
  public function __construct(
    protected BookOutlineStorageInterface $bookOutlineStorage,
    protected EntityTypeManagerInterface $entityTypeManager,
    TranslationInterface $string_translation,
  ) {
    $this->stringTranslation = $string_translation;
  }

  /**
   * {@inheritdoc}
   */
  public function validate($module): array {
    $reasons = [];
    if ($module == 'book') {
      if ($this->hasBookOutlines()) {
        $reasons[] = $this->t('To uninstall Book, delete all content that is part of a book');
      }
      else {
        // The book node type is provided by the Book module. Prevent uninstall
        // if there are any nodes of that type.
        if ($this->hasBookNodes()) {
          $reasons[] = $this->t('To uninstall Book, delete all content that has the Book content type');
        }
      }
    }
    return $reasons;
  }

  /**
   * Checks if there are any books in an outline.
   *
   * @return bool
   *   TRUE if there are books, FALSE if not.
   */
  protected function hasBookOutlines(): bool {
    return $this->bookOutlineStorage->hasBooks();
  }

  /**
   * Determines if there is any book nodes or not.
   *
   * @return bool
   *   TRUE if there are book nodes, FALSE otherwise.
   */
  protected function hasBookNodes(): bool {
    try {
      $nodes = $this->entityTypeManager->getStorage('node')->getQuery()
        ->condition('type', 'book')
        ->accessCheck(FALSE)
        ->range(0, 1)
        ->execute();
      return !empty($nodes);
    }
    catch (InvalidPluginDefinitionException | PluginNotFoundException) {
      return FALSE;
    }
  }

}

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

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