2 namespace Robo\Task\File;
5 use Robo\Task\BaseTask;
8 * Performs search and replace inside a files.
12 * $this->taskReplaceInFile('VERSION')
17 * $this->taskReplaceInFile('README.md')
22 * $this->taskReplaceInFile('config.yml')
23 * ->regex('~^service:~')
27 * $this->taskReplaceInFile('box/robo.txt')
28 * ->from(array('##dbname##', '##dbhost##'))
29 * ->to(array('robo', 'localhost'))
34 class Replace extends BaseTask
42 * @var string|string[]
47 * @var string|string[]
57 * @param string $filename
59 public function __construct($filename)
61 $this->filename = $filename;
65 * @param string $filename
69 public function filename($filename)
71 $this->filename = $filename;
76 * String(s) to be replaced.
78 * @param string|string[] $from
82 public function from($from)
89 * Value(s) to be set as a replacement.
91 * @param string|string[] $to
95 public function to($to)
102 * Regex to match string to be replaced.
104 * @param string $regex
108 public function regex($regex)
110 $this->regex = $regex;
117 public function run()
119 if (!file_exists($this->filename)) {
120 $this->printTaskError('File {filename} does not exist', ['filename' => $this->filename]);
124 $text = file_get_contents($this->filename);
126 $text = preg_replace($this->regex, $this->to, $text, -1, $count);
128 $text = str_replace($this->from, $this->to, $text, $count);
131 $res = file_put_contents($this->filename, $text);
132 if ($res === false) {
133 return Result::error($this, "Error writing to file {filename}.", ['filename' => $this->filename]);
135 $this->printTaskSuccess("{filename} updated. {count} items replaced", ['filename' => $this->filename, 'count' => $count]);
137 $this->printTaskInfo("{filename} unchanged. {count} items replaced", ['filename' => $this->filename, 'count' => $count]);
139 return Result::success($this, '', ['replaced' => $count]);