MenuLinkStorageController.php 9.79 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php

/**
 * @file
 * Contains \Drupal\menu_link\MenuLinkStorageController.
 */

namespace Drupal\menu_link;

use Drupal\Core\Entity\DatabaseStorageController;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;

/**
 * Controller class for menu links.
 *
 * This extends the Drupal\entity\DatabaseStorageController class, adding
 * required special handling for menu_link entities.
 */
20
class MenuLinkStorageController extends DatabaseStorageController implements MenuLinkStorageControllerInterface {
21 22

  /**
23
   * Indicates whether the delete operation should re-parent children items.
24
   *
25
   * @var bool
26
   */
27
  protected $preventReparenting = FALSE;
28

29 30 31
  /**
   * {@inheritdoc}
   */
32
  public function create(array $values = array()) {
33 34 35 36 37 38 39 40
    // The bundle of menu links being the menu name is not enforced but is the
    // default behavior if no bundle is set.
    if (!isset($values['bundle']) && isset($values['menu_name'])) {
      $values['bundle'] = $values['menu_name'];
    }
    return parent::create($values);
  }

41 42 43 44
  /**
   * Overrides DatabaseStorageController::save().
   */
  public function save(EntityInterface $entity) {
45

46 47 48 49 50
    // We return SAVED_UPDATED by default because the logic below might not
    // update the entity if its values haven't changed, so returning FALSE
    // would be confusing in that situation.
    $return = SAVED_UPDATED;

51
    $transaction = $this->database->startTransaction();
52 53 54
    try {
      // Load the stored entity, if any.
      if (!$entity->isNew() && !isset($entity->original)) {
55
        $entity->original = entity_load_unchanged($this->entityTypeId, $entity->id());
56 57 58
      }

      if ($entity->isNew()) {
59
        $entity->mlid = $this->database->insert($this->entityType->getBaseTable())->fields(array('menu_name' => $entity->menu_name))->execute();
60 61 62 63 64 65 66
        $entity->enforceIsNew();
      }

      // Unlike the save() method from DatabaseStorageController, we invoke the
      // 'presave' hook first because we want to allow modules to alter the
      // entity before all the logic from our preSave() method.
      $this->invokeHook('presave', $entity);
67
      $entity->preSave($this);
68 69 70 71 72 73 74

      // If every value in $entity->original is the same in the $entity, there
      // is no reason to run the update queries or clear the caches. We use
      // array_intersect_key() with the $entity as the first parameter because
      // $entity may have additional keys left over from building a router entry.
      // The intersect removes the extra keys, allowing a meaningful comparison.
      if ($entity->isNew() || (array_intersect_key(get_object_vars($entity), get_object_vars($entity->original)) != get_object_vars($entity->original))) {
75
        $return = drupal_write_record($this->entityType->getBaseTable(), $entity, $this->idKey);
76 77 78 79

        if ($return) {
          if (!$entity->isNew()) {
            $this->resetCache(array($entity->{$this->idKey}));
80
            $entity->postSave($this, TRUE);
81 82 83 84 85 86 87
            $this->invokeHook('update', $entity);
          }
          else {
            $return = SAVED_NEW;
            $this->resetCache();

            $entity->enforceIsNew(FALSE);
88
            $entity->postSave($this, FALSE);
89 90 91 92 93 94 95 96 97 98 99 100 101
            $this->invokeHook('insert', $entity);
          }
        }
      }

      // Ignore slave server temporarily.
      db_ignore_slave();
      unset($entity->original);

      return $return;
    }
    catch (\Exception $e) {
      $transaction->rollback();
102
      watchdog_exception($this->entityTypeId, $e);
103 104 105 106 107
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
108
   * {@inheritdoc}
109
   */
110
  public function setPreventReparenting($value = FALSE) {
111 112 113 114
    $this->preventReparenting = $value;
  }

  /**
115
   * {@inheritdoc}
116
   */
117 118
  public function getPreventReparenting() {
    return $this->preventReparenting;
119 120 121
  }

  /**
122
   * {@inheritdoc}
123 124 125 126 127 128 129 130 131 132 133 134 135 136
   */
  public function loadUpdatedCustomized(array $router_paths) {
    $query = parent::buildQuery(NULL);
    $query
      ->condition(db_or()
      ->condition('updated', 1)
      ->condition(db_and()
        ->condition('router_path', $router_paths, 'NOT IN')
        ->condition('external', 0)
        ->condition('customized', 1)
        )
      );
    $query_result = $query->execute();

137
    if ($class = $this->entityType->getClass()) {
138 139
      // We provide the necessary arguments for PDO to create objects of the
      // specified entity class.
140
      // @see \Drupal\Core\Entity\EntityInterface::__construct()
141
      $query_result->setFetchMode(\PDO::FETCH_CLASS, $class, array(array(), $this->entityTypeId));
142 143 144 145 146 147
    }

    return $query_result->fetchAllAssoc($this->idKey);
  }

  /**
148
   * {@inheritdoc}
149 150 151 152 153 154 155
   */
  public function loadModuleAdminTasks() {
    $query = $this->buildQuery(NULL);
    $query
      ->condition('base.link_path', 'admin/%', 'LIKE')
      ->condition('base.hidden', 0, '>=')
      ->condition('base.module', 'system')
156
      ->condition('base.route_name', 'system.admin', '<>');
157 158
    $ids = $query->execute()->fetchCol(1);

159
    return $this->loadMultiple($ids);
160 161 162
  }

  /**
163
   * {@inheritdoc}
164
   */
165
  public function updateParentalStatus(EntityInterface $entity, $exclude = FALSE) {
166
    // If plid == 0, there is nothing to update.
167
    if ($entity->plid) {
168
      // Check if at least one visible child exists in the table.
169
      $query = $this->getQuery();
170 171 172 173 174 175 176 177 178 179 180
      $query
        ->condition('menu_name', $entity->menu_name)
        ->condition('hidden', 0)
        ->condition('plid', $entity->plid)
        ->count();

      if ($exclude) {
        $query->condition('mlid', $entity->id(), '<>');
      }

      $parent_has_children = ((bool) $query->execute()) ? 1 : 0;
181
      $this->database->update('menu_links')
182 183 184
        ->fields(array('has_children' => $parent_has_children))
        ->condition('mlid', $entity->plid)
        ->execute();
185 186 187 188
    }
  }

  /**
189
   * {@inheritdoc}
190 191 192 193
   */
  public function findChildrenRelativeDepth(EntityInterface $entity) {
    // @todo Since all we need is a specific field from the base table, does it
    // make sense to convert to EFQ?
194
    $query = $this->database->select('menu_links');
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    $query->addField('menu_links', 'depth');
    $query->condition('menu_name', $entity->menu_name);
    $query->orderBy('depth', 'DESC');
    $query->range(0, 1);

    $i = 1;
    $p = 'p1';
    while ($i <= MENU_MAX_DEPTH && $entity->{$p}) {
      $query->condition($p, $entity->{$p});
      $p = 'p' . ++$i;
    }

    $max_depth = $query->execute()->fetchField();

    return ($max_depth > $entity->depth) ? $max_depth - $entity->depth : 0;
  }

  /**
213
   * {@inheritdoc}
214
   */
215
  public function moveChildren(EntityInterface $entity) {
216
    $query = $this->database->update($this->entityType->getBaseTable());
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

    $query->fields(array('menu_name' => $entity->menu_name));

    $p = 'p1';
    $expressions = array();
    for ($i = 1; $i <= $entity->depth; $p = 'p' . ++$i) {
      $expressions[] = array($p, ":p_$i", array(":p_$i" => $entity->{$p}));
    }
    $j = $entity->original->depth + 1;
    while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
      $expressions[] = array('p' . $i++, 'p' . $j++, array());
    }
    while ($i <= MENU_MAX_DEPTH) {
      $expressions[] = array('p' . $i++, 0, array());
    }

    $shift = $entity->depth - $entity->original->depth;
    if ($shift > 0) {
      // The order of expressions must be reversed so the new values don't
      // overwrite the old ones before they can be used because "Single-table
      // UPDATE assignments are generally evaluated from left to right"
      // @see http://dev.mysql.com/doc/refman/5.0/en/update.html
      $expressions = array_reverse($expressions);
    }
    foreach ($expressions as $expression) {
      $query->expression($expression[0], $expression[1], $expression[2]);
    }

    $query->expression('depth', 'depth + :depth', array(':depth' => $shift));
    $query->condition('menu_name', $entity->original->menu_name);
    $p = 'p1';
    for ($i = 1; $i <= MENU_MAX_DEPTH && $entity->original->{$p}; $p = 'p' . ++$i) {
      $query->condition($p, $entity->original->{$p});
    }

    $query->execute();

    // Check the has_children status of the parent, while excluding this item.
    $this->updateParentalStatus($entity->original, TRUE);
  }

  /**
259
   * {@inheritdoc}
260 261
   */
  public function countMenuLinks($menu_name) {
262
    $query = $this->getQuery();
263 264 265 266 267
    $query
      ->condition('menu_name', $menu_name)
      ->count();
    return $query->execute();
  }
268 269 270 271 272 273 274 275 276 277

  /**
   * {@inheritdoc}
   */
  public function getParentFromHierarchy(EntityInterface $entity) {
    $parent_path = $entity->link_path;
    do {
      $parent = FALSE;
      $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));

278
      $query = $this->getQuery();
279 280 281 282 283 284 285 286 287 288 289
      $query
        ->condition('mlid', $entity->id(), '<>')
        ->condition('module', 'system')
        // We always respect the link's 'menu_name'; inheritance for router
        // items is ensured in _menu_router_build().
        ->condition('menu_name', $entity->menu_name)
        ->condition('link_path', $parent_path);

      $result = $query->execute();
      // Only valid if we get a unique result.
      if (count($result) == 1) {
290
        $parent = $this->load(reset($result));
291 292 293 294 295 296
      }
    } while ($parent === FALSE && $parent_path);

    return $parent;
  }

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  /**
   * {@inheritdoc}
   */
  public function createFromDefaultLink(array $item) {
    // Suggested items are disabled by default.
    $item += array(
      'type' => MENU_NORMAL_ITEM,
      'hidden' => 0,
      'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
    );
    if ($item['type'] == MENU_SUGGESTED_ITEM) {
      $item['hidden'] = 1;
    }
    // Note, we set this as 'system', so that we can be sure to distinguish all
    // the menu links generated automatically from hook_menu_link_defaults().
    $item['module'] = 'system';
    return $this->create($item);
  }

316
}