QR_code_generator/app/Services/Registries/RegistryImportService.php

63 lines
2.1 KiB
PHP

<?php
namespace App\Services\Registries;
use App\Models\Asset;
use App\Models\Registries\Registry;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use PHPHtmlParser\Dom;
class RegistryImportService {
protected Registry $registry;
protected string $url;
protected Dom $dom;
protected array $mimes = [
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'pdf' => 'application/pdf',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
public function __construct(Registry $registry, string $url) {
$this->registry = $registry;
$this->url = $url;
$this->dom = new Dom;
$this->dom->loadFromUrl($url);
}
public function download($url, $dir = null, $filename = null): ?Asset {
$urlInfo = parse_url($url);
if (empty($urlInfo['host'])) {
$url = str_replace('//', '/', "faufcc.ru/{$url}");
$url = "https://{$url}";
}
$info = pathinfo($url);
if ($info['extension'] ?? null) {
$path = "public/documents/registries";
$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
]);
}
}