VersionInfoManager.php in Admin Toolbar Version 1.0.x
File
src/VersionInfoManager.php
View source
<?php
namespace Drupal\admin_toolbar_version;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleExtensionList;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
class VersionInfoManager {
use StringTranslationTrait;
public function __construct(ConfigFactoryInterface $config_factory, ModuleExtensionList $extensionList, FileSystemInterface $fileSystem) {
$this->extension_list = $extensionList;
$this->config_factory = $config_factory;
$this->config = $this->config_factory
->getEditable('admin_toolbar_version.settings');
$this->file_system = $fileSystem;
}
public function getUrl() {
$url = $this->config
->get('version_url') ?? "/";
if (empty($url)) {
$url = "/";
}
$url = Url::fromUserInput($url)
->toUriString();
return $url;
}
public function getApplicationVersion() {
$version = '';
$version_source = $this->config
->get('version_source');
if (empty($version_source)) {
$version_source = \Drupal::installProfile();
}
$info = $this->extension_list
->getExtensionInfo($version_source);
if (isset($info['version'])) {
$version = $info['version'];
}
return $version;
}
public function getDrupalVersion() {
return \Drupal::VERSION;
}
public function getGitBranch() {
$branch = '';
$environment = $this
->getEnvironmentConfig();
if ($environment['git']) {
$git = $environment['git'];
$path = $this->file_system
->realpath(DRUPAL_ROOT . $git);
if (file_exists($path)) {
$git_file = file_get_contents($path);
$branch = trim(implode('/', array_slice(explode('/', $git_file ?: ''), 2)));
}
}
return $branch;
}
public function getEnvironment() {
$environment = '';
$config = $this
->getEnvironmentConfig();
if ($config) {
$environment = $config['name'];
}
return $environment;
}
public function getTitle() {
$title = [
'drupal' => $this
->getDrupalVersion(),
'version' => $this
->getApplicationVersion(),
'environment' => $this
->getEnvironment(),
'git' => $this
->getGitBranch(),
];
return implode(' - ', array_filter($title));
}
public function getStyle() {
$style = [];
$environment = $this
->getEnvironment();
if ($environment) {
$config = $this
->getEnvironmentConfig();
$style = [
'color' => $config['color'] ?? '#0000FF',
'icon' => preg_replace('@[^a-z0-9_]+@', '_', trim(strtolower($environment))),
];
}
return $style;
}
protected function getEnvironmentConfig() {
static $environment = false;
if (!$environment) {
$request = \Drupal::request();
$environments = $this->config
->get('environments');
foreach ($environments as $econfig) {
if (!empty($econfig['domain']) && !preg_match($econfig['domain'], $request
->getHost())) {
continue;
}
if (!empty($econfig['variable']) && !isset($_ENV[$econfig['variable']])) {
continue;
}
if (empty($econfig['domain']) && empty($econfig['variable'])) {
continue;
}
$environment = $econfig;
break;
}
}
return $environment;
}
}