Passed
Push — main ( 28d658...6dddcc )
by Michiel
06:12
created

MoveTask::okToDelete()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.5069

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 20
ccs 8
cts 11
cp 0.7272
rs 9.6111
cc 5
nc 5
nop 1
crap 5.5069
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\Io\File;
26
use Phing\Io\IOException;
27
28
/**
29
 * Moves a file or directory to a new file or directory.
30
 *
31
 * By default, the destination file is overwritten if it
32
 * already exists.  When overwrite is turned off, then files
33
 * are only moved if the source file is newer than the
34
 * destination file, or when the destination file does not
35
 * exist.
36
 *
37
 * Source files and directories are only deleted when the file or
38
 * directory has been copied to the destination successfully.
39
 */
40
class MoveTask extends CopyTask
41
{
42 6
    public function __construct()
43
    {
44 6
        parent::__construct();
45 6
        $this->overwrite = true;
46
    }
47
48
    /**
49
     * Validates attributes coming in from XML.
50
     *
51
     * @throws BuildException
52
     */
53 6
    protected function validateAttributes()
54
    {
55 6
        if (null !== $this->file && $this->file->isDirectory()) {
56
            if (
57 1
                (null !== $this->destFile
58 1
                && null !== $this->destDir)
59 1
                || (null === $this->destFile
60 1
                && null === $this->destDir)
61
            ) {
62
                throw new BuildException('One and only one of tofile and todir must be set.');
63
            }
64
65 1
            if (null === $this->destFile) {
66
                $this->destFile = new File($this->destDir, $this->file->getName());
67
            }
68
69 1
            if (null === $this->destDir) {
70 1
                $this->destDir = $this->destFile->getParentFile();
71
            }
72
73 1
            $this->completeDirMap[$this->file->getAbsolutePath()] = $this->destFile->getAbsolutePath();
74
75 1
            $this->file = null;
76
        } else {
77 5
            parent::validateAttributes();
78
        }
79
    }
80
81 6
    protected function doWork()
82
    {
83 6
        if (count($this->completeDirMap) > 0) {
84 1
            foreach ($this->completeDirMap as $from => $to) {
85 1
                $f = new File($from);
86 1
                $d = new File($to);
87
88
                try { // try to rename
89 1
                    $this->log("Attempting to rename {$from} to {$to}", $this->verbosity);
90 1
                    if (!empty($this->filterChains)) {
91
                        $this->fileUtils->copyFile(
92
                            $f,
93
                            $d,
94
                            $this->getProject(),
95
                            $this->overwrite,
96
                            $this->preserveLMT,
97
                            $this->filterChains,
98
                            $this->mode,
99
                            $this->preservePermissions,
100
                            $this->granularity
101
                        );
102
                        $f->delete(true);
103
                    } else {
104 1
                        $this->fileUtils->renameFile($f, $d, $this->overwrite);
105
                    }
106
                } catch (IOException $ioe) {
107
                    $this->logError("Failed to rename {$from} to {$to}: " . $ioe->getMessage());
108
                }
109
            }
110
        }
111
112 6
        $copyMapSize = count($this->fileCopyMap);
113 6
        if ($copyMapSize > 0) {
114
            // files to move
115 3
            $this->log("Moving {$copyMapSize} files to " . $this->destDir->getAbsolutePath());
116
117 3
            foreach ($this->fileCopyMap as $from => $to) {
118 3
                if ($from == $to) {
119
                    $this->log("Skipping self-move of {$from}", $this->verbosity);
120
121
                    continue;
122
                }
123
124 3
                $f = new File($from);
125 3
                $d = new File($to);
126
127
                try { // try to move
128 3
                    $this->log("Moving {$from} to {$to}", $this->verbosity);
129
130 3
                    $this->fileUtils->copyFile(
131 3
                        $f,
132 3
                        $d,
133 3
                        $this->getProject(),
134 3
                        $this->overwrite,
135 3
                        $this->preserveLMT,
136 3
                        $this->filterChains,
137 3
                        $this->mode,
138 3
                        $this->preservePermissions,
139 3
                        $this->granularity
140 3
                    );
141
142 3
                    $f->delete();
143
                } catch (IOException $ioe) {
144
                    $this->logError("Failed to move {$from} to {$to}: " . $ioe->getMessage(), $this->getLocation());
145
                }
146
            } // foreach fileCopyMap
147
        } // if copyMapSize
148
149
        // handle empty dirs if appropriate
150 6
        if ($this->includeEmpty) {
151 6
            $count = 0;
152 6
            foreach ($this->dirCopyMap as $srcDir => $destDir) {
153
                $d = new File((string) $destDir);
154
                if (!$d->exists()) {
155
                    if (!$d->mkdirs()) {
156
                        $this->logError('Unable to create directory ' . $d->getAbsolutePath());
157
                    } else {
158
                        ++$count;
159
                    }
160
                }
161
            }
162 6
            if ($count > 0) {
163
                $this->log(
164
                    "moved {$count} empty director" . (1 == $count ? 'y' : 'ies') . ' to ' . $this->destDir->getAbsolutePath(
165
                    )
166
                );
167
            }
168
        }
169
170 6
        if (count($this->filesets) > 0) {
171
            // process filesets
172 1
            foreach ($this->filesets as $fs) {
173 1
                $dir = $fs->getDir($this->project);
174 1
                if ($this->okToDelete($dir)) {
175 1
                    $this->deleteDir($dir);
176
                }
177
            }
178
        }
179
180 6
        $dirsets = $this->getDirSets();
181 6
        if (count($dirsets) > 0) {
182
            // process dirsets
183
            foreach ($dirsets as $ds) {
184
                $dir = $ds->getDir($this->project);
185
                if ($this->okToDelete($dir)) {
186
                    $this->deleteDir($dir);
187
                }
188
            }
189
        }
190
    }
191
192
    /**
193
     * Its only ok to delete a dir tree if there are no files in it.
194
     *
195
     * @throws IOException
196
     *
197
     * @return bool
198
     */
199 1
    private function okToDelete(File $dir)
200
    {
201 1
        $list = $dir->listDir();
202 1
        if (null === $list) {
203
            return false; // maybe io error?
204
        }
205
206 1
        foreach ($list as $s) {
207 1
            $f = new File($dir, $s);
208 1
            if ($f->isDirectory()) {
209 1
                if (!$this->okToDelete($f)) {
210
                    return false;
211
                }
212
            } else {
213
                // found a file
214
                return false;
215
            }
216
        }
217
218 1
        return true;
219
    }
220
221
    /**
222
     * Go and delete the directory tree.
223
     *
224
     * @throws BuildException
225
     * @throws IOException
226
     */
227 1
    private function deleteDir(File $dir)
228
    {
229 1
        $list = $dir->listDir();
230 1
        if (null === $list) {
231
            return; // on an io error list() can return null
232
        }
233
234 1
        foreach ($list as $fname) {
235 1
            $f = new File($dir, $fname);
236 1
            if ($f->isDirectory()) {
237 1
                $this->deleteDir($f);
238
            } else {
239
                throw new BuildException('UNEXPECTED ERROR - The file ' . $f->getAbsolutePath() . ' should not exist!');
240
            }
241
        }
242
243 1
        $this->log('Deleting directory ' . $dir->getPath(), $this->verbosity);
244
245
        try {
246 1
            $dir->delete();
247
        } catch (Exception $e) {
248
            $this->logError('Unable to delete directory ' . $dir->__toString() . ': ' . $e->getMessage());
249
        }
250
    }
251
}
252