4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Filesystem
;
14 use Symfony\Component\Filesystem\Exception\IOException
;
17 * Provides basic utility to manipulate the file system.
19 * @author Fabien Potencier <fabien@symfony.com>
26 * This method only copies the file if the origin file is newer than the target file.
28 * By default, if the target already exists, it is not overridden.
30 * @param string $originFile The original filename
31 * @param string $targetFile The target filename
32 * @param boolean $override Whether to override an existing file or not
34 * @throws IOException When copy fails
36 public function copy($originFile, $targetFile, $override = false)
38 if (stream_is_local($originFile) && !is_file($originFile)) {
39 throw new IOException(sprintf('Failed to copy %s because file not exists', $originFile));
42 $this->mkdir(dirname($targetFile));
44 if (!$override && is_file($targetFile)) {
45 $doCopy = filemtime($originFile) > filemtime($targetFile);
51 // https://bugs.php.net/bug.php?id=64634
52 $source = fopen($originFile, 'r');
53 $target = fopen($targetFile, 'w+');
54 stream_copy_to_stream($source, $target);
57 unset($source, $target);
59 if (!is_file($targetFile)) {
60 throw new IOException(sprintf('Failed to copy %s to %s', $originFile, $targetFile));
66 * Creates a directory recursively.
68 * @param string|array|\Traversable $dirs The directory path
69 * @param integer $mode The directory mode
71 * @throws IOException On any directory creation failure
73 public function mkdir($dirs, $mode = 0777)
75 foreach ($this->toIterator($dirs) as $dir) {
80 if (true !== @mkdir($dir, $mode, true)) {
81 throw new IOException(sprintf('Failed to create %s', $dir));
87 * Checks the existence of files or directories.
89 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to check
91 * @return Boolean true if the file exists, false otherwise
93 public function exists($files)
95 foreach ($this->toIterator($files) as $file) {
96 if (!file_exists($file)) {
105 * Sets access and modification time of file.
107 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to create
108 * @param integer $time The touch time as a unix timestamp
109 * @param integer $atime The access time as a unix timestamp
111 * @throws IOException When touch fails
113 public function touch($files, $time = null, $atime = null)
115 foreach ($this->toIterator($files) as $file) {
116 $touch = $time ? @touch($file, $time, $atime) : @touch($file);
117 if (true !== $touch) {
118 throw new IOException(sprintf('Failed to touch %s', $file));
124 * Removes files or directories.
126 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to remove
128 * @throws IOException When removal fails
130 public function remove($files)
132 $files = iterator_to_array($this->toIterator($files));
133 $files = array_reverse($files);
134 foreach ($files as $file) {
135 if (!file_exists($file) && !is_link($file)) {
139 if (is_dir($file) && !is_link($file)) {
140 $this->remove(new \
FilesystemIterator($file));
142 if (true !== @rmdir($file)) {
143 throw new IOException(sprintf('Failed to remove directory %s', $file));
146 // https://bugs.php.net/bug.php?id=52176
147 if (defined('PHP_WINDOWS_VERSION_MAJOR') && is_dir($file)) {
148 if (true !== @rmdir($file)) {
149 throw new IOException(sprintf('Failed to remove file %s', $file));
152 if (true !== @unlink($file)) {
153 throw new IOException(sprintf('Failed to remove file %s', $file));
161 * Change mode for an array of files or directories.
163 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode
164 * @param integer $mode The new mode (octal)
165 * @param integer $umask The mode mask (octal)
166 * @param Boolean $recursive Whether change the mod recursively or not
168 * @throws IOException When the change fail
170 public function chmod($files, $mode, $umask = 0000, $recursive = false)
172 foreach ($this->toIterator($files) as $file) {
173 if ($recursive && is_dir($file) && !is_link($file)) {
174 $this->chmod(new \
FilesystemIterator($file), $mode, $umask, true);
176 if (true !== @chmod($file, $mode & ~
$umask)) {
177 throw new IOException(sprintf('Failed to chmod file %s', $file));
183 * Change the owner of an array of files or directories
185 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner
186 * @param string $user The new owner user name
187 * @param Boolean $recursive Whether change the owner recursively or not
189 * @throws IOException When the change fail
191 public function chown($files, $user, $recursive = false)
193 foreach ($this->toIterator($files) as $file) {
194 if ($recursive && is_dir($file) && !is_link($file)) {
195 $this->chown(new \
FilesystemIterator($file), $user, true);
197 if (is_link($file) && function_exists('lchown')) {
198 if (true !== @lchown($file, $user)) {
199 throw new IOException(sprintf('Failed to chown file %s', $file));
202 if (true !== @chown($file, $user)) {
203 throw new IOException(sprintf('Failed to chown file %s', $file));
210 * Change the group of an array of files or directories
212 * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group
213 * @param string $group The group name
214 * @param Boolean $recursive Whether change the group recursively or not
216 * @throws IOException When the change fail
218 public function chgrp($files, $group, $recursive = false)
220 foreach ($this->toIterator($files) as $file) {
221 if ($recursive && is_dir($file) && !is_link($file)) {
222 $this->chgrp(new \
FilesystemIterator($file), $group, true);
224 if (is_link($file) && function_exists('lchgrp')) {
225 if (true !== @lchgrp($file, $group)) {
226 throw new IOException(sprintf('Failed to chgrp file %s', $file));
229 if (true !== @chgrp($file, $group)) {
230 throw new IOException(sprintf('Failed to chgrp file %s', $file));
237 * Renames a file or a directory.
239 * @param string $origin The origin filename or directory
240 * @param string $target The new filename or directory
241 * @param Boolean $overwrite Whether to overwrite the target if it already exists
243 * @throws IOException When target file or directory already exists
244 * @throws IOException When origin cannot be renamed
246 public function rename($origin, $target, $overwrite = false)
248 // we check that target does not exist
249 if (!$overwrite && is_readable($target)) {
250 throw new IOException(sprintf('Cannot rename because the target "%s" already exist.', $target));
253 if (true !== @rename($origin, $target)) {
254 throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target));
259 * Creates a symbolic link or copy a directory.
261 * @param string $originDir The origin directory path
262 * @param string $targetDir The symbolic link name
263 * @param Boolean $copyOnWindows Whether to copy files if on Windows
265 * @throws IOException When symlink fails
267 public function symlink($originDir, $targetDir, $copyOnWindows = false)
269 if (!function_exists('symlink') && $copyOnWindows) {
270 $this->mirror($originDir, $targetDir);
275 $this->mkdir(dirname($targetDir));
278 if (is_link($targetDir)) {
279 if (readlink($targetDir) != $originDir) {
280 $this->remove($targetDir);
287 if (true !== @symlink($originDir, $targetDir)) {
288 $report = error_get_last();
289 if (is_array($report)) {
290 if (defined('PHP_WINDOWS_VERSION_MAJOR') && false !== strpos($report['message'], 'error code(1314)')) {
291 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?');
294 throw new IOException(sprintf('Failed to create symbolic link from %s to %s', $originDir, $targetDir));
300 * Given an existing path, convert it to a path relative to a given starting path
302 * @param string $endPath Absolute path of target
303 * @param string $startPath Absolute path where traversal begins
305 * @return string Path of target relative to starting path
307 public function makePathRelative($endPath, $startPath)
309 // Normalize separators on windows
310 if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
311 $endPath = strtr($endPath, '\\', '/');
312 $startPath = strtr($startPath, '\\', '/');
315 // Split the paths into arrays
316 $startPathArr = explode('/', trim($startPath, '/'));
317 $endPathArr = explode('/', trim($endPath, '/'));
319 // Find for which directory the common path stops
321 while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
325 // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
326 $depth = count($startPathArr) - $index;
328 // Repeated "../" for each level need to reach the common path
329 $traverser = str_repeat('../', $depth);
331 $endPathRemainder = implode('/', array_slice($endPathArr, $index));
333 // Construct $endPath from traversing to the common path, then to the remaining $endPath
334 $relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
336 return (strlen($relativePath) === 0) ? './' : $relativePath;
340 * Mirrors a directory to another.
342 * @param string $originDir The origin directory
343 * @param string $targetDir The target directory
344 * @param \Traversable $iterator A Traversable instance
345 * @param array $options An array of boolean options
347 * - $options['override'] Whether to override an existing file on copy or not (see copy())
348 * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink())
349 * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
351 * @throws IOException When file type is unknown
353 public function mirror($originDir, $targetDir, \Traversable
$iterator = null, $options = array())
355 $targetDir = rtrim($targetDir, '/\\');
356 $originDir = rtrim($originDir, '/\\');
358 // Iterate in destination folder to remove obsolete entries
359 if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
360 $deleteIterator = $iterator;
361 if (null === $deleteIterator) {
362 $flags = \FilesystemIterator
::SKIP_DOTS
;
363 $deleteIterator = new \
RecursiveIteratorIterator(new \
RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator
::CHILD_FIRST
);
365 foreach ($deleteIterator as $file) {
366 $origin = str_replace($targetDir, $originDir, $file->getPathname());
367 if (!$this->exists($origin)) {
368 $this->remove($file);
373 $copyOnWindows = false;
374 if (isset($options['copy_on_windows']) && !function_exists('symlink')) {
375 $copyOnWindows = $options['copy_on_windows'];
378 if (null === $iterator) {
379 $flags = $copyOnWindows ? \FilesystemIterator
::SKIP_DOTS
| \FilesystemIterator
::FOLLOW_SYMLINKS
: \FilesystemIterator
::SKIP_DOTS
;
380 $iterator = new \
RecursiveIteratorIterator(new \
RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator
::SELF_FIRST
);
383 foreach ($iterator as $file) {
384 $target = str_replace($originDir, $targetDir, $file->getPathname());
386 if ($copyOnWindows) {
387 if (is_link($file) || is_file($file)) {
388 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
389 } elseif (is_dir($file)) {
390 $this->mkdir($target);
392 throw new IOException(sprintf('Unable to guess "%s" file type.', $file));
395 if (is_link($file)) {
396 $this->symlink($file, $target);
397 } elseif (is_dir($file)) {
398 $this->mkdir($target);
399 } elseif (is_file($file)) {
400 $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
402 throw new IOException(sprintf('Unable to guess "%s" file type.', $file));
409 * Returns whether the file path is an absolute path.
411 * @param string $file A file path
415 public function isAbsolutePath($file)
417 if (strspn($file, '/\\', 0, 1)
418 || (strlen($file) > 3 && ctype_alpha($file[0])
419 && substr($file, 1, 1) === ':'
420 && (strspn($file, '/\\', 2, 1))
422 || null !== parse_url($file, PHP_URL_SCHEME
)
431 * @param mixed $files
433 * @return \Traversable
435 private function toIterator($files)
437 if (!$files instanceof \Traversable
) {
438 $files = new \
ArrayObject(is_array($files) ? $files : array($files));
445 * Atomically dumps content into a file.
447 * @param string $filename The file to be written to.
448 * @param string $content The data to write into the file.
449 * @param integer $mode The file mode (octal).
450 * @throws IOException If the file cannot be written to.
452 public function dumpFile($filename, $content, $mode = 0666)
454 $dir = dirname($filename);
458 } elseif (!is_writable($dir)) {
459 throw new IOException(sprintf('Unable to write in the %s directory\n', $dir));
462 $tmpFile = tempnam($dir, basename($filename));
464 if (false === @file_put_contents($tmpFile, $content)) {
465 throw new IOException(sprintf('Failed to write file "%s".', $filename));
468 $this->rename($tmpFile, $filename, true);
469 $this->chmod($filename, $mode);