You are here

function environment_switch in Environment 8

Same name and namespace in other branches
  1. 6 environment.module \environment_switch()
  2. 7 environment.module \environment_switch()

Switches between two environments.

Parameters

string $target_env: Name of the environment to change to.

bool $force: (optional) Whether to trigger a change even if the environment is the currently set one. Defaults to FALSE.

Return value

bool Return TRUE if successful.

4 calls to environment_switch()
drush_environment_switch in ./environment.drush.inc
Implements drush_hook_COMMAND for environment_switch.
EnvironmentAdminSettings::submitForm in src/Form/EnvironmentAdminSettings.php
Form submission handler.
EnvironmentSubscriber::checkForEnvironmentSwitch in src/EventSubscriber/EnvironmentSubscriber.php
EnvironmentSwitchConfirm::submitForm in src/Form/EnvironmentSwitchConfirm.php
Form submission handler.

File

./environment.module, line 20
Module for handling changes in server environments

Code

function environment_switch($target_env, $force = FALSE, $clear_cache = TRUE) {
  $result = FALSE;
  $messages = array();
  $target_state = environment_load($target_env);
  $current_env = environment_current();
  $override = \Drupal::config('environment.settings')
    ->get('environment_override');
  if (!$force && $current_env == $target_env) {
    drupal_set_message(t("The current environment is already set to '!environment'.", array(
      '!environment' => $target_env,
    )), 'notice');
    $result = TRUE;

    // This option is only available in drush.
    if (function_exists('drush_print')) {
      drush_print("To force the environment switch to run anyway, use the '--force' flag.");
    }
  }
  if (!$force && !empty($override)) {
    drupal_set_message(t("The current environment is overriden with '!override'.", array(
      '!override' => $override,
    )), 'error');

    // This option is only available in drush.
    if (function_exists('drush_print')) {
      drush_print("To force the environment switch to run anyway, use the '--force' flag.");
    }
  }
  elseif ($current_env != $target_env || $force) {
    if (empty($target_state)) {
      drupal_set_message(t('Environment !environment does not exist.', array(
        '!environment' => $target_env,
      )), 'warning');
    }
    else {
      environment_set($target_env);
      \Drupal::moduleHandler()
        ->invokeAll('environment_switch', [
        $target_env,
        $current_env,
      ]);
      if ($clear_cache) {
        drupal_flush_all_caches();
        drupal_set_message('Cleared cache.');
      }
      $result = TRUE;
    }
  }
  return $result;
}