View source
<?php
namespace Drupal\feeds\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Url;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
class Uri extends Url {
public function getInfo() {
$info = parent::getInfo();
$info['#allowed_schemes'] = [];
return $info;
}
public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form, StreamWrapperManagerInterface $stream_wrapper_manager = NULL) {
if (empty($stream_wrapper_manager)) {
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
}
$value = $stream_wrapper_manager
->normalizeUri(trim($element['#value']));
$form_state
->setValueForElement($element, $value);
if (!$value) {
return;
}
$parsed = parse_url($value);
$valid = $parsed && !empty($parsed['scheme']) && !empty($parsed['host']);
if (!$valid) {
$form_state
->setError($element, t('The URI %url is not valid.', [
'%url' => $value,
]));
return;
}
if ($element['#allowed_schemes'] && !in_array(static::getScheme($value), $element['#allowed_schemes'], TRUE)) {
$args = [
'%scheme' => static::getScheme($value),
'@schemes' => implode(', ', $element['#allowed_schemes']),
];
$form_state
->setError($element, t("The scheme %scheme is invalid. Available schemes: @schemes.", $args));
}
}
protected static function getScheme($uri) {
$position = strpos($uri, '://');
return $position ? substr($uri, 0, $position) : FALSE;
}
}