Skip to content

Instantly share code, notes, and snippets.

@asciito
Last active October 6, 2023 19:14
Show Gist options
  • Save asciito/1e0cb1d35bde32b3e2176aedfbd98f10 to your computer and use it in GitHub Desktop.
Save asciito/1e0cb1d35bde32b3e2176aedfbd98f10 to your computer and use it in GitHub Desktop.
PHP - Helper Functions
<?php
if (! function_exists('join_paths')) {
/**
* Join two or more paths together
*/
function join_paths(string ...$paths): string
{
$first = array_shift($paths);
$paths = array_filter(
array_map(fn (string $p) => trim($p, DIRECTORY_SEPARATOR), $paths)
);
return join(DIRECTORY_SEPARATOR, [rtrim($first, DIRECTORY_SEPARATOR), ...$paths]);
}
}
if (! function_exists('unzip')) {
/**
* Unzip the given filename
*
* This function will attempt to unzip the given zip file name into the given location, but if the location
* is not provided, we'll use the file directory.
*
* @param string $filename The file name of the ZIP file
* @param ?string $to The location where to extract the content
* @return void
*/
function unzip(string $filename, string $to = null): void
{
if (! extension_loaded('zip')) {
throw new \RuntimeException('Extension [ext-zip] not found');
}
$zip = new \ZipArchive();
$to ??= dirname($filename);
try {
$zip->open($filename);
$zip->extractTo($to);
} finally {
$zip->close();
}
}
}
@asciito
Copy link
Author

asciito commented Oct 6, 2023

These are the most common functions I use in my projects, and because I don't to create a package just for helper functions, I decided to create this Gist to keep track of them.

You're free to comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment