48 lines
1.6 KiB
PHP
48 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Documents;
|
|
|
|
use App\Models\Asset;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class DocumentDownloadService {
|
|
protected array $mimes = [
|
|
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'pdf' => 'application/pdf',
|
|
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
|
];
|
|
|
|
|
|
public function __construct() {
|
|
}
|
|
|
|
|
|
public function download($url, $dir = null, $filename = null): ?Asset {
|
|
$info = pathinfo($url);
|
|
if (!empty($this->mimes[$info['extension'] ?? null])) {
|
|
$path = "public/documents";
|
|
$filename = $filename ? "{$filename}.{$info['extension']}" : $info['basename'];
|
|
$path = $dir ? "{$path}/{$dir}/{$filename}" : "{$path}/{$filename}";
|
|
$asset = Asset::query()->where(['path' => $path])->first();
|
|
if (!$asset && Storage::put($path, Http::get($url)->body())) $asset = $this->makeAsset($path);
|
|
elseif ($asset) var_dump($asset->path);
|
|
}
|
|
return $asset ?? null;
|
|
}
|
|
public function makeAsset($path, $name = null) {
|
|
$info = pathinfo($path);
|
|
return Asset::create([
|
|
'type' => 'document',
|
|
'path' => $path,
|
|
'mime' => $this->mimes[$info['extension']] ?? null,
|
|
'name' => $name ?? $info['basename'],
|
|
'filename' => $info['basename'],
|
|
'extension' => $info['extension'],
|
|
'user_id' => ($user = Auth::user()) ? $user->id : null
|
|
]);
|
|
}
|
|
|
|
|
|
} |