Files
plugi/plugi-core/src/Repositories/UploadRepository.php
T
deepDiverPaul e1767dcd2c media-library search, MIME-type and virtual-folder filters, persisted
folder and alt-text editing, and safe defaults for legacy uploads
2026-11-30 16:51:14 +01:00

86 lines
2.2 KiB
PHP

<?php
namespace Plugi\Repositories;
use Plugi\UploadedFile;
class UploadRepository extends BaseRepository
{
/**
* The uploads database table.
*
* @var string
*/
protected $table = 'uploads';
/**
* The class that represents each uploaded file.
*
* @var string
*/
protected $class = UploadedFile::class;
/**
* Create a new uploaded file.
*
* @param array $data
* @return bool|object
*/
public function create(array $data)
{
$fields = ['public_id', 'original_file', 'mime_type', 'server_file'];
foreach ($fields as $field) {
if (! isset($data[$field]) || ! is_string($data[$field])) {
return false;
}
}
return parent::create([
'public_id' => $data['public_id'],
'original_file' => $data['original_file'],
'mime_type' => $data['mime_type'],
'server_file' => $data['server_file'],
'alt_text' => '',
'folder' => '',
]);
}
/**
* Update supported media-library metadata for the upload with the given public ID.
*/
public function updateMetadata(string $publicId, array $metadata): bool
{
$fieldLimits = [
'alt_text' => 1000,
'folder' => 255,
];
if ($publicId === '' || strlen($publicId) > 50 || empty($metadata)) {
return false;
}
$validatedMetadata = [];
foreach ($metadata as $field => $value) {
if (! isset($fieldLimits[$field]) || ! is_string($value) || ! $this->isValidMetadataValue($value, $fieldLimits[$field])) {
return false;
}
$validatedMetadata[$field] = $field === 'folder' ? trim($value) : $value;
}
$uploads = $this->findWhere('public_id', $publicId);
if (empty($uploads)) {
return false;
}
return $this->update($uploads[0], $validatedMetadata);
}
private function isValidMetadataValue(string $value, int $maxLength): bool
{
if (strlen($value) > $maxLength * 4 || ! preg_match('//u', $value)) {
return false;
}
return preg_match_all('/./us', $value) <= $maxLength;
}
}