originDir The origin directory * @param string $targetDir The target directory * @param \Traversable|null $iterator Iterator that filters which files and directories to copy, if null a recursive iterator is created * @param array $options An array of boolean options * Valid options are: * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false) * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false) * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false) * * @throws IOException When file type is unknown */ public function mirror($originDir, $targetDir, \Traversable $iterator = null, $options = []) { $targetDir = rtrim($targetDir, '/\\'); $originDir = rtrim($originDir, '/\\'); $originDirLen = \strlen($originDir); // Iterate in destination folder to remove obsolete entries if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) { $deleteIterator = $iterator; if (null === $deleteIterator) { $flags = \FilesystemIterator::SKIP_DOTS; $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST); } $targetDirLen = \strlen($targetDir); foreach ($deleteIterator as $file) { $origin = $originDir.substr($file->getPathname(), $targetDirLen); if (!$this->exists($origin)) { $this->remove($file); } } } $copyOnWindows = false; if (isset($options['copy_on_windows'])) { $copyOnWindows = $options['copy_on_windows']; } if (null === $iterator) { $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS; $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST); } if ($this->exists($originDir)) { $this->mkdir($targetDir); } foreach ($iterator as $file) { $target = $targetDir.substr($file->getPathname(), $originDirLen); if ($copyOnWindows) { if (is_file($file)) { $this->copy($file, $target, isset($options['override']) ? $options['override'] : false); } elseif (is_dir($file)) { $this->mkdir($target); } else { throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file); } } else { if (is_link($file)) { $this->symlink($file->getLinkTarget(), $target); } elseif (is_dir($file)) { $this->mkdir($target); } elseif (is_file($file)) { $this->copy($file, $target, isset($options['override']) ? $options['override'] : false); } else { throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file); } } } } /** * Returns whether the file path is an absolute path. * * @param string $file A file path * * @return bool */ public function isAbsolutePath($file) { return '' !== (string) $file && (strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) || null !== parse_url($file, \PHP_URL_SCHEME) ); } /** * Creates a temporary file with support for custom stream wrappers. * * @param string $dir The directory where the temporary filename will be created * @param string $prefix The prefix of the generated temporary filename * Note: Windows uses only the first three characters of prefix * * @return string The new temporary filename (with path), or throw an exception on failure */ public function tempnam($dir, $prefix) { list($scheme, $hierarchy) = $this->getSchemeAndHierarchy($dir); // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem if (null === $scheme || 'file' === $scheme || 'gs' === $scheme) { $tmpFile = @tempnam($hierarchy, $prefix); // If tempnam failed or no scheme return the filename otherwise prepend the scheme if (false !== $tmpFile) { if (null !== $scheme && 'gs' !== $scheme) { return $scheme.'://'.$tmpFile; } return $tmpFile; } throw new IOException('A temporary file could not be created.'); } // Loop until we create a valid temp file or have reached 10 attempts for ($i = 0; $i < 10; ++$i) { // Create a unique filename $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true); // Use fopen instead of file_exists as some streams do not support stat // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability $handle = @fopen($tmpFile, 'x+'); // If unsuccessful restart the loop if (false === $handle) { continue; } // Close the file if it was successfully opened @fclose($handle); return $tmpFile; } throw new IOException('A temporary file could not be created.'); } /** * Atomically dumps content into a file. * * @param string $filename The file to be written to * @param string $content The data to write into the file * * @throws IOException if the file cannot be written to */ public function dumpFile($filename, $content) { $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } // Will create a temp file with 0600 access rights // when the filesystem supports chmod. $tmpFile = $this->tempnam($dir, basename($filename)); if (false === @file_put_contents($tmpFile, $content)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask()); $this->rename($tmpFile, $filename, true); } /** * Appends content to an existing file. * * @param string $filename The file to which to append content * @param string $content The content to append * * @throws IOException If the file is not writable */ public function appendToFile($filename, $content) { $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } if (false === @file_put_contents($filename, $content, \FILE_APPEND)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } } /** * @param mixed $files * * @return array|\Traversable */ private function toIterable($files) { return \is_array($files) || $files instanceof \Traversable ? $files : [$files]; } /** * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> [file, tmp]). * * @param string $filename The filename to be parsed * * @return array The filename scheme and hierarchical part */ private function getSchemeAndHierarchy($filename) { $components = explode('://', $filename, 2); return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]]; } /** * @param callable $func * * @return mixed */ private static function box($func) { self::$lastError = null; set_error_handler(__CLASS__.'::handleError'); try { $result = \call_user_func_array($func, \array_slice(\func_get_args(), 1)); restore_error_handler(); return $result; } catch (\Throwable $e) { } catch (\Exception $e) { } restore_error_handler(); throw $e; } /** * @internal */ public static function handleError($type, $msg) { self::$lastError = $msg; } }