chore: minor refactoring

This commit is contained in:
Phan An 2024-01-10 01:47:09 +01:00
parent 64b664addf
commit f22f1e0cba
13 changed files with 37 additions and 44 deletions

View file

@ -112,9 +112,9 @@ class InitCommand extends Command
private function loadEnvFile(): void
{
if (!file_exists(base_path('.env'))) {
if (!File::exists(base_path('.env'))) {
$this->components->task('Copying .env file', static function (): void {
copy(base_path('.env.example'), base_path('.env'));
File::copy(base_path('.env.example'), base_path('.env'));
});
} else {
$this->components->info('.env file exists -- skipping');

View file

@ -3,14 +3,10 @@
namespace App\Http\Requests\API;
use App\Rules\ImageData;
use Illuminate\Support\Str;
abstract class MediaImageUpdateRequest extends Request
{
public function authorize(): bool
{
return auth()->user()->is_admin;
}
/** @return array<mixed> */
public function rules(): array
{
@ -19,19 +15,19 @@ abstract class MediaImageUpdateRequest extends Request
];
}
public function authorize(): bool
{
return auth()->user()->is_admin;
}
public function getFileContentAsBinaryString(): string
{
[, $data] = explode(',', $this->{$this->getImageFieldName()});
return base64_decode($data, true);
return base64_decode(Str::after($this->{$this->getImageFieldName()}, ','), true);
}
public function getFileExtension(): string
{
[$type,] = explode(';', $this->{$this->getImageFieldName()});
[, $extension] = explode('/', $type);
return $extension;
return Str::after(Str::before($this->{$this->getImageFieldName()}, ';'), '/');
}
abstract protected function getImageFieldName(): string;

View file

@ -5,7 +5,7 @@ namespace App\Listeners;
use App\Events\MediaScanCompleted;
use App\Values\ScanResult;
use Illuminate\Support\Collection;
use Throwable;
use Illuminate\Support\Facades\File;
class WriteSyncLog
{
@ -18,10 +18,9 @@ class WriteSyncLog
? $event->results->map($transformer)
: $event->results->error()->map($transformer);
try {
attempt(static function () use ($messages): void {
$file = storage_path('logs/sync-' . now()->format('Ymd-His') . '.log');
file_put_contents($file, implode(PHP_EOL, $messages->toArray()));
} catch (Throwable) {
}
File::put($file, implode(PHP_EOL, $messages->toArray()));
});
}
}

View file

@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Laravel\Scout\Searchable;
/**
@ -93,7 +94,7 @@ class Album extends Model
protected function hasCover(): Attribute
{
return Attribute::get(fn (): bool => $this->cover_path
&& (app()->runningUnitTests() || file_exists($this->cover_path)));
&& (app()->runningUnitTests() || File::exists($this->cover_path)));
}
protected function coverPath(): Attribute

View file

@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Laravel\Scout\Searchable;
/**
@ -116,7 +117,7 @@ class Artist extends Model
return Attribute::get(function (): bool {
$image = Arr::get($this->attributes, 'image');
return $image && (app()->runningUnitTests() || file_exists(artist_image_path($image)));
return $image && (app()->runningUnitTests() || File::exists(artist_image_path($image)));
});
}

View file

@ -10,6 +10,7 @@ use App\Values\LicenseMeta;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
/**
* @property-read string $short_key
@ -32,12 +33,7 @@ class License extends Model
protected function shortKey(): Attribute
{
return Attribute::get(function (): string {
$parts = explode('-', $this->key);
$last = array_pop($parts);
return '****-' . $last;
});
return Attribute::get(fn (): string => '****-' . Str::afterLast($this->key, '-'));
}
protected function activatedAt(): Attribute

View file

@ -4,6 +4,7 @@ namespace App\Models;
use App\Facades\Download;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use RuntimeException;
use ZipArchive;
@ -31,9 +32,7 @@ class SongZipArchive
public function addSongs(Collection $songs): static
{
$songs->each(function (Song $song): void {
$this->addSong($song);
});
$songs->each(fn (Song $song) => $this->addSong($song));
return $this;
}
@ -71,10 +70,8 @@ class SongZipArchive
if (array_key_exists($name, $this->fileNames)) {
++$this->fileNames[$name];
$parts = explode('.', $name);
$ext = $parts[count($parts) - 1];
$parts[count($parts) - 1] = $this->fileNames[$name] . ".$ext";
$name = implode('.', $parts);
$extension = Str::afterLast($name, '.');
$name = Str::beforeLast($name, '.') . $this->fileNames[$name] . ".$extension";
} else {
$this->fileNames[$name] = 1;
}

View file

@ -3,6 +3,7 @@
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Webmozart\Assert\Assert;
@ -25,7 +26,7 @@ class RouteServiceProvider extends ServiceProvider
$apiVersion = self::getApiVersion();
$routeFile = $apiVersion ? base_path(sprintf('routes/%s.%s.php', $type, $apiVersion)) : null;
if ($routeFile && file_exists($routeFile)) {
if ($routeFile && File::exists($routeFile)) {
Route::group([], $routeFile);
}
}

View file

@ -3,15 +3,14 @@
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Str;
class ImageData implements Rule
{
public function passes($attribute, $value): bool
{
return attempt(static function () use ($value) {
[$header,] = explode(';', $value);
return (bool) preg_match('/data:image\/(jpe?g|png|webp|gif)/i', $header);
return (bool) preg_match('/data:image\/(jpe?g|png|webp|gif)/i', Str::before($value, ';'));
}, false) ?? false;
}

View file

@ -32,13 +32,15 @@ class DownloadService
// The song is hosted on Amazon S3.
// We download it back to our local server first.
$url = $this->s3Service->getSongPublicUrl($song);
// @todo decouple http from services
abort_unless((bool) $url, Response::HTTP_NOT_FOUND);
$localPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . basename($song->s3_params['key']);
// The following function requires allow_url_fopen to be ON.
// We're just assuming that to be the case here.
copy($url, $localPath);
File::copy($url, $localPath);
} else {
// The song is hosted locally. Make sure the file exists.
$localPath = $song->path;

View file

@ -3,6 +3,7 @@
namespace App\Services\Streamers;
use App\Models\Song;
use Illuminate\Support\Facades\File;
class Streamer
{
@ -20,7 +21,7 @@ class Streamer
{
$this->song = $song;
abort_unless($this->song->s3_params || file_exists($this->song->path), 404);
abort_unless($this->song->s3_params || File::exists($this->song->path), 404);
// Hard code the content type instead of relying on PHP's fileinfo()
// or even Symfony's MIMETypeGuesser, since they appear to be wrong sometimes.

View file

@ -69,7 +69,7 @@ class UploadService
// If there's no existing file with the same name in the upload directory, use the original name.
// Otherwise, prefix the original name with a hash.
// The whole point is to keep a readable file name when we can.
if (!file_exists($this->getUploadDirectory($uploader) . $file->getClientOriginalName())) {
if (!File::exists($this->getUploadDirectory($uploader) . $file->getClientOriginalName())) {
return $file->getClientOriginalName();
}

View file

@ -44,7 +44,7 @@ class StreamerFactoryTest extends TestCase
$streamerFactory = app(StreamerFactory::class);
/** @var Song $song */
$song = Song::factory()->make();
$song = Song::factory()->make(['path' => test_path('songs/blank.mp3')]);
self::assertInstanceOf(TranscodingStreamer::class, $streamerFactory->createStreamer($song));
}
@ -58,7 +58,7 @@ class StreamerFactoryTest extends TestCase
$streamerFactory = app(StreamerFactory::class);
/** @var Song $song */
$song = Song::factory()->make();
$song = Song::factory()->make(['path' => test_path('songs/blank.mp3')]);
self::assertInstanceOf(TranscodingStreamer::class, $streamerFactory->createStreamer($song, true));
}
@ -90,7 +90,7 @@ class StreamerFactoryTest extends TestCase
$streamerFactory = app(StreamerFactory::class);
/** @var Song $song */
$song = Song::factory()->make();
$song = Song::factory()->make(['path' => test_path('songs/blank.mp3')]);
self::assertInstanceOf($expectedClass, $streamerFactory->createStreamer($song));
}
}