diff --git a/src/Format.php b/src/Format.php index 1d28296c..843e4d19 100644 --- a/src/Format.php +++ b/src/Format.php @@ -64,6 +64,21 @@ enum Format return $format; } + /** + * Try to create format from given identifier and return null on failure + * + * @param string|Format|MediaType|FileExtension $identifier + * @return Format|null + */ + public static function tryCreate(string|self|MediaType|FileExtension $identifier): self|null + { + try { + return self::create($identifier); + } catch (NotSupportedException) { + return null; + } + } + /** * Return the possible media (MIME) types for the current format * diff --git a/tests/Unit/FormatTest.php b/tests/Unit/FormatTest.php index afc70cc6..0d7d0f1b 100644 --- a/tests/Unit/FormatTest.php +++ b/tests/Unit/FormatTest.php @@ -38,6 +38,18 @@ final class FormatTest extends BaseTestCase Format::create('foo'); } + public function testTryCreate(): void + { + $this->assertEquals(Format::JPEG, Format::tryCreate(Format::JPEG)); + $this->assertEquals(Format::JPEG, Format::tryCreate('jpg')); + $this->assertEquals(Format::JPEG, Format::tryCreate('jpeg')); + $this->assertEquals(Format::JPEG, Format::tryCreate('image/jpeg')); + $this->assertEquals(Format::GIF, Format::tryCreate('image/gif')); + $this->assertEquals(Format::PNG, Format::tryCreate(FileExtension::PNG)); + $this->assertEquals(Format::WEBP, Format::tryCreate(MediaType::IMAGE_WEBP)); + $this->assertNull(Format::tryCreate('no-format')); + } + public function testMediaTypesJpeg(): void { $format = Format::JPEG;