koel/app/Providers/MacroProvider.php

43 lines
1.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Providers;
2024-01-03 17:02:18 +00:00
use Illuminate\Database\Eloquent\Builder;
2024-01-07 12:43:10 +00:00
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
2024-01-07 12:43:10 +00:00
use Illuminate\Support\Facades\File;
2024-01-03 17:02:18 +00:00
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
2024-01-07 12:43:10 +00:00
use Illuminate\Testing\TestResponse;
class MacroProvider extends ServiceProvider
{
public function boot(): void
{
Collection::macro('orderByArray', function (array $orderBy, string $key = 'id'): Collection {
/** @var Collection $this */
2024-01-10 23:11:45 +00:00
return $this->sortBy(static fn ($item) => array_search($item->$key, $orderBy, true))->values();
});
2024-01-03 17:02:18 +00:00
Builder::macro('logSql', function (): Builder {
/** @var Builder $this */
Log::info($this->toSql());
return $this;
});
2024-01-07 12:43:10 +00:00
if (app()->runningUnitTests()) {
UploadedFile::macro('fromFile', static function (string $path, ?string $name = null): UploadedFile {
return UploadedFile::fake()->createWithContent($name ?? basename($path), File::get($path));
});
TestResponse::macro('log', function (string $file = 'test-response.json'): TestResponse {
/** @var TestResponse $this */
File::put(storage_path('logs/' . $file), $this->getContent());
return $this;
});
}
}
}