Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / modules / migrate / src / Plugin / migrate / process / UrlEncode.php
1 <?php
2
3 namespace Drupal\migrate\Plugin\migrate\process;
4
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;
10
11 /**
12  * URL-encodes the input value.
13  *
14  * Example:
15  *
16  * @code
17  * process:
18  *   new_url:
19  *     plugin: urlencode
20  *     source: 'http://example.com/a url with spaces.html'
21  * @endcode
22  *
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'.
25  *
26  * @see \Drupal\migrate\Plugin\MigrateProcessInterface
27  *
28  * @MigrateProcessPlugin(
29  *   id = "urlencode"
30  * )
31  */
32 class UrlEncode extends ProcessPluginBase {
33
34   /**
35    * {@inheritdoc}
36    */
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");
45       }
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) {
54             case 'query':
55               $urlencoded_parsed_url_value = str_replace('%26', '&', $urlencoded_parsed_url_value);
56               break;
57
58             case 'path':
59               $urlencoded_parsed_url_value = str_replace('%2F', '/', $urlencoded_parsed_url_value);
60               break;
61           }
62
63           $parsed_url[$parsed_url_key] = $urlencoded_parsed_url_value;
64         }
65       }
66       $value = (string) Uri::fromParts($parsed_url);
67     }
68     return $value;
69   }
70
71 }