Skip to content
Snippets Groups Projects

ISTWCMS-7266: Refactor link handling logic in UwCblLinks block.

Merged Igor Biki requested to merge feature/ISTWCMS-7266-ibiki-links_and_titles into 1.1.x
1 file
+ 34
7
Compare changes
  • Side-by-side
  • Inline
@@ -8,6 +8,7 @@ use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Path\PathValidatorInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Drupal\media\Entity\Media;
use Drupal\path_alias\AliasManager;
use Drupal\uw_cfg_common\Service\UWService;
@@ -946,12 +947,8 @@ class UwCblLinks extends BlockBase implements ContainerFactoryPluginInterface {
$link = substr_replace($link, '', 0, strlen('internal:'));
}
// Remove base path, this will be used to validate url.
if ($base_path && str_starts_with($link, $base_path)) {
$link = substr_replace($link, '', 0, strlen($base_path));
}
// If an external link is detected, and it has a leading slash, remove it.
// In some cases, the external link is prefixed with a leading slash. This
// removes that leading slash.
$updated = preg_replace(self::LEADING_SLASH_REPLACE_REGEX, '$1', $link);
// In case match is not found, unchanged value is returned.
@@ -960,7 +957,7 @@ class UwCblLinks extends BlockBase implements ContainerFactoryPluginInterface {
$link = $updated;
}
$path = $this->pathValidator->getUrlIfValidWithoutAccessCheck($link);
$path = $this->getInternalUrlIfValid($link, $base_path);
// If node alias is used, modify it so a canonical link is used.
if ($path && !$path->isExternal()) {
@@ -1045,4 +1042,34 @@ class UwCblLinks extends BlockBase implements ContainerFactoryPluginInterface {
return $title ?? "";
}
/**
* Validates and retrieves an internal URL if applicable.
*
* Checks if the provided URL starts with the specified base path
* and attempts to validate it as an internal path without access checks.
*
* @param string $url
* The URL to be validated.
* @param string $base_path
* The base path to check against.
*
* @return \Drupal\Core\Url|null
* The valid internal URL object if the URL is valid and matches the
* base path, or NULL otherwise.
*/
private function getInternalUrlIfValid(string $url, string $base_path): ?Url {
$link = $url;
// Remove base path, this will be used to validate url.
if ($base_path && str_starts_with($link, $base_path)) {
$link = substr_replace($link, '', 0, strlen($base_path));
}
if ($path = $this->pathValidator->getUrlIfValidWithoutAccessCheck($link)) {
return $path;
}
return NULL;
}
}
Loading