BookManager.php 2.24 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @file
 * Contains \Drupal\book\BookManager.
 */

namespace Drupal\book;

use Drupal\Core\Database\Connection;
10 11
use Drupal\Core\Entity\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
12 13 14 15 16 17 18 19 20 21 22 23 24

/**
 * Book Manager Service.
 */
class BookManager {

  /**
   * Database Service Object.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

25 26 27 28 29 30 31
  /**
   * Entity manager Service Object.
   *
   * @var \Drupal\Core\Entity\EntityManager
   */
  protected $entityManager;

32 33 34 35 36 37 38 39 40 41
  /**
   * Books Array.
   *
   * @var array
   */
  protected $books;

  /**
   * Constructs a BookManager object.
   */
42
  public function __construct(Connection $database, EntityManager $entityManager) {
43
    $this->database = $database;
44
    $this->entityManager = $entityManager;
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  }

  /**
   * Returns an array of all books.
   *
   * This list may be used for generating a list of all the books, or for building
   * the options for a form select.
   *
   * @return
   *   An array of all books.
   */
  public function getAllBooks() {
    if (!isset($this->books)) {
      $this->loadBooks();
    }
    return $this->books;
  }

  /**
   * Loads Books Array.
   */
  protected function loadBooks() {
    $this->books = array();
    $nids = $this->database->query("SELECT DISTINCT(bid) FROM {book}")->fetchCol();
69

70 71 72 73 74
    if ($nids) {
      $query = $this->database->select('book', 'b', array('fetch' => \PDO::FETCH_ASSOC));
      $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
      $query->fields('b');
      $query->fields('ml');
75
      $query->condition('b.nid', $nids);
76 77 78
      $query->orderBy('ml.weight');
      $query->orderBy('ml.link_title');
      $query->addTag('node_access');
79
      $query->addMetaData('base_table', 'book');
80
      $book_links = $query->execute();
81 82 83

      $nodes = $this->entityManager->getStorageController('node')->load($nids);

84
      foreach ($book_links as $link) {
85 86 87 88 89 90 91 92
        $nid = $link['nid'];
        if (isset($nodes[$nid]) && $nodes[$nid]->status) {
          $link['href'] = $link['link_path'];
          $link['options'] = unserialize($link['options']);
          $link['title'] = $nodes[$nid]->label();
          $link['type'] = $nodes[$nid]->bundle();
          $this->books[$link['bid']] = $link;
        }
93 94 95 96 97
      }
    }
  }

}