Classes List

Symfony\Component\Filesystem\Filesystem

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
 83 
 84 
 85 
 86 
 87 
 88 
 89 
 90 
 91 
 92 
 93 
 94 
 95 
 96 
 97 
 98 
 99 
 100 
 101 
 102 
 103 
 104 
 105 
 106 
 107 
 108 
 109 
 110 
 111 
 112 
 113 
 114 
 115 
 116 
 117 
 118 
 119 
 120 
 121 
 122 
 123 
 124 
 125 
 126 
 127 
 128 
 129 
 130 
 131 
 132 
 133 
 134 
 135 
 136 
 137 
 138 
 139 
 140 
 141 
 142 
 143 
 144 
 145 
 146 
 147 
 148 
 149 
 150 
 151 
 152 
 153 
 154 
 155 
 156 
 157 
 158 
 159 
 160 
 161 
 162 
 163 
 164 
 165 
 166 
 167 
 168 
 169 
 170 
 171 
 172 
 173 
 174 
 175 
 176 
 177 
 178 
 179 
 180 
 181 
 182 
 183 
 184 
 185 
 186 
 187 
 188 
 189 
 190 
 191 
 192 
 193 
 194 
 195 
 196 
 197 
 198 
 199 
 200 
 201 
 202 
 203 
 204 
 205 
 206 
 207 
 208 
 209 
 210 
 211 
 212 
 213 
 214 
 215 
 216 
 217 
 218 
 219 
 220 
 221 
 222 
 223 
 224 
 225 
 226 
 227 
 228 
 229 
 230 
 231 
 232 
 233 
 234 
 235 
 236 
 237 
 238 
 239 
 240 
 241 
 242 
 243 
 244 
 245 
 246 
 247 
 248 
 249 
 250 
 251 
 252 
 253 
 254 
 255 
 256 
 257 
 258 
 259 
 260 
 261 
 262 
 263 
 264 
 265 
 266 
 267 
 268 
 269 
 270 
 271 
 272 
 273 
 274 
 275 
 276 
 277 
 278 
 279 
 280 
 281 
 282 
 283 
 284 
 285 
 286 
 287 
 288 
 289 
 290 
 291 
 292 
 293 
 294 
 295 
 296 
 297 
 298 
 299 
 300 
 301 
 302 
 303 
 304 
 305 
 306 
 307 
 308 
 309 
 310 
 311 
 312 
 313 
 314 
 315 
 316 
 317 
 318 
 319 
 320 
 321 
 322 
 323 
 324 
 325 
 326 
 327 
 328 
 329 
 330 
 331 
 332 
 333 
 334 
 335 
 336 
 337 
 338 
 339 
 340 
 341 
 342 
 343 
 344 
 345 
 346 
 347 
 348 
 349 
 350 
 351 
 352 
 353 
 354 
 355 
 356 
 357 
 358 
 359 
 360 
 361 
 362 
 363 
 364 
 365 
 366 
 367 
 368 
 369 
 370 
 371 
 372 
 373 
 374 
 375 
 376 
 377 
 378 
 379 
 380 
 381 
 382 
 383 
 384 
 385 
 386 
 387 
 388 
 389 
 390 
 391 
 392 
 393 
 394 
 395 
 396 
 397 
 398 
 399 
 400 
 401 
 402 
 403 
 404 
 405 
 406 
 407 
 408 
 409 
 410 
 411 
 412 
 413 
 414 
 415 
 416 
 417 
 418 
 419 
 420 
 421 
 422 
 423 
 424 
 425 
 426 
 427 
 428 
 429 
 430 
 431 
 432 
 433 
 434 
 435 
 436 
 437 
 438 
 439 
 440 
 441 
 442 
 443 
 444 
 445 
 446 
 447 
 448 
 449 
 450 
 451 
 452 
 453 
 454 
 455 
 456 
 457 
 458 
 459 
 460 
 461 
 462 
 463 
 464 
 465 
 466 
 467 
 468 
 469 
 470 
 471 
 472 
 473 
 474 
 475 
 476 
 477 
 478 
 479 
 480 
 481 
 482 
 483 
 484 
 485 
 486 
 487 
 488 
 489 
 490 
 491 
 492 
 493 
 494 
 495 
 496 
 497 
 498 
 499 
 500 
 501 
 502 
 503 
 504 
 505 
 506 
 507 
 508 
 509 
 510 
 511 
 512 
 513 
 514 
 515 
 516 
 517 
 518 
 519 
 520 
 521 
 522 
 523 
 524 
 525 
 526 
 527 
 528 
 529 
 530 
 531 
 532 
 533 
 534 
 535 
 536 
 537 
 538 
 539 
 540 
 541 
 542 
 543 
 544 
 545 
 546 
 547 
 548 
 549 
 550 
 551 
 552 
 553 
 554 
 555 
 556 
 557 
 558 
 559 
 560 
 561 
 562 
 563 
 564 
 565 
 566 
 567 
 568 
 569 
 570 
 571 
 572 
 573 
 574 
 575 
 576 
 577 
 578 
 579 
 580 
 581 
 582 
 583 
 584 
 585 
 586 
 587 
 588 
 589 
 590 
 591 
 592 
 593 
 594 
 595 
 596 
 597 
 598 
 599 
 600 
 601 
 602 
 603 
 604 
 605 
 606 
 607 
 608 
 609 
 610 
 611 
 612 
 613 
 614 
 615 
 616 
 617 
 618 
 619 
 620 
 621 
 622 
 623 
 624 
 625 
 626 
 627 
 628 
 629 
 630 
 631 
 632 
 633 
 634 
 635 
 636 
 637 
 638 
 639 
 640 
 641 
 642 
 643 
 644 
 645 
 646 
 647 
 648 
 649 
 650 
 651 
 652 
 653 
 654 
 655 
 656 
 657 
 658 
 659 
 660 
 661 
 662 
 663 
 664 
 665 
 666 
 667 
 668 
 669 
 670 
 671 
 672 
 673 
 674 
 675 
 676 
 677 
 678 
 679 
 680 
 681 
 682 
 683 
 684 
 685 
 686 
 687 
 688 
 689 
 690 
 691 
 692 
 693 
 694 
 695 
 696 
 697 
 698 
 699 
 700 
 701 
 702 
 703 
 704 
 705 
 706 
 707 
 708 
 709 
 710 
 711 
 712 
 713 
 714 
 715 
 716 
 717 
 718 
 719 
 720 
 721 
 722 
 723 
 724 
 725 
 726 
 727 
 728 
 729 
 730 
 731 
 732 
 733 
 734 
 735 
 736 
 737 
 738 
 739 
 740 
 741 
 742 
 743 
 744 
 745 
 746 
 747 
 748 
 749 
 750 
 751 
 752 
 753 
 754 
 755 
 756 
 757 
 758 
 759 
 760 
 761 
 762 
 763 
 764 
 765 
 766 
 767 
 768 
 769 
 770 
 771 
<?php

/* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */


namespace Symfony\Component\Filesystem;

use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;

/** * Provides basic utility to manipulate the file system. * * @author Fabien Potencier <fabien@symfony.com> */
class Filesystem
{
    private static $lastError;

    /** * Copies a file. * * If the target file is older than the origin file, it's always overwritten. * If the target file is newer, it is overwritten only when the * $overwriteNewerFiles option is set to true. * * @param string $originFile The original filename * @param string $targetFile The target filename * @param bool $overwriteNewerFiles If true, target files newer than origin files are overwritten * * @throws FileNotFoundException When originFile doesn't exist * @throws IOException When copy fails */
    public function copy($originFile$targetFile$overwriteNewerFiles = false)
    {
        $originIsLocal = stream_is_local($originFile|| 0 === stripos($originFile'file://');
        if ($originIsLocal && !is_file($originFile)) {
            throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.'$originFile), 0null$originFile);
        }

        $this->mkdir(dirname($targetFile));

        $doCopy = true;
        if (!$overwriteNewerFiles && null === parse_url($originFilePHP_URL_HOST&& is_file($targetFile)) {
            $doCopy = filemtime($originFile) > filemtime($targetFile);
        }

        if ($doCopy) {
            // https://bugs.php.net/bug.php?id=64634
            if (false === $source = @fopen($originFile'r')) {
                throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.'$originFile$targetFile), 0null$originFile);
            }

            // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
            if (false === $target = @fopen($targetFile'w'nullstream_context_create(array('ftp' => array('overwrite' => true))))) {
                throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.'$originFile$targetFile), 0null$originFile);
            }

            $bytesCopied = stream_copy_to_stream($source$target);
            fclose($source);
            fclose($target);
            unset($source$target);

            if (!is_file($targetFile)) {
                throw new IOException(sprintf('Failed to copy "%s" to "%s".'$originFile$targetFile), 0null$originFile);
            }

            if ($originIsLocal) {
                // Like `cp`, preserve executable permission bits
                @chmod($targetFilefileperms($targetFile) | (fileperms($originFile) & 0111));

                if ($bytesCopied !== $bytesOrigin = filesize($originFile)) {
                    throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).'$originFile$targetFile$bytesCopied$bytesOrigin), 0null$originFile);
                }
            }
        }
    }

    /** * Creates a directory recursively. * * @param string|iterable $dirs The directory path * @param int $mode The directory mode * * @throws IOException On any directory creation failure */
    public function mkdir($dirs$mode = 0777)
    {
        foreach ($this->toIterable($dirsas $dir) {
            if (is_dir($dir)) {
                continue;
            }

            if (!self::box('mkdir'$dir$modetrue)) {
                if (!is_dir($dir)) {
                    // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
                    if (self::$lastError) {
                        throw new IOException(sprintf('Failed to create "%s": %s.'$dirself::$lastError), 0null$dir);
                    }
                    throw new IOException(sprintf('Failed to create "%s"'$dir), 0null$dir);
                }
            }
        }
    }

    /** * Checks the existence of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check * * @return bool true if the file exists, false otherwise */
    public function exists($files)
    {
        $maxPathLength = PHP_MAXPATHLEN - 2;

        foreach ($this->toIterable($filesas $file) {
            if (strlen($file) > $maxPathLength) {
                throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.'$maxPathLength), 0null$file);
            }

            if (!file_exists($file)) {
                return false;
            }
        }

        return true;
    }

    /** * Sets access and modification time of file. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create * @param int $time The touch time as a Unix timestamp * @param int $atime The access time as a Unix timestamp * * @throws IOException When touch fails */
    public function touch($files$time = null$atime = null)
    {
        foreach ($this->toIterable($filesas $file) {
            $touch = $time ? @touch($file$time$atime) : @touch($file);
            if (true !== $touch) {
                throw new IOException(sprintf('Failed to touch "%s".'$file), 0null$file);
            }
        }
    }

    /** * Removes files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove * * @throws IOException When removal fails */
    public function remove($files)
    {
        if ($files instanceof \Traversable) {
            $files = iterator_to_array($filesfalse);
        } elseif (!is_array($files)) {
            $files = array($files);
        }
        $files = array_reverse($files);
        foreach ($files as $file) {
            if (is_link($file)) {
                // See https://bugs.php.net/52176
                if (!(self::box('unlink'$file|| '\\' !== DIRECTORY_SEPARATOR || self::box('rmdir'$file)) && file_exists($file)) {
                    throw new IOException(sprintf('Failed to remove symlink "%s": %s.'$fileself::$lastError));
                }
            } elseif (is_dir($file)) {
                $this->remove(new \FilesystemIterator($file\FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS));

                if (!self::box('rmdir'$file&& file_exists($file)) {
                    throw new IOException(sprintf('Failed to remove directory "%s": %s.'$fileself::$lastError));
                }
            } elseif (!self::box('unlink'$file&& file_exists($file)) {
                throw new IOException(sprintf('Failed to remove file "%s": %s.'$fileself::$lastError));
            }
        }
    }

    /** * Change mode for an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode * @param int $mode The new mode (octal) * @param int $umask The mode mask (octal) * @param bool $recursive Whether change the mod recursively or not * * @throws IOException When the change fail */
    public function chmod($files$mode$umask = 0000$recursive = false)
    {
        foreach ($this->toIterable($filesas $file) {
            if (true !== @chmod($file$mode & ~$umask)) {
                throw new IOException(sprintf('Failed to chmod file "%s".'$file), 0null$file);
            }
            if ($recursive && is_dir($file&& !is_link($file)) {
                $this->chmod(new \FilesystemIterator($file), $mode$umasktrue);
            }
        }
    }

    /** * Change the owner of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner * @param string $user The new owner user name * @param bool $recursive Whether change the owner recursively or not * * @throws IOException When the change fail */
    public function chown($files$user$recursive = false)
    {
        foreach ($this->toIterable($filesas $file) {
            if ($recursive && is_dir($file&& !is_link($file)) {
                $this->chown(new \FilesystemIterator($file), $usertrue);
            }
            if (is_link($file&& function_exists('lchown')) {
                if (true !== @lchown($file$user)) {
                    throw new IOException(sprintf('Failed to chown file "%s".'$file), 0null$file);
                }
            } else {
                if (true !== @chown($file$user)) {
                    throw new IOException(sprintf('Failed to chown file "%s".'$file), 0null$file);
                }
            }
        }
    }

    /** * Change the group of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group * @param string $group The group name * @param bool $recursive Whether change the group recursively or not * * @throws IOException When the change fail */
    public function chgrp($files$group$recursive = false)
    {
        foreach ($this->toIterable($filesas $file) {
            if ($recursive && is_dir($file&& !is_link($file)) {
                $this->chgrp(new \FilesystemIterator($file), $grouptrue);
            }
            if (is_link($file&& function_exists('lchgrp')) {
                if (true !== @lchgrp($file$group|| (defined('HHVM_VERSION'&& !posix_getgrnam($group))) {
                    throw new IOException(sprintf('Failed to chgrp file "%s".'$file), 0null$file);
                }
            } else {
                if (true !== @chgrp($file$group)) {
                    throw new IOException(sprintf('Failed to chgrp file "%s".'$file), 0null$file);
                }
            }
        }
    }

    /** * Renames a file or a directory. * * @param string $origin The origin filename or directory * @param string $target The new filename or directory * @param bool $overwrite Whether to overwrite the target if it already exists * * @throws IOException When target file or directory already exists * @throws IOException When origin cannot be renamed */
    public function rename($origin$target$overwrite = false)
    {
        // we check that target does not exist
        if (!$overwrite && $this->isReadable($target)) {
            throw new IOException(sprintf('Cannot rename because the target "%s" already exists.'$target), 0null$target);
        }

        if (true !== @rename($origin$target)) {
            if (is_dir($origin)) {
                // See https://bugs.php.net/bug.php?id=54097 & http://php.net/manual/en/function.rename.php#113943
                $this->mirror($origin$targetnullarray('override' => $overwrite'delete' => $overwrite));
                $this->remove($origin);

                return;
            }
            throw new IOException(sprintf('Cannot rename "%s" to "%s".'$origin$target), 0null$target);
        }
    }

    /** * Tells whether a file exists and is readable. * * @param string $filename Path to the file * * @return bool * * @throws IOException When windows path is longer than 258 characters */
    private function isReadable($filename)
    {
        $maxPathLength = PHP_MAXPATHLEN - 2;

        if (strlen($filename) > $maxPathLength) {
            throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.'$maxPathLength), 0null$filename);
        }

        return is_readable($filename);
    }

    /** * Creates a symbolic link or copy a directory. * * @param string $originDir The origin directory path * @param string $targetDir The symbolic link name * @param bool $copyOnWindows Whether to copy files if on Windows * * @throws IOException When symlink fails */
    public function symlink($originDir$targetDir$copyOnWindows = false)
    {
        if ('\\' === DIRECTORY_SEPARATOR) {
            $originDir = strtr($originDir'/''\\');
            $targetDir = strtr($targetDir'/''\\');

            if ($copyOnWindows) {
                $this->mirror($originDir$targetDir);

                return;
            }
        }

        $this->mkdir(dirname($targetDir));

        if (is_link($targetDir)) {
            if (readlink($targetDir=== $originDir) {
                return;
            }
            $this->remove($targetDir);
        }

        if (!self::box('symlink'$originDir$targetDir)) {
            $this->linkException($originDir$targetDir'symbolic');
        }
    }

    /** * Creates a hard link, or several hard links to a file. * * @param string $originFile The original file * @param string|string[] $targetFiles The target file(s) * * @throws FileNotFoundException When original file is missing or not a file * @throws IOException When link fails, including if link already exists */
    public function hardlink($originFile$targetFiles)
    {
        if (!$this->exists($originFile)) {
            throw new FileNotFoundException(null0null$originFile);
        }

        if (!is_file($originFile)) {
            throw new FileNotFoundException(sprintf('Origin file "%s" is not a file'$originFile));
        }

        foreach ($this->toIterable($targetFilesas $targetFile) {
            if (is_file($targetFile)) {
                if (fileinode($originFile=== fileinode($targetFile)) {
                    continue;
                }
                $this->remove($targetFile);
            }

            if (!self::box('link'$originFile$targetFile)) {
                $this->linkException($originFile$targetFile'hard');
            }
        }
    }

    /** * @param string $origin * @param string $target * @param string $linkType Name of the link type, typically 'symbolic' or 'hard' */
    private function linkException($origin$target$linkType)
    {
        if (self::$lastError) {
            if ('\\' === DIRECTORY_SEPARATOR && false !== strpos(self::$lastError'error code(1314)')) {
                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), 0null$target);
            }
        }
        throw new IOException(sprintf('Failed to create %s link from "%s" to "%s".'$linkType$origin$target), 0null$target);
    }

    /** * Resolves links in paths. * * With $canonicalize = false (default) * - if $path does not exist or is not a link, returns null * - if $path is a link, returns the next direct target of the link without considering the existence of the target * * With $canonicalize = true * - if $path does not exist, returns null * - if $path exists, returns its absolute fully resolved final version * * @param string $path A filesystem path * @param bool $canonicalize Whether or not to return a canonicalized path * * @return string|null */
    public function readlink($path$canonicalize = false)
    {
        if (!$canonicalize && !is_link($path)) {
            return;
        }

        if ($canonicalize) {
            if (!$this->exists($path)) {
                return;
            }

            if ('\\' === DIRECTORY_SEPARATOR) {
                $path = readlink($path);
            }

            return realpath($path);
        }

        if ('\\' === DIRECTORY_SEPARATOR) {
            return realpath($path);
        }

        return readlink($path);
    }

    /** * Given an existing path, convert it to a path relative to a given starting path. * * @param string $endPath Absolute path of target * @param string $startPath Absolute path where traversal begins * * @return string Path of target relative to starting path */
    public function makePathRelative($endPath$startPath)
    {
        if (!$this->isAbsolutePath($endPath|| !$this->isAbsolutePath($startPath)) {
            @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);
        }

        // Normalize separators on Windows
        if ('\\' === DIRECTORY_SEPARATOR) {
            $endPath = str_replace('\\''/'$endPath);
            $startPath = str_replace('\\''/'$startPath);
        }

        $stripDriveLetter = function ($path) {
            if (strlen($path) > 2 && ':' === $path[1&& '/' === $path[2&& ctype_alpha($path[0])) {
                return substr($path2);
            }

            return $path;
        };

        $endPath = $stripDriveLetter($endPath);
        $startPath = $stripDriveLetter($startPath);

        // Split the paths into arrays
        $startPathArr = explode('/'trim($startPath'/'));
        $endPathArr = explode('/'trim($endPath'/'));

        $normalizePathArray = function ($pathSegments$absolute) {
            $result = array();

            foreach ($pathSegments as $segment) {
                if ('..' === $segment && ($absolute || count($result))) {
                    array_pop($result);
                } elseif ('.' !== $segment) {
                    $result[] = $segment;
                }
            }

            return $result;
        };

        $startPathArr = $normalizePathArray($startPathArrstatic::isAbsolutePath($startPath));
        $endPathArr = $normalizePathArray($endPathArrstatic::isAbsolutePath($endPath));

        // Find for which directory the common path stops
        $index = 0;
        while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index=== $endPathArr[$index]) {
            ++$index;
        }

        // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
        if (1 === count($startPathArr&& '' === $startPathArr[0]) {
            $depth = 0;
        } else {
            $depth = count($startPathArr) - $index;
        }

        // Repeated "../" for each level need to reach the common path
        $traverser = str_repeat('../'$depth);

        $endPathRemainder = implode('/'array_slice($endPathArr$index));

        // Construct $endPath from traversing to the common path, then to the remaining $endPath
        $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : '');

        return '' === $relativePath ? './' : $relativePath;
    }

    /** * Mirrors a directory to another. * * Copies files and directories from the origin directory into the target directory. By default: * * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option) * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option) * * @param string $originDir The origin directory * @param string $targetDir The target directory * @param \Traversable $iterator Iterator that filters which files and directories to copy * @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 = array())
    {
        $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$targetisset($options['override']) ? $options['override'] : false);
                } elseif (is_dir($file)) {
                    $this->mkdir($target);
                } else {
                    throw new IOException(sprintf('Unable to guess "%s" file type.'$file), 0null$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$targetisset($options['override']) ? $options['override'] : false);
                } else {
                    throw new IOException(sprintf('Unable to guess "%s" file type.'$file), 0null$file);
                }
            }
        }
    }

    /** * Returns whether the file path is an absolute path. * * @param string $file A file path * * @return bool */
    public function isAbsolutePath($file)
    {
        return strspn($file'/\\'01)
            || (strlen($file) > 3 && ctype_alpha($file[0])
                && ':' === $file[1]
                && strspn($file'/\\'21)
            )
            || null !== parse_url($filePHP_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), 0null$dir);
        }

        // Will create a temp file with 0600 access rights
        // when the filesystem supports chmod.
        $tmpFile = $this->tempnam($dirbasename($filename));

        if (false === @file_put_contents($tmpFile$content)) {
            throw new IOException(sprintf('Failed to write file "%s".'$filename), 0null$filename);
        }

        @chmod($tmpFilefile_exists($filename) ? fileperms($filename) : 0666 & ~umask());

        $this->rename($tmpFile$filenametrue);
    }

    /** * 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), 0null$dir);
        }

        if (false === @file_put_contents($filename$contentFILE_APPEND)) {
            throw new IOException(sprintf('Failed to write file "%s".'$filename), 0null$filename);
        }
    }

    /** * @param mixed $files * * @return array|\Traversable */
    private function toIterable($files)
    {
        return is_array($files|| $files instanceof \Traversable ? $files : array($files);
    }

    /** * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> array(file, tmp)). * * @param string $filename The filename to be parsed * * @return array The filename scheme and hierarchical part */
    private function getSchemeAndHierarchy($filename)
    {
        $components = explode('://'$filename2);

        return 2 === count($components) ? array($components[0], $components[1]) : array(null$components[0]);
    }

    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;
    }
}