entity_reference_hierarchy_book_nav-1.0.0/src/Book.php

src/Book.php
<?php

declare(strict_types=1);

namespace Drupal\entity_reference_hierarchy_book_nav;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;

/**
 * Common methods for dealing with books.
 */
final class Book {

  /**
   * Constructs a Book object.
   */
  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * Check to see if a node is in a book, and return the book if it is.
   */
  public function getBook(NodeInterface $node) {
    if ($node->getType() == 'book') {
      return $node;
    }

    $book = NULL;

    $book = $this->entityTypeManager->getStorage('node')->getQuery()
      ->condition('type', 'book')
      ->condition('field_book_structure', $node->id())
      ->accessCheck(TRUE)
      ->execute();

    if ($book) {
      return $this->entityTypeManager->getStorage('node')->load(reset($book));
    }
    return FALSE;
  }

  /**
   * Get the node that is the next page.
   */
  public function nextPage(NodeInterface $book, NodeInterface $page) {
    $page_id = $page->id();

    if ($page_id == $book->id()) {
      return $this->nextPageNotChapter(0, $book);
    }

    foreach ($book->get('field_book_structure') as $delta => $item) {
      if ($item->target_id == $page_id) {
        return $this->nextPageNotChapter($delta + 1, $book);
      }
    }
  }

  /**
   * Get the node that is the previous page.
   */
  public function previousPage($book, $page) {
    $page_id = $page->id();

    if ($page_id == $book->id()) {
      return FALSE;
    }

    foreach ($book->get('field_book_structure') as $delta => $item) {
      if ($item->target_id == $page_id) {
        return $this->previousPageNotChapter($delta - 1, $book);
      }
    }
  }

  /**
   * Get the node that is the next page and isn't a chapter heading.
   */
  public function nextPageNotChapter($id, $book) {
    while (isset($book->get('field_book_structure')[$id]) && $book->get('field_book_structure')[$id]->target_id) {
      $page = $book->get('field_book_structure')[$id]->entity;
      if (!$page) {
        return FALSE;
      }
      if ($page->getType() == 'book_chapter' || !$page->access()) {
        $id++;
        continue;
      }
      return $page;
    }
  }

  /**
   * Get the node that is the previous page and isn't a chapter heading.
   */
  public function previousPageNotChapter($id, $book) {
    while (isset($book->get('field_book_structure')[$id]) && $book->get('field_book_structure')[$id]->target_id) {
      $page = $book->get('field_book_structure')[$id]->entity;
      if (!$page) {
        return FALSE;
      }
      if ($page->getType() == 'book_chapter' || !$page->access()) {
        $id--;
        continue;
      }
      return $page;
    }

    if ($id < 0) {
      return $book;
    }
  }

}

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

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