Last active
October 6, 2023 19:14
-
-
Save asciito/1e0cb1d35bde32b3e2176aedfbd98f10 to your computer and use it in GitHub Desktop.
PHP - Helper Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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