Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Component / Utility / Tags.php
1 <?php
2
3 namespace Drupal\Component\Utility;
4
5 /**
6  * Defines a class that can explode and implode tags.
7  *
8  * @ingroup utility
9  */
10 class Tags {
11
12   /**
13    * Explodes a string of tags into an array.
14    *
15    * @param string $tags
16    *   A string to explode.
17    *
18    * @return array
19    *   An array of tags.
20    */
21   public static function explode($tags) {
22     // This regexp allows the following types of user input:
23     // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
24     $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
25     preg_match_all($regexp, $tags, $matches);
26     $typed_tags = array_unique($matches[1]);
27
28     $tags = [];
29     foreach ($typed_tags as $tag) {
30       // If a user has escaped a term (to demonstrate that it is a group,
31       // or includes a comma or quote character), we remove the escape
32       // formatting so to save the term into the database as the user intends.
33       $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
34       if ($tag != "") {
35         $tags[] = $tag;
36       }
37     }
38
39     return $tags;
40   }
41
42   /**
43    * Encodes a tag string, taking care of special cases like commas and quotes.
44    *
45    * @param string $tag
46    *   A tag string.
47    *
48    * @return string
49    *   The encoded string.
50    */
51   public static function encode($tag) {
52     if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
53       return '"' . str_replace('"', '""', $tag) . '"';
54     }
55     return $tag;
56   }
57
58   /**
59    * Implodes an array of tags into a string.
60    *
61    * @param array $tags
62    *   An array of tags.
63    *
64    * @return string
65    *   The imploded string.
66    */
67   public static function implode($tags) {
68     $encoded_tags = [];
69     foreach ($tags as $tag) {
70       $encoded_tags[] = self::encode($tag);
71     }
72     return implode(', ', $encoded_tags);
73   }
74
75 }