Set the application environment from command-line arguments.

@param  mixed   $environments
@param  array  $args

@return string
962786
protected function detectConsoleEnvironment($environments, array $args)
    {
        // First we will check if an environment argument was passed via console arguments
        // and if it was that automatically overrides as the environment. Otherwise, we
        // will check the environment as a "web" request like a typical HTTP request.
        if (!is_null($value = $this->getEnvironmentArgument($args))) {
            return head(array_slice(explode('=', $value), 1));
        }
    }
692497
public static function EnvironmentDetectBySystemConfig (array $environmentsSectionData = []) {
		$environment = NULL;
		$app = self::$app ?: self::$app = & \MvcCore\Application::GetInstance();
		$request = $app->GetRequest();
		$clientIp = NULL;
		$serverHostName = NULL;
		$serverGlobals = NULL;
		foreach ((array) $environmentsSectionData as $environmentName => $environmentSection) {
			$sectionData = static::envDetectParseSysConfigEnvSectionData($environmentSection);
			$detected = static::envDetectBySystemConfigEnvSection(
				$sectionData, $request, $clientIp, $serverHostName, $serverGlobals
			);
			if ($detected) {
				$environment = $environmentName;
				break;
			}
		}
		if ($environment && !static::$environment) {
			static::SetEnvironment($environment);
		} else if (!static::$environment) {
			static::SetEnvironment('production');
		}
		return static::$environment;
	}
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;
    }
1062997
public function set(array $args = array()) {
        if (!file_exists('application/data/cache')
            || !file_exists('application/data/logs')
            || !file_exists('public/uploads')
        ) {
            Garp_Cli::lineOut(
                'It looks like there are no directories for me to set permissions on.',
                Garp_Cli::YELLOW
            );
            return true;
        }
        Garp_Cli::lineOut('Setting permissions on writable folders...');
        passthru('chmod -R 777 application/data/cache');
        passthru('chmod -R 777 application/data/logs');
        passthru('chmod -R 777 public/uploads');

        Garp_Cli::lineOut('Done.');
        Garp_Cli::lineOut('');
        return true;
    }
332338
protected function setParams(array $args)
    {
        if (!empty($args)) {
            $request = '?';
        } else {
            $request = '';
        }

        foreach ($args as $key => $value) {
            if (is_numeric($key)) {
                if ($request != '?') {
                    $request .= '&';
                }
                $request .= $value;
            } elseif (is_string($key)) {
                if ($request != '?') {
                    $request .= '&';
                }
                $request .= $key.'='.$value;
            }
        }

        return $request;
    }
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';
	}
937846
protected function environmentStatus(InputInterface $input, OutputInterface $output)
    {

        // If there are no apps, return
        if (count($this->getApplication()->getTerra()->getConfig()->get('apps')) == 0) {
            $output->writeln('<comment>There are no apps!</comment>');
            $output->writeln('Use the command <info>terra app:add</info> to add your first app.');

            return;
        }

        $app_name = $input->getArgument('app_name');
        $environment_name = $input->getArgument('environment_name');

        $app = $this->getApplication()->getTerra()->getConfig()->get('apps', $app_name);

        // If no environments:
        if (count(($app['environments'])) == 0) {
            $output->writeln('<comment>There are no environments!</comment>');
            $output->writeln('Use the command <info>terra environment:add</info> to add your first environment.');

            return;
        }

        // If no environment by that name...
        if (!isset($app['environments'][$environment_name])) {
            $output->writeln("<error>There is no environment named {$environment_name} in the app {$app_name}</error>");

            return;
        }

        $environment = $app['environments'][$environment_name];
        $environment_factory = new EnvironmentFactory($environment, $app);

        $environment['scale'] = $environment_factory->getScale();
        $environment['url'] = 'http://'. $environment_factory->getHost() . ':' . $environment_factory->getPort();
        $environment['url'] .= PHP_EOL.'http://'.$environment_factory->getUrl();

        $table = $this->getHelper('table');
        $table->setHeaders(array(
          'Name',
          'Code Path',
          'docroot',
          'URLs',
          'Version',
          'Scale',
        ));

        $rows = array(
          $environment
        );
        $table->setRows($rows);
        $table->render($output);

        $output->writeln('Docker Compose Path: '.$environment_factory->getDockerComposePath());
    }
308909
public function run($args)
    {
        if (!isset($args[0])) {
            $this->usageError('The environment id is not specified.');
        }
        $id = $args[0];

        $this->flush();

        echo "\nCopying environment files... \n";
        $environmentPath = $this->basePath . '/' . $this->environmentsDir . '/' . $id;
        if (!file_exists($environmentPath)) {
            throw new CException(sprintf("Failed to change environment. Unknown environment '%s'!", $id));
        }
        $fileList = $this->buildFileList($environmentPath, $this->basePath);
        $this->copyFiles($fileList);

        echo "\nEnvironment successfully changed to '{$id}'.\n";
    }
916764
public function getEnvironment(InputInterface $input, OutputInterface $output)
    {

        // If no app...
        if (empty($this->app)) {
            throw new \Exception('App not defined. Call Command::getApp() first.');
        }

        // If no environments:
        if (count(($this->app->environments)) == 0) {
            $output->writeln("<comment>There are no environments for the app {$this->app->name}!</comment>");
            $output->writeln('Use the command <info>terra environment:add</info> to add your first environment.');
            return;
        }

        $helper = $this->getHelper('question');
        $environment_name = $input->getArgument('environment_name');

        // If no environment name specified provide options
        if (empty($environment_name)) {
            $environments = array_flip(array_keys($this->app->environments));
            foreach (array_keys($environments) as $env_key) {
              $environments[$env_key] = $env_key;
            }
            $question = new ChoiceQuestion(
                'Which environment? ',
                $environments,
                null
            );
            $environment_name = $helper->ask($input, $output, $question);
        }

        // Set the environment for this command.
        $this->environment = (object) $this->app->environments[$environment_name];
    }
1050661
public static function cli($args)
    {
        $cwd = getcwd();
        $cli = new self($cwd);

        return $cli->run(array_slice($args, 1));
    }
751389
protected function executeCommand($args)
    {
        $io = clone $this->io;

        $io->setArguments($args);
        $io->setOption('no-backup', true);
        $io->setOption('no-create-database', true);

//        foreach ($this->io->getOptions() as $k => $v)
//        {
//            $io->setOption($k, $v);
//        }

        return $this->console->getRootCommand()->setIO($io)->execute();
    }
1128137
public static function escape(array $args): string
  {
    $command = '';
    foreach ($args as $arg)
    {
      if ($command!='') $command .= ' ';
      $command .= escapeshellarg($arg);
    }

    return $command;
  }
1010115
private function setEnvironmentOption()
    {
        if (!array_key_exists('env', $this->options)) {
            $this->options = array_merge(
                $this->options,
                ['env' => App::environment()]
            );
        }
    }
43816
public function setEnvironment($environment)
    {
        if (array_key_exists('environments', $this->configuration) && array_key_exists($environment, $this->configuration['environments'])) {
            $this->environment = $environment;
            return $this;
        }

        throw new RuntimeException(sprintf('The environment "%s" does not exists.', $environment), 100);
    }
541520
public function getCommand($command = null, $arguments = [], $flags = [], $environmentVariables = [])
    {
        // Format arguments
        $arguments = $this->buildArguments($arguments);
        $options = $this->buildOptions($flags);
        $environmentVariables = $this->buildEnvironmentVariables($environmentVariables);

        // Build command
        $binary = $this->getBinary();
        $components = [$command, $arguments, $options];
        foreach ($components as $component) {
            if ($component) {
                $binary .= ' '.$component;
            }
        }

        // If the binary has a parent, wrap the call with it
        $parent = $this->parent instanceof self ? $this->parent->getBinary() : $this->parent;
        $command = $environmentVariables.$parent.' '.$binary;

        return trim($command);
    }
1121876
public static function setEnvName($arg_env_name)
    {
        if($arg_env_name == 'stage'){
            self::$envName = 'stage';
            self::$domain = self::$domainStage;
        }elseif($arg_env_name == 'prod'){
            self::$envName = 'prod';
            self::$domain = self::$domainProd;
        }else{
            throw new \Exception('Invalid Environment Given',4046969);
        }
    }
115585
public function setEnv($properties)
    {
        $envPath = app()->environmentFilePath();

        $contents = File::get($envPath);
        if(!$contents) {
            throw new \Exception('Could not read env file');
        }

        foreach($properties as $key => $value){
            // Env value must be set so the already loaded file reflect changes
            $this->setEnvValue($key, $value);

            // Change content
            $contents = preg_replace('/' . $key . '=(.*)/', $key . '=' . $value, $contents);
        }

        if (File::put($envPath, $contents) === false) {
            throw new \Exception('Could not write env file');
        }

        return true;
    }