Skip to content

Instantly share code, notes, and snippets.

@abdoulmouctard
Created December 28, 2021 08:57
Show Gist options
  • Save abdoulmouctard/f1716583f412aa62f460b4b251f5ee40 to your computer and use it in GitHub Desktop.
Save abdoulmouctard/f1716583f412aa62f460b4b251f5ee40 to your computer and use it in GitHub Desktop.
Laravel Helpers
<?php
use App\Client\ClientApplicationInterface;
// use App\Exceptions\Fail;
use App\Models\Contracts\Notifiable;
use App\Models\PersonalAccessToken;
use App\Notifications\Notification;
use Carbon\Carbon;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Notification as NotificationFacade;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
if (!function_exists('replace_params')) {
/**
* @param array $config
* @param string $open
* @param string|null $close
* @return array
*/
function replace_params(array $config, string $open = '__', ?string $close = null): array
{
$close ??= $open;
$config = collect(Arr::dot($config))->map(function ($value) use (&$open, &$close) {
if (!is_string($value)) {
return $value;
}
$matchs = [];
if (preg_match("#($open)(.*?)($close)#", $value, $matchs)) {
try {
$value = Str::replaceArray("$open$matchs[2]$close", Arr::wrap(param($matchs[2], $matchs[2])), $value);
} catch (Throwable) {
}
}
return $value;
})->toArray();
return Arr::unDot($config, []);
}
}
if (!function_exists('seed_of')) {
/**
* @param string $file
* @param null|string $environment
* @return null|array
*/
function seed_of(string $file, ?string $environment = null): ?array
{
$file = Str::finish($file, ".json");
$seeds = Cache::remember(substr(sha1(base_path("seeds/$file")), 0, 10), 300, function () use ($file) {
return json_decode(File::get(base_path("seeds/$file")), true);
});
return data_get($seeds, $environment);
}
}
if (!function_exists('rules_of')) {
/**
* @param string $file
* @param string $action
* @return array
*/
function rules_of(string $file, string $action): array
{
$file = Str::finish($file, '.json');
$path = app_path("Rules" . DS . "config" . DS . $file);
$config = Cache::remember(substr(sha1($path), 0, 10), 300, function () use ($file, $path) {
return json_decode(file_exists($path) ? File::get($path) : "", true);
});
$global = data_get($config, "global", []);
$customs = data_get($config, "customs.$action", []);
$config = [];
foreach ($customs as $key => $rules) {
$config[$key] = array_unique(array_merge($global[$key] ?? [], Arr::wrap($rules)));
}
return collect($config)->filter(function ($rules, $key) {
$result = true;
foreach ($rules as $rule) {
if (str_contains($rule, "required_with_param")) {
$param = Str::after($rule, ":");
$result &= (bool)param($param, false);
} elseif (str_contains($rule, "allow_when_param_is_not:")) {
$data = Str::after($rule, "allow_when_param_is_not:");
$param = explode(":", $data)[0] ?: "";
$values = explode(":", $data)[1] ?: "";
$result &= !in_array(param($param), explode(",", $values));
} elseif (str_contains($rule, "allow_when_param_is:")) {
$data = Str::after($rule, "allow_when_param_is:");
$param = explode(":", $data)[0] ?: "";
$values = explode(":", $data)[1] ?: "";
$result &= in_array(param($param), explode(",", $values));
}
}
return $result;
})->toArray();
}
}
if (!function_exists('translate_rules')) {
/**
* @param string $attribute
* @param string|array $rules
* @param string $ruleSeparator
* @return array
*/
function translate_rules(string $attribute, string|array $rules = [], string $ruleSeparator = '|'): array
{
if (is_string($rules)) {
$rules = explode($ruleSeparator, $rules);
}
return collect($rules)->map(function ($rule) use (&$attribute) {
$before = Str::before($rule, ':');
$after = Str::after($rule, ':');
return __('validation.' . $before, ['attribute' => $attribute, $before => $after]);
})->toArray();
}
}
if (!function_exists('current_user')) {
/**
* @return User
*/
function current_user(): User
{
return request()->user();
}
}
if (!function_exists('notify')) {
/**
* @param User|array|string $notifiable
* @param Notification $notification
*/
function notify(Notifiable|array|string $notifiable, Notification $notification): void
{
if (param("mails.active")) {
$notifiable = $notifiable instanceof Notifiable ? $notifiable->getEmail() : $notifiable;
NotificationFacade::route('mail', Arr::wrap($notifiable))->notify($notification);
}
}
}
if (!function_exists("http_status")) {
/**
* @return array
*/
function http_status(): array
{
$reflection = new ReflectionClass(new Response());
$constants = $reflection->getConstants(ReflectionClassConstant::IS_PUBLIC);
$errors = [];
foreach ($constants as $value => $key) {
$errors['' . $key . ''] = $value;
}
return $errors;
}
}
if (!function_exists('is_one_of')) {
/**
* @param mixed $objectOrClass
* @param array $classes
* @return bool
*/
function is_one_of(mixed $objectOrClass, array $classes = []): bool
{
foreach ($classes as $class) {
if (is_a($objectOrClass, $class, true)) {
return true;
}
}
return false;
}
}
if (!function_exists('fail_if')) {
/**
* @param mixed $predicate
* @param string $code
* @param int $statusCode
* @param string|null $message
* @param array $data
* @param array $headers
* @return bool
*/
function fail_if(mixed $predicate, string $code, int $statusCode = Response::HTTP_BAD_REQUEST, ?string $message = null, array $data = [], array $headers = []): bool
{
if ($predicate) {
// Fail::with($code, $statusCode, $message, $data, $headers);
}
return !!$predicate;
}
}
if (!function_exists('fail_unless')) {
/**
* @param mixed $predicate
* @param string $code
* @param int $statusCode
* @param string|null $message
* @param array $data
* @param array $headers
* @return bool
*/
function fail_unless(mixed $predicate, string $code, int $statusCode = Response::HTTP_BAD_REQUEST, ?string $message = null, array $data = [], array $headers = []): bool
{
return fail_if(!$predicate, $code, $statusCode, $message, $data, $headers);
}
}
if (!function_exists('lines_count')) {
/**
* @param string $file
* @return int
*/
function lines_count(string $file): int
{
$file = new SplFileObject($file, 'r');
$file->setFlags(SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
$file->seek(PHP_INT_MAX);
return $file->key() + 1;
}
}
if (!function_exists('data_pull')) {
/**
* @param array $data
* @param array|string $keys
* @param null|mixed $default
* @return mixed
*/
function data_pull(mixed &$data, array|string $keys, mixed $default = null): mixed
{
$result = null;
$keys = Arr::wrap($keys);
foreach ($keys as $key) {
$result = data_get($data, $key, $result);
}
foreach ($keys as $key) {
Arr::pull($data, $key);
Arr::pull($data, Str::before($key, "."));
}
return $result ?? $default;
}
}
if (!function_exists("merge_files")) {
/**
* Merge JSON Files
* @param string $baseFile
* @param array $files
* @param bool $associative
* @return mixed
*/
function merge_files(string $baseFile, array $files = [], bool $associative = true): mixed
{
$keyBase = substr(sha1($baseFile), 0, 10);
$baseConfig = Cache::remember($keyBase, 300, function () use ($baseFile, $associative) {
return file_exists($baseFile) ? json_decode(File::get($baseFile), $associative) : [];
});
collect($files)->each(function ($file) use (&$associative, &$baseConfig) {
$key = substr(sha1($file), 0, 10);
$data = Cache::remember($key, config('cache.lifetime'), function () use ($file, $associative) {
return (file_exists($file) ? json_decode(File::get($file), $associative) : []) ?? [];
});
$config = Arr::dot($data);
foreach ($config as $key => $value) {
data_set($baseConfig, $key, $value);
}
});
return $baseConfig ?? [];
}
}
if (!function_exists("choose")) {
/**
* @param mixed $predicate
* @param mixed|null $valueIfTrue
* @param null $valueIfFalse
* @return mixed
*/
function choose(mixed $predicate, mixed $valueIfTrue = null, $valueIfFalse = null): mixed
{
return !!$predicate ? $valueIfTrue : $valueIfFalse;
}
}
if (!function_exists("catcher")) {
/**
* @param Closure $callback
* @return mixed
*/
function catcher(Closure $callback): void
{
try {
$callback();
} catch (Throwable) {
}
}
}
if (!function_exists("base_url")) {
/**
* @param string $url
* @return string
*/
function base_url(string $url = ""): string
{
return Str::finish(env("APP_URL", ""), "/") . $url;
}
}
if (!function_exists("utf8_converter")) {
/**
* Convert character with accent to unaccented
*
* @param string $value
* @return string
*/
function utf8_converter(string $value): string
{
$normalizeCharset = [
'Š' => 'S', 'š' => 's', 'Ð' => 'Dj', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U',
'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e',
'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u',
'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y', 'ƒ' => 'f', 'a' => 'a', 'î' => 'i', 'â' => 'a', '?' => 's', '?' => 't', 'A' => 'A', 'Î' => 'I', 'Â' => 'A',
'?' => 'S', '?' => 'T', '.' => ' ', ',' => '', '(' => '', ')' => '', '&' => ' et ', '~' => '', '"' => '', '#' => '', '{' => '', '[' => '', '|' => '',
'`' => "'", '\\' => '', '^' => '', '@' => '', ']' => '', '}' => '', '=' => '', '+' => '', '¨' => '', '£' => '', '$' => '', '¤' => '', '%' => '',
'*' => '', '<' => '', '>' => '', ',' => '', ';' => '', ':' => '', '/' => '', '!' => '', '§' => '', '°' => ''
];
return strtr($value, $normalizeCharset);
}
}
if (!function_exists("image_to_base64")) {
/**
* @param string $path
* @param bool $url
* @return string
*/
function image_to_base64(string $path = "", bool $url = false): string
{
$path = base_path("public/$path");
if ("svg" === ($type = pathinfo($path, PATHINFO_EXTENSION))) {
$type .= "+xml";
}
return "data:image/$type;base64," . base64_encode(file_get_contents($path));
}
}
if (!function_exists("sql_query_without_bindings")) {
/**
* @param QueryBuilder|EloquentBuilder|HasMany $builder
* @return string
*/
function sql_query_without_bindings(QueryBuilder|EloquentBuilder|HasMany $builder): string
{
return vsprintf(str_replace('?', '%s', $builder->toSql()), collect($builder->getBindings())->map(function ($binding) {
return is_numeric($binding) ? $binding : "'{$binding}'";
})->toArray());
}
}
if (!function_exists("route_is")) {
/**
* @param string $route
* @return bool
*/
function route_is(string $route): bool
{
return request()->routeIs($route);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment