You are here

public function RuleChainManager::rebuildChain in ThemeKey 8

Overrides RuleChainManagerInterface::rebuildChain

File

src/RuleChainManager.php, line 62
Contains OperatorManager.

Class

RuleChainManager
ThemeKey Rule Chain manager.

Namespace

Drupal\themekey

Code

public function rebuildChain() {
  $changed = FALSE;
  $chain = $this
    ->ruleChainConfig()
    ->get('chain');
  if (!is_array($chain)) {
    $chain = array();
  }

  // Get max weight.
  $weight = 0;
  foreach ($chain as $element) {
    if ($element['weight'] > $weight) {
      $weight = $element['weight'];
    }
  }
  $rules = ThemeKeyRule::loadMultiple();

  // Add new rules to chain.
  $ruleIds = array();
  foreach ($rules as $rule) {
    $id = $rule
      ->id();
    $ruleIds[] = $id;
    if (!array_key_exists($id, $chain)) {
      $chain[$id] = array(
        'weight' => ++$weight,
        'parent' => NULL,
        'enabled' => TRUE,
        'depth' => 0,
      );
      $changed = TRUE;
    }
  }

  // Remove deleted rules from chain.
  $deletedRuleIds = array_diff(array_keys($chain), $ruleIds);
  foreach ($deletedRuleIds as $id) {
    $parent = $chain[$id]['parent'];
    unset($chain[$id]);
    foreach ($chain as $element) {
      if ($element['parent'] == $id) {
        $element['parent'] = $parent;
      }
    }
    $changed = TRUE;
  }
  if ($changed) {
    $this
      ->setChain($chain);
  }
}