Skip to content

Commit

Permalink
feat: support minimizing media types (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
neoncitylights authored Mar 27, 2024
1 parent 52320ec commit 40a67da
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
27 changes: 27 additions & 0 deletions src/MediaType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 69 additions & 0 deletions tests/MediaTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 [
[
Expand Down

0 comments on commit 40a67da

Please sign in to comment.