71 lines
1.7 KiB
PHP
71 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class DisplayQrCodeService
|
|
{
|
|
/**
|
|
* @return array{path: string, url: string}|null
|
|
*/
|
|
public function generateForUrl(?string $url): ?array
|
|
{
|
|
$normalizedUrl = $this->normalizeUrl($url);
|
|
|
|
if ($normalizedUrl === '') {
|
|
return null;
|
|
}
|
|
|
|
$path = 'display-qr-codes/'.sha1($normalizedUrl).'.png';
|
|
$disk = Storage::disk('public');
|
|
|
|
if (! $disk->exists($path)) {
|
|
try {
|
|
$response = Http::timeout(10)
|
|
->retry(2, 300)
|
|
->get($this->remoteQrUrl($normalizedUrl));
|
|
|
|
if (! $response->successful() || $response->body() === '') {
|
|
return null;
|
|
}
|
|
|
|
$disk->put($path, $response->body());
|
|
} catch (\Throwable) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
return [
|
|
'path' => $path,
|
|
'url' => asset('storage/'.$path),
|
|
];
|
|
}
|
|
|
|
public function normalizeUrl(?string $url): string
|
|
{
|
|
$url = trim((string) $url);
|
|
|
|
if ($url === '') {
|
|
return '';
|
|
}
|
|
|
|
if (str_starts_with($url, 'http://') || str_starts_with($url, 'https://')) {
|
|
return $url;
|
|
}
|
|
|
|
return 'https://'.$url;
|
|
}
|
|
|
|
private function remoteQrUrl(string $url): string
|
|
{
|
|
return 'https://api.qrserver.com/v1/create-qr-code/?'.http_build_query([
|
|
'size' => '300x300',
|
|
'margin' => '8',
|
|
'color' => '000000',
|
|
'bgcolor' => 'ffffff',
|
|
'data' => $url,
|
|
]);
|
|
}
|
|
}
|