Example #1
0
 /**
  * copies a file or directory
  *
  * @param string $source
  * @param string $dest
  * @param bool $overwrite
  *
  * @throws FileException
  * @throws InvalidStateException
  */
 public static function copy($source, $dest, $overwrite = true)
 {
     if (stream_is_local($source) && !file_exists($source)) {
         throw new FileException("File or directory [{$source}] not found.");
     } else {
         if (!$overwrite && file_exists($dest)) {
             throw new InvalidStateException("File or directory [{$dest}] already exists.");
         } else {
             if (is_dir($source)) {
                 static::createDir($dest);
                 foreach (new \FilesystemIterator($dest) as $item) {
                     static::delete($item);
                 }
                 foreach (new \RecursiveIteratorIterator($iterator = new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) {
                     if ($item->isDir()) {
                         static::createDir($dest . '/' . $iterator->getSubPathName());
                     } else {
                         static::copy($item, $dest . '/' . $iterator->getSubPathName());
                     }
                 }
             }
         }
     }
     static::createDir(dirname($dest));
     if (!is_dir($source) && @stream_copy_to_stream(fopen($source, 'r'), fopen($dest, 'w')) === false) {
         throw new FileException("Unable to copy file '{$source}' to '{$dest}'.");
     }
 }