Skip to content
Snippets Groups Projects

Issue #3483508 by pdureau: Use a valid URI scheme and rethink...

Merged Pierre Dureau requested to merge issue/ui_patterns-3483508:3483508-2.0.0-beta4-use-a into 2.0.x
Files
4
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Drupal\ui_patterns\Plugin\UiPatterns\PropType;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\ui_patterns\Attribute\PropType;
use Drupal\ui_patterns\PropTypePluginBase;
@@ -22,4 +23,48 @@ use Drupal\ui_patterns\PropTypePluginBase;
)]
class UrlPropType extends PropTypePluginBase {
/**
* {@inheritdoc}
*/
public static function normalize(mixed $value): mixed {
if (is_a($value, '\Drupal\Core\Url')) {
$value = $value->toString();
}
if (!is_string($value)) {
return "";
}
if ($value == "<front>") {
$value = "internal:/";
}
elseif ($value == "<none>") {
$value = "internal:";
}
// We don't use filter_var($value, FILTER_VALIDATE_URL) because too
// restrictive: catch only "scheme://foo".
if (preg_match("/^[a-z]+\:/", $value)) {
return self::resolveUrl($value);
}
// Any other string is considered as a valid path.
// This is not our work to do further checks and transformations.
return $value;
}
/**
* Normalize URL.
*/
protected static function resolveUrl(string $value): string {
// PHP_URL_SCHEME works with "scheme://foo" and "scheme:foo".
$scheme = parse_url($value, PHP_URL_SCHEME);
if (in_array($scheme, ['public', 'private', 'temp'])) {
$generator = \Drupal::service('file_url_generator');
$value = $generator->generateAbsoluteString($value);
return Url::fromUri($value)->toString();
}
if (in_array($scheme, ['internal', 'entity', 'route'])) {
return Url::fromUri($value)->toString();
}
return $value;
}
}
Loading