radfusion/app/helpers.php
2025-01-10 18:56:27 +06:00

131 lines
3.1 KiB
PHP

<?php
use App\Models\Study;
use App\Models\User;
use App\Services\AuditTrail\ActivityLogger;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
if (! function_exists('_h')) {
function _h(int $key): string
{
return Hashids::encode($key);
}
}
if (! function_exists('unhash_it')) {
function unhash_it(string $hashid): int
{
return (int) Hashids::decode($hashid)[0];
}
}
if (! function_exists('audit')) {
function audit(): ActivityLogger
{
return app(ActivityLogger::class);
}
}
if (! function_exists('array_purge')) {
function array_purge(array $ary): array
{
return array_filter($ary, fn ($v) => filled($v));
}
}
if (! function_exists('array_trim_strings')) {
function array_trim_strings(array $ary): array
{
return array_filter($ary, function ($v) {
if (! is_string($v)) {
return $v;
}
$v = trim($v);
return blank($v) ? null : $v;
});
}
}
if (! function_exists('sync_agent_id')) {
function sync_agent_id(): int
{
return cache()->rememberForever('sync_agent_id',
fn () => User::where('username', '$$_pacs_sync_$$')->first()->id);
}
}
if (! function_exists('user_per_page')) {
function user_per_page(?int $user_id = null): int
{
$user_id = (int) ($user_id ?? auth()->id());
return settings()->get("user.{$user_id}.pagination.per_page", config('app.pagination.per_page'));
}
}
if (! function_exists('may')) {
function may(BackedEnum|iterable|string $perm): bool
{
if (auth()->user()->isAdmin()) {
return true;
}
return auth()->user()->can($perm);
}
}
if (! function_exists('human_filesize')) {
function human_filesize(int $bytes, $dec = 0): string
{
$size = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$factor = floor((strlen($bytes) - 1) / 3);
if ($factor == 0) {
$dec = 0;
}
return sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]);
}
}
if (! function_exists('chomp')) {
function chomp(string $s, int $len, int $right = 6): string
{
$length = strlen($s);
if ($length <= ($len + $right)) {
return $s;
}
$start = substr($s, 0, $len);
$end = substr($s, -$right);
return $start . '...' . $end;
}
}
if (! function_exists('thumb_url')) {
function thumb_url(Media $media): string
{
if ($media->mime_type === 'application/pdf') {
return asset(Study::FALLBACK_IMAGE);
}
return $media->getUrl('tn') ?? asset(Study::FALLBACK_IMAGE);
}
}
if (! function_exists('me')) {
/**
* Gets the user. If no user is provided, it will return the authenticated user.
*/
function me(User|int|null $user = null): User
{
if (is_int($user) && $user > 0) {
return User::find($user);
} elseif ($user instanceof User) {
return $user;
} else {
return auth()->user();
}
}
}