Переглянути джерело

Refactor les méthodes iniSizeToBytes et bytesToHuman pour gérer les tailles de fichiers avec des valeurs par défaut et des unités optionnelles.

stany.ferer 2 місяців тому
батько
коміт
6762aad778
1 змінених файлів з 32 додано та 7 видалено
  1. 32 7
      core/class/fichier.class.php

+ 32 - 7
core/class/fichier.class.php

@@ -252,12 +252,41 @@ class fichier
         }
     }
 
-    static public function iniSizeToBytes()
+    static public function iniSizeToBytes($upload_max_filesize = null)
     {
-        $upload_max_filesize = ini_get('upload_max_filesize');
+        $upload_max_filesize = $upload_max_filesize ?? ini_get('upload_max_filesize');
         $val = trim($upload_max_filesize);
+
+        // Parse a numeric value and an optional unit (K, M, G) with optional trailing "B"
+        if (preg_match('/^(\d+(?:\.\d+)?)\s*([kKmMgG])?(?:b|B)?$/', $val, $matches)) {
+            $num = (float)$matches[1];
+            $unit = isset($matches[2]) ? strtolower($matches[2]) : '';
+
+            // Fall-through intentional to multiply by 1024 per unit level
+            switch ($unit) {
+                case 'g':
+                    $num *= 1024;
+                case 'm':
+                    $num *= 1024;
+                case 'k':
+                    $num *= 1024;
+            }
+
+            return (int)$num;
+        }
+
+        return (int)(float)$val;
+    }
+
+    static public function bytesToHuman($size = null)
+    {
+        // Récupère la valeur si non fournie
+        $val = $size ?? ini_get('post_max_size');
+        $val = trim($val);
         $last = strtolower($val[strlen($val) - 1]);
         $num = (float)$val;
+
+        // Convertit les suffixes en octets (fall-through voulu)
         switch ($last) {
             case 'g':
                 $num *= 1024;
@@ -266,12 +295,8 @@ class fichier
             case 'k':
                 $num *= 1024;
         }
-        return (int)$num;
-    }
 
-    static public function bytesToHuman()
-    {
-        $bytes = ini_get('post_max_size');
+        $bytes = (float)$num;
         $units = ['B', 'KB', 'MB', 'GB', 'TB'];
         $i = 0;
         while ($bytes >= 1024 && $i < count($units) - 1) {