3 namespace Drupal\migrate\Plugin\migrate\process;
5 use Drupal\migrate\MigrateExecutableInterface;
6 use Drupal\migrate\MigrateException;
7 use Drupal\migrate\ProcessPluginBase;
8 use Drupal\migrate\Row;
9 use GuzzleHttp\Psr7\Uri;
12 * URL-encodes the input value.
20 * source: 'http://example.com/a url with spaces.html'
23 * This will convert the source URL 'http://example.com/a url with spaces.html'
24 * into 'http://example.com/a%20url%20with%20spaces.html'.
26 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
28 * @MigrateProcessPlugin(
32 class UrlEncode extends ProcessPluginBase {
37 public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
38 // Only apply to a full URL.
39 if (is_string($value) && strpos($value, '://') > 0) {
40 // URL encode everything after the hostname.
41 $parsed_url = parse_url($value);
42 // Fail on seriously malformed URLs.
43 if ($parsed_url === FALSE) {
44 throw new MigrateException("Value '$value' is not a valid URL");
46 // Iterate over specific pieces of the URL rawurlencoding each one.
47 $url_parts_to_encode = ['path', 'query', 'fragment'];
48 foreach ($parsed_url as $parsed_url_key => $parsed_url_value) {
49 if (in_array($parsed_url_key, $url_parts_to_encode)) {
50 // urlencode() would convert spaces to + signs.
51 $urlencoded_parsed_url_value = rawurlencode($parsed_url_value);
52 // Restore special characters depending on which part of the URL this is.
53 switch ($parsed_url_key) {
55 $urlencoded_parsed_url_value = str_replace('%26', '&', $urlencoded_parsed_url_value);
59 $urlencoded_parsed_url_value = str_replace('%2F', '/', $urlencoded_parsed_url_value);
63 $parsed_url[$parsed_url_key] = $urlencoded_parsed_url_value;
66 $value = (string) Uri::fromParts($parsed_url);