Completed
Push — master ( 061d1e...31cfb3 )
by Greg
02:26
created

src/Task/File/Write.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Robo\Task\File;
4
5
use Robo\Result;
6
use Robo\Task\BaseTask;
7
8
/**
9
 * Writes to file.
10
 *
11
 * ``` php
12
 * <?php
13
 * $this->taskWriteToFile('blogpost.md')
14
 *      ->line('-----')
15
 *      ->line(date('Y-m-d').' '.$title)
16
 *      ->line('----')
17
 *      ->run();
18
 * ?>
19
 * ```
20
 */
21
class Write extends BaseTask
22
{
23
    /**
24
     * @var array
25
     */
26
    protected $stack = [];
27
28
    /**
29
     * @var string
30
     */
31
    protected $filename;
32
33
    /**
34
     * @var bool
35
     */
36
    protected $append = false;
37
38
    /**
39
     * @var null|string
40
     */
41
    protected $originalContents = null;
42
43
    /**
44
     * @param string $filename
45
     */
46
    public function __construct($filename)
47
    {
48
        $this->filename = $filename;
49
    }
50
51
    /**
52
     * @param string $filename
53
     *
54
     * @return $this
55
     */
56
    public function filename($filename)
57
    {
58
        $this->filename = $filename;
59
        return $this;
60
    }
61
62
    /**
63
     * @param bool $append
64
     *
65
     * @return $this
66
     */
67
    public function append($append = true)
68
    {
69
        $this->append = $append;
70
        return $this;
71
    }
72
73
    /**
74
     * add a line.
75
     *
76
     * @param string $line
77
     *
78
     * @return $this The current instance
79
     */
80
    public function line($line)
81
    {
82
        $this->text($line . "\n");
83
        return $this;
84
    }
85
86
    /**
87
     * add more lines.
88
     *
89
     * @param array $lines
90
     *
91
     * @return $this The current instance
92
     */
93
    public function lines(array $lines)
94
    {
95
        $this->text(implode("\n", $lines) . "\n");
96
        return $this;
97
    }
98
99
    /**
100
     * add a text.
101
     *
102
     * @param string $text
103
     *
104
     * @return $this The current instance
105
     */
106
    public function text($text)
107
    {
108
        $this->stack[] = array_merge([__FUNCTION__ . 'Collect'], func_get_args());
109
        return $this;
110
    }
111
112
    /**
113
     * add a text from a file.
114
     *
115
     * Note that the file is read in the run() method of this task.
116
     * To load text from the current state of a file (e.g. one that may
117
     * be deleted or altered by other tasks prior the execution of this one),
118
     * use:
119
     *       $task->text(file_get_contents($filename));
120
     *
121
     * @param string $filename
122
     *
123
     * @return $this The current instance
124
     */
125
    public function textFromFile($filename)
126
    {
127
        $this->stack[] = array_merge([__FUNCTION__ . 'Collect'], func_get_args());
128
        return $this;
129
    }
130
131
    /**
132
     * substitute a placeholder with value, placeholder must be enclosed by `{}`.
133
     *
134
     * @param string $name
135
     * @param string $val
136
     *
137
     * @return $this The current instance
138
     */
139
    public function place($name, $val)
140
    {
141
        $this->replace('{'.$name.'}', $val);
142
143
        return $this;
144
    }
145
146
    /**
147
     * replace any string with value.
148
     *
149
     * @param string $string
150
     * @param string $replacement
151
     *
152
     * @return $this The current instance
153
     */
154
    public function replace($string, $replacement)
0 ignored issues
show
The parameter $string is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $replacement is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
155
    {
156
        $this->stack[] = array_merge([__FUNCTION__ . 'Collect'], func_get_args());
157
        return $this;
158
    }
159
160
    /**
161
     * replace any string with value using regular expression.
162
     *
163
     * @param string $pattern
164
     * @param string $replacement
165
     *
166
     * @return $this The current instance
167
     */
168
    public function regexReplace($pattern, $replacement)
0 ignored issues
show
The parameter $pattern is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $replacement is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
169
    {
170
        $this->stack[] = array_merge([__FUNCTION__ . 'Collect'], func_get_args());
171
        return $this;
172
    }
173
174
    /**
175
     * Append the provided text to the end of the buffer if the provided
176
     * regex pattern matches any text already in the buffer.
177
     *
178
     * @param string $pattern
179
     * @param string $text
180
     *
181
     * @return $this
182
     */
183
    public function appendIfMatches($pattern, $text)
184
    {
185
        $this->stack[] = array_merge(['appendIfMatchesCollect'], [$pattern, $text, true]);
186
        return $this;
187
    }
188
189
    /**
190
     * Append the provided text to the end of the buffer unless the provided
191
     * regex pattern matches any text already in the buffer.
192
     *
193
     * @param string $pattern
194
     * @param string $text
195
     *
196
     * @return $this
197
     */
198
    public function appendUnlessMatches($pattern, $text)
199
    {
200
        $this->stack[] = array_merge(['appendIfMatchesCollect'], [$pattern, $text, false]);
201
        return $this;
202
    }
203
204
    /**
205
     * @param $contents string
206
     * @param $filename string
207
     *
208
     * @return string
209
     */
210
    protected function textFromFileCollect($contents, $filename)
211
    {
212
        if (file_exists($filename)) {
213
            $contents .= file_get_contents($filename);
214
        }
215
        return $contents;
216
    }
217
218
    /**
219
     * @param string|string[] $contents
220
     * @param string|string[] $string
221
     * @param string|string[] $replacement
222
     *
223
     * @return string|string[]
224
     */
225
    protected function replaceCollect($contents, $string, $replacement)
226
    {
227
        return str_replace($string, $replacement, $contents);
228
    }
229
230
    /**
231
     * @param string|string[] $contents
232
     * @param string|string[] $pattern
233
     * @param string|string[] $replacement
234
     *
235
     * @return string|string[]
236
     */
237
    protected function regexReplaceCollect($contents, $pattern, $replacement)
238
    {
239
        return preg_replace($pattern, $replacement, $contents);
240
    }
241
242
    /**
243
     * @param string $contents
244
     * @param string $text
245
     *
246
     * @return string
247
     */
248
    protected function textCollect($contents, $text)
249
    {
250
        return $contents . $text;
251
    }
252
253
    /**
254
     * @param string $contents
255
     * @param string $pattern
256
     * @param string $text
257
     * @param bool $shouldMatch
258
     *
259
     * @return string
260
     */
261
    protected function appendIfMatchesCollect($contents, $pattern, $text, $shouldMatch)
262
    {
263
        if (preg_match($pattern, $contents) == $shouldMatch) {
264
            $contents .= $text;
265
        }
266
        return $contents;
267
    }
268
269
    /**
270
     * @return string
271
     */
272
    public function originalContents()
273
    {
274
        if (!isset($this->originalContents)) {
275
            $this->originalContents = '';
276
            if (file_exists($this->filename)) {
277
                $this->originalContents = file_get_contents($this->filename);
278
            }
279
        }
280
        return $this->originalContents;
281
    }
282
283
    /**
284
     * @return bool
285
     */
286
    public function wouldChange()
287
    {
288
        return $this->originalContents() != $this->getContentsToWrite();
289
    }
290
291
    /**
292
     * @return string
293
     */
294
    protected function getContentsToWrite()
295
    {
296
        $contents = "";
297
        if ($this->append) {
298
            $contents = $this->originalContents();
299
        }
300
        foreach ($this->stack as $action) {
301
            $command = array_shift($action);
302
            if (method_exists($this, $command)) {
303
                array_unshift($action, $contents);
304
                $contents = call_user_func_array([$this, $command], $action);
305
            }
306
        }
307
        return $contents;
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     */
313
    public function run()
314
    {
315
        $this->printTaskInfo("Writing to {filename}.", ['filename' => $this->filename]);
316
        $contents = $this->getContentsToWrite();
317
        if (!file_exists(dirname($this->filename))) {
318
            mkdir(dirname($this->filename), 0777, true);
319
        }
320
        $res = file_put_contents($this->filename, $contents);
321
        if ($res === false) {
322
            return Result::error($this, "File {$this->filename} couldn't be created");
323
        }
324
325
        return Result::success($this);
326
    }
327
328
    /**
329
     * @return string
330
     */
331
    public function getPath()
332
    {
333
        return $this->filename;
334
    }
335
}
336