3 namespace Drupal\drupalmoduleupgrader\Plugin\DMU\Converter\Functions;
5 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
6 use Drupal\Core\Routing\RouteProviderInterface;
7 use Drupal\Core\StringTranslation\TranslationInterface;
8 use Drupal\drupalmoduleupgrader\TargetInterface;
9 use Pharborist\Functions\FunctionCallNode;
10 use Pharborist\Objects\ClassMethodCallNode;
11 use Pharborist\Types\StringNode;
12 use Psr\Log\LoggerInterface;
17 * description = @Translation("Rewrites calls to url()."),
18 * fixme = @Translation("url() expects a route name or an external URI."),
19 * dependencies = { "router.route_provider" }
22 class URL extends FunctionCallModifier implements ContainerFactoryPluginInterface {
25 * @var \Drupal\Core\Routing\RouteProviderInterface
27 protected $routeProvider;
29 public function __construct(array $configuration, $plugin_id, $plugin_definition, TranslationInterface $translator, LoggerInterface $log, RouteProviderInterface $route_provider) {
30 parent::__construct($configuration, $plugin_id, $plugin_definition, $translator, $log);
31 $this->routeProvider = $route_provider;
35 * Looks up routes by path, and returns TRUE if at least one was found.
38 * The path to search for, not including the leading slash. Can be an
42 * TRUE if the path matches a route, FALSE otherwise. External URLs will
43 * always return FALSE.
45 protected function routeExists($path) {
46 // If there's a scheme in the URL, consider this an external URL and don't even
48 $scheme = parse_url($path, PHP_URL_SCHEME);
53 $routes = $this->routeProvider->getRoutesByPattern('/' . $path);
54 return (sizeof($routes) > 0);
61 public function rewrite(FunctionCallNode $call, TargetInterface $target) {
62 $arguments = $call->getArguments();
63 if ($arguments[0] instanceof StringNode) {
64 $path = $arguments[0]->toValue();
66 // If the URL has a scheme (e.g., http://), it's external.
67 if (parse_url($path, PHP_URL_SCHEME)) {
68 return ClassMethodCallNode::create('\Drupal\Core\Url', 'fromUri')
69 ->appendArgument(clone $arguments[0]);
71 elseif ($this->routeExists($path)) {
72 $route = $this->routeProvider->getRoutesByPattern('/' . $path)->getIterator()->key();
73 return ClassMethodCallNode::create('\Drupal\Core\Url', 'fromRoute')
74 ->appendArgument(StringNode::fromValue($route));