Passed
Push — main ( f8c128...609b6a )
by Siad
05:26
created

ReplaceRegexpTask::setFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

111
    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...
112
    {
113
    }
114
115
    /**
116
     * Match only per line.
117
     *
118
     * @param bool $yesNo
119
     */
120
    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

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