86 lines
3.2 KiB
PHP
86 lines
3.2 KiB
PHP
<?php
|
|
class SiteUploadHandler {
|
|
private $uploadDir;
|
|
private $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
|
|
private $maxFileSize = 2097152; // 2MB
|
|
|
|
public function __construct() {
|
|
$this->uploadDir = __DIR__ . '/../assets/images/site/';
|
|
$this->ensureUploadDirectory();
|
|
}
|
|
|
|
public function handleLogoUpload($file) {
|
|
try {
|
|
if ($file['error'] !== UPLOAD_ERR_OK) {
|
|
throw new Exception($this->getUploadErrorMessage($file['error']));
|
|
}
|
|
|
|
// Vérifier le type MIME
|
|
$finfo = new finfo(FILEINFO_MIME_TYPE);
|
|
$mimeType = $finfo->file($file['tmp_name']);
|
|
if (!in_array($mimeType, $this->allowedTypes)) {
|
|
throw new Exception('Type de fichier non autorisé. Types acceptés : JPG, PNG, GIF, SVG');
|
|
}
|
|
|
|
// Vérifier la taille
|
|
if ($file['size'] > $this->maxFileSize) {
|
|
throw new Exception('Fichier trop volumineux. Taille maximum : 2MB');
|
|
}
|
|
|
|
// Générer le nom de fichier
|
|
$extension = $this->getExtensionFromMimeType($mimeType);
|
|
$filename = 'logo.' . $extension;
|
|
$targetPath = $this->uploadDir . $filename;
|
|
|
|
// Supprimer l'ancien logo s'il existe
|
|
$this->removeOldLogo();
|
|
|
|
// Déplacer le fichier
|
|
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
|
|
throw new Exception('Erreur lors du déplacement du fichier uploadé');
|
|
}
|
|
|
|
return 'assets/images/site/' . $filename;
|
|
|
|
} catch (Exception $e) {
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
private function ensureUploadDirectory() {
|
|
if (!file_exists($this->uploadDir)) {
|
|
if (!mkdir($this->uploadDir, 0755, true)) {
|
|
throw new Exception('Impossible de créer le dossier d\'upload');
|
|
}
|
|
}
|
|
}
|
|
|
|
private function removeOldLogo() {
|
|
foreach (glob($this->uploadDir . 'logo.*') as $file) {
|
|
unlink($file);
|
|
}
|
|
}
|
|
|
|
private function getExtensionFromMimeType($mimeType) {
|
|
$map = [
|
|
'image/jpeg' => 'jpg',
|
|
'image/png' => 'png',
|
|
'image/gif' => 'gif',
|
|
'image/svg+xml' => 'svg'
|
|
];
|
|
return $map[$mimeType] ?? 'png';
|
|
}
|
|
|
|
private function getUploadErrorMessage($error) {
|
|
$errors = [
|
|
UPLOAD_ERR_INI_SIZE => 'Le fichier dépasse la taille maximale autorisée par PHP',
|
|
UPLOAD_ERR_FORM_SIZE => 'Le fichier dépasse la taille maximale autorisée par le formulaire',
|
|
UPLOAD_ERR_PARTIAL => 'Le fichier n\'a été que partiellement uploadé',
|
|
UPLOAD_ERR_NO_FILE => 'Aucun fichier n\'a été uploadé',
|
|
UPLOAD_ERR_NO_TMP_DIR => 'Dossier temporaire manquant',
|
|
UPLOAD_ERR_CANT_WRITE => 'Échec de l\'écriture du fichier sur le disque',
|
|
UPLOAD_ERR_EXTENSION => 'Une extension PHP a arrêté l\'upload'
|
|
];
|
|
return $errors[$error] ?? 'Erreur inconnue lors de l\'upload';
|
|
}
|
|
} |