5 * Contains Drupal\drupalmoduleupgrader\Utility\StringTransformTrait.
8 namespace Drupal\drupalmoduleupgrader\Utility;
11 * Contains methods for transforming strings in various helpful ways.
13 trait StringTransformTrait {
16 * Converts a string toCamelCase :)
18 * @param string $string
19 * The string to convert.
23 public function toCamelCase($string) {
24 return preg_replace_callback('/_[a-z]/', function (array $match) { return strToUpper($match[0]{1}); }, $string);
28 * Converts a string ToTitleCase.
30 * @param string $string
31 * The string to convert.
35 public function toTitleCase($string) {
36 $string = $this->toCamelCase($string);
37 $string{0} = strToUpper($string{0});
43 * Trims a prefix (as well as leading or trailing underscore, if any) from a
46 * @param string $string
47 * The string to process.
48 * @param string $prefix
49 * The prefix to trim off, without leading or trailing underscores.
53 public function unPrefix($string, $prefix) {
54 return preg_replace('/^_?' . $prefix . '_/', NULL, $string);
58 * Trims a suffix (as well as leading underscore, if any) from a string.
60 * @param string $string
61 * The string to process.
62 * @param string $suffix
63 * The suffix to trim off, without leading underscore.
67 public function unSuffix($string, $suffix) {
68 return preg_replace('/^_?' . $suffix . '$/', NULL, $string);
72 * Deletes {wildcards} from a route path.
78 public function deleteWildcards($path) {
79 return preg_replace('/\/?\{([a-zA-Z0-9_]+)\}/', NULL, $path);
83 * Deletes %wildcards from a route path.
89 public function deleteLegacyWildcards($path) {
90 return preg_replace('/\/?%[a-zA-Z0-9_]+/', NULL, $path);
94 * Generates an identifier from a Drupal 7 path.
97 * The input path, including any %wildcards.
102 public function getIdentifierFromLegacyPath($path) {
103 return $this->getIdentifierFromPath($this->deleteLegacyWildcards($path));
107 * Generates an identifier from a path.
109 * @param string $path
110 * The input path, including any {wildcards}.
115 public function getIdentifierFromPath($path) {
116 return $this->getIdentifier($this->deleteWildcards($path));
120 * Generates an identifier (prefixed with the module name, if $this->module exists)
121 * from an arbitrary string.
129 public function getIdentifier($string) {
130 // Replace all non-alphanumeric character sequences with an underscore.
131 $id = preg_replace('/[^a-zA-Z0-9_]+/', '_', $string);
133 if (isset($this->module)) {
134 // If the name begins with MODULE_, replace that underscore with a period. Otherwise,
135 // prefix the key with the module's machine name. We want all routes to look like
137 if (strIPos($id, $this->module->getMachineName() . '_') === 0) {
138 $id = preg_replace('/_/', '.', $id, 1);
141 $id = $this->module->getMachineName() . '.' . $id;