Skip to content

Commit 15d0f15

Browse files
committed
add compression order to the config (optional) #5
1 parent b8518ca commit 15d0f15

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

config/response-compression.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
*/
1515

1616
'enable' => env('RESPONSE_COMPRESSION_ENABLE', true),
17+
18+
'order' => explode(',', env('RESPONSE_COMPRESSION_ORDER', '')),
1719

1820
// Threshold size in bytes from where the compression will be applied to responses
1921
// @see https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#http-api-quotas

src/ResponseCompression.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,22 @@ protected function shouldCompressResponse($response): bool
7878
*/
7979
protected function shouldCompressUsing($request): ?array
8080
{
81+
$clientSupportedList = $request->getEncodings();
82+
8183
$supportedList = CompressionEncoding::listSupported();
8284

83-
$fromSupportedList = array_intersect($request->getEncodings(), array_keys($supportedList));
85+
/** @var string[] $preferenceList */
86+
$preferenceList = config('response-compression.order', []);
87+
88+
if (count($preferenceList) > 0) {
89+
$preferenceList = array_merge($preferenceList, array_diff(array_keys($supportedList), $preferenceList));
90+
}
91+
92+
$fromSupportedList = array_intersect(
93+
$preferenceList ?: $clientSupportedList,
94+
$clientSupportedList,
95+
array_keys($supportedList)
96+
);
8497

8598
if ($fromSupportedList[0] ?? false) {
8699
return [$fromSupportedList[0], $supportedList[$fromSupportedList[0]]];

tests/ResponseCompressionTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,24 @@ public function testClientGetResponseInThePreferredEncoding()
9191
json_encode(['content' => $this->heavyResponseContent])
9292
);
9393
}
94+
95+
public function testClientGetResponseInThePreferredAsFirstOrderConfiguredEncoding()
96+
{
97+
config(['response-compression.order' => ['br', 'gzip']]);
98+
99+
$response = $this->get('/heavy', ['Accept-Encoding' => implode(', ', [
100+
CompressionEncoding::Zstandard->value,
101+
CompressionEncoding::Gzip->value,
102+
CompressionEncoding::Brotli->value,
103+
])]);
104+
105+
$response->assertHeader('Content-Encoding', CompressionEncoding::Brotli->value);
106+
107+
$this->assertEquals(
108+
brotli_uncompress($response->getContent()),
109+
json_encode(['content' => $this->heavyResponseContent])
110+
);
111+
}
94112

95113
public function testClientGetResponseAskingAnUnrecognisedEncodingReceivesRawResponse()
96114
{

0 commit comments

Comments
 (0)