View source
<?php
namespace Drupal\domain;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
class DomainValidator implements DomainValidatorInterface {
use StringTranslationTrait;
protected $moduleHandler;
protected $httpClient;
protected $configFactory;
protected $entityTypeManager;
public function __construct(ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, ClientInterface $http_client, EntityTypeManagerInterface $entity_type_manager) {
$this->moduleHandler = $module_handler;
$this->configFactory = $config_factory;
$this->httpClient = $http_client;
$this->entityTypeManager = $entity_type_manager;
}
public function validate($hostname) {
$error_list = [];
$localhost_check = explode(':', $hostname);
if (substr_count($hostname, '.') == 0 && $localhost_check[0] != 'localhost') {
$error_list[] = $this
->t('At least one dot (.) is required, except when using <em>localhost</em>.');
}
if (substr_count($hostname, ':') > 1) {
$error_list[] = $this
->t('Only one colon (:) is allowed.');
}
elseif (substr_count($hostname, ':') == 1) {
$parts = explode(':', $hostname);
$port = (int) $parts[1];
if (strcmp($port, $parts[1])) {
$error_list[] = $this
->t('The port protocol must be an integer.');
}
}
if (substr($hostname, 0, 1) == '.') {
$error_list[] = $this
->t('The domain must not begin with a dot (.)');
}
if (substr($hostname, -1) == '.') {
$error_list[] = $this
->t('The domain must not end with a dot (.)');
}
$config = $this->configFactory
->get('domain.settings');
$non_ascii = $config
->get('allow_non_ascii');
if (!$non_ascii) {
$pattern = '/^[a-z0-9\\.\\-:]*$/i';
if (!preg_match($pattern, $hostname)) {
$error_list[] = $this
->t('Only alphanumeric characters, dashes, and a colon are allowed.');
}
}
if ($hostname != mb_strtolower($hostname)) {
$error_list[] = $this
->t('Only lower-case characters are allowed.');
}
if ($config
->get('www_prefix') && substr($hostname, 0, strpos($hostname, '.')) == 'www') {
$error_list[] = $this
->t('WWW prefix handling: Domains must be registered without the www. prefix.');
}
$this->moduleHandler
->alter('domain_validate', $error_list, $hostname);
return $error_list;
}
public function checkResponse(DomainInterface $domain) {
$url = $domain
->getPath() . drupal_get_path('module', 'domain') . '/tests/200.png';
try {
$request = $this->httpClient
->get($url);
} catch (RequestException $e) {
$domain
->setResponse(500);
return $domain
->getResponse();
}
$domain
->setResponse($request
->getStatusCode());
return $domain
->getResponse();
}
public function getRequiredFields() {
return [
'hostname',
'name',
'scheme',
'status',
'weight',
];
}
}