Passed
Push — master ( 601cfd...7bcbf1 )
by Michiel
22:46
created

ReplaceRegexpTask   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 185
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 21
eloc 57
dl 0
loc 185
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A setFlags() 0 2 1
A setReplace() 0 3 1
A setByline() 0 2 1
A setFile() 0 3 1
A init() 0 3 1
D main() 0 79 14
A setMatch() 0 3 1
A setPattern() 0 3 1
1
<?php
2
/**
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the LGPL. For more information please see
17
 * <http://phing.info>.
18
 */
19
20
namespace Phing\Task\System;
21
22
use Exception;
23
use Phing\Exception\BuildException;
24
use Phing\Filter\ReplaceRegexp;
25
use Phing\Io\FileReader;
26
use Phing\Io\FileUtils;
27
use Phing\Io\FileWriter;
28
use Phing\Io\File;
29
use Phing\Project;
30
use Phing\Task;
31
use Phing\Type\Element\FileSetAware;
32
use Phing\Type\FilterChain;
33
use Phing\Type\RegularExpression;
34
35
/**
36
 * ReplaceRegExp is a directory based task for replacing the occurrence of a
37
 * given regular expression with a substitution pattern in a selected file or
38
 * set of files.
39
 *
40
 * <code>
41
 * <replaceregexp file="${src}/build.properties"
42
 *                        match="OldProperty=(.*)"
43
 *                        replace="NewProperty=\1"
44
 *                        byline="true"/>
45
 * </code>
46
 *
47
 * @author Jonathan Bond-Caron <[email protected]>
48
 *
49
 * @package phing.tasks.system
50
 *
51
 * @link http://ant.apache.org/manual/OptionalTasks/replaceregexp.html
52
 */
53
class ReplaceRegexpTask extends Task
54
{
55
    use FileSetAware;
56
57
    /**
58
     * Single file to process.
59
     */
60
    private $file;
61
62
    /**
63
     * Regular expression
64
     *
65
     * @var RegularExpression
66
     */
67
    private $regexp;
68
69
    /**
70
     * File to apply regexp on
71
     *
72
     * @param File $path
73
     *
74
     * @return void
75
     */
76
    public function setFile(File $path)
77
    {
78
        $this->file = $path;
79
    }
80
81
    /**
82
     * Sets the regexp match pattern
83
     *
84
     * @param string $regexp
85
     *
86
     * @return void
87
     */
88
    public function setMatch($regexp)
89
    {
90
        $this->regexp->setPattern($regexp);
91
    }
92
93
    /**
94
     * @param $regexp
95
     *
96
     * @return void
97
     * @see setMatch()
98
     *
99
     */
100
    public function setPattern($regexp)
101
    {
102
        $this->setMatch($regexp);
103
    }
104
105
    /**
106
     * Sets the replacement string
107
     *
108
     * @param string $string
109
     *
110
     * @return void
111
     */
112
    public function setReplace($string)
113
    {
114
        $this->regexp->setReplace($string);
115
    }
116
117
    /**
118
     * Sets the regexp flags
119
     *
120
     * @param string $flags
121
     *
122
     * @return void
123
     *
124
     * todo ... `$this->_regexp->setFlags( $flags );`
125
     */
126
    public function setFlags($flags)
0 ignored issues
show
Unused Code introduced by
The parameter $flags is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

126
    public function setFlags(/** @scrutinizer ignore-unused */ $flags)

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

Loading history...
127
    {
128
    }
129
130
    /**
131
     * Match only per line
132
     *
133
     * @param bool $yesNo
134
     *
135
     * @return void
136
     */
137
    public function setByline($yesNo)
0 ignored issues
show
Unused Code introduced by
The parameter $yesNo is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

137
    public function setByline(/** @scrutinizer ignore-unused */ $yesNo)

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

Loading history...
138
    {
139
        // TODO... $this->_regexp->
140
    }
141
142
    /**
143
     * {@inheritdoc}
144
     *
145
     * @return void
146
     */
147
    public function init()
148
    {
149
        $this->regexp = new RegularExpression();
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     *
155
     * @return void
156
     *
157
     * @throws BuildException
158
     */
159
    public function main()
160
    {
161
        if ($this->file === null && empty($this->filesets)) {
162
            throw new BuildException("You must specify a file or fileset(s) for the <ReplaceRegexp> task.");
163
        }
164
165
        // compile a list of all files to modify, both file attrib and fileset elements
166
        // can be used.
167
        $files = [];
168
169
        if ($this->file !== null) {
170
            $files[] = $this->file;
171
        }
172
173
        if (!empty($this->filesets)) {
174
            $filenames = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $filenames is dead and can be removed.
Loading history...
175
            foreach ($this->filesets as $fs) {
176
                try {
177
                    $ds = $fs->getDirectoryScanner($this->project);
178
                    $filenames = $ds->getIncludedFiles(); // get included filenames
179
                    $dir = $fs->getDir($this->project);
180
                    foreach ($filenames as $fname) {
181
                        $files[] = new File($dir, $fname);
182
                    }
183
                } catch (BuildException $be) {
184
                    $this->log($be->getMessage(), Project::MSG_WARN);
185
                }
186
            }
187
        }
188
189
        $this->log("Applying Regexp processing to " . count($files) . " files.");
190
191
        // These "slots" allow filters to retrieve information about the currently-being-process files
192
        $slot = $this->getRegisterSlot("currentFile");
193
        $basenameSlot = $this->getRegisterSlot("currentFile.basename");
194
195
        $filter = new FilterChain($this->project);
196
197
        $r = new ReplaceRegexp();
198
        $r->setRegexps([$this->regexp]);
199
200
        $filter->addReplaceRegexp($r);
201
        $filters = [$filter];
202
203
        foreach ($files as $file) {
204
            // set the register slots
205
206
            $slot->setValue($file->getPath());
207
            $basenameSlot->setValue($file->getName());
208
209
            // 1) read contents of file, pulling through any filters
210
            $in = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $in is dead and can be removed.
Loading history...
211
            $out = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $out is dead and can be removed.
Loading history...
212
            $contents = "";
213
214
            try {
215
                $in = FileUtils::getChainedReader(new FileReader($file), $filters, $this->project);
216
                while (-1 !== ($buffer = $in->read())) {
217
                    $contents .= $buffer;
218
                }
219
                $in->close();
220
            } catch (Exception $e) {
221
                if ($in) {
222
                    $in->close();
223
                }
224
                $this->log("Error reading file: " . $e->getMessage(), Project::MSG_WARN);
225
            }
226
227
            try {
228
                // now create a FileWriter w/ the same file, and write to the file
229
                $out = new FileWriter($file);
230
                $out->write($contents);
231
                $out->close();
232
                $this->log("Applying regexp processing to " . $file->getPath(), Project::MSG_VERBOSE);
233
            } catch (Exception $e) {
234
                if ($out) {
235
                    $out->close();
236
                }
237
                $this->log("Error writing file back: " . $e->getMessage(), Project::MSG_WARN);
238
            }
239
        }
240
    }
241
}
242