Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active June 27, 2023 22:45
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 fjarrett/af3b213e361e3b298abeb7a4c027f078 to your computer and use it in GitHub Desktop.
Save fjarrett/af3b213e361e3b298abeb7a4c027f078 to your computer and use it in GitHub Desktop.
Just some useful helper functions for Laravel
<?php
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
if (! function_exists('add_query_arg')) {
/**
* Add query arg(s) to a URL.
*
* Examples:
* ```
* add_query_arg('foo=1&bar=2', ['baz' => 3]);
* add_query_arg('https://example.com', 'key');
* add_query_arg('https://example.com', ['key' => 'value']);
* ```
*
* @see https://developer.wordpress.org/reference/functions/add_query_arg/
*
* @param string $url
* @param string|array $args
* @param bool|int $sort
* @return string
*/
function add_query_arg(string $url, string|array $args, bool|int $sort = false): string
{
$args = (array) $args;
// Trim all keys/values.
$args = array_combine(
array_map('trim', array_keys($args)),
array_map('trim', $args)
);
// Do nothing.
if (! $args || $args === ['']) {
return $url;
}
$uuid = (string) Str::uuid();
// Special support for numerical index arrays.
if (! Arr::isAssoc($args)) {
$args = array_combine($args, array_fill(0, count($args), $uuid));
$query = Str::replace("={$uuid}", '', http_build_query($args));
}
if (is_url($url)) {
$parts = explode('?', $url);
} else {
$parts[1] = $url;
}
// Merge with existing query args, if present.
if (! empty($parts[1])) {
parse_str($parts[1], $query);
$args = array_merge($query, $args);
}
// Sort keys.
if ($sort) {
ksort($args, is_int($sort) ? $sort : SORT_REGULAR);
}
$query = Str::replace("={$uuid}", '', http_build_query($args));
return isset($parts[0]) ? sprintf('%s?%s', trailingslashit($parts[0]), $query) : $query;
}
}
if (! function_exists('remove_query_arg')) {
/**
* Remove query args from a URL.
*
* Examples:
* ```
* remove_query_arg('foo=1&bar=2&baz=3', 'foo');
* remove_query_arg('https://example.com?foo=1', 'foo');
* remove_query_arg('https://example.com?foo=1&bar=2', ['foo', 'bar']);
* remove_query_arg('https://example.com?foo=1&bar=2'); // Remove all query args.
* ```
*
* @see https://developer.wordpress.org/reference/functions/remove_query_arg/
*
* @param string $url
* @param string|array $args
* @param bool|int $sort
* @return string
*/
function remove_query_arg(string $url, string|array $args = null, bool|int $sort = false): string
{
$parts = explode('?', $url);
// Remove all query args.
if (is_null($args)) {
return $parts[0];
}
$args = (array) $args;
// Do nothing.
if (! $args || $args === ['']) {
return $url;
}
$queryString = $parts[1] ?? $parts[0];
// Do nothing.
if (is_url($queryString)) {
return $url;
}
parse_str($queryString, $query);
$args = Arr::except($query, $args);
// Do nothing.
if (! $args) {
return $parts[0];
}
// Sort keys.
if ($sort) {
ksort($args, is_int($sort) ? $sort : SORT_REGULAR);
}
return empty($parts[1]) ? http_build_query($args) : $parts[0].'?'.http_build_query($args);
}
}
if (! function_exists('carbon')) {
/**
* Create a new Carbon instance for the current time.
*
* @param \DateTimeInterface|string|null $time
* @param \DateTimeZone|string|null $tz
* @return \Illuminate\Support\Carbon
*/
function carbon($time = null, $tz = null)
{
return Carbon::parse($time, $tz);
}
}
if (! function_exists('empty_response')) {
/**
* Return an empty response (useful for CORS).
*
* @return \Illuminate\Http\Response
*/
function empty_response()
{
return response('', 204);
}
}
if (! function_exists('exception_to_array')) {
/**
* Convert exception info into array format, like you
* would expect $e->toArray() to work, plus a few
* handy options.
*/
function exception_to_array(Throwable $e, bool $withStackTrace = false, bool $withPrevious = false): array
{
$array = [
'class' => $e::class,
'code' => $e->getCode(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'message' => $e->getMessage(),
];
if ($withPrevious && $e->getPrevious()) {
$array['previous'] = exception_to_array($e->getPrevious(), $withStackTrace);
}
if ($withStackTrace) {
$array['trace'] = $e->getTrace();
}
return $array;
}
}
if (! function_exists('is_domain_name')) {
/**
* Determine whether a string is a valid domain name format.
*
* This is not perfect, but broad enough to weed out most invalid formats.
*
* 1. Hostname only (no scheme, port, path, query, or fragment)
* 2. 255 characters or less
* 3. Contains at least one period
* 4. Contains only alphanumeric characters, hyphens, and periods
* 5. Does not begin with a hyphen or period
* 6. Does not end with a number, hyphen, or period
*
* @param mixed $input
* @return bool
*/
function is_domain_name($input): bool
{
// foo.bar.com/path/?query=arg => foo.bar.com
$host = parse_url("//{$input}", PHP_URL_HOST);
return $input === $host && strlen($input) <= 255 && strpos($input, '.') > 0 && strpos($input, '-') !== 0 && preg_match('/^[a-z0-9\-\.]+(?<![0-9\-\.])$/', $input);
}
}
if (! function_exists('is_not_null')) {
/**
* Determine whether a value is null.
*
* Useful as a callback function for array_filter().
*
* @param mixed $input
* @return bool
*/
function is_not_null($input): bool
{
return ! is_null($input);
}
}
if (! function_exists('is_url')) {
/**
* Determine whether a string is a URL.
*
* @param mixed $input
* @return bool
*/
function is_url($input): bool
{
return (bool) preg_match('~^(https?:)?//.+~', $input);
}
}
if (! function_exists('prd') && config('app.debug')) {
/**
* Print human-readable data and die.
*
* @return never
*/
function prd(...$vars)
{
foreach ($vars as $var) {
print_r($var);
}
exit(1);
}
}
if (! function_exists('leadingslashit')) {
/**
* Ensure a string beings with exactly one slash.
*
* @param string $string
* @return string
*/
function leadingslashit(string $string): string
{
return '/'.unleadingslashit($string);
}
}
if (! function_exists('trailingslashit')) {
/**
* Ensure a string ends with exactly one slash.
*
* @param string $string
* @return string
*/
function trailingslashit(string $string): string
{
return untrailingslashit($string).'/';
}
}
if (! function_exists('unleadingslashit')) {
/**
* Ensure a string begins without any slashes.
*
* @param string $string
* @return string
*/
function unleadingslashit(string $string): string
{
return preg_replace('~^/+~', '', trim($string));
}
}
if (! function_exists('untrailingslashit')) {
/**
* Ensure a string ends without any slashes.
*
* @param string $string
* @return string
*/
function untrailingslashit(string $string): string
{
return preg_replace('~/+$~', '', trim($string));
}
}
if (! function_exists('vdd') && config('app.debug')) {
/**
* Var dump and die.
*
* @return never
*/
function vdd(...$vars)
{
foreach ($vars as $var) {
var_dump($var);
}
exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment