You are here

public function UrlEncode::transform in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/migrate/src/Plugin/migrate/process/UrlEncode.php \Drupal\migrate\Plugin\migrate\process\UrlEncode::transform()
  2. 9 core/modules/migrate/src/Plugin/migrate/process/UrlEncode.php \Drupal\migrate\Plugin\migrate\process\UrlEncode::transform()

Performs the associated process.

Parameters

mixed $value: The value to be transformed.

\Drupal\migrate\MigrateExecutableInterface $migrate_executable: The migration in which this process is being executed.

\Drupal\migrate\Row $row: The row from the source to process. Normally, just transforming the value is adequate but very rarely you might need to change two columns at the same time or something like that.

string $destination_property: The destination property currently worked on. This is only used together with the $row above.

Return value

mixed The newly transformed value.

Overrides ProcessPluginBase::transform

File

core/modules/migrate/src/Plugin/migrate/process/UrlEncode.php, line 37

Class

UrlEncode
URL-encodes the input value.

Namespace

Drupal\migrate\Plugin\migrate\process

Code

public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

  // Only apply to a full URL.
  if (is_string($value) && strpos($value, '://') > 0) {

    // URL encode everything after the hostname.
    $parsed_url = parse_url($value);

    // Fail on seriously malformed URLs.
    if ($parsed_url === FALSE) {
      throw new MigrateException("Value '{$value}' is not a valid URL");
    }

    // Iterate over specific pieces of the URL raw URL encoding each one.
    $url_parts_to_encode = [
      'path',
      'query',
      'fragment',
    ];
    foreach ($parsed_url as $parsed_url_key => $parsed_url_value) {
      if (in_array($parsed_url_key, $url_parts_to_encode)) {

        // urlencode() would convert spaces to + signs.
        $urlencoded_parsed_url_value = rawurlencode($parsed_url_value);

        // Restore special characters depending on which part of the URL this is.
        switch ($parsed_url_key) {
          case 'query':
            $urlencoded_parsed_url_value = str_replace('%26', '&', $urlencoded_parsed_url_value);
            break;
          case 'path':
            $urlencoded_parsed_url_value = str_replace('%2F', '/', $urlencoded_parsed_url_value);
            break;
        }
        $parsed_url[$parsed_url_key] = $urlencoded_parsed_url_value;
      }
    }
    $value = (string) Uri::fromParts($parsed_url);
  }
  return $value;
}