Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 501 lines (446 sloc) 19.755 kb
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Filesystem;
13
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
14 use Symfony\Component\Filesystem\Exception\IOException;
cdd6b28 @ChristianGaertner [Filesystem] introduced new Exception base classes
ChristianGaertner authored
15 use Symfony\Component\Filesystem\Exception\FileNotFoundException;
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
16
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
17 /**
18 * Provides basic utility to manipulate the file system.
19 *
20 * @author Fabien Potencier <fabien@symfony.com>
21 */
22 class Filesystem
23 {
24 /**
25 * Copies a file.
26 *
27 * This method only copies the file if the origin file is newer than the target file.
28 *
29 * By default, if the target already exists, it is not overridden.
30 *
692d07c @GrahamCampbell Docblock fixes
GrahamCampbell authored
31 * @param string $originFile The original filename
32 * @param string $targetFile The target filename
33 * @param bool $override Whether to override an existing file or not
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
34 *
f975c63 @GrahamCampbell CS fixes
GrahamCampbell authored
35 * @throws FileNotFoundException When originFile doesn't exist
36 * @throws IOException When copy fails
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
37 */
38 public function copy($originFile, $targetFile, $override = false)
39 {
51393fc @stloyd [Filesystem] Fix regression introduced in 10dea948
stloyd authored
40 if (stream_is_local($originFile) && !is_file($originFile)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
41 throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
c8f0ee4 @stloyd [Filesystem] copy() is not working when open_basedir is set
stloyd authored
42 }
43
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
44 $this->mkdir(dirname($targetFile));
45
806aa73 @kalessil [2.3] Static Code Analysis for Components
kalessil authored
46 $doCopy = true;
47 if (!$override && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
48 $doCopy = filemtime($originFile) > filemtime($targetFile);
49 }
50
51 if ($doCopy) {
c8f0ee4 @stloyd [Filesystem] copy() is not working when open_basedir is set
stloyd authored
52 // https://bugs.php.net/bug.php?id=64634
38f95d9 @djotto [Filesystem] Throw Exception on copying from an unreadable file or to an...
djotto authored
53 if (false === $source = @fopen($originFile, 'r')) {
54 throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
55 }
cce2118 @fabpot Merge branch '2.5'
fabpot authored
56
bc2a0a3 [Filesystem] Add FTP stream wrapper context option to enable overwrite (...
Damian Sromek authored
57 // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
75f5f5c @jderusse Ignore warning on fopen
jderusse authored
58 if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
38f95d9 @djotto [Filesystem] Throw Exception on copying from an unreadable file or to an...
djotto authored
59 throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
60 }
cce2118 @fabpot Merge branch '2.5'
fabpot authored
61
db1ff65 @skigun [Filesystem] Check number of bytes copied.
skigun authored
62 $bytesCopied = stream_copy_to_stream($source, $target);
c8f0ee4 @stloyd [Filesystem] copy() is not working when open_basedir is set
stloyd authored
63 fclose($source);
64 fclose($target);
65 unset($source, $target);
66
67 if (!is_file($targetFile)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
68 throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
69 }
db1ff65 @skigun [Filesystem] Check number of bytes copied.
skigun authored
70
afaca2a @nicolas-grekas [Filesystem] keep exec perms when copying
nicolas-grekas authored
71 // Like `cp`, preserve executable permission bits
72 @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
508105c @joelwurtz [Filesystem] Keep executable permission when a file is copied
joelwurtz authored
73
cb5db1c @King2500 [Filesystem] Improve exception message for copy method
King2500 authored
74 if (stream_is_local($originFile) && $bytesCopied !== ($bytesOrigin = filesize($originFile))) {
75 throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile);
db1ff65 @skigun [Filesystem] Check number of bytes copied.
skigun authored
76 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
77 }
78 }
79
80 /**
81 * Creates a directory recursively.
82 *
e1f7c29 @fabpot fixed phpdoc @param alignment
fabpot authored
83 * @param string|array|\Traversable $dirs The directory path
b519d4f @fabpot made phpdoc types consistent with those defined in Hack
fabpot authored
84 * @param int $mode The directory mode
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
85 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
86 * @throws IOException On any directory creation failure
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
87 */
88 public function mkdir($dirs, $mode = 0777)
89 {
90 foreach ($this->toIterator($dirs) as $dir) {
91 if (is_dir($dir)) {
92 continue;
93 }
94
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
95 if (true !== @mkdir($dir, $mode, true)) {
67c1d6b @kcassam [Filesystem Component] mkdir race condition fix #11626
kcassam authored
96 $error = error_get_last();
97 if (!is_dir($dir)) {
98 // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
99 if ($error) {
d28b507 @fabpot Merge branch '2.3' into 2.4
fabpot authored
100 throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
67c1d6b @kcassam [Filesystem Component] mkdir race condition fix #11626
kcassam authored
101 }
d28b507 @fabpot Merge branch '2.3' into 2.4
fabpot authored
102 throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
67c1d6b @kcassam [Filesystem Component] mkdir race condition fix #11626
kcassam authored
103 }
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
104 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
105 }
106 }
107
108 /**
22d3e3e @aerialls [Filesystem] added exists method
aerialls authored
109 * Checks the existence of files or directories.
110 *
111 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check
112 *
692d07c @GrahamCampbell Docblock fixes
GrahamCampbell authored
113 * @return bool true if the file exists, false otherwise
22d3e3e @aerialls [Filesystem] added exists method
aerialls authored
114 */
115 public function exists($files)
116 {
117 foreach ($this->toIterator($files) as $file) {
118 if (!file_exists($file)) {
119 return false;
120 }
121 }
122
123 return true;
124 }
125
126 /**
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
127 * Sets access and modification time of file.
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
128 *
c9ed9c2 @jakzal [Filesystem] Fixed typos in the docblocks.
jakzal authored
129 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to create
b519d4f @fabpot made phpdoc types consistent with those defined in Hack
fabpot authored
130 * @param int $time The touch time as a Unix timestamp
131 * @param int $atime The access time as a Unix timestamp
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
132 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
133 * @throws IOException When touch fails
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
134 */
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
135 public function touch($files, $time = null, $atime = null)
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
136 {
137 foreach ($this->toIterator($files) as $file) {
ed1e991 @iltar Filesystem::touch() not working with different owners (utime/atime issue...
iltar authored
138 $touch = $time ? @touch($file, $time, $atime) : @touch($file);
139 if (true !== $touch) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
140 throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
141 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
142 }
143 }
144
145 /**
146 * Removes files or directories.
147 *
148 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
149 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
150 * @throws IOException When removal fails
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
151 */
152 public function remove($files)
153 {
154 $files = iterator_to_array($this->toIterator($files));
155 $files = array_reverse($files);
156 foreach ($files as $file) {
dc5c654 @jakzal [Filesystem] Fixed a bug in remove being unable to remove symlinks to un...
jakzal authored
157 if (!file_exists($file) && !is_link($file)) {
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
158 continue;
159 }
160
161 if (is_dir($file) && !is_link($file)) {
162 $this->remove(new \FilesystemIterator($file));
163
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
164 if (true !== @rmdir($file)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
165 throw new IOException(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
166 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
167 } else {
31abac1 @ErikTrapman [FileSystem] added if-windows check
ErikTrapman authored
168 // https://bugs.php.net/bug.php?id=52176
827637c @xabbuh use value of DIRECTORY_SEPARATOR to detect Windows
xabbuh authored
169 if ('\\' === DIRECTORY_SEPARATOR && is_dir($file)) {
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
170 if (true !== @rmdir($file)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
171 throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
172 }
31abac1 @ErikTrapman [FileSystem] added if-windows check
ErikTrapman authored
173 } else {
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
174 if (true !== @unlink($file)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
175 throw new IOException(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
176 }
31abac1 @ErikTrapman [FileSystem] added if-windows check
ErikTrapman authored
177 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
178 }
179 }
180 }
181
182 /**
183 * Change mode for an array of files or directories.
184 *
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
185 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode
b519d4f @fabpot made phpdoc types consistent with those defined in Hack
fabpot authored
186 * @param int $mode The new mode (octal)
187 * @param int $umask The mode mask (octal)
188 * @param bool $recursive Whether change the mod recursively or not
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
189 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
190 * @throws IOException When the change fail
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
191 */
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
192 public function chmod($files, $mode, $umask = 0000, $recursive = false)
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
193 {
194 foreach ($this->toIterator($files) as $file) {
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
195 if ($recursive && is_dir($file) && !is_link($file)) {
196 $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
197 }
198 if (true !== @chmod($file, $mode & ~$umask)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
199 throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
200 }
201 }
202 }
203
204 /**
f4c4e02 @GrahamCampbell [2.3] CS And DocBlock Fixes
GrahamCampbell authored
205 * Change the owner of an array of files or directories.
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
206 *
207 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner
208 * @param string $user The new owner user name
b519d4f @fabpot made phpdoc types consistent with those defined in Hack
fabpot authored
209 * @param bool $recursive Whether change the owner recursively or not
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
210 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
211 * @throws IOException When the change fail
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
212 */
213 public function chown($files, $user, $recursive = false)
214 {
215 foreach ($this->toIterator($files) as $file) {
216 if ($recursive && is_dir($file) && !is_link($file)) {
217 $this->chown(new \FilesystemIterator($file), $user, true);
218 }
219 if (is_link($file) && function_exists('lchown')) {
220 if (true !== @lchown($file, $user)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
221 throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
222 }
223 } else {
224 if (true !== @chown($file, $user)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
225 throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
226 }
227 }
228 }
229 }
230
231 /**
f4c4e02 @GrahamCampbell [2.3] CS And DocBlock Fixes
GrahamCampbell authored
232 * Change the group of an array of files or directories.
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
233 *
234 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group
235 * @param string $group The group name
b519d4f @fabpot made phpdoc types consistent with those defined in Hack
fabpot authored
236 * @param bool $recursive Whether change the group recursively or not
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
237 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
238 * @throws IOException When the change fail
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
239 */
240 public function chgrp($files, $group, $recursive = false)
241 {
242 foreach ($this->toIterator($files) as $file) {
243 if ($recursive && is_dir($file) && !is_link($file)) {
244 $this->chgrp(new \FilesystemIterator($file), $group, true);
245 }
246 if (is_link($file) && function_exists('lchgrp')) {
247 if (true !== @lchgrp($file, $group)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
248 throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
249 }
250 } else {
251 if (true !== @chgrp($file, $group)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
252 throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
253 }
254 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
255 }
256 }
257
258 /**
89f93fa @lyrixx Fixed doc block on Filesystem::rename
lyrixx authored
259 * Renames a file or a directory.
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
260 *
692d07c @GrahamCampbell Docblock fixes
GrahamCampbell authored
261 * @param string $origin The origin filename or directory
262 * @param string $target The new filename or directory
263 * @param bool $overwrite Whether to overwrite the target if it already exists
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
264 *
89f93fa @lyrixx Fixed doc block on Filesystem::rename
lyrixx authored
265 * @throws IOException When target file or directory already exists
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
266 * @throws IOException When origin cannot be renamed
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
267 */
edc1bc3 @jakzal [Filesystem] Made sure Filesystem::dumpFile() overwrites an existing fil...
jakzal authored
268 public function rename($origin, $target, $overwrite = false)
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
269 {
270 // we check that target does not exist
edc1bc3 @jakzal [Filesystem] Made sure Filesystem::dumpFile() overwrites an existing fil...
jakzal authored
271 if (!$overwrite && is_readable($target)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
272 throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
273 }
274
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
275 if (true !== @rename($origin, $target)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
276 throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
4573f17 @alessandro1997 [Filesystem] rename() throws RuntimeException on error (fixes #3848).
alessandro1997 authored
277 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
278 }
279
280 /**
281 * Creates a symbolic link or copy a directory.
282 *
692d07c @GrahamCampbell Docblock fixes
GrahamCampbell authored
283 * @param string $originDir The origin directory path
284 * @param string $targetDir The symbolic link name
285 * @param bool $copyOnWindows Whether to copy files if on Windows
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
286 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
287 * @throws IOException When symlink fails
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
288 */
289 public function symlink($originDir, $targetDir, $copyOnWindows = false)
290 {
ee728f8 @xabbuh use value of DIRECTORY_SEPARATOR to detect Windows
xabbuh authored
291 if ('\\' === DIRECTORY_SEPARATOR && $copyOnWindows) {
02f003c @rvanginneken Make assets:install smarter with symlinks
rvanginneken authored
292 $this->mirror($originDir, $targetDir);
6900b65 @GrahamCampbell [2.6] CS Fixes And Removed An Unused Import
GrahamCampbell authored
293
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
294 return;
295 }
296
d732070 @michalpipa [Filesystem] symlink() creates target directories
michalpipa authored
297 $this->mkdir(dirname($targetDir));
298
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
299 $ok = false;
300 if (is_link($targetDir)) {
301 if (readlink($targetDir) != $originDir) {
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
302 $this->remove($targetDir);
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
303 } else {
304 $ok = true;
305 }
306 }
307
806aa73 @kalessil [2.3] Static Code Analysis for Components
kalessil authored
308 if (!$ok && true !== @symlink($originDir, $targetDir)) {
309 $report = error_get_last();
310 if (is_array($report)) {
311 if ('\\' === DIRECTORY_SEPARATOR && false !== strpos($report['message'], 'error code(1314)')) {
312 throw new IOException('Unable to create symlink due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?');
ba54074 @ErikTrapman [FileSystem] explains possible failure of symlink creation in windows
ErikTrapman authored
313 }
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
314 throw new IOException(sprintf('Failed to create symbolic link from "%s" to "%s".', $originDir, $targetDir), 0, null, $targetDir);
9355c28 @romainneutron [Filesystem] Added few new behaviors:
romainneutron authored
315 }
806aa73 @kalessil [2.3] Static Code Analysis for Components
kalessil authored
316 throw new IOException(sprintf('Failed to create symbolic link from %s to %s', $originDir, $targetDir));
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
317 }
318 }
319
320 /**
f4c4e02 @GrahamCampbell [2.3] CS And DocBlock Fixes
GrahamCampbell authored
321 * Given an existing path, convert it to a path relative to a given starting path.
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
322 *
c9ed9c2 @jakzal [Filesystem] Fixed typos in the docblocks.
jakzal authored
323 * @param string $endPath Absolute path of target
324 * @param string $startPath Absolute path where traversal begins
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
325 *
326 * @return string Path of target relative to starting path
327 */
328 public function makePathRelative($endPath, $startPath)
329 {
38411e8 @fabpot fixed various typos
fabpot authored
330 // Normalize separators on Windows
827637c @xabbuh use value of DIRECTORY_SEPARATOR to detect Windows
xabbuh authored
331 if ('\\' === DIRECTORY_SEPARATOR) {
0f913fa @Seldaek [Filesystem] Fix makePathRelative on windows with mixed paths, fix tests
Seldaek authored
332 $endPath = strtr($endPath, '\\', '/');
333 $startPath = strtr($startPath, '\\', '/');
334 }
335
fb6c06f @aharonp Refactored Filesystem::makePathRelative function to correctly handle mor...
aharonp authored
336 // Split the paths into arrays
337 $startPathArr = explode('/', trim($startPath, '/'));
338 $endPathArr = explode('/', trim($endPath, '/'));
339
340 // Find for which directory the common path stops
341 $index = 0;
342 while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
343 $index++;
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
344 }
345
346 // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
fb6c06f @aharonp Refactored Filesystem::makePathRelative function to correctly handle mor...
aharonp authored
347 $depth = count($startPathArr) - $index;
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
348
349 // Repeated "../" for each level need to reach the common path
350 $traverser = str_repeat('../', $depth);
351
fb6c06f @aharonp Refactored Filesystem::makePathRelative function to correctly handle mor...
aharonp authored
352 $endPathRemainder = implode('/', array_slice($endPathArr, $index));
353
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
354 // Construct $endPath from traversing to the common path, then to the remaining $endPath
806aa73 @kalessil [2.3] Static Code Analysis for Components
kalessil authored
355 $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
fb6c06f @aharonp Refactored Filesystem::makePathRelative function to correctly handle mor...
aharonp authored
356
806aa73 @kalessil [2.3] Static Code Analysis for Components
kalessil authored
357 return '' === $relativePath ? './' : $relativePath;
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
358 }
359
360 /**
361 * Mirrors a directory to another.
362 *
e1f7c29 @fabpot fixed phpdoc @param alignment
fabpot authored
363 * @param string $originDir The origin directory
364 * @param string $targetDir The target directory
365 * @param \Traversable $iterator A Traversable instance
366 * @param array $options An array of boolean options
692d07c @GrahamCampbell Docblock fixes
GrahamCampbell authored
367 * Valid options are:
368 * - $options['override'] Whether to override an existing file on copy or not (see copy())
369 * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink())
370 * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
371 *
bd4799b @romainneutron Add Changelog BC Break note
romainneutron authored
372 * @throws IOException When file type is unknown
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
373 */
374 public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
375 {
1b73a23 @mylen [Filesystem] [mirror] added "delete" option
mylen authored
376 $targetDir = rtrim($targetDir, '/\\');
377 $originDir = rtrim($originDir, '/\\');
378
379 // Iterate in destination folder to remove obsolete entries
380 if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
381 $deleteIterator = $iterator;
382 if (null === $deleteIterator) {
383 $flags = \FilesystemIterator::SKIP_DOTS;
384 $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
385 }
386 foreach ($deleteIterator as $file) {
387 $origin = str_replace($targetDir, $originDir, $file->getPathname());
388 if (!$this->exists($origin)) {
389 $this->remove($file);
390 }
391 }
392 }
393
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
394 $copyOnWindows = false;
02f003c @rvanginneken Make assets:install smarter with symlinks
rvanginneken authored
395 if (isset($options['copy_on_windows'])) {
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
396 $copyOnWindows = $options['copy_on_windows'];
397 }
398
399 if (null === $iterator) {
400 $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
401 $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
402 }
403
441bc3f @yosmanyga Fixed case for empty folder
yosmanyga authored
404 if ($this->exists($originDir)) {
405 $this->mkdir($targetDir);
406 }
407
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
408 foreach ($iterator as $file) {
52fd6a4 @jakzal [Filesystem] Prevented infiite loop on windows while calling mirror on s...
jakzal authored
409 $target = str_replace($originDir, $targetDir, $file->getPathname());
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
410
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
411 if ($copyOnWindows) {
412 if (is_link($file) || is_file($file)) {
413 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
8ede4b6 @fabpot fixed CS
fabpot authored
414 } elseif (is_dir($file)) {
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
415 $this->mkdir($target);
416 } else {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
417 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
418 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
419 } else {
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
420 if (is_link($file)) {
35ac501 @aitboudad [Filesystem] symlink use RealPath instead LinkTarget
aitboudad authored
421 $this->symlink($file->getRealPath(), $target);
8ede4b6 @fabpot fixed CS
fabpot authored
422 } elseif (is_dir($file)) {
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
423 $this->mkdir($target);
8ede4b6 @fabpot fixed CS
fabpot authored
424 } elseif (is_file($file)) {
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
425 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
426 } else {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
427 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
aa34ce6 @malaney Filesystem Component mirror symlinked directory fix
malaney authored
428 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
429 }
430 }
431 }
432
433 /**
434 * Returns whether the file path is an absolute path.
435 *
436 * @param string $file A file path
437 *
b8e0239 @fabpot fixed types in phpdocs
fabpot authored
438 * @return bool
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
439 */
440 public function isAbsolutePath($file)
441 {
227f2a1 @stealth35 Prevent empty value in isAbsolutePath, use rtrim in mirror
stealth35 authored
442 if (strspn($file, '/\\', 0, 1)
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
443 || (strlen($file) > 3 && ctype_alpha($file[0])
227f2a1 @stealth35 Prevent empty value in isAbsolutePath, use rtrim in mirror
stealth35 authored
444 && substr($file, 1, 1) === ':'
445 && (strspn($file, '/\\', 2, 1))
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
446 )
447 || null !== parse_url($file, PHP_URL_SCHEME)
448 ) {
449 return true;
450 }
451
452 return false;
453 }
454
60dcad3 @jakzal [Filesystem] Added missing docblock comment.
jakzal authored
455 /**
5142584 @mpdude Mitigate dependency upon ConfigCache
mpdude authored
456 * Atomically dumps content into a file.
457 *
692d07c @GrahamCampbell Docblock fixes
GrahamCampbell authored
458 * @param string $filename The file to be written to.
459 * @param string $content The data to write into the file.
460 * @param null|int $mode The file mode (octal). If null, file permissions are not modified
461 * Deprecated since version 2.3.12, to be removed in 3.0.
462 *
463 * @throws IOException If the file cannot be written to.
5142584 @mpdude Mitigate dependency upon ConfigCache
mpdude authored
464 */
465 public function dumpFile($filename, $content, $mode = 0666)
466 {
467 $dir = dirname($filename);
468
469 if (!is_dir($dir)) {
470 $this->mkdir($dir);
471 } elseif (!is_writable($dir)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
472 throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
5142584 @mpdude Mitigate dependency upon ConfigCache
mpdude authored
473 }
474
475 $tmpFile = tempnam($dir, basename($filename));
476
477 if (false === @file_put_contents($tmpFile, $content)) {
e558fd5 @fabpot [Filesystem] removed getPath() on Exceptions and cleaned up CS and error...
fabpot authored
478 throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
5142584 @mpdude Mitigate dependency upon ConfigCache
mpdude authored
479 }
480
edc1bc3 @jakzal [Filesystem] Made sure Filesystem::dumpFile() overwrites an existing fil...
jakzal authored
481 $this->rename($tmpFile, $filename, true);
6c0dbd6 @romainneutron Fix #8205 : Deprecate file mode update when calling dumpFile
romainneutron authored
482 if (null !== $mode) {
483 $this->chmod($filename, $mode);
484 }
5142584 @mpdude Mitigate dependency upon ConfigCache
mpdude authored
485 }
cdd6b28 @ChristianGaertner [Filesystem] introduced new Exception base classes
ChristianGaertner authored
486
487 /**
488 * @param mixed $files
489 *
490 * @return \Traversable
491 */
492 private function toIterator($files)
493 {
494 if (!$files instanceof \Traversable) {
495 $files = new \ArrayObject(is_array($files) ? $files : array($files));
496 }
497
498 return $files;
499 }
547969d @willdurand [Component] Moved Filesystem class to its own component
willdurand authored
500 }
Something went wrong with that request. Please try again.