/** * Copy a random file from the source directory to the target directory and returns the filename/fullpath * * @param string $sourceDirectory * The directory to look for random file taking * @param string $targetDirectory * @param boolean $fullPath * Whether to have the full path or just the filename * @return string */ public static function file($sourceDirectory = '/tmp', $targetDirectory = '/tmp', $fullPath = true) { if (!is_dir($sourceDirectory)) { throw new \InvalidArgumentException(sprintf('Source directory %s does not exist or is not a directory.', $sourceDirectory)); } if (!is_dir($targetDirectory)) { throw new \InvalidArgumentException(sprintf('Target directory %s does not exist or is not a directory.', $targetDirectory)); } if ($sourceDirectory == $targetDirectory) { throw new \InvalidArgumentException('Source and target directories must differ.'); } // Drop . and .. and reset array keys $files = array_filter(array_values(array_diff(scandir($sourceDirectory), array('.', '..'))), function ($file) use($sourceDirectory) { return is_file($sourceDirectory . DIRECTORY_SEPARATOR . $file) && is_readable($sourceDirectory . DIRECTORY_SEPARATOR . $file); }); if (empty($files)) { throw new \InvalidArgumentException(sprintf('Source directory %s is empty.', $sourceDirectory)); } $sourceFullPath = $sourceDirectory . DIRECTORY_SEPARATOR . static::randomElement($files); $destinationFile = Uuid::uuid() . '.' . pathinfo($sourceFullPath, PATHINFO_EXTENSION); $destinationFullPath = $targetDirectory . DIRECTORY_SEPARATOR . $destinationFile; if (false === copy($sourceFullPath, $destinationFullPath)) { return false; } return $fullPath ? $destinationFullPath : $destinationFile; }