protected function selectEnvironment($environmentId = null, $required = true, $selectDefaultEnv = false)
    {
        $envPrefix = $this->config()->get('service.env_prefix');
        if ($environmentId === null && getenv($envPrefix . 'BRANCH')) {
            $environmentId = getenv($envPrefix . 'BRANCH');
            $this->stdErr->writeln(sprintf(
                'Environment ID read from environment variable %s: %s',
                $envPrefix . 'BRANCH',
                $environmentId
            ), OutputInterface::VERBOSITY_VERBOSE);
        }

        if ($environmentId !== null) {
            $environment = $this->api()->getEnvironment($environmentId, $this->project, null, true);
            if (!$environment) {
                throw new ConsoleInvalidArgumentException('Specified environment not found: ' . $environmentId);
            }

            $this->environment = $environment;
            $this->debug('Selected environment: ' . $this->api()->getEnvironmentLabel($environment));
            return;
        }

        if ($environment = $this->getCurrentEnvironment($this->project)) {
            $this->environment = $environment;
            return;
        }

        if ($selectDefaultEnv) {
            $environments = $this->api()->getEnvironments($this->project);
            $defaultId = $this->api()->getDefaultEnvironmentId($environments);
            if ($defaultId && isset($environments[$defaultId])) {
                $this->environment = $environments[$defaultId];
                return;
            }
        }

        if ($required && isset($this->input) && $this->input->isInteractive()) {
            $this->debug('No environment specified: offering a choice...');
            $this->environment = $this->offerEnvironmentChoice($this->api()->getEnvironments($this->project));
            return;
        }

        if ($required) {
            if ($this->getProjectRoot()) {
                $message = 'Could not determine the current environment.'
                    . "\n" . 'Specify it manually using --environment (-e).';
            } else {
                $message = 'No environment specified.'
                    . "\n" . 'Specify one using --environment (-e), or go to a project directory.';
            }
            throw new ConsoleInvalidArgumentException($message);
        }
    }