public function getCurrentEnvironment(Project $expectedProject = null, $refresh = null)
{
if (!($projectRoot = $this->getProjectRoot()) || !($project = $this->getCurrentProject()) || $expectedProject !== null && $expectedProject->id !== $project->id) {
return false;
}
$gitHelper = $this->getHelper('git');
$gitHelper->setDefaultRepositoryDir($this->getProjectRoot());
$config = $this->localProject->getProjectConfig($projectRoot);
// Check if there is a manual mapping set for the current branch.
if (!empty($config['mapping']) && ($currentBranch = $gitHelper->getCurrentBranch()) && !empty($config['mapping'][$currentBranch])) {
$environment = $this->api()->getEnvironment($config['mapping'][$currentBranch], $project, $refresh);
if ($environment) {
$this->debug('Found mapped environment for branch ' . $currentBranch . ': ' . $environment->id);
return $environment;
} else {
unset($config['mapping'][$currentBranch]);
$this->localProject->writeCurrentProjectConfig($config, $projectRoot);
}
}
// Check whether the user has a Git upstream set to a remote environment
// ID.
$upstream = $gitHelper->getUpstream();
if ($upstream && strpos($upstream, '/') !== false) {
list(, $potentialEnvironment) = explode('/', $upstream, 2);
$environment = $this->api()->getEnvironment($potentialEnvironment, $project, $refresh);
if ($environment) {
$this->debug('Selected environment ' . $potentialEnvironment . ', based on Git upstream: ' . $upstream);
return $environment;
}
}
// There is no Git remote set. Fall back to trying the current branch
// name.
if (!empty($currentBranch) || ($currentBranch = $gitHelper->getCurrentBranch())) {
$environment = $this->api()->getEnvironment($currentBranch, $project, $refresh);
if (!$environment) {
// Try a sanitized version of the branch name too.
$currentBranchSanitized = Environment::sanitizeId($currentBranch);
$environment = $this->api()->getEnvironment($currentBranchSanitized, $project, $refresh);
}
if ($environment) {
$this->debug('Selected environment ' . $environment->id . ' based on branch name: ' . $currentBranch);
return $environment;
}
}
return false;
}