Browse Source

move uuid generation into a dedicated service

Olivier Massot 3 years ago
parent
commit
01266b220c
3 changed files with 41 additions and 4 deletions
  1. 2 4
      src/Service/Storage/FileStorage.php
  2. 24 0
      src/Service/Utils/Uuid.php
  3. 15 0
      tests/Service/Utils/UuidTest.php

+ 2 - 4
src/Service/Storage/FileStorage.php

@@ -11,14 +11,13 @@ use App\Enum\Core\FileStatusEnum;
 use App\Enum\Core\FileTypeEnum;
 use App\Repository\Access\AccessRepository;
 use App\Service\Utils\Path;
+use App\Service\Utils\Uuid;
 use DateTime;
 use Doctrine\ORM\EntityManagerInterface;
-use Exception;
 use Gaufrette\Filesystem;
 use JetBrains\PhpStorm\Pure;
 use Knp\Bundle\GaufretteBundle\FilesystemMap;
 use Mimey\MimeTypes;
-use Ramsey\Uuid\Uuid;
 use RuntimeException;
 
 /**
@@ -158,8 +157,7 @@ class FileStorage
                 $file->getType()
             );
 
-            /** @noinspection PhpUnhandledExceptionInspection */
-            $uid = date('Ymd_His') . '_' . substr(Uuid::uuid4()->toString(), 0, 5);
+            $uid = date('Ymd_His') . '_' . Uuid::uuid(5);
 
             $key = Path::join($prefix, $uid, $file->getName());
         } else {

+ 24 - 0
src/Service/Utils/Uuid.php

@@ -0,0 +1,24 @@
+<?php
+
+namespace App\Service\Utils;
+
+class Uuid
+{
+    /**
+     * Generate an UUID v4
+     *
+     * @var int $length Max length of the uuid
+     */
+    public static function uuid(int $length = 8): string
+    {
+        try {
+            $uuid = \Ramsey\Uuid\Uuid::uuid4()->toString();
+        } catch (\Exception $e) {
+            throw new \RuntimeException('An error occurred while generating the UUID', 0, $e);
+        }
+        if ($length !== null) {
+            return substr($uuid, 0, $length);
+        }
+        return $uuid;
+    }
+}

+ 15 - 0
tests/Service/Utils/UuidTest.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace App\Tests\Service\Utils;
+
+use App\Service\Utils\Uuid;
+use PHPUnit\Framework\TestCase;
+
+class UuidTest extends TestCase
+{
+    public function testUuid(): void
+    {
+        $this->assertMatchesRegularExpression('/\w{8}/', Uuid::uuid());
+        $this->assertMatchesRegularExpression('/\w{5}/', Uuid::uuid(5));
+    }
+}