diff --git a/CHANGELOG.md b/CHANGELOG.md index 736e694..f6582b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased (YYYY-MM-DD) + +### Features + +- `MediaType` now has a new method, `minimize( $isSupported )`. This method allows returning a consistent essence as a string, depending on what category the media type is and whether the user agent supports the media type. For example, if the media type is a JavaScript type, then it will consistently return `"text/javascript"`. + ## 2.0.0 (2023-12-11) ### Features diff --git a/src/MediaType.php b/src/MediaType.php index 7602bfa..cb2b65e 100644 --- a/src/MediaType.php +++ b/src/MediaType.php @@ -191,6 +191,33 @@ public function isJson(): bool { || $this->getEssence() === 'text/json'; } + /** + * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type + */ + public function minimize( bool $isSupported ): string { + if ( $this->isJavaScript() ) { + return 'text/javascript'; + } + + if ( $this->isJson() ) { + return 'application/json'; + } + + if ( $this->getEssence() === 'image/svg+xml' ) { + return 'image/svg+xml'; + } + + if ( $this->isXml() ) { + return 'application/xml'; + } + + if ( $isSupported ) { + return $this->getEssence(); + } + + return ""; + } + /** * @see https://mimesniff.spec.whatwg.org/#serializing-a-mime-type * @return string diff --git a/tests/MediaTypeTest.php b/tests/MediaTypeTest.php index fd55836..f7bc0f9 100644 --- a/tests/MediaTypeTest.php +++ b/tests/MediaTypeTest.php @@ -47,6 +47,22 @@ public function testGetParameterValue( ); } + /** + * @covers ::minimize + * @dataProvider provideMinimize + */ + public function testMinimize( + string $type, + string $subType, + string $expectedEssence, + bool $isSupported, + ) { + $this->assertEquals( + $expectedEssence, + ( new MediaType( $type, $subType, [] ) )->minimize( $isSupported ) + ); + } + /** * @covers ::__toString * @dataProvider provideStrings @@ -119,6 +135,59 @@ public function provideParameterValues() { ]; } + public function provideMinimize() { + return [ + [ + 'application', + 'ecmascript', + 'text/javascript', + true, + ], + [ + 'text', + 'json', + 'application/json', + true, + ], + [ + 'image', + 'svg+xml', + 'image/svg+xml', + true, + ], + [ + 'text', + 'xml', + 'application/xml', + true, + ], + [ + 'text', + 'plain', + 'text/plain', + true, + ], + [ + 'application', + 'xhtml+xml', + 'application/xml', + true, + ], + [ + 'application', + 'vnd.openxmlformats-officedocument.presentationml.presentation', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + true, + ], + [ + 'foo', + 'bar', + '', + false, + ] + ]; + } + public function provideStrings() { return [ [