vendor/symfony/filesystem/Filesystem.php line 128

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Filesystem;
  11. use Symfony\Component\Filesystem\Exception\FileNotFoundException;
  12. use Symfony\Component\Filesystem\Exception\InvalidArgumentException;
  13. use Symfony\Component\Filesystem\Exception\IOException;
  14. /**
  15.  * Provides basic utility to manipulate the file system.
  16.  *
  17.  * @author Fabien Potencier <fabien@symfony.com>
  18.  */
  19. class Filesystem
  20. {
  21.     private static $lastError;
  22.     /**
  23.      * Copies a file.
  24.      *
  25.      * If the target file is older than the origin file, it's always overwritten.
  26.      * If the target file is newer, it is overwritten only when the
  27.      * $overwriteNewerFiles option is set to true.
  28.      *
  29.      * @throws FileNotFoundException When originFile doesn't exist
  30.      * @throws IOException           When copy fails
  31.      */
  32.     public function copy(string $originFile, string $targetFile, bool $overwriteNewerFiles = false)
  33.     {
  34.         $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://');
  35.         if ($originIsLocal && !is_file($originFile)) {
  36.             throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
  37.         }
  38.         $this->mkdir(\dirname($targetFile));
  39.         $doCopy = true;
  40.         if (!$overwriteNewerFiles && null === parse_url($originFile, \PHP_URL_HOST) && is_file($targetFile)) {
  41.             $doCopy = filemtime($originFile) > filemtime($targetFile);
  42.         }
  43.         if ($doCopy) {
  44.             // https://bugs.php.net/64634
  45.             if (!$source = self::box('fopen', $originFile, 'r')) {
  46.                 throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading: ', $originFile, $targetFile).self::$lastError, 0, null, $originFile);
  47.             }
  48.             // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
  49.             if (!$target = self::box('fopen', $targetFile, 'w', false, stream_context_create(['ftp' => ['overwrite' => true]]))) {
  50.                 throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing: ', $originFile, $targetFile).self::$lastError, 0, null, $originFile);
  51.             }
  52.             $bytesCopied = stream_copy_to_stream($source, $target);
  53.             fclose($source);
  54.             fclose($target);
  55.             unset($source, $target);
  56.             if (!is_file($targetFile)) {
  57.                 throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
  58.             }
  59.             if ($originIsLocal) {
  60.                 // Like `cp`, preserve executable permission bits
  61.                 self::box('chmod', $targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111));
  62.                 if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
  63.                     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);
  64.                 }
  65.             }
  66.         }
  67.     }
  68.     /**
  69.      * Creates a directory recursively.
  70.      *
  71.      * @throws IOException On any directory creation failure
  72.      */
  73.     public function mkdir(string|iterable $dirs, int $mode = 0777)
  74.     {
  75.         foreach ($this->toIterable($dirs) as $dir) {
  76.             if (is_dir($dir)) {
  77.                 continue;
  78.             }
  79.             if (!self::box('mkdir', $dir, $mode, true) && !is_dir($dir)) {
  80.                 throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir);
  81.             }
  82.         }
  83.     }
  84.     /**
  85.      * Checks the existence of files or directories.
  86.      */
  87.     public function exists(string|iterable $files): bool
  88.     {
  89.         $maxPathLength = \PHP_MAXPATHLEN - 2;
  90.         foreach ($this->toIterable($files) as $file) {
  91.             if (\strlen($file) > $maxPathLength) {
  92.                 throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file);
  93.             }
  94.             if (!file_exists($file)) {
  95.                 return false;
  96.             }
  97.         }
  98.         return true;
  99.     }
  100.     /**
  101.      * Sets access and modification time of file.
  102.      *
  103.      * @param int|null $time  The touch time as a Unix timestamp, if not supplied the current system time is used
  104.      * @param int|null $atime The access time as a Unix timestamp, if not supplied the current system time is used
  105.      *
  106.      * @throws IOException When touch fails
  107.      */
  108.     public function touch(string|iterable $files, int $time = null, int $atime = null)
  109.     {
  110.         foreach ($this->toIterable($files) as $file) {
  111.             if (!($time ? self::box('touch', $file, $time, $atime) : self::box('touch', $file))) {
  112.                 throw new IOException(sprintf('Failed to touch "%s": ', $file).self::$lastError, 0, null, $file);
  113.             }
  114.         }
  115.     }
  116.     /**
  117.      * Removes files or directories.
  118.      *
  119.      * @throws IOException When removal fails
  120.      */
  121.     public function remove(string|iterable $files)
  122.     {
  123.         if ($files instanceof \Traversable) {
  124.             $files = iterator_to_array($files, false);
  125.         } elseif (!\is_array($files)) {
  126.             $files = [$files];
  127.         }
  128.         self::doRemove($files, false);
  129.     }
  130.     private static function doRemove(array $files, bool $isRecursive): void
  131.     {
  132.         $files = array_reverse($files);
  133.         foreach ($files as $file) {
  134.             if (is_link($file)) {
  135.                 // See https://bugs.php.net/52176
  136.                 if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) {
  137.                     throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError);
  138.                 }
  139.             } elseif (is_dir($file)) {
  140.                 if (!$isRecursive) {
  141.                     $tmpName = \dirname(realpath($file)).'/.'.strrev(strtr(base64_encode(random_bytes(2)), '/=', '-.'));
  142.                     if (file_exists($tmpName)) {
  143.                         try {
  144.                             self::doRemove([$tmpName], true);
  145.                         } catch (IOException $e) {
  146.                         }
  147.                     }
  148.                     if (!file_exists($tmpName) && self::box('rename', $file, $tmpName)) {
  149.                         $origFile = $file;
  150.                         $file = $tmpName;
  151.                     } else {
  152.                         $origFile = null;
  153.                     }
  154.                 }
  155.                 $files = new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
  156.                 self::doRemove(iterator_to_array($files, true), true);
  157.                 if (!self::box('rmdir', $file) && file_exists($file) && !$isRecursive) {
  158.                     $lastError = self::$lastError;
  159.                     if (null !== $origFile && self::box('rename', $file, $origFile)) {
  160.                         $file = $origFile;
  161.                     }
  162.                     throw new IOException(sprintf('Failed to remove directory "%s": ', $file).$lastError);
  163.                 }
  164.             } elseif (!self::box('unlink', $file) && (str_contains(self::$lastError, 'Permission denied') || file_exists($file))) {
  165.                 throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError);
  166.             }
  167.         }
  168.     }
  169.     /**
  170.      * Change mode for an array of files or directories.
  171.      *
  172.      * @param int  $mode      The new mode (octal)
  173.      * @param int  $umask     The mode mask (octal)
  174.      * @param bool $recursive Whether change the mod recursively or not
  175.      *
  176.      * @throws IOException When the change fails
  177.      */
  178.     public function chmod(string|iterable $files, int $mode, int $umask = 0000, bool $recursive = false)
  179.     {
  180.         foreach ($this->toIterable($files) as $file) {
  181.             if (\is_int($mode) && !self::box('chmod', $file, $mode & ~$umask)) {
  182.                 throw new IOException(sprintf('Failed to chmod file "%s": ', $file).self::$lastError, 0, null, $file);
  183.             }
  184.             if ($recursive && is_dir($file) && !is_link($file)) {
  185.                 $this->chmod(new \FilesystemIterator($file), $mode, $umask, true);
  186.             }
  187.         }
  188.     }
  189.     /**
  190.      * Change the owner of an array of files or directories.
  191.      *
  192.      * @param string|int $user      A user name or number
  193.      * @param bool       $recursive Whether change the owner recursively or not
  194.      *
  195.      * @throws IOException When the change fails
  196.      */
  197.     public function chown(string|iterable $files, string|int $user, bool $recursive = false)
  198.     {
  199.         foreach ($this->toIterable($files) as $file) {
  200.             if ($recursive && is_dir($file) && !is_link($file)) {
  201.                 $this->chown(new \FilesystemIterator($file), $user, true);
  202.             }
  203.             if (is_link($file) && \function_exists('lchown')) {
  204.                 if (!self::box('lchown', $file, $user)) {
  205.                     throw new IOException(sprintf('Failed to chown file "%s": ', $file).self::$lastError, 0, null, $file);
  206.                 }
  207.             } else {
  208.                 if (!self::box('chown', $file, $user)) {
  209.                     throw new IOException(sprintf('Failed to chown file "%s": ', $file).self::$lastError, 0, null, $file);
  210.                 }
  211.             }
  212.         }
  213.     }
  214.     /**
  215.      * Change the group of an array of files or directories.
  216.      *
  217.      * @param string|int $group     A group name or number
  218.      * @param bool       $recursive Whether change the group recursively or not
  219.      *
  220.      * @throws IOException When the change fails
  221.      */
  222.     public function chgrp(string|iterable $files, string|int $group, bool $recursive = false)
  223.     {
  224.         foreach ($this->toIterable($files) as $file) {
  225.             if ($recursive && is_dir($file) && !is_link($file)) {
  226.                 $this->chgrp(new \FilesystemIterator($file), $group, true);
  227.             }
  228.             if (is_link($file) && \function_exists('lchgrp')) {
  229.                 if (!self::box('lchgrp', $file, $group)) {
  230.                     throw new IOException(sprintf('Failed to chgrp file "%s": ', $file).self::$lastError, 0, null, $file);
  231.                 }
  232.             } else {
  233.                 if (!self::box('chgrp', $file, $group)) {
  234.                     throw new IOException(sprintf('Failed to chgrp file "%s": ', $file).self::$lastError, 0, null, $file);
  235.                 }
  236.             }
  237.         }
  238.     }
  239.     /**
  240.      * Renames a file or a directory.
  241.      *
  242.      * @throws IOException When target file or directory already exists
  243.      * @throws IOException When origin cannot be renamed
  244.      */
  245.     public function rename(string $origin, string $target, bool $overwrite = false)
  246.     {
  247.         // we check that target does not exist
  248.         if (!$overwrite && $this->isReadable($target)) {
  249.             throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target);
  250.         }
  251.         if (!self::box('rename', $origin, $target)) {
  252.             if (is_dir($origin)) {
  253.                 // See https://bugs.php.net/54097 & https://php.net/rename#113943
  254.                 $this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]);
  255.                 $this->remove($origin);
  256.                 return;
  257.             }
  258.             throw new IOException(sprintf('Cannot rename "%s" to "%s": ', $origin, $target).self::$lastError, 0, null, $target);
  259.         }
  260.     }
  261.     /**
  262.      * Tells whether a file exists and is readable.
  263.      *
  264.      * @throws IOException When windows path is longer than 258 characters
  265.      */
  266.     private function isReadable(string $filename): bool
  267.     {
  268.         $maxPathLength = \PHP_MAXPATHLEN - 2;
  269.         if (\strlen($filename) > $maxPathLength) {
  270.             throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename);
  271.         }
  272.         return is_readable($filename);
  273.     }
  274.     /**
  275.      * Creates a symbolic link or copy a directory.
  276.      *
  277.      * @throws IOException When symlink fails
  278.      */
  279.     public function symlink(string $originDir, string $targetDir, bool $copyOnWindows = false)
  280.     {
  281.         if ('\\' === \DIRECTORY_SEPARATOR) {
  282.             $originDir = strtr($originDir, '/', '\\');
  283.             $targetDir = strtr($targetDir, '/', '\\');
  284.             if ($copyOnWindows) {
  285.                 $this->mirror($originDir, $targetDir);
  286.                 return;
  287.             }
  288.         }
  289.         $this->mkdir(\dirname($targetDir));
  290.         if (is_link($targetDir)) {
  291.             if (readlink($targetDir) === $originDir) {
  292.                 return;
  293.             }
  294.             $this->remove($targetDir);
  295.         }
  296.         if (!self::box('symlink', $originDir, $targetDir)) {
  297.             $this->linkException($originDir, $targetDir, 'symbolic');
  298.         }
  299.     }
  300.     /**
  301.      * Creates a hard link, or several hard links to a file.
  302.      *
  303.      * @param string|string[] $targetFiles The target file(s)
  304.      *
  305.      * @throws FileNotFoundException When original file is missing or not a file
  306.      * @throws IOException           When link fails, including if link already exists
  307.      */
  308.     public function hardlink(string $originFile, string|iterable $targetFiles)
  309.     {
  310.         if (!$this->exists($originFile)) {
  311.             throw new FileNotFoundException(null, 0, null, $originFile);
  312.         }
  313.         if (!is_file($originFile)) {
  314.             throw new FileNotFoundException(sprintf('Origin file "%s" is not a file.', $originFile));
  315.         }
  316.         foreach ($this->toIterable($targetFiles) as $targetFile) {
  317.             if (is_file($targetFile)) {
  318.                 if (fileinode($originFile) === fileinode($targetFile)) {
  319.                     continue;
  320.                 }
  321.                 $this->remove($targetFile);
  322.             }
  323.             if (!self::box('link', $originFile, $targetFile)) {
  324.                 $this->linkException($originFile, $targetFile, 'hard');
  325.             }
  326.         }
  327.     }
  328.     /**
  329.      * @param string $linkType Name of the link type, typically 'symbolic' or 'hard'
  330.      */
  331.     private function linkException(string $origin, string $target, string $linkType)
  332.     {
  333.         if (self::$lastError) {
  334.             if ('\\' === \DIRECTORY_SEPARATOR && str_contains(self::$lastError, 'error code(1314)')) {
  335.                 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);
  336.             }
  337.         }
  338.         throw new IOException(sprintf('Failed to create "%s" link from "%s" to "%s": ', $linkType, $origin, $target).self::$lastError, 0, null, $target);
  339.     }
  340.     /**
  341.      * Resolves links in paths.
  342.      *
  343.      * With $canonicalize = false (default)
  344.      *      - if $path does not exist or is not a link, returns null
  345.      *      - if $path is a link, returns the next direct target of the link without considering the existence of the target
  346.      *
  347.      * With $canonicalize = true
  348.      *      - if $path does not exist, returns null
  349.      *      - if $path exists, returns its absolute fully resolved final version
  350.      */
  351.     public function readlink(string $path, bool $canonicalize = false): ?string
  352.     {
  353.         if (!$canonicalize && !is_link($path)) {
  354.             return null;
  355.         }
  356.         if ($canonicalize) {
  357.             if (!$this->exists($path)) {
  358.                 return null;
  359.             }
  360.             return realpath($path);
  361.         }
  362.         return readlink($path);
  363.     }
  364.     /**
  365.      * Given an existing path, convert it to a path relative to a given starting path.
  366.      */
  367.     public function makePathRelative(string $endPath, string $startPath): string
  368.     {
  369.         if (!$this->isAbsolutePath($startPath)) {
  370.             throw new InvalidArgumentException(sprintf('The start path "%s" is not absolute.', $startPath));
  371.         }
  372.         if (!$this->isAbsolutePath($endPath)) {
  373.             throw new InvalidArgumentException(sprintf('The end path "%s" is not absolute.', $endPath));
  374.         }
  375.         // Normalize separators on Windows
  376.         if ('\\' === \DIRECTORY_SEPARATOR) {
  377.             $endPath = str_replace('\\', '/', $endPath);
  378.             $startPath = str_replace('\\', '/', $startPath);
  379.         }
  380.         $splitDriveLetter = function ($path) {
  381.             return (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0]))
  382.                 ? [substr($path, 2), strtoupper($path[0])]
  383.                 : [$path, null];
  384.         };
  385.         $splitPath = function ($path) {
  386.             $result = [];
  387.             foreach (explode('/', trim($path, '/')) as $segment) {
  388.                 if ('..' === $segment) {
  389.                     array_pop($result);
  390.                 } elseif ('.' !== $segment && '' !== $segment) {
  391.                     $result[] = $segment;
  392.                 }
  393.             }
  394.             return $result;
  395.         };
  396.         [$endPath, $endDriveLetter] = $splitDriveLetter($endPath);
  397.         [$startPath, $startDriveLetter] = $splitDriveLetter($startPath);
  398.         $startPathArr = $splitPath($startPath);
  399.         $endPathArr = $splitPath($endPath);
  400.         if ($endDriveLetter && $startDriveLetter && $endDriveLetter != $startDriveLetter) {
  401.             // End path is on another drive, so no relative path exists
  402.             return $endDriveLetter.':/'.($endPathArr ? implode('/', $endPathArr).'/' : '');
  403.         }
  404.         // Find for which directory the common path stops
  405.         $index = 0;
  406.         while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
  407.             ++$index;
  408.         }
  409.         // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
  410.         if (1 === \count($startPathArr) && '' === $startPathArr[0]) {
  411.             $depth = 0;
  412.         } else {
  413.             $depth = \count($startPathArr) - $index;
  414.         }
  415.         // Repeated "../" for each level need to reach the common path
  416.         $traverser = str_repeat('../', $depth);
  417.         $endPathRemainder = implode('/', \array_slice($endPathArr, $index));
  418.         // Construct $endPath from traversing to the common path, then to the remaining $endPath
  419.         $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');
  420.         return '' === $relativePath ? './' : $relativePath;
  421.     }
  422.     /**
  423.      * Mirrors a directory to another.
  424.      *
  425.      * Copies files and directories from the origin directory into the target directory. By default:
  426.      *
  427.      *  - existing files in the target directory will be overwritten, except if they are newer (see the `override` option)
  428.      *  - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option)
  429.      *
  430.      * @param \Traversable|null $iterator Iterator that filters which files and directories to copy, if null a recursive iterator is created
  431.      * @param array             $options  An array of boolean options
  432.      *                                    Valid options are:
  433.      *                                    - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false)
  434.      *                                    - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false)
  435.      *                                    - $options['delete'] Whether to delete files that are not in the source directory (defaults to false)
  436.      *
  437.      * @throws IOException When file type is unknown
  438.      */
  439.     public function mirror(string $originDir, string $targetDir, \Traversable $iterator = null, array $options = [])
  440.     {
  441.         $targetDir = rtrim($targetDir, '/\\');
  442.         $originDir = rtrim($originDir, '/\\');
  443.         $originDirLen = \strlen($originDir);
  444.         if (!$this->exists($originDir)) {
  445.             throw new IOException(sprintf('The origin directory specified "%s" was not found.', $originDir), 0, null, $originDir);
  446.         }
  447.         // Iterate in destination folder to remove obsolete entries
  448.         if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) {
  449.             $deleteIterator = $iterator;
  450.             if (null === $deleteIterator) {
  451.                 $flags = \FilesystemIterator::SKIP_DOTS;
  452.                 $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST);
  453.             }
  454.             $targetDirLen = \strlen($targetDir);
  455.             foreach ($deleteIterator as $file) {
  456.                 $origin = $originDir.substr($file->getPathname(), $targetDirLen);
  457.                 if (!$this->exists($origin)) {
  458.                     $this->remove($file);
  459.                 }
  460.             }
  461.         }
  462.         $copyOnWindows = $options['copy_on_windows'] ?? false;
  463.         if (null === $iterator) {
  464.             $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS;
  465.             $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST);
  466.         }
  467.         $this->mkdir($targetDir);
  468.         $filesCreatedWhileMirroring = [];
  469.         foreach ($iterator as $file) {
  470.             if ($file->getPathname() === $targetDir || $file->getRealPath() === $targetDir || isset($filesCreatedWhileMirroring[$file->getRealPath()])) {
  471.                 continue;
  472.             }
  473.             $target = $targetDir.substr($file->getPathname(), $originDirLen);
  474.             $filesCreatedWhileMirroring[$target] = true;
  475.             if (!$copyOnWindows && is_link($file)) {
  476.                 $this->symlink($file->getLinkTarget(), $target);
  477.             } elseif (is_dir($file)) {
  478.                 $this->mkdir($target);
  479.             } elseif (is_file($file)) {
  480.                 $this->copy($file, $target, $options['override'] ?? false);
  481.             } else {
  482.                 throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file);
  483.             }
  484.         }
  485.     }
  486.     /**
  487.      * Returns whether the file path is an absolute path.
  488.      */
  489.     public function isAbsolutePath(string $file): bool
  490.     {
  491.         return '' !== $file && (strspn($file, '/\\', 0, 1)
  492.             || (\strlen($file) > 3 && ctype_alpha($file[0])
  493.                 && ':' === $file[1]
  494.                 && strspn($file, '/\\', 2, 1)
  495.             )
  496.             || null !== parse_url($file, \PHP_URL_SCHEME)
  497.         );
  498.     }
  499.     /**
  500.      * Creates a temporary file with support for custom stream wrappers.
  501.      *
  502.      * @param string $prefix The prefix of the generated temporary filename
  503.      *                       Note: Windows uses only the first three characters of prefix
  504.      * @param string $suffix The suffix of the generated temporary filename
  505.      *
  506.      * @return string The new temporary filename (with path), or throw an exception on failure
  507.      */
  508.     public function tempnam(string $dir, string $prefix, string $suffix = ''): string
  509.     {
  510.         [$scheme, $hierarchy] = $this->getSchemeAndHierarchy($dir);
  511.         // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem
  512.         if ((null === $scheme || 'file' === $scheme || 'gs' === $scheme) && '' === $suffix) {
  513.             // If tempnam failed or no scheme return the filename otherwise prepend the scheme
  514.             if ($tmpFile = self::box('tempnam', $hierarchy, $prefix)) {
  515.                 if (null !== $scheme && 'gs' !== $scheme) {
  516.                     return $scheme.'://'.$tmpFile;
  517.                 }
  518.                 return $tmpFile;
  519.             }
  520.             throw new IOException('A temporary file could not be created: '.self::$lastError);
  521.         }
  522.         // Loop until we create a valid temp file or have reached 10 attempts
  523.         for ($i = 0; $i < 10; ++$i) {
  524.             // Create a unique filename
  525.             $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true).$suffix;
  526.             // Use fopen instead of file_exists as some streams do not support stat
  527.             // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability
  528.             if (!$handle = self::box('fopen', $tmpFile, 'x+')) {
  529.                 continue;
  530.             }
  531.             // Close the file if it was successfully opened
  532.             self::box('fclose', $handle);
  533.             return $tmpFile;
  534.         }
  535.         throw new IOException('A temporary file could not be created: '.self::$lastError);
  536.     }
  537.     /**
  538.      * Atomically dumps content into a file.
  539.      *
  540.      * @param string|resource $content The data to write into the file
  541.      *
  542.      * @throws IOException if the file cannot be written to
  543.      */
  544.     public function dumpFile(string $filename, $content)
  545.     {
  546.         if (\is_array($content)) {
  547.             throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__));
  548.         }
  549.         $dir = \dirname($filename);
  550.         if (!is_dir($dir)) {
  551.             $this->mkdir($dir);
  552.         }
  553.         // Will create a temp file with 0600 access rights
  554.         // when the filesystem supports chmod.
  555.         $tmpFile = $this->tempnam($dir, basename($filename));
  556.         try {
  557.             if (false === self::box('file_put_contents', $tmpFile, $content)) {
  558.                 throw new IOException(sprintf('Failed to write file "%s": ', $filename).self::$lastError, 0, null, $filename);
  559.             }
  560.             self::box('chmod', $tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());
  561.             $this->rename($tmpFile, $filename, true);
  562.         } finally {
  563.             if (file_exists($tmpFile)) {
  564.                 self::box('unlink', $tmpFile);
  565.             }
  566.         }
  567.     }
  568.     /**
  569.      * Appends content to an existing file.
  570.      *
  571.      * @param string|resource $content The content to append
  572.      * @param bool            $lock    Whether the file should be locked when writing to it
  573.      *
  574.      * @throws IOException If the file is not writable
  575.      */
  576.     public function appendToFile(string $filename, $content/*, bool $lock = false*/)
  577.     {
  578.         if (\is_array($content)) {
  579.             throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__));
  580.         }
  581.         $dir = \dirname($filename);
  582.         if (!is_dir($dir)) {
  583.             $this->mkdir($dir);
  584.         }
  585.         $lock = \func_num_args() > 2 && func_get_arg(2);
  586.         if (false === self::box('file_put_contents', $filename, $content, \FILE_APPEND | ($lock ? \LOCK_EX : 0))) {
  587.             throw new IOException(sprintf('Failed to write file "%s": ', $filename).self::$lastError, 0, null, $filename);
  588.         }
  589.     }
  590.     private function toIterable(string|iterable $files): iterable
  591.     {
  592.         return is_iterable($files) ? $files : [$files];
  593.     }
  594.     /**
  595.      * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> [file, tmp]).
  596.      */
  597.     private function getSchemeAndHierarchy(string $filename): array
  598.     {
  599.         $components = explode('://', $filename, 2);
  600.         return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]];
  601.     }
  602.     private static function box(callable $func, mixed ...$args): mixed
  603.     {
  604.         self::$lastError = null;
  605.         set_error_handler(__CLASS__.'::handleError');
  606.         try {
  607.             return $func(...$args);
  608.         } finally {
  609.             restore_error_handler();
  610.         }
  611.     }
  612.     /**
  613.      * @internal
  614.      */
  615.     public static function handleError(int $type, string $msg)
  616.     {
  617.         self::$lastError = $msg;
  618.     }
  619. }