Jun 27, 2014

Function drupal_lookup_path() has been removed

In one place in the Optimizely code, I replaced the function as follows, where the first parameter to drupal_lookup_path() is 'alias'.

Drupal 7:
$path .= drupal_lookup_path('alias', $path);
Drupal 8:
$alias =
  \Drupal::service('path.alias_manager')
    ->getPathAlias($path);

if (strcmp($alias, $path) == 0) {
  $alias = '';  // No alias was found.
}

$path .= $alias;

If no alias is found, getPathAlias() returns its argument, hence the string comparison to check whether an alias was found or not.

In one of the new classes AddUpdateForm of the converted module, there was code copied over that contained numerous calls to drupal_lookup_path().

I decided to write two adapter methods to interface with the new alias manager. Those methods pass back return values that are identical to those of drupal_lookup_path() so that the methods can be easily dropped into the existing code that calls the old function.
private function lookupPathAlias($path) {
  $alias =
    \Drupal::service('path.alias_manager')
      ->getPathAlias($path);

  return (strcmp($alias, $path) == 0) ?
            FALSE : $alias;
}

private function lookupSystemPath($alias) {
  $path =
    \Drupal::service('path.alias_manager')
      ->getSystemPath($alias);

  return (strcmp($path, $alias) == 0) ?
            FALSE : $path;
}

With these two methods, the following, for example,
if (drupal_lookup_path('alias', $path) === FALSE &&
    drupal_lookup_path('source', $path) === FALSE) {
  return $path;

}
is simply replaced with
if ($this->lookupPathAlias($path) === FALSE &&
    $this->lookupSystemPath($path) === FALSE) {
  return $path;
}

Update for Drupal 8, alpha 13: method names for class AliasManager have changed. See  http://optimizely-to-drupal-8.blogspot.com/2014/08/drupal-8-alpha11-alpha13.html

Sources:

function drupal_lookup_path
https://api.drupal.org/api/drupal/includes!path.inc/function/drupal_lookup_path/7

Path alias management is now pluggable
https://www.drupal.org/node/1853148

No comments:

Post a Comment