Detect the application's current environment.

@param  array|string  $environments
@param  array|null  $consoleArgs

@return string
12731
public function detect($environments, $consoleArgs = null)
    {
        if ($consoleArgs && $env = $this->detectConsoleEnvironment($environments, $consoleArgs)) {
            return $env;
        } elseif ($env = $this->detectClosureEnvironment($environments)) {
            return $env;
        } elseif ($env = $this->detectVariableEnvironment($environments)) {
            return $env;
        }
        return $this->detectWebEnvironment($environments);
    }
1089780
public ServiceCall<Environment> getEnvironment(GetEnvironmentOptions getEnvironmentOptions) {
    Validator.notNull(getEnvironmentOptions, "getEnvironmentOptions cannot be null");
    String[] pathSegments = { "v1/environments" };
    String[] pathParameters = { getEnvironmentOptions.environmentId() };
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
        pathParameters));
    builder.query("version", versionDate);
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "getEnvironment");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
      builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Environment.class));
  }
735262
private void read_env() {
        String env;
        try {
            if ((env = System.getProperty("TANGO_HOST")) == null) {
		if ((env = System.getenv("TANGO_HOST")) == null) {
		    Except.throw_connection_failed("TangoApi_TANGO_HOST_NOT_SET",
			    "Property \"TANGO_HOST\" not exported", "TangoDs.Util.read_env()");
		}
	    }

	    assert env != null;
	    if (env.indexOf(":") < 0) {
		Except.throw_connection_failed("TangoApi_TANGO_HOST_NOT_SET",
			"Unknown \"TANGO_HOST\" property " + env, "TangoDs.Util.read_env()");
	    }
	    final String[] array = ApiUtil.parseTangoHost(env);
	    db_host = array[0];
	} catch (final DevFailed e) {
	    Except.print_exception(e);
	    System.exit(-1);
	}
    }
1271677
protected final function offerEnvironmentChoice(array $environments)
    {
        if (!isset($this->input) || !isset($this->output) || !$this->input->isInteractive()) {
            throw new \BadMethodCallException('Not interactive: an environment choice cannot be offered.');
        }

        /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
        $questionHelper = $this->getService('question_helper');
        $default = $this->api()->getDefaultEnvironmentId($environments);

        // Build and sort a list of options (environment IDs).
        $ids = array_keys($environments);
        sort($ids, SORT_NATURAL | SORT_FLAG_CASE);

        $id = $questionHelper->askInput('Environment ID', $default, array_keys($environments), function ($value) use ($environments) {
            if (!isset($environments[$value])) {
                throw new \RuntimeException('Environment not found: ' . $value);
            }

            return $value;
        });

        $this->stdErr->writeln('');

        return $environments[$id];
    }
461008
public function getEnvironment($config = null)
    {
        if ( ! $this->environment) {
            if (null == $config) {
                $config = $this->getConfig();
            }

            $this->environment = new Environment($config);
        }

        return $this->environment;
    }
932108
public static function selectEnvironment($env = null) 
    {
        if (strlen($env) < 1) {
            $getenv = self::_getEnvironment();
            if (strlen($getenv) > 0) {
                $env = $getenv;
            } else {
                $env = "development";
            }
        }
        return $env;
    }
903382
public function detectEnvironment($environments)
    {
        $r = Request::getInstance();
        $pos = stripos($r->server->get('SCRIPT_NAME'), DISPATCHER_FILENAME);
        if ($pos > 0) {
            //we do this because in CLI circumstances (and some random ones) we would end up with index.ph instead of index.php
            $pos = $pos - 1;
        }
        $home = substr($r->server->get('SCRIPT_NAME'), 0, $pos);
        $this['app_relative_path'] = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $home), '/');

        $args = $this->isRunThroughCommandLineInterface() && isset($_SERVER['argv']) ? $_SERVER['argv'] : null;

        $detector = new EnvironmentDetector();

        return $this->environment = $detector->detect($environments, $args);
    }
1272275
protected function setDefaultEnvironment() {
		#Using _ENV_ and $_SERVER only as the last chance to guess the environment.
		#User can and should set the environment through constructor or setEnv($env).

		if(isset($this->params['env']))
			return;
		if(defined('_ENV_'))
			$this->params['env'] = _ENV_;
		elseif(file_exists($file = $this->params['root'].'/storage/environment'))
			$this->params['env'] = trim(file_get_contents($file));
		elseif($this->get('consoleMode')) {
			foreach($_SERVER['argv'] as $k=>$v) {
				if($v === '--env' && isset($_SERVER['argv'][$k+1])) {
					$this->params['env'] = $_SERVER['argv'][$k+1];
					return;
				}
			}
			$this->params['env'] = 'dev';
		}
		elseif(php_sapi_name() === 'cli' || (isset($_SERVER['HTTP_HOST']) && ($_SERVER['HTTP_HOST'] == '127.0.0.1' || $_SERVER['HTTP_HOST'] == 'localhost')))
			$this->params['env'] = 'dev';
		else
			$this->params['env'] = 'prod';
	}
1165679
public function setup($environment = null, $default = 'development')
    {
        if (Configure::read('Environment.setup')) {
            return false;
        }

        $current = $this->currentEnvironment($environment, $default);

        if (!isset($this->environments[$current])) {
            throw new Exception(sprintf('Environment %s does not exist.', $current));
        }

        $config = array_merge(
            $this->environments[$current]['config'],
            ['Environment.name' => $current]
        );
        foreach ($config as $param => $value) {
            Configure::write($param, $value);
        }

        if (is_callable($this->environments[$current]['callable'])) {
            $this->environments[$current]['callable']();
        }

        Configure::write('Environment.setup', true);

        return true;
    }
1219095
public function getDefaultEnvironmentId(array $environments)
    {
        // If there is only one environment, use that.
        if (count($environments) <= 1) {
            $environment = reset($environments);

            return $environment ? $environment->id : null;
        }

        // Check if there is only one "main" environment.
        $main = array_filter($environments, function (Environment $environment) {
            return $environment->is_main;
        });
        if (count($main) === 1) {
            $environment = reset($main);

            return $environment ? $environment->id : null;
        }

        // Check if there is a "master" environment.
        if (isset($environments['master'])) {
            return 'master';
        }

        return null;
    }
255799
public function detectEnvironment(Closure $callback)
    {
        $args = $_SERVER['argv'] ?? null;

        return $this['env'] = (new EnvironmentDetector())->detect($callback, $args);
    }
150631
protected function currentEnvironment($environment = null, $default = 'development')
    {
        $current = ($environment === null) ? $default : $environment;
        if (empty($environment)) {
            foreach ($this->environments as $name => $config) {
                if ($this->_match($name, $config['params'])) {
                    $current = $name;
                    break;
                }
            }
        }

        return $current;
    }
1061040
public function getCurrentEnvironmentName()
    {
        if (!empty($this->currentEnvironmentName)) {
            return $this->currentEnvironmentName;
        }

        // get current environments
        $environments = $this->applicationConfig->get('Application.Environments', false);

        if($environments){
            // get current url
            $currentUrl = $this->str($this->httpRequest()->getCurrentUrl());

            // loop over all registered environments in the config, and try to match the current based on the domain
            foreach ($environments as $eName => $e) {
                if ($currentUrl->contains($e->Domain)) {
                    $this->currentEnvironmentName = $eName;
                }
            }
        }

        if (empty($this->currentEnvironmentName)) {
            $this->currentEnvironmentName = 'Production';
        }

        return $this->currentEnvironmentName;
    }
1310287
public function environment(...$environments)
    {
        $env = \env('APP_ENV', 'production');

        if (\func_num_args() > 0) {
            $patterns = \is_array($environments[0]) ? $environments[0] : $environments;

            foreach ($patterns as $pattern) {
                if (Str::is($pattern, $env)) {
                    return true;
                }
            }

            return false;
        }

        return $env;
    }
1122557
public static function factory(?Enviroment $environment = null): Parser
    {
        $environment = $environment ?? Enviroment::getFromSapi(PHP_SAPI);

        return self::evaluate($environment)->isInstanceOf(Parser::class)->getValue();
    }
372490
public function getEnvironment($name)
    {
        if (isset($this->environments[$name])) {
            return $this->environments[$name];
        }

        // check the environment exists
        if (!$this->getConfig()->hasEnvironment($name)) {
            throw new \InvalidArgumentException(sprintf(
                'The environment "%s" does not exist',
                $name
            ));
        }

        // create an environment instance and cache it
        $envOptions = $this->getConfig()->getEnvironment($name);
        $envOptions['version_order'] = $this->getConfig()->getVersionOrder();

        $environment = new Environment($name, $envOptions);
        $this->environments[$name] = $environment;
        $environment->setCommand($this->getCommand());

        return $environment;
    }
802674
protected static function duskEnvironment($options)
    {
        if (! isset($options['environments'])) {
            return false;
        }

        if (is_string($options['environments'])) {
            $options['environments'] = [$options['environments']];
        }

        if (! is_array($options['environments'])) {
            throw new InvalidArgumentException('Dusk environments must be listed as an array.');
        }

        return app()->environment(...$options['environments']);
    }