Use observers for model events

This commit is contained in:
Phan An 2018-08-29 14:58:46 +07:00
parent e17c2e29d8
commit ca2e737554
5 changed files with 50 additions and 22 deletions

View file

@ -109,7 +109,7 @@ class SyncMediaCommand extends Command
/**
* Log a song's sync status to console.
*/
public function logSyncStatusToConsole(string $path, int $result, string $reason = ''): void
public function logSyncStatusToConsole(string $path, int $result, ?string $reason = null): void
{
$name = basename($path);

View file

@ -328,7 +328,7 @@ class File
/**
* Get the last parsing error's text.
*/
public function getSyncError(): string
public function getSyncError(): ?string
{
return $this->syncError;
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Observers;
use App\Models\Album;
use Exception;
use Log;
class AlbumObserver
{
public function deleted(Album $album): void
{
if (!$album->has_cover) {
return;
}
try {
unlink($album->cover_path);
} catch (Exception $e) {
Log::error($e);
}
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Observers;
use App\Models\Song;
use App\Services\HelperService;
class SongObserver
{
private $helperService;
public function __construct(HelperService $helperService)
{
$this->helperService = $helperService;
}
public function creating(Song $song): void
{
$song->id = $this->helperService->getFileHash($song->path);
}
}

View file

@ -15,10 +15,9 @@ use App\Listeners\TidyLibrary;
use App\Listeners\UpdateLastfmNowPlaying;
use App\Models\Album;
use App\Models\Song;
use App\Services\HelperService;
use Exception;
use App\Observers\AlbumObserver;
use App\Observers\SongObserver;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Log;
class EventServiceProvider extends ServiceProvider
{
@ -57,22 +56,7 @@ class EventServiceProvider extends ServiceProvider
{
parent::boot();
// Generate a unique hash for a song from its path to be the ID
Song::creating(static function (Song $song): void {
/** @var HelperService $helperService */
$helperService = app(HelperService::class);
$song->id = $helperService->getFileHash($song->path);
});
// Remove the cover file if the album is deleted
Album::deleted(static function (Album $album): void {
if ($album->has_cover) {
try {
unlink($album->cover_path);
} catch (Exception $e) {
Log::error($e);
}
}
});
Song::observe(SongObserver::class);
Album::observe(AlbumObserver::class);
}
}