42 lines
2.0 KiB
PHP
42 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\SupplyRecord;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use League\Flysystem\FilesystemException;
|
|
|
|
/** Read the bounded private original once and return exactly the bytes that were verified. */
|
|
final class ImportEvidence
|
|
{
|
|
public function bytes(SupplyRecord $record): string
|
|
{
|
|
$evidence = $record->snapshot['evidence'] ?? [];
|
|
$prefix = match ($record->kind) {
|
|
'import_cost_doc' => 'import-costs',
|
|
'import_document' => 'import-dossier',
|
|
'import_legal_source' => 'import-legal',
|
|
default => null,
|
|
};
|
|
$path = $evidence['path'] ?? null;
|
|
$expected = $prefix.'/'.$record->tenant_id.'/'.($record->kind === 'import_legal_source' ? '' : $record->purchase_order_id.'/').$record->record_key.'-'.$record->version;
|
|
abort_unless($prefix !== null && preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|
|
&& ($evidence['disk'] ?? null) === 'local' && is_string($path)
|
|
&& preg_match('/^'.preg_quote($expected, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
|
|
&& is_int($evidence['size'] ?? null) && $evidence['size'] > 0 && $evidence['size'] <= ($record->kind === 'import_legal_source' ? 67108864 : 2097152)
|
|
&& is_string($evidence['sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256']), 409,
|
|
'A referência do original privado está incompleta.');
|
|
$disk = Storage::disk('local');
|
|
try {
|
|
abort_unless($disk->exists($path) && $disk->size($path) === $evidence['size'], 409, 'O original está indisponível ou alterado.');
|
|
$bytes = $disk->get($path);
|
|
} catch (FilesystemException) {
|
|
abort(409, 'O original está indisponível ou alterado.');
|
|
}
|
|
abort_unless(is_string($bytes) && strlen($bytes) === $evidence['size'] && hash_equals($evidence['sha256'], hash('sha256', $bytes)), 409,
|
|
'O original está indisponível ou alterado.');
|
|
|
|
return $bytes;
|
|
}
|
|
}
|