Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / vendor / symfony / filesystem / Filesystem.php
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
14 use Symfony\Component\Filesystem\Exception\IOException;
15 use Symfony\Component\Filesystem\Exception\FileNotFoundException;
16
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      * If the target file is older than the origin file, it's always overwritten.
28      * If the target file is newer, it is overwritten only when the
29      * $overwriteNewerFiles option is set to true.
30      *
31      * @param string $originFile          The original filename
32      * @param string $targetFile          The target filename
33      * @param bool   $overwriteNewerFiles If true, target files newer than origin files are overwritten
34      *
35      * @throws FileNotFoundException When originFile doesn't exist
36      * @throws IOException           When copy fails
37      */
38     public function copy($originFile, $targetFile, $overwriteNewerFiles = false)
39     {
40         $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://');
41         if ($originIsLocal && !is_file($originFile)) {
42             throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
43         }
44
45         $this->mkdir(dirname($targetFile));
46
47         $doCopy = true;
48         if (!$overwriteNewerFiles && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) {
49             $doCopy = filemtime($originFile) > filemtime($targetFile);
50         }
51
52         if ($doCopy) {
53             // https://bugs.php.net/bug.php?id=64634
54             if (false === $source = @fopen($originFile, 'r')) {
55                 throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
56             }
57
58             // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
59             if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))))) {
60                 throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
61             }
62
63             $bytesCopied = stream_copy_to_stream($source, $target);
64             fclose($source);
65             fclose($target);
66             unset($source, $target);
67
68             if (!is_file($targetFile)) {
69                 throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
70             }
71
72             if ($originIsLocal) {
73                 // Like `cp`, preserve executable permission bits
74                 @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
75
76                 if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
77                     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);
78                 }
79             }
80         }
81     }
82
83     /**
84      * Creates a directory recursively.
85      *
86      * @param string|iterable $dirs The directory path
87      * @param int             $mode The directory mode
88      *
89      * @throws IOException On any directory creation failure
90      */
91     public function mkdir($dirs, $mode = 0777)
92     {
93         foreach ($this->toIterable($dirs) as $dir) {
94             if (is_dir($dir)) {
95                 continue;
96             }
97
98             if (true !== @mkdir($dir, $mode, true)) {
99                 $error = error_get_last();
100                 if (!is_dir($dir)) {
101                     // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
102                     if ($error) {
103                         throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']), 0, null, $dir);
104                     }
105                     throw new IOException(sprintf('Failed to create "%s"', $dir), 0, null, $dir);
106                 }
107             }
108         }
109     }
110
111     /**
112      * Checks the existence of files or directories.
113      *
114      * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check
115      *
116      * @return bool true if the file exists, false otherwise
117      */
118     public function exists($files)
119     {
120         $maxPathLength = PHP_MAXPATHLEN - 2;
121
122         foreach ($this->toIterable($files) as $file) {
123             if (strlen($file) > $maxPathLength) {
124                 throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file);
125             }
126
127             if (!file_exists($file)) {
128                 return false;
129             }
130         }
131
132         return true;
133     }
134
135     /**
136      * Sets access and modification time of file.
137      *
138      * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create
139      * @param int             $time  The touch time as a Unix timestamp
140      * @param int             $atime The access time as a Unix timestamp
141      *
142      * @throws IOException When touch fails
143      */
144     public function touch($files, $time = null, $atime = null)
145     {
146         foreach ($this->toIterable($files) as $file) {
147             $touch = $time ? @touch($file, $time, $atime) : @touch($file);
148             if (true !== $touch) {
149                 throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
150             }
151         }
152     }
153
154     /**
155      * Removes files or directories.
156      *
157      * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove
158      *
159      * @throws IOException When removal fails
160      */
161     public function remove($files)
162     {
163         if ($files instanceof \Traversable) {
164             $files = iterator_to_array($files, false);
165         } elseif (!is_array($files)) {
166             $files = array($files);
167         }
168         $files = array_reverse($files);
169         foreach ($files as $file) {
170             if (is_link($file)) {
171                 // See https://bugs.php.net/52176
172                 if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {
173                     $error = error_get_last();
174                     throw new IOException(sprintf('Failed to remove symlink "%s": %s.', $file, $error['message']));
175                 }
176             } elseif (is_dir($file)) {
177                 $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));
178
179                 if (!@rmdir($file) && file_exists($file)) {
180                     $error = error_get_last();
181                     throw new IOException(sprintf('Failed to remove directory "%s": %s.', $file, $error['message']));
182                 }
183             } elseif (!@unlink($file) && file_exists($file)) {
184                 $error = error_get_last();
185                 throw new IOException(sprintf('Failed to remove file "%s": %s.', $file, $error['message']));
186             }
187         }
188     }
189
190     /**
191      * Change mode for an array of files or directories.
192      *
193      * @param string|iterable $files     A filename, an array of files, or a \Traversable instance to change mode
194      * @param int             $mode      The new mode (octal)
195      * @param int             $umask     The mode mask (octal)
196      * @param bool            $recursive Whether change the mod recursively or not
197      *
198      * @throws IOException When the change fail
199      */
200     public function chmod($files, $mode, $umask = 0000, $recursive = false)
201     {
202         foreach ($this->toIterable($files) as $file) {
203             if (true !== @chmod($file, $mode & ~$umask)) {
204                 throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
205             }
206             if ($recursive && is_dir($file) && !is_link($file)) {
207                 $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
208             }
209         }
210     }
211
212     /**
213      * Change the owner of an array of files or directories.
214      *
215      * @param string|iterable $files     A filename, an array of files, or a \Traversable instance to change owner
216      * @param string          $user      The new owner user name
217      * @param bool            $recursive Whether change the owner recursively or not
218      *
219      * @throws IOException When the change fail
220      */
221     public function chown($files, $user, $recursive = false)
222     {
223         foreach ($this->toIterable($files) as $file) {
224             if ($recursive && is_dir($file) && !is_link($file)) {
225                 $this->chown(new \FilesystemIterator($file), $user, true);
226             }
227             if (is_link($file) && function_exists('lchown')) {
228                 if (true !== @lchown($file, $user)) {
229                     throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
230                 }
231             } else {
232                 if (true !== @chown($file, $user)) {
233                     throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file);
234                 }
235             }
236         }
237     }
238
239     /**
240      * Change the group of an array of files or directories.
241      *
242      * @param string|iterable $files     A filename, an array of files, or a \Traversable instance to change group
243      * @param string          $group     The group name
244      * @param bool            $recursive Whether change the group recursively or not
245      *
246      * @throws IOException When the change fail
247      */
248     public function chgrp($files, $group, $recursive = false)
249     {
250         foreach ($this->toIterable($files) as $file) {
251             if ($recursive && is_dir($file) && !is_link($file)) {
252                 $this->chgrp(new \FilesystemIterator($file), $group, true);
253             }
254             if (is_link($file) && function_exists('lchgrp')) {
255                 if (true !== @lchgrp($file, $group) || (defined('HHVM_VERSION') && !posix_getgrnam($group))) {
256                     throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
257                 }
258             } else {
259                 if (true !== @chgrp($file, $group)) {
260                     throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file);
261                 }
262             }
263         }
264     }
265
266     /**
267      * Renames a file or a directory.
268      *
269      * @param string $origin    The origin filename or directory
270      * @param string $target    The new filename or directory
271      * @param bool   $overwrite Whether to overwrite the target if it already exists
272      *
273      * @throws IOException When target file or directory already exists
274      * @throws IOException When origin cannot be renamed
275      */
276     public function rename($origin, $target, $overwrite = false)
277     {
278         // we check that target does not exist
279         if (!$overwrite && $this->isReadable($target)) {
280             throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
281         }
282
283         if (true !== @rename($origin, $target)) {
284             if (is_dir($origin)) {
285                 // See https://bugs.php.net/bug.php?id=54097 & http://php.net/manual/en/function.rename.php#113943
286                 $this->mirror($origin, $target, null, array('override' => $overwrite, 'delete' => $overwrite));
287                 $this->remove($origin);
288
289                 return;
290             }
291             throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target);
292         }
293     }
294
295     /**
296      * Tells whether a file exists and is readable.
297      *
298      * @param string $filename Path to the file
299      *
300      * @return bool
301      *
302      * @throws IOException When windows path is longer than 258 characters
303      */
304     private function isReadable($filename)
305     {
306         $maxPathLength = PHP_MAXPATHLEN - 2;
307
308         if (strlen($filename) > $maxPathLength) {
309             throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename);
310         }
311
312         return is_readable($filename);
313     }
314
315     /**
316      * Creates a symbolic link or copy a directory.
317      *
318      * @param string $originDir     The origin directory path
319      * @param string $targetDir     The symbolic link name
320      * @param bool   $copyOnWindows Whether to copy files if on Windows
321      *
322      * @throws IOException When symlink fails
323      */
324     public function symlink($originDir, $targetDir, $copyOnWindows = false)
325     {
326         if ('\\' === DIRECTORY_SEPARATOR) {
327             $originDir = strtr($originDir, '/', '\\');
328             $targetDir = strtr($targetDir, '/', '\\');
329
330             if ($copyOnWindows) {
331                 $this->mirror($originDir, $targetDir);
332
333                 return;
334             }
335         }
336
337         $this->mkdir(dirname($targetDir));
338
339         $ok = false;
340         if (is_link($targetDir)) {
341             if (readlink($targetDir) != $originDir) {
342                 $this->remove($targetDir);
343             } else {
344                 $ok = true;
345             }
346         }
347
348         if (!$ok && true !== @symlink($originDir, $targetDir)) {
349             $this->linkException($originDir, $targetDir, 'symbolic');
350         }
351     }
352
353     /**
354      * Creates a hard link, or several hard links to a file.
355      *
356      * @param string          $originFile  The original file
357      * @param string|string[] $targetFiles The target file(s)
358      *
359      * @throws FileNotFoundException When original file is missing or not a file
360      * @throws IOException           When link fails, including if link already exists
361      */
362     public function hardlink($originFile, $targetFiles)
363     {
364         if (!$this->exists($originFile)) {
365             throw new FileNotFoundException(null, 0, null, $originFile);
366         }
367
368         if (!is_file($originFile)) {
369             throw new FileNotFoundException(sprintf('Origin file "%s" is not a file', $originFile));
370         }
371
372         foreach ($this->toIterable($targetFiles) as $targetFile) {
373             if (is_file($targetFile)) {
374                 if (fileinode($originFile) === fileinode($targetFile)) {
375                     continue;
376                 }
377                 $this->remove($targetFile);
378             }
379
380             if (true !== @link($originFile, $targetFile)) {
381                 $this->linkException($originFile, $targetFile, 'hard');
382             }
383         }
384     }
385
386     /**
387      * @param string $origin
388      * @param string $target
389      * @param string $linkType Name of the link type, typically 'symbolic' or 'hard'
390      */
391     private function linkException($origin, $target, $linkType)
392     {
393         $report = error_get_last();
394         if (is_array($report)) {
395             if ('\\' === DIRECTORY_SEPARATOR && false !== strpos($report['message'], 'error code(1314)')) {
396                 throw new IOException(sprintf('Unable to create %s link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target);
397             }
398         }
399         throw new IOException(sprintf('Failed to create %s link from "%s" to "%s".', $linkType, $origin, $target), 0, null, $target);
400     }
401
402     /**
403      * Resolves links in paths.
404      *
405      * With $canonicalize = false (default)
406      *      - if $path does not exist or is not a link, returns null
407      *      - if $path is a link, returns the next direct target of the link without considering the existence of the target
408      *
409      * With $canonicalize = true
410      *      - if $path does not exist, returns null
411      *      - if $path exists, returns its absolute fully resolved final version
412      *
413      * @param string $path         A filesystem path
414      * @param bool   $canonicalize Whether or not to return a canonicalized path
415      *
416      * @return string|null
417      */
418     public function readlink($path, $canonicalize = false)
419     {
420         if (!$canonicalize && !is_link($path)) {
421             return;
422         }
423
424         if ($canonicalize) {
425             if (!$this->exists($path)) {
426                 return;
427             }
428
429             if ('\\' === DIRECTORY_SEPARATOR) {
430                 $path = readlink($path);
431             }
432
433             return realpath($path);
434         }
435
436         if ('\\' === DIRECTORY_SEPARATOR) {
437             return realpath($path);
438         }
439
440         return readlink($path);
441     }
442
443     /**
444      * Given an existing path, convert it to a path relative to a given starting path.
445      *
446      * @param string $endPath   Absolute path of target
447      * @param string $startPath Absolute path where traversal begins
448      *
449      * @return string Path of target relative to starting path
450      */
451     public function makePathRelative($endPath, $startPath)
452     {
453         if (!$this->isAbsolutePath($endPath) || !$this->isAbsolutePath($startPath)) {
454             @trigger_error(sprintf('Support for passing relative paths to %s() is deprecated since Symfony 3.4 and will be removed in 4.0.', __METHOD__), E_USER_DEPRECATED);
455         }
456
457         // Normalize separators on Windows
458         if ('\\' === DIRECTORY_SEPARATOR) {
459             $endPath = str_replace('\\', '/', $endPath);
460             $startPath = str_replace('\\', '/', $startPath);
461         }
462
463         $stripDriveLetter = function ($path) {
464             if (strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) {
465                 return substr($path, 2);
466             }
467
468             return $path;
469         };
470
471         $endPath = $stripDriveLetter($endPath);
472         $startPath = $stripDriveLetter($startPath);
473
474         // Split the paths into arrays
475         $startPathArr = explode('/', trim($startPath, '/'));
476         $endPathArr = explode('/', trim($endPath, '/'));
477
478         $normalizePathArray = function ($pathSegments, $absolute) {
479             $result = array();
480
481             foreach ($pathSegments as $segment) {
482                 if ('..' === $segment && ($absolute || count($result))) {
483                     array_pop($result);
484                 } elseif ('.' !== $segment) {
485                     $result[] = $segment;
486                 }
487             }
488
489             return $result;
490         };
491
492         $startPathArr = $normalizePathArray($startPathArr, static::isAbsolutePath($startPath));
493         $endPathArr = $normalizePathArray($endPathArr, static::isAbsolutePath($endPath));
494
495         // Find for which directory the common path stops
496         $index = 0;
497         while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
498             ++$index;
499         }
500
501         // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
502         if (1 === count($startPathArr) && '' === $startPathArr[0]) {
503             $depth = 0;
504         } else {
505             $depth = count($startPathArr) - $index;
506         }
507
508         // Repeated "../" for each level need to reach the common path
509         $traverser = str_repeat('../', $depth);
510
511         $endPathRemainder = implode('/', array_slice($endPathArr, $index));
512
513         // Construct $endPath from traversing to the common path, then to the remaining $endPath
514         $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
515
516         return '' === $relativePath ? './' : $relativePath;
517     }
518
519     /**
520      * Mirrors a directory to another.
521      *
522      * Copies files and directories from the origin directory into the target directory. By default:
523      *
524      *  - existing files in the target directory will be overwritten, except if they are newer (see the `override` option)
525      *  - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option)
526      *
527      * @param string       $originDir The origin directory
528      * @param string       $targetDir The target directory
529      * @param \Traversable $iterator  Iterator that filters which files and directories to copy
530      * @param array        $options   An array of boolean options
531      *                                Valid options are:
532      *                                - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false)
533      *                                - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false)
534      *                                - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
535      *
536      * @throws IOException When file type is unknown
537      */
538     public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = array())
539     {
540         $targetDir = rtrim($targetDir, '/\\');
541         $originDir = rtrim($originDir, '/\\');
542         $originDirLen = strlen($originDir);
543
544         // Iterate in destination folder to remove obsolete entries
545         if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
546             $deleteIterator = $iterator;
547             if (null === $deleteIterator) {
548                 $flags = \FilesystemIterator::SKIP_DOTS;
549                 $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
550             }
551             $targetDirLen = strlen($targetDir);
552             foreach ($deleteIterator as $file) {
553                 $origin = $originDir.substr($file->getPathname(), $targetDirLen);
554                 if (!$this->exists($origin)) {
555                     $this->remove($file);
556                 }
557             }
558         }
559
560         $copyOnWindows = false;
561         if (isset($options['copy_on_windows'])) {
562             $copyOnWindows = $options['copy_on_windows'];
563         }
564
565         if (null === $iterator) {
566             $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
567             $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
568         }
569
570         if ($this->exists($originDir)) {
571             $this->mkdir($targetDir);
572         }
573
574         foreach ($iterator as $file) {
575             $target = $targetDir.substr($file->getPathname(), $originDirLen);
576
577             if ($copyOnWindows) {
578                 if (is_file($file)) {
579                     $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
580                 } elseif (is_dir($file)) {
581                     $this->mkdir($target);
582                 } else {
583                     throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
584                 }
585             } else {
586                 if (is_link($file)) {
587                     $this->symlink($file->getLinkTarget(), $target);
588                 } elseif (is_dir($file)) {
589                     $this->mkdir($target);
590                 } elseif (is_file($file)) {
591                     $this->copy($file, $target, isset($options['override']) ? $options['override'] : false);
592                 } else {
593                     throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
594                 }
595             }
596         }
597     }
598
599     /**
600      * Returns whether the file path is an absolute path.
601      *
602      * @param string $file A file path
603      *
604      * @return bool
605      */
606     public function isAbsolutePath($file)
607     {
608         return strspn($file, '/\\', 0, 1)
609             || (strlen($file) > 3 && ctype_alpha($file[0])
610                 && ':' === $file[1]
611                 && strspn($file, '/\\', 2, 1)
612             )
613             || null !== parse_url($file, PHP_URL_SCHEME)
614         ;
615     }
616
617     /**
618      * Creates a temporary file with support for custom stream wrappers.
619      *
620      * @param string $dir    The directory where the temporary filename will be created
621      * @param string $prefix The prefix of the generated temporary filename
622      *                       Note: Windows uses only the first three characters of prefix
623      *
624      * @return string The new temporary filename (with path), or throw an exception on failure
625      */
626     public function tempnam($dir, $prefix)
627     {
628         list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir);
629
630         // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
631         if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) {
632             $tmpFile = @tempnam($hierarchy, $prefix);
633
634             // If tempnam failed or no scheme return the filename otherwise prepend the scheme
635             if (false !== $tmpFile) {
636                 if (null !== $scheme && 'gs' !== $scheme) {
637                     return $scheme.'://'.$tmpFile;
638                 }
639
640                 return $tmpFile;
641             }
642
643             throw new IOException('A temporary file could not be created.');
644         }
645
646         // Loop until we create a valid temp file or have reached 10 attempts
647         for ($i = 0; $i < 10; ++$i) {
648             // Create a unique filename
649             $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true);
650
651             // Use fopen instead of file_exists as some streams do not support stat
652             // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
653             $handle = @fopen($tmpFile, 'x+');
654
655             // If unsuccessful restart the loop
656             if (false === $handle) {
657                 continue;
658             }
659
660             // Close the file if it was successfully opened
661             @fclose($handle);
662
663             return $tmpFile;
664         }
665
666         throw new IOException('A temporary file could not be created.');
667     }
668
669     /**
670      * Atomically dumps content into a file.
671      *
672      * @param string $filename The file to be written to
673      * @param string $content  The data to write into the file
674      *
675      * @throws IOException if the file cannot be written to
676      */
677     public function dumpFile($filename, $content)
678     {
679         $dir = dirname($filename);
680
681         if (!is_dir($dir)) {
682             $this->mkdir($dir);
683         }
684
685         if (!is_writable($dir)) {
686             throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
687         }
688
689         // Will create a temp file with 0600 access rights
690         // when the filesystem supports chmod.
691         $tmpFile = $this->tempnam($dir, basename($filename));
692
693         if (false === @file_put_contents($tmpFile, $content)) {
694             throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
695         }
696
697         @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
698
699         $this->rename($tmpFile, $filename, true);
700     }
701
702     /**
703      * Appends content to an existing file.
704      *
705      * @param string $filename The file to which to append content
706      * @param string $content  The content to append
707      *
708      * @throws IOException If the file is not writable
709      */
710     public function appendToFile($filename, $content)
711     {
712         $dir = dirname($filename);
713
714         if (!is_dir($dir)) {
715             $this->mkdir($dir);
716         }
717
718         if (!is_writable($dir)) {
719             throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
720         }
721
722         if (false === @file_put_contents($filename, $content, FILE_APPEND)) {
723             throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
724         }
725     }
726
727     /**
728      * @param mixed $files
729      *
730      * @return array|\Traversable
731      */
732     private function toIterable($files)
733     {
734         return is_array($files) || $files instanceof \Traversable ? $files : array($files);
735     }
736
737     /**
738      * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)).
739      *
740      * @param string $filename The filename to be parsed
741      *
742      * @return array The filename scheme and hierarchical part
743      */
744     private function getSchemeAndHierarchy($filename)
745     {
746         $components = explode('://', $filename, 2);
747
748         return 2 === count($components) ? array($components[0], $components[1]) : array(null, $components[0]);
749     }
750 }