From ebae5c57c88306231ef928efe5c5c59f81715e16 Mon Sep 17 00:00:00 2001 From: Steffan Date: Fri, 26 Jul 2024 16:49:47 +0200 Subject: [PATCH] refactor: allow whitespace, rename vars to replace --- Taskfile.yml | 4 ++-- src/StringHelper.php | 10 +++------- src/TaskHelper.php | 6 +++--- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/Taskfile.yml b/Taskfile.yml index abae228..0018876 100755 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -19,9 +19,9 @@ tasks: env: TASK_CWD: '{{.cwd}}' cmds: - - composer run:task -q -- placeholder {{q .src}} {{q (toRawJson .vars)}} + - composer run:task -q -- placeholder {{q .src}} {{q (toRawJson .replace)}} {{if .ignore}}{{.ignore}}{{end}} requires: - vars: [src, vars] + vars: [src, replace] internal: true zip: diff --git a/src/StringHelper.php b/src/StringHelper.php index 5c3dff3..a437fa2 100644 --- a/src/StringHelper.php +++ b/src/StringHelper.php @@ -4,14 +4,10 @@ class StringHelper { - public static function placeholder(string $data, array $vars): string + public static function placeholder(string $str, array $replace): string { - $replace = []; + $callback = fn($matches) => $replace[$matches[1]] ?? $matches[0]; - foreach ($vars as $key => $value) { - $replace["{{ {$key} }}"] = $value; - } - - return str_replace(array_keys($replace), array_values($replace), $data); + return preg_replace_callback('/{{\s*(\w+?)\s*}}/', $callback, $str); } } diff --git a/src/TaskHelper.php b/src/TaskHelper.php index c6f3460..fcce885 100644 --- a/src/TaskHelper.php +++ b/src/TaskHelper.php @@ -43,11 +43,11 @@ public function copy(string $src, string $dest, string $ignore = ''): void " to '{$dest}'\n"; } - public function placeholder(string $src, string $vars): void + public function placeholder(string $src, string $replace, string $ignore = ''): void { $fs = new Filesystem(); - $files = self::findFiles($this->cwd, $src); - $variables = json_decode($vars, true); + $files = self::findFiles($this->cwd, $src, $ignore); + $variables = json_decode($replace, true); foreach ($files as $file) { $fs->dumpFile($file->getPathname(), Str::placeholder($file->getContents(), $variables));