Chris@0: 'entity.manager'];
Chris@0:
Chris@0: /**
Chris@0: * Defines the maximum supported depth of the book tree.
Chris@0: */
Chris@0: const BOOK_MAX_DEPTH = 9;
Chris@0:
Chris@0: /**
Chris@18: * Entity type manager.
Chris@0: *
Chris@18: * @var \Drupal\Core\Entity\EntityTypeManagerInterface
Chris@0: */
Chris@18: protected $entityTypeManager;
Chris@0:
Chris@0: /**
Chris@0: * Config Factory Service Object.
Chris@0: *
Chris@0: * @var \Drupal\Core\Config\ConfigFactoryInterface
Chris@0: */
Chris@0: protected $configFactory;
Chris@0:
Chris@0: /**
Chris@0: * Books Array.
Chris@0: *
Chris@0: * @var array
Chris@0: */
Chris@0: protected $books;
Chris@0:
Chris@0: /**
Chris@0: * Book outline storage.
Chris@0: *
Chris@0: * @var \Drupal\book\BookOutlineStorageInterface
Chris@0: */
Chris@0: protected $bookOutlineStorage;
Chris@0:
Chris@0: /**
Chris@0: * Stores flattened book trees.
Chris@0: *
Chris@0: * @var array
Chris@0: */
Chris@0: protected $bookTreeFlattened;
Chris@0:
Chris@0: /**
Chris@0: * The renderer.
Chris@0: *
Chris@0: * @var \Drupal\Core\Render\RendererInterface
Chris@0: */
Chris@0: protected $renderer;
Chris@0:
Chris@0: /**
Chris@0: * Constructs a BookManager object.
Chris@18: *
Chris@18: * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
Chris@18: * The entity type manager.
Chris@18: * @param \Drupal\Core\StringTranslation\TranslationInterface $translation
Chris@18: * The string translation service.
Chris@18: * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
Chris@18: * The config factory.
Chris@18: * @param \Drupal\book\BookOutlineStorageInterface $book_outline_storage
Chris@18: * The book outline storage.
Chris@18: * @param \Drupal\Core\Render\RendererInterface $renderer
Chris@18: * The renderer.
Chris@0: */
Chris@18: public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $translation, ConfigFactoryInterface $config_factory, BookOutlineStorageInterface $book_outline_storage, RendererInterface $renderer) {
Chris@18: $this->entityTypeManager = $entity_type_manager;
Chris@0: $this->stringTranslation = $translation;
Chris@0: $this->configFactory = $config_factory;
Chris@0: $this->bookOutlineStorage = $book_outline_storage;
Chris@0: $this->renderer = $renderer;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function getAllBooks() {
Chris@0: if (!isset($this->books)) {
Chris@0: $this->loadBooks();
Chris@0: }
Chris@0: return $this->books;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Loads Books Array.
Chris@0: */
Chris@0: protected function loadBooks() {
Chris@0: $this->books = [];
Chris@0: $nids = $this->bookOutlineStorage->getBooks();
Chris@0:
Chris@0: if ($nids) {
Chris@0: $book_links = $this->bookOutlineStorage->loadMultiple($nids);
Chris@18: $nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);
Chris@0: // @todo: Sort by weight and translated title.
Chris@0:
Chris@0: // @todo: use route name for links, not system path.
Chris@0: foreach ($book_links as $link) {
Chris@0: $nid = $link['nid'];
Chris@0: if (isset($nodes[$nid]) && $nodes[$nid]->status) {
Chris@18: $link['url'] = $nodes[$nid]->toUrl();
Chris@0: $link['title'] = $nodes[$nid]->label();
Chris@0: $link['type'] = $nodes[$nid]->bundle();
Chris@0: $this->books[$link['bid']] = $link;
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function getLinkDefaults($nid) {
Chris@0: return [
Chris@0: 'original_bid' => 0,
Chris@0: 'nid' => $nid,
Chris@0: 'bid' => 0,
Chris@0: 'pid' => 0,
Chris@0: 'has_children' => 0,
Chris@0: 'weight' => 0,
Chris@0: 'options' => [],
Chris@0: ];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function getParentDepthLimit(array $book_link) {
Chris@0: return static::BOOK_MAX_DEPTH - 1 - (($book_link['bid'] && $book_link['has_children']) ? $this->findChildrenRelativeDepth($book_link) : 0);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Determine the relative depth of the children of a given book link.
Chris@0: *
Chris@0: * @param array $book_link
Chris@0: * The book link.
Chris@0: *
Chris@0: * @return int
Chris@0: * The difference between the max depth in the book tree and the depth of
Chris@0: * the passed book link.
Chris@0: */
Chris@0: protected function findChildrenRelativeDepth(array $book_link) {
Chris@0: $max_depth = $this->bookOutlineStorage->getChildRelativeDepth($book_link, static::BOOK_MAX_DEPTH);
Chris@0: return ($max_depth > $book_link['depth']) ? $max_depth - $book_link['depth'] : 0;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function addFormElements(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
Chris@0: // If the form is being processed during the Ajax callback of our book bid
Chris@0: // dropdown, then $form_state will hold the value that was selected.
Chris@0: if ($form_state->hasValue('book')) {
Chris@0: $node->book = $form_state->getValue('book');
Chris@0: }
Chris@0: $form['book'] = [
Chris@0: '#type' => 'details',
Chris@0: '#title' => $this->t('Book outline'),
Chris@0: '#weight' => 10,
Chris@0: '#open' => !$collapsed,
Chris@0: '#group' => 'advanced',
Chris@0: '#attributes' => [
Chris@0: 'class' => ['book-outline-form'],
Chris@0: ],
Chris@0: '#attached' => [
Chris@0: 'library' => ['book/drupal.book'],
Chris@0: ],
Chris@0: '#tree' => TRUE,
Chris@0: ];
Chris@0: foreach (['nid', 'has_children', 'original_bid', 'parent_depth_limit'] as $key) {
Chris@0: $form['book'][$key] = [
Chris@0: '#type' => 'value',
Chris@0: '#value' => $node->book[$key],
Chris@0: ];
Chris@0: }
Chris@0:
Chris@0: $form['book']['pid'] = $this->addParentSelectFormElements($node->book);
Chris@0:
Chris@0: // @see \Drupal\book\Form\BookAdminEditForm::bookAdminTableTree(). The
Chris@0: // weight may be larger than 15.
Chris@0: $form['book']['weight'] = [
Chris@0: '#type' => 'weight',
Chris@0: '#title' => $this->t('Weight'),
Chris@0: '#default_value' => $node->book['weight'],
Chris@0: '#delta' => max(15, abs($node->book['weight'])),
Chris@0: '#weight' => 5,
Chris@0: '#description' => $this->t('Pages at a given level are ordered first by weight and then by title.'),
Chris@0: ];
Chris@0: $options = [];
Chris@0: $nid = !$node->isNew() ? $node->id() : 'new';
Chris@0: if ($node->id() && ($nid == $node->book['original_bid']) && ($node->book['parent_depth_limit'] == 0)) {
Chris@0: // This is the top level node in a maximum depth book and thus cannot be
Chris@0: // moved.
Chris@0: $options[$node->id()] = $node->label();
Chris@0: }
Chris@0: else {
Chris@0: foreach ($this->getAllBooks() as $book) {
Chris@0: $options[$book['nid']] = $book['title'];
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: if ($account->hasPermission('create new books') && ($nid == 'new' || ($nid != $node->book['original_bid']))) {
Chris@0: // The node can become a new book, if it is not one already.
Chris@0: $options = [$nid => $this->t('- Create a new book -')] + $options;
Chris@0: }
Chris@0: if (!$node->book['bid']) {
Chris@0: // The node is not currently in the hierarchy.
Chris@0: $options = [0 => $this->t('- None -')] + $options;
Chris@0: }
Chris@0:
Chris@0: // Add a drop-down to select the destination book.
Chris@0: $form['book']['bid'] = [
Chris@0: '#type' => 'select',
Chris@0: '#title' => $this->t('Book'),
Chris@0: '#default_value' => $node->book['bid'],
Chris@0: '#options' => $options,
Chris@0: '#access' => (bool) $options,
Chris@0: '#description' => $this->t('Your page will be a part of the selected book.'),
Chris@0: '#weight' => -5,
Chris@0: '#attributes' => ['class' => ['book-title-select']],
Chris@0: '#ajax' => [
Chris@0: 'callback' => 'book_form_update',
Chris@0: 'wrapper' => 'edit-book-plid-wrapper',
Chris@0: 'effect' => 'fade',
Chris@0: 'speed' => 'fast',
Chris@0: ],
Chris@0: ];
Chris@0: return $form;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function checkNodeIsRemovable(NodeInterface $node) {
Chris@0: return (!empty($node->book['bid']) && (($node->book['bid'] != $node->id()) || !$node->book['has_children']));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function updateOutline(NodeInterface $node) {
Chris@0: if (empty($node->book['bid'])) {
Chris@0: return FALSE;
Chris@0: }
Chris@0:
Chris@0: if (!empty($node->book['bid'])) {
Chris@0: if ($node->book['bid'] == 'new') {
Chris@0: // New nodes that are their own book.
Chris@0: $node->book['bid'] = $node->id();
Chris@0: }
Chris@0: elseif (!isset($node->book['original_bid'])) {
Chris@0: $node->book['original_bid'] = $node->book['bid'];
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: // Ensure we create a new book link if either the node itself is new, or the
Chris@0: // bid was selected the first time, so that the original_bid is still empty.
Chris@0: $new = empty($node->book['nid']) || empty($node->book['original_bid']);
Chris@0:
Chris@0: $node->book['nid'] = $node->id();
Chris@0:
Chris@0: // Create a new book from a node.
Chris@0: if ($node->book['bid'] == $node->id()) {
Chris@0: $node->book['pid'] = 0;
Chris@0: }
Chris@0: elseif ($node->book['pid'] < 0) {
Chris@0: // -1 is the default value in BookManager::addParentSelectFormElements().
Chris@0: // The node save should have set the bid equal to the node ID, but
Chris@0: // handle it here if it did not.
Chris@0: $node->book['pid'] = $node->book['bid'];
Chris@0: }
Chris@0:
Chris@0: // Prevent changes to the book outline if the node being saved is not the
Chris@0: // default revision.
Chris@0: $updated = FALSE;
Chris@0: if (!$new) {
Chris@0: $original = $this->loadBookLink($node->id(), FALSE);
Chris@0: if ($node->book['bid'] != $original['bid'] || $node->book['pid'] != $original['pid'] || $node->book['weight'] != $original['weight']) {
Chris@0: $updated = TRUE;
Chris@0: }
Chris@0: }
Chris@0: if (($new || $updated) && !$node->isDefaultRevision()) {
Chris@0: return FALSE;
Chris@0: }
Chris@0:
Chris@0: return $this->saveBookLink($node->book, $new);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function getBookParents(array $item, array $parent = []) {
Chris@0: $book = [];
Chris@0: if ($item['pid'] == 0) {
Chris@0: $book['p1'] = $item['nid'];
Chris@0: for ($i = 2; $i <= static::BOOK_MAX_DEPTH; $i++) {
Chris@0: $parent_property = "p$i";
Chris@0: $book[$parent_property] = 0;
Chris@0: }
Chris@0: $book['depth'] = 1;
Chris@0: }
Chris@0: else {
Chris@0: $i = 1;
Chris@0: $book['depth'] = $parent['depth'] + 1;
Chris@0: while ($i < $book['depth']) {
Chris@0: $p = 'p' . $i++;
Chris@0: $book[$p] = $parent[$p];
Chris@0: }
Chris@0: $p = 'p' . $i++;
Chris@0: // The parent (p1 - p9) corresponding to the depth always equals the nid.
Chris@0: $book[$p] = $item['nid'];
Chris@0: while ($i <= static::BOOK_MAX_DEPTH) {
Chris@0: $p = 'p' . $i++;
Chris@0: $book[$p] = 0;
Chris@0: }
Chris@0: }
Chris@0: return $book;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Builds the parent selection form element for the node form or outline tab.
Chris@0: *
Chris@0: * This function is also called when generating a new set of options during
Chris@0: * the Ajax callback, so an array is returned that can be used to replace an
Chris@0: * existing form element.
Chris@0: *
Chris@0: * @param array $book_link
Chris@0: * A fully loaded book link that is part of the book hierarchy.
Chris@0: *
Chris@0: * @return array
Chris@0: * A parent selection form element.
Chris@0: */
Chris@0: protected function addParentSelectFormElements(array $book_link) {
Chris@0: $config = $this->configFactory->get('book.settings');
Chris@0: if ($config->get('override_parent_selector')) {
Chris@0: return [];
Chris@0: }
Chris@0: // Offer a message or a drop-down to choose a different parent page.
Chris@0: $form = [
Chris@0: '#type' => 'hidden',
Chris@0: '#value' => -1,
Chris@0: '#prefix' => '
',
Chris@0: '#suffix' => '
',
Chris@0: ];
Chris@0:
Chris@0: if ($book_link['nid'] === $book_link['bid']) {
Chris@0: // This is a book - at the top level.
Chris@0: if ($book_link['original_bid'] === $book_link['bid']) {
Chris@0: $form['#prefix'] .= '' . $this->t('This is the top-level page in this book.') . '';
Chris@0: }
Chris@0: else {
Chris@0: $form['#prefix'] .= '' . $this->t('This will be the top-level page in this book.') . '';
Chris@0: }
Chris@0: }
Chris@0: elseif (!$book_link['bid']) {
Chris@0: $form['#prefix'] .= '' . $this->t('No book selected.') . '';
Chris@0: }
Chris@0: else {
Chris@0: $form = [
Chris@0: '#type' => 'select',
Chris@0: '#title' => $this->t('Parent item'),
Chris@0: '#default_value' => $book_link['pid'],
Chris@0: '#description' => $this->t('The parent page in the book. The maximum depth for a book and all child pages is @maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', ['@maxdepth' => static::BOOK_MAX_DEPTH]),
Chris@0: '#options' => $this->getTableOfContents($book_link['bid'], $book_link['parent_depth_limit'], [$book_link['nid']]),
Chris@0: '#attributes' => ['class' => ['book-title-select']],
Chris@0: '#prefix' => '',
Chris@0: '#suffix' => '
',
Chris@0: ];
Chris@0: }
Chris@0: $this->renderer->addCacheableDependency($form, $config);
Chris@0:
Chris@0: return $form;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Recursively processes and formats book links for getTableOfContents().
Chris@0: *
Chris@0: * This helper function recursively modifies the table of contents array for
Chris@0: * each item in the book tree, ignoring items in the exclude array or at a
Chris@0: * depth greater than the limit. Truncates titles over thirty characters and
Chris@0: * appends an indentation string incremented by depth.
Chris@0: *
Chris@0: * @param array $tree
Chris@0: * The data structure of the book's outline tree. Includes hidden links.
Chris@0: * @param string $indent
Chris@0: * A string appended to each node title. Increments by '--' per depth
Chris@0: * level.
Chris@0: * @param array $toc
Chris@0: * Reference to the table of contents array. This is modified in place, so
Chris@0: * the function does not have a return value.
Chris@0: * @param array $exclude
Chris@0: * Optional array of Node ID values. Any link whose node ID is in this
Chris@0: * array will be excluded (along with its children).
Chris@0: * @param int $depth_limit
Chris@0: * Any link deeper than this value will be excluded (along with its
Chris@0: * children).
Chris@0: */
Chris@0: protected function recurseTableOfContents(array $tree, $indent, array &$toc, array $exclude, $depth_limit) {
Chris@0: $nids = [];
Chris@0: foreach ($tree as $data) {
Chris@0: if ($data['link']['depth'] > $depth_limit) {
Chris@0: // Don't iterate through any links on this level.
Chris@0: return;
Chris@0: }
Chris@0: if (!in_array($data['link']['nid'], $exclude)) {
Chris@0: $nids[] = $data['link']['nid'];
Chris@0: }
Chris@0: }
Chris@0:
Chris@18: $nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);
Chris@0:
Chris@0: foreach ($tree as $data) {
Chris@0: $nid = $data['link']['nid'];
Chris@0: // Check for excluded or missing node.
Chris@0: if (empty($nodes[$nid])) {
Chris@0: continue;
Chris@0: }
Chris@0: $toc[$nid] = $indent . ' ' . Unicode::truncate($nodes[$nid]->label(), 30, TRUE, TRUE);
Chris@0: if ($data['below']) {
Chris@0: $this->recurseTableOfContents($data['below'], $indent . '--', $toc, $exclude, $depth_limit);
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function getTableOfContents($bid, $depth_limit, array $exclude = []) {
Chris@0: $tree = $this->bookTreeAllData($bid);
Chris@0: $toc = [];
Chris@0: $this->recurseTableOfContents($tree, '', $toc, $exclude, $depth_limit);
Chris@0:
Chris@0: return $toc;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function deleteFromBook($nid) {
Chris@0: $original = $this->loadBookLink($nid, FALSE);
Chris@0: $this->bookOutlineStorage->delete($nid);
Chris@0:
Chris@0: if ($nid == $original['bid']) {
Chris@0: // Handle deletion of a top-level post.
Chris@0: $result = $this->bookOutlineStorage->loadBookChildren($nid);
Chris@18: $children = $this->entityTypeManager->getStorage('node')->loadMultiple(array_keys($result));
Chris@0: foreach ($children as $child) {
Chris@0: $child->book['bid'] = $child->id();
Chris@0: $this->updateOutline($child);
Chris@0: }
Chris@0: }
Chris@0: $this->updateOriginalParent($original);
Chris@0: $this->books = NULL;
Chris@0: Cache::invalidateTags(['bid:' . $original['bid']]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookTreeAllData($bid, $link = NULL, $max_depth = NULL) {
Chris@0: $tree = &drupal_static(__METHOD__, []);
Chris@0: $language_interface = \Drupal::languageManager()->getCurrentLanguage();
Chris@0:
Chris@0: // Use $nid as a flag for whether the data being loaded is for the whole
Chris@0: // tree.
Chris@0: $nid = isset($link['nid']) ? $link['nid'] : 0;
Chris@0: // Generate a cache ID (cid) specific for this $bid, $link, $language, and
Chris@0: // depth.
Chris@0: $cid = 'book-links:' . $bid . ':all:' . $nid . ':' . $language_interface->getId() . ':' . (int) $max_depth;
Chris@0:
Chris@0: if (!isset($tree[$cid])) {
Chris@0: // If the tree data was not in the static cache, build $tree_parameters.
Chris@0: $tree_parameters = [
Chris@0: 'min_depth' => 1,
Chris@0: 'max_depth' => $max_depth,
Chris@0: ];
Chris@0: if ($nid) {
Chris@0: $active_trail = $this->getActiveTrailIds($bid, $link);
Chris@0: $tree_parameters['expanded'] = $active_trail;
Chris@0: $tree_parameters['active_trail'] = $active_trail;
Chris@0: $tree_parameters['active_trail'][] = $nid;
Chris@0: }
Chris@0:
Chris@0: // Build the tree using the parameters; the resulting tree will be cached.
Chris@0: $tree[$cid] = $this->bookTreeBuild($bid, $tree_parameters);
Chris@0: }
Chris@0:
Chris@0: return $tree[$cid];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function getActiveTrailIds($bid, $link) {
Chris@0: // The tree is for a single item, so we need to match the values in its
Chris@0: // p columns and 0 (the top level) with the plid values of other links.
Chris@0: $active_trail = [0];
Chris@0: for ($i = 1; $i < static::BOOK_MAX_DEPTH; $i++) {
Chris@0: if (!empty($link["p$i"])) {
Chris@0: $active_trail[] = $link["p$i"];
Chris@0: }
Chris@0: }
Chris@0: return $active_trail;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookTreeOutput(array $tree) {
Chris@0: $items = $this->buildItems($tree);
Chris@0:
Chris@0: $build = [];
Chris@0:
Chris@0: if ($items) {
Chris@0: // Make sure drupal_render() does not re-order the links.
Chris@0: $build['#sorted'] = TRUE;
Chris@0: // Get the book id from the last link.
Chris@0: $item = end($items);
Chris@0: // Add the theme wrapper for outer markup.
Chris@0: // Allow menu-specific theme overrides.
Chris@0: $build['#theme'] = 'book_tree__book_toc_' . $item['original_link']['bid'];
Chris@0: $build['#items'] = $items;
Chris@0: // Set cache tag.
Chris@0: $build['#cache']['tags'][] = 'config:system.book.' . $item['original_link']['bid'];
Chris@0: }
Chris@0:
Chris@0: return $build;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Builds the #items property for a book tree's renderable array.
Chris@0: *
Chris@0: * Helper function for ::bookTreeOutput().
Chris@0: *
Chris@0: * @param array $tree
Chris@0: * A data structure representing the tree.
Chris@0: *
Chris@0: * @return array
Chris@0: * The value to use for the #items property of a renderable menu.
Chris@0: */
Chris@0: protected function buildItems(array $tree) {
Chris@0: $items = [];
Chris@0:
Chris@0: foreach ($tree as $data) {
Chris@0: $element = [];
Chris@0:
Chris@0: // Generally we only deal with visible links, but just in case.
Chris@0: if (!$data['link']['access']) {
Chris@0: continue;
Chris@0: }
Chris@0: // Set a class for the tag. Since $data['below'] may contain local
Chris@0: // tasks, only set 'expanded' to true if the link also has children within
Chris@0: // the current book.
Chris@0: $element['is_expanded'] = FALSE;
Chris@0: $element['is_collapsed'] = FALSE;
Chris@0: if ($data['link']['has_children'] && $data['below']) {
Chris@0: $element['is_expanded'] = TRUE;
Chris@0: }
Chris@0: elseif ($data['link']['has_children']) {
Chris@0: $element['is_collapsed'] = TRUE;
Chris@0: }
Chris@0:
Chris@0: // Set a helper variable to indicate whether the link is in the active
Chris@0: // trail.
Chris@0: $element['in_active_trail'] = FALSE;
Chris@0: if ($data['link']['in_active_trail']) {
Chris@0: $element['in_active_trail'] = TRUE;
Chris@0: }
Chris@0:
Chris@0: // Allow book-specific theme overrides.
Chris@0: $element['attributes'] = new Attribute();
Chris@0: $element['title'] = $data['link']['title'];
Chris@18: $node = $this->entityTypeManager->getStorage('node')->load($data['link']['nid']);
Chris@18: $element['url'] = $node->toUrl();
Chris@0: $element['localized_options'] = !empty($data['link']['localized_options']) ? $data['link']['localized_options'] : [];
Chris@0: $element['localized_options']['set_active_class'] = TRUE;
Chris@0: $element['below'] = $data['below'] ? $this->buildItems($data['below']) : [];
Chris@0: $element['original_link'] = $data['link'];
Chris@0: // Index using the link's unique nid.
Chris@0: $items[$data['link']['nid']] = $element;
Chris@0: }
Chris@0:
Chris@0: return $items;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Builds a book tree, translates links, and checks access.
Chris@0: *
Chris@0: * @param int $bid
Chris@0: * The Book ID to find links for.
Chris@0: * @param array $parameters
Chris@0: * (optional) An associative array of build parameters. Possible keys:
Chris@0: * - expanded: An array of parent link IDs to return only book links that
Chris@0: * are children of one of the parent link IDs in this list. If empty,
Chris@0: * the whole outline is built, unless 'only_active_trail' is TRUE.
Chris@0: * - active_trail: An array of node IDs, representing the currently active
Chris@0: * book link.
Chris@0: * - only_active_trail: Whether to only return links that are in the active
Chris@0: * trail. This option is ignored if 'expanded' is non-empty.
Chris@0: * - min_depth: The minimum depth of book links in the resulting tree.
Chris@0: * Defaults to 1, which is to build the whole tree for the book.
Chris@0: * - max_depth: The maximum depth of book links in the resulting tree.
Chris@0: * - conditions: An associative array of custom database select query
Chris@0: * condition key/value pairs; see
Chris@0: * \Drupal\book\BookOutlineStorage::getBookMenuTree() for the actual
Chris@0: * query.
Chris@0: *
Chris@0: * @return array
Chris@0: * A fully built book tree.
Chris@0: */
Chris@0: protected function bookTreeBuild($bid, array $parameters = []) {
Chris@0: // Build the book tree.
Chris@0: $data = $this->doBookTreeBuild($bid, $parameters);
Chris@0: // Check access for the current user to each item in the tree.
Chris@0: $this->bookTreeCheckAccess($data['tree'], $data['node_links']);
Chris@0: return $data['tree'];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Builds a book tree.
Chris@0: *
Chris@0: * This function may be used build the data for a menu tree only, for example
Chris@0: * to further massage the data manually before further processing happens.
Chris@0: * _menu_tree_check_access() needs to be invoked afterwards.
Chris@0: *
Chris@0: * @param int $bid
Chris@0: * The book ID to find links for.
Chris@0: * @param array $parameters
Chris@0: * (optional) An associative array of build parameters. Possible keys:
Chris@0: * - expanded: An array of parent link IDs to return only book links that
Chris@0: * are children of one of the parent link IDs in this list. If empty,
Chris@0: * the whole outline is built, unless 'only_active_trail' is TRUE.
Chris@0: * - active_trail: An array of node IDs, representing the currently active
Chris@0: * book link.
Chris@0: * - only_active_trail: Whether to only return links that are in the active
Chris@0: * trail. This option is ignored if 'expanded' is non-empty.
Chris@0: * - min_depth: The minimum depth of book links in the resulting tree.
Chris@0: * Defaults to 1, which is to build the whole tree for the book.
Chris@0: * - max_depth: The maximum depth of book links in the resulting tree.
Chris@0: * - conditions: An associative array of custom database select query
Chris@0: * condition key/value pairs; see
Chris@0: * \Drupal\book\BookOutlineStorage::getBookMenuTree() for the actual
Chris@0: * query.
Chris@0: *
Chris@0: * @return array
Chris@0: * An array with links representing the tree structure of the book.
Chris@0: *
Chris@0: * @see \Drupal\book\BookOutlineStorageInterface::getBookMenuTree()
Chris@0: */
Chris@0: protected function doBookTreeBuild($bid, array $parameters = []) {
Chris@0: // Static cache of already built menu trees.
Chris@0: $trees = &drupal_static(__METHOD__, []);
Chris@0: $language_interface = \Drupal::languageManager()->getCurrentLanguage();
Chris@0:
Chris@0: // Build the cache id; sort parents to prevent duplicate storage and remove
Chris@0: // default parameter values.
Chris@0: if (isset($parameters['expanded'])) {
Chris@0: sort($parameters['expanded']);
Chris@0: }
Chris@0: $tree_cid = 'book-links:' . $bid . ':tree-data:' . $language_interface->getId() . ':' . hash('sha256', serialize($parameters));
Chris@0:
Chris@0: // If we do not have this tree in the static cache, check {cache_data}.
Chris@0: if (!isset($trees[$tree_cid])) {
Chris@0: $cache = \Drupal::cache('data')->get($tree_cid);
Chris@0: if ($cache && $cache->data) {
Chris@0: $trees[$tree_cid] = $cache->data;
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: if (!isset($trees[$tree_cid])) {
Chris@0: $min_depth = (isset($parameters['min_depth']) ? $parameters['min_depth'] : 1);
Chris@0: $result = $this->bookOutlineStorage->getBookMenuTree($bid, $parameters, $min_depth, static::BOOK_MAX_DEPTH);
Chris@0:
Chris@0: // Build an ordered array of links using the query result object.
Chris@0: $links = [];
Chris@0: foreach ($result as $link) {
Chris@0: $link = (array) $link;
Chris@0: $links[$link['nid']] = $link;
Chris@0: }
Chris@0: $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : []);
Chris@0: $data['tree'] = $this->buildBookOutlineData($links, $active_trail, $min_depth);
Chris@0: $data['node_links'] = [];
Chris@0: $this->bookTreeCollectNodeLinks($data['tree'], $data['node_links']);
Chris@0:
Chris@0: // Cache the data, if it is not already in the cache.
Chris@0: \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, ['bid:' . $bid]);
Chris@0: $trees[$tree_cid] = $data;
Chris@0: }
Chris@0:
Chris@0: return $trees[$tree_cid];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookTreeCollectNodeLinks(&$tree, &$node_links) {
Chris@0: // All book links are nodes.
Chris@0: // @todo clean this up.
Chris@0: foreach ($tree as $key => $v) {
Chris@0: $nid = $v['link']['nid'];
Chris@0: $node_links[$nid][$tree[$key]['link']['nid']] = &$tree[$key]['link'];
Chris@0: $tree[$key]['link']['access'] = FALSE;
Chris@0: if ($tree[$key]['below']) {
Chris@0: $this->bookTreeCollectNodeLinks($tree[$key]['below'], $node_links);
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookTreeGetFlat(array $book_link) {
Chris@0: if (!isset($this->bookTreeFlattened[$book_link['nid']])) {
Chris@0: // Call $this->bookTreeAllData() to take advantage of caching.
Chris@0: $tree = $this->bookTreeAllData($book_link['bid'], $book_link, $book_link['depth'] + 1);
Chris@0: $this->bookTreeFlattened[$book_link['nid']] = [];
Chris@0: $this->flatBookTree($tree, $this->bookTreeFlattened[$book_link['nid']]);
Chris@0: }
Chris@0:
Chris@0: return $this->bookTreeFlattened[$book_link['nid']];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Recursively converts a tree of menu links to a flat array.
Chris@0: *
Chris@0: * @param array $tree
Chris@0: * A tree of menu links in an array.
Chris@0: * @param array $flat
Chris@0: * A flat array of the menu links from $tree, passed by reference.
Chris@0: *
Chris@0: * @see static::bookTreeGetFlat()
Chris@0: */
Chris@0: protected function flatBookTree(array $tree, array &$flat) {
Chris@0: foreach ($tree as $data) {
Chris@0: $flat[$data['link']['nid']] = $data['link'];
Chris@0: if ($data['below']) {
Chris@0: $this->flatBookTree($data['below'], $flat);
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function loadBookLink($nid, $translate = TRUE) {
Chris@0: $links = $this->loadBookLinks([$nid], $translate);
Chris@0: return isset($links[$nid]) ? $links[$nid] : FALSE;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function loadBookLinks($nids, $translate = TRUE) {
Chris@0: $result = $this->bookOutlineStorage->loadMultiple($nids, $translate);
Chris@0: $links = [];
Chris@0: foreach ($result as $link) {
Chris@0: if ($translate) {
Chris@0: $this->bookLinkTranslate($link);
Chris@0: }
Chris@0: $links[$link['nid']] = $link;
Chris@0: }
Chris@0:
Chris@0: return $links;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function saveBookLink(array $link, $new) {
Chris@0: // Keep track of Book IDs for cache clear.
Chris@0: $affected_bids[$link['bid']] = $link['bid'];
Chris@0: $link += $this->getLinkDefaults($link['nid']);
Chris@0: if ($new) {
Chris@0: // Insert new.
Chris@0: $parents = $this->getBookParents($link, (array) $this->loadBookLink($link['pid'], FALSE));
Chris@0: $this->bookOutlineStorage->insert($link, $parents);
Chris@0:
Chris@0: // Update the has_children status of the parent.
Chris@0: $this->updateParent($link);
Chris@0: }
Chris@0: else {
Chris@0: $original = $this->loadBookLink($link['nid'], FALSE);
Chris@0: // Using the Book ID as the key keeps this unique.
Chris@0: $affected_bids[$original['bid']] = $original['bid'];
Chris@0: // Handle links that are moving.
Chris@0: if ($link['bid'] != $original['bid'] || $link['pid'] != $original['pid']) {
Chris@0: // Update the bid for this page and all children.
Chris@0: if ($link['pid'] == 0) {
Chris@0: $link['depth'] = 1;
Chris@0: $parent = [];
Chris@0: }
Chris@0: // In case the form did not specify a proper PID we use the BID as new
Chris@0: // parent.
Chris@0: elseif (($parent_link = $this->loadBookLink($link['pid'], FALSE)) && $parent_link['bid'] != $link['bid']) {
Chris@0: $link['pid'] = $link['bid'];
Chris@0: $parent = $this->loadBookLink($link['pid'], FALSE);
Chris@0: $link['depth'] = $parent['depth'] + 1;
Chris@0: }
Chris@0: else {
Chris@0: $parent = $this->loadBookLink($link['pid'], FALSE);
Chris@0: $link['depth'] = $parent['depth'] + 1;
Chris@0: }
Chris@0: $this->setParents($link, $parent);
Chris@0: $this->moveChildren($link, $original);
Chris@0:
Chris@0: // Update the has_children status of the original parent.
Chris@0: $this->updateOriginalParent($original);
Chris@0: // Update the has_children status of the new parent.
Chris@0: $this->updateParent($link);
Chris@0: }
Chris@0: // Update the weight and pid.
Chris@0: $this->bookOutlineStorage->update($link['nid'], [
Chris@0: 'weight' => $link['weight'],
Chris@0: 'pid' => $link['pid'],
Chris@0: 'bid' => $link['bid'],
Chris@0: ]);
Chris@0: }
Chris@0: $cache_tags = [];
Chris@0: foreach ($affected_bids as $bid) {
Chris@0: $cache_tags[] = 'bid:' . $bid;
Chris@0: }
Chris@0: Cache::invalidateTags($cache_tags);
Chris@0: return $link;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Moves children from the original parent to the updated link.
Chris@0: *
Chris@0: * @param array $link
Chris@0: * The link being saved.
Chris@0: * @param array $original
Chris@0: * The original parent of $link.
Chris@0: */
Chris@0: protected function moveChildren(array $link, array $original) {
Chris@0: $p = 'p1';
Chris@0: $expressions = [];
Chris@0: for ($i = 1; $i <= $link['depth']; $p = 'p' . ++$i) {
Chris@0: $expressions[] = [$p, ":p_$i", [":p_$i" => $link[$p]]];
Chris@0: }
Chris@0: $j = $original['depth'] + 1;
Chris@0: while ($i <= static::BOOK_MAX_DEPTH && $j <= static::BOOK_MAX_DEPTH) {
Chris@0: $expressions[] = ['p' . $i++, 'p' . $j++, []];
Chris@0: }
Chris@0: while ($i <= static::BOOK_MAX_DEPTH) {
Chris@0: $expressions[] = ['p' . $i++, 0, []];
Chris@0: }
Chris@0:
Chris@0: $shift = $link['depth'] - $original['depth'];
Chris@0: if ($shift > 0) {
Chris@0: // The order of expressions must be reversed so the new values don't
Chris@0: // overwrite the old ones before they can be used because "Single-table
Chris@0: // UPDATE assignments are generally evaluated from left to right"
Chris@0: // @see http://dev.mysql.com/doc/refman/5.0/en/update.html
Chris@0: $expressions = array_reverse($expressions);
Chris@0: }
Chris@0:
Chris@0: $this->bookOutlineStorage->updateMovedChildren($link['bid'], $original, $expressions, $shift);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Sets the has_children flag of the parent of the node.
Chris@0: *
Chris@0: * This method is mostly called when a book link is moved/created etc. So we
Chris@0: * want to update the has_children flag of the new parent book link.
Chris@0: *
Chris@0: * @param array $link
Chris@0: * The book link, data reflecting its new position, whose new parent we want
Chris@0: * to update.
Chris@0: *
Chris@0: * @return bool
Chris@0: * TRUE if the update was successful (either there is no parent to update,
Chris@0: * or the parent was updated successfully), FALSE on failure.
Chris@0: */
Chris@0: protected function updateParent(array $link) {
Chris@0: if ($link['pid'] == 0) {
Chris@0: // Nothing to update.
Chris@0: return TRUE;
Chris@0: }
Chris@0: return $this->bookOutlineStorage->update($link['pid'], ['has_children' => 1]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Updates the has_children flag of the parent of the original node.
Chris@0: *
Chris@0: * This method is called when a book link is moved or deleted. So we want to
Chris@0: * update the has_children flag of the parent node.
Chris@0: *
Chris@0: * @param array $original
Chris@0: * The original link whose parent we want to update.
Chris@0: *
Chris@0: * @return bool
Chris@0: * TRUE if the update was successful (either there was no original parent to
Chris@0: * update, or the original parent was updated successfully), FALSE on
Chris@0: * failure.
Chris@0: */
Chris@0: protected function updateOriginalParent(array $original) {
Chris@0: if ($original['pid'] == 0) {
Chris@0: // There were no parents of this link. Nothing to update.
Chris@0: return TRUE;
Chris@0: }
Chris@0: // Check if $original had at least one child.
Chris@0: $original_number_of_children = $this->bookOutlineStorage->countOriginalLinkChildren($original);
Chris@0:
Chris@0: $parent_has_children = ((bool) $original_number_of_children) ? 1 : 0;
Chris@0: // Update the parent. If the original link did not have children, then the
Chris@0: // parent now does not have children. If the original had children, then the
Chris@0: // the parent has children now (still).
Chris@0: return $this->bookOutlineStorage->update($original['pid'], ['has_children' => $parent_has_children]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Sets the p1 through p9 properties for a book link being saved.
Chris@0: *
Chris@0: * @param array $link
Chris@0: * The book link to update, passed by reference.
Chris@0: * @param array $parent
Chris@0: * The parent values to set.
Chris@0: */
Chris@0: protected function setParents(array &$link, array $parent) {
Chris@0: $i = 1;
Chris@0: while ($i < $link['depth']) {
Chris@0: $p = 'p' . $i++;
Chris@0: $link[$p] = $parent[$p];
Chris@0: }
Chris@0: $p = 'p' . $i++;
Chris@0: // The parent (p1 - p9) corresponding to the depth always equals the nid.
Chris@0: $link[$p] = $link['nid'];
Chris@0: while ($i <= static::BOOK_MAX_DEPTH) {
Chris@0: $p = 'p' . $i++;
Chris@0: $link[$p] = 0;
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookTreeCheckAccess(&$tree, $node_links = []) {
Chris@0: if ($node_links) {
Chris@0: // @todo Extract that into its own method.
Chris@0: $nids = array_keys($node_links);
Chris@0:
Chris@0: // @todo This should be actually filtering on the desired node status
Chris@0: // field language and just fall back to the default language.
Chris@0: $nids = \Drupal::entityQuery('node')
Chris@0: ->condition('nid', $nids, 'IN')
Chris@0: ->condition('status', 1)
Chris@0: ->execute();
Chris@0:
Chris@0: foreach ($nids as $nid) {
Chris@0: foreach ($node_links[$nid] as $mlid => $link) {
Chris@0: $node_links[$nid][$mlid]['access'] = TRUE;
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: $this->doBookTreeCheckAccess($tree);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Sorts the menu tree and recursively checks access for each item.
Chris@0: *
Chris@0: * @param array $tree
Chris@0: * The book tree to operate on.
Chris@0: */
Chris@0: protected function doBookTreeCheckAccess(&$tree) {
Chris@0: $new_tree = [];
Chris@0: foreach ($tree as $key => $v) {
Chris@0: $item = &$tree[$key]['link'];
Chris@0: $this->bookLinkTranslate($item);
Chris@0: if ($item['access']) {
Chris@0: if ($tree[$key]['below']) {
Chris@0: $this->doBookTreeCheckAccess($tree[$key]['below']);
Chris@0: }
Chris@0: // The weights are made a uniform 5 digits by adding 50000 as an offset.
Chris@0: // After calling $this->bookLinkTranslate(), $item['title'] has the
Chris@0: // translated title. Adding the nid to the end of the index insures that
Chris@0: // it is unique.
Chris@0: $new_tree[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' . $item['nid']] = $tree[$key];
Chris@0: }
Chris@0: }
Chris@0: // Sort siblings in the tree based on the weights and localized titles.
Chris@0: ksort($new_tree);
Chris@0: $tree = $new_tree;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookLinkTranslate(&$link) {
Chris@0: $node = NULL;
Chris@0: // Access will already be set in the tree functions.
Chris@0: if (!isset($link['access'])) {
Chris@18: $node = $this->entityTypeManager->getStorage('node')->load($link['nid']);
Chris@0: $link['access'] = $node && $node->access('view');
Chris@0: }
Chris@0: // For performance, don't localize a link the user can't access.
Chris@0: if ($link['access']) {
Chris@0: // @todo - load the nodes en-mass rather than individually.
Chris@0: if (!$node) {
Chris@18: $node = $this->entityTypeManager->getStorage('node')
Chris@0: ->load($link['nid']);
Chris@0: }
Chris@0: // The node label will be the value for the current user's language.
Chris@0: $link['title'] = $node->label();
Chris@0: $link['options'] = [];
Chris@0: }
Chris@0: return $link;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Sorts and returns the built data representing a book tree.
Chris@0: *
Chris@0: * @param array $links
Chris@0: * A flat array of book links that are part of the book. Each array element
Chris@0: * is an associative array of information about the book link, containing
Chris@0: * the fields from the {book} table. This array must be ordered depth-first.
Chris@0: * @param array $parents
Chris@0: * An array of the node ID values that are in the path from the current
Chris@0: * page to the root of the book tree.
Chris@0: * @param int $depth
Chris@0: * The minimum depth to include in the returned book tree.
Chris@0: *
Chris@0: * @return array
Chris@0: * An array of book links in the form of a tree. Each item in the tree is an
Chris@0: * associative array containing:
Chris@0: * - link: The book link item from $links, with additional element
Chris@0: * 'in_active_trail' (TRUE if the link ID was in $parents).
Chris@0: * - below: An array containing the sub-tree of this item, where each
Chris@0: * element is a tree item array with 'link' and 'below' elements. This
Chris@0: * array will be empty if the book link has no items in its sub-tree
Chris@0: * having a depth greater than or equal to $depth.
Chris@0: */
Chris@0: protected function buildBookOutlineData(array $links, array $parents = [], $depth = 1) {
Chris@0: // Reverse the array so we can use the more efficient array_pop() function.
Chris@0: $links = array_reverse($links);
Chris@0: return $this->buildBookOutlineRecursive($links, $parents, $depth);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Builds the data representing a book tree.
Chris@0: *
Chris@0: * The function is a bit complex because the rendering of a link depends on
Chris@0: * the next book link.
Chris@0: *
Chris@0: * @param array $links
Chris@0: * A flat array of book links that are part of the book. Each array element
Chris@0: * is an associative array of information about the book link, containing
Chris@0: * the fields from the {book} table. This array must be ordered depth-first.
Chris@0: * @param array $parents
Chris@0: * An array of the node ID values that are in the path from the current page
Chris@0: * to the root of the book tree.
Chris@0: * @param int $depth
Chris@0: * The minimum depth to include in the returned book tree.
Chris@0: *
Chris@0: * @return array
Chris@0: * Book tree.
Chris@0: */
Chris@0: protected function buildBookOutlineRecursive(&$links, $parents, $depth) {
Chris@0: $tree = [];
Chris@0: while ($item = array_pop($links)) {
Chris@0: // We need to determine if we're on the path to root so we can later build
Chris@0: // the correct active trail.
Chris@0: $item['in_active_trail'] = in_array($item['nid'], $parents);
Chris@0: // Add the current link to the tree.
Chris@0: $tree[$item['nid']] = [
Chris@0: 'link' => $item,
Chris@0: 'below' => [],
Chris@0: ];
Chris@0: // Look ahead to the next link, but leave it on the array so it's
Chris@0: // available to other recursive function calls if we return or build a
Chris@0: // sub-tree.
Chris@0: $next = end($links);
Chris@0: // Check whether the next link is the first in a new sub-tree.
Chris@0: if ($next && $next['depth'] > $depth) {
Chris@0: // Recursively call buildBookOutlineRecursive to build the sub-tree.
Chris@0: $tree[$item['nid']]['below'] = $this->buildBookOutlineRecursive($links, $parents, $next['depth']);
Chris@0: // Fetch next link after filling the sub-tree.
Chris@0: $next = end($links);
Chris@0: }
Chris@0: // Determine if we should exit the loop and $request = return.
Chris@0: if (!$next || $next['depth'] < $depth) {
Chris@0: break;
Chris@0: }
Chris@0: }
Chris@0: return $tree;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * {@inheritdoc}
Chris@0: */
Chris@0: public function bookSubtreeData($link) {
Chris@0: $tree = &drupal_static(__METHOD__, []);
Chris@0:
Chris@0: // Generate a cache ID (cid) specific for this $link.
Chris@0: $cid = 'book-links:subtree-cid:' . $link['nid'];
Chris@0:
Chris@0: if (!isset($tree[$cid])) {
Chris@0: $tree_cid_cache = \Drupal::cache('data')->get($cid);
Chris@0:
Chris@0: if ($tree_cid_cache && $tree_cid_cache->data) {
Chris@0: // If the cache entry exists, it will just be the cid for the actual
Chris@0: // data. This avoids duplication of large amounts of data.
Chris@0: $cache = \Drupal::cache('data')->get($tree_cid_cache->data);
Chris@0:
Chris@0: if ($cache && isset($cache->data)) {
Chris@0: $data = $cache->data;
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: // If the subtree data was not in the cache, $data will be NULL.
Chris@0: if (!isset($data)) {
Chris@0: $result = $this->bookOutlineStorage->getBookSubtree($link, static::BOOK_MAX_DEPTH);
Chris@0: $links = [];
Chris@0: foreach ($result as $item) {
Chris@0: $links[] = $item;
Chris@0: }
Chris@0: $data['tree'] = $this->buildBookOutlineData($links, [], $link['depth']);
Chris@0: $data['node_links'] = [];
Chris@0: $this->bookTreeCollectNodeLinks($data['tree'], $data['node_links']);
Chris@0: // Compute the real cid for book subtree data.
Chris@0: $tree_cid = 'book-links:subtree-data:' . hash('sha256', serialize($data));
Chris@0: // Cache the data, if it is not already in the cache.
Chris@0:
Chris@0: if (!\Drupal::cache('data')->get($tree_cid)) {
Chris@0: \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, ['bid:' . $link['bid']]);
Chris@0: }
Chris@0: // Cache the cid of the (shared) data using the book and item-specific
Chris@0: // cid.
Chris@0: \Drupal::cache('data')->set($cid, $tree_cid, Cache::PERMANENT, ['bid:' . $link['bid']]);
Chris@0: }
Chris@0: // Check access for the current user to each item in the tree.
Chris@0: $this->bookTreeCheckAccess($data['tree'], $data['node_links']);
Chris@0: $tree[$cid] = $data['tree'];
Chris@0: }
Chris@0:
Chris@0: return $tree[$cid];
Chris@0: }
Chris@0:
Chris@0: }