Skip to content

Instantly share code, notes, and snippets.

@DarkVss
Last active June 14, 2023 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarkVss/5ede7ccf5fef2a04e0c767d5e8329a5f to your computer and use it in GitHub Desktop.
Save DarkVss/5ede7ccf5fef2a04e0c767d5e8329a5f to your computer and use it in GitHub Desktop.
Add recursive adding directory to standard PharData class
<?php
namespace PharData;
class Custom extends \PharData {
/**
* Add directory and sub-file/directory
*
* @param string $directory
* @param ?string $excludingPath string what path in beginning must by ignore on adding to archive. If pass NULL - set as the parent directory of
* copy directory
*
* @return void
*
* @throws \PharException
*/
function addDirectoryRecursive(string $directory, ?string $excludingPath = null) : void {
if ($excludingPath !== null && str_starts_with($directory, $excludingPath) === false) {
throw new \PharException(message: "Directory path must be start with excluding path", code: 400);
}
if ($excludingPath === null) {
$excludingPath = dirname($directory);
}
for ($handle = opendir($directory); false !== ($entry = readdir($handle));) {
if ($entry == "." || $entry == "..") {
continue;
}
$file = $directory . DIRECTORY_SEPARATOR . $entry;
if (is_dir($file) === true) {
$this->addDirectoryRecursive($file, $excludingPath ?? dirname($directory));
} else {
$this->addFile($file, str_replace($excludingPath, '', $file));
}
}
closedir($handle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment