Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ S3_SECRET_KEY=minio_local
S3_PATH_STYLE_ENDPOINT=1

# Compression
IMAGE_COMPRESSION=75
AVIF_COMPRESSION=85
JPEG_COMPRESSION=75
WEBP_COMPRESSION=75
AVIF_ENABLED=true
WEBP_ENABLED=true

# HTTP fetch
FETCH_TIMEOUT=10
Expand Down
22 changes: 13 additions & 9 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,19 @@ Tests mirror `src/` structure under `tests/`. The base `TestCase` class provides

The app is configured entirely via environment variables (see `.env`):

| Variable | Purpose |
|---------------------------------------------------------------------------|---------------------------------------------------|
| `ALLOWED_DOMAINS` | Comma-separated list of authorized source domains |
| `DOMAINS_ALIASES` | Domain aliases, e.g. `example.com/secret=ex` |
| `STORAGE_DRIVER` | `local` or `s3` |
| `S3_BUCKET`, `S3_ENDPOINT`, `S3_REGION`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` | S3 config |
| `IMAGE_COMPRESSION` | JPEG/WebP quality (0–100) |
| `CACHE_TTL` | HTTP cache TTL in seconds (default: 1 year) |
| `LOG_LEVEL` | PSR-3 log level |
| Variable | Purpose |
|---------------------------------------------------------------------------|--------------------------------------------------------------------------------|
| `ALLOWED_DOMAINS` | Comma-separated list of authorized source domains |
| `DOMAINS_ALIASES` | Domain aliases, e.g. `example.com/secret=ex` |
| `STORAGE_DRIVER` | `local` or `s3` |
| `S3_BUCKET`, `S3_ENDPOINT`, `S3_REGION`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` | S3 config |
| `AVIF_COMPRESSION` | AVIF quality (0–100), default 85 |
| `JPEG_COMPRESSION` | JPEG quality (0–100), default 75 |
| `WEBP_COMPRESSION` | WebP quality (0–100), default 75 |
| `AVIF_ENABLED` | `true`/`false` — enable AVIF output when browser supports it (default: `true`) |
| `WEBP_ENABLED` | `true`/`false` — enable WebP output when browser supports it (default: `true`) |
| `CACHE_TTL` | HTTP cache TTL in seconds (default: 1 year) |
| `LOG_LEVEL` | PSR-3 log level |

In production, secrets are pulled from AWS SSM Parameter Store (see `serverless.yml`). Local dev uses MinIO (S3-compatible) on port 9001.

Expand Down
17 changes: 14 additions & 3 deletions serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ params:
default:
storage_driver: s3
cache_ttl: 31536000
avif_enabled: 'true'
webp_enabled: 'true'

prod:
app_debug: 0
Expand All @@ -15,7 +17,10 @@ params:
s3_region: ${ssm:/cdn-php/prod/s3-region}
s3_access_key: ${ssm:/cdn-php/prod/s3-access-key}
s3_secret_key: ${ssm:/cdn-php/prod/s3-secret-key}
image_compression: ${ssm:/cdn-php/prod/image-compression}
avif_enabled: ${ssm:/cdn-php/prod/avif-enabled}
webp_enabled: ${ssm:/cdn-php/prod/webp-enabled}
jpeg_compression: ${ssm:/cdn-php/prod/jpeg-compression}
webp_compression: ${ssm:/cdn-php/prod/webp-compression}
avif_compression: ${ssm:/cdn-php/prod/avif-compression}
force_token: ${ssm:/cdn-php/prod/force-token}

Expand All @@ -29,7 +34,10 @@ params:
s3_region: ${ssm:/cdn-php/dev/s3-region}
s3_access_key: ${ssm:/cdn-php/dev/s3-access-key}
s3_secret_key: ${ssm:/cdn-php/dev/s3-secret-key}
image_compression: ${ssm:/cdn-php/dev/image-compression}
avif_enabled: ${ssm:/cdn-php/dev/avif-enabled}
webp_enabled: ${ssm:/cdn-php/dev/webp-enabled}
jpeg_compression: ${ssm:/cdn-php/dev/jpeg-compression}
webp_compression: ${ssm:/cdn-php/dev/webp-compression}
avif_compression: ${ssm:/cdn-php/dev/avif-compression}
force_token: ${ssm:/cdn-php/dev/force-token}

Expand Down Expand Up @@ -81,8 +89,11 @@ functions:
S3_SECRET_KEY: ${param:s3_secret_key}
LOG_STREAM: php://stderr
LOG_LEVEL: ${param:log_level}
IMAGE_COMPRESSION: ${param:image_compression}
AVIF_COMPRESSION: ${param:avif_compression}
AVIF_ENABLED: ${param:avif_enabled}
WEBP_ENABLED: ${param:webp_enabled}
JPEG_COMPRESSION: ${param:jpeg_compression}
WEBP_COMPRESSION: ${param:webp_compression}

package:
patterns:
Expand Down
15 changes: 9 additions & 6 deletions src/Cdn.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public function __construct(
private readonly string $forceToken = '',
private readonly ?UrlSigner $urlSigner = null,
private readonly string $appVersion = '',
private readonly bool $avifEnabled = true,
private readonly bool $webpEnabled = true,
) {
}

Expand Down Expand Up @@ -212,13 +214,14 @@ private function detectOutputFormat(Request $request, bool $isImage): array
return [false, false];
}

$supportAvif = $this->supportsAvif($request);
$outputAvif = true === $this->avifEnabled ? $this->supportsAvif($request) : false;
$outputWebp = true === $this->webpEnabled ? $this->supportsWebp($request) : false;

if (true === $supportAvif) {
return [true, false];
}

return [false, $this->supportsWebp($request)];
return match (true) {
$outputAvif => [true, false],
$outputWebp => [false, true],
default => [false, false],
};
}

private function supportsAvif(Request $request): bool
Expand Down
25 changes: 19 additions & 6 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ final class Container
private const string KEY_STORAGE_DRIVER = 'storage_driver';
private const string KEY_STORAGE_PATH = 'storage_path';
private const string KEY_CACHE_TTL = 'cache_ttl';
private const string KEY_IMAGE_COMPRESSION = 'image_compression';
private const string KEY_AVIF_COMPRESSION = 'avif_compression';
private const string KEY_JPEG_COMPRESSION = 'jpeg_compression';
private const string KEY_WEBP_COMPRESSION = 'webp_compression';
private const string KEY_AVIF_ENABLED = 'avif_enabled';
private const string KEY_WEBP_ENABLED = 'webp_enabled';
private const string KEY_FETCH_TIMEOUT = 'fetch_timeout';
private const string KEY_FETCH_MAX_SIZE = 'fetch_max_size';
private const string KEY_FETCH_ALLOW_REDIRECTS = 'fetch_allow_redirects';
Expand Down Expand Up @@ -76,6 +79,8 @@ public function boot(): void
$this->get(self::KEY_FORCE_TOKEN),
$urlSigner,
$this->getEnv('APP_VERSION') ?? '',
$this->get(self::KEY_AVIF_ENABLED),
$this->get(self::KEY_WEBP_ENABLED),
),
);
}
Expand Down Expand Up @@ -235,20 +240,28 @@ private function bootCache(): void

private function bootImageProcessor(): void
{
$this->add(self::KEY_IMAGE_COMPRESSION, (int) $this->getEnv('IMAGE_COMPRESSION'));
$avifCompressionEnv = $this->getEnv('AVIF_COMPRESSION');
$this->add(self::KEY_AVIF_COMPRESSION, (int) ($this->getEnv('AVIF_COMPRESSION') ?? '85'));
$this->add(self::KEY_JPEG_COMPRESSION, (int) ($this->getEnv('JPEG_COMPRESSION') ?? '75'));
$this->add(self::KEY_WEBP_COMPRESSION, (int) ($this->getEnv('WEBP_COMPRESSION') ?? '75'));

$this->add(
self::KEY_AVIF_ENABLED,
filter_var($this->getEnv('AVIF_ENABLED') ?? 'true', FILTER_VALIDATE_BOOLEAN),
);
$this->add(
self::KEY_AVIF_COMPRESSION,
null !== $avifCompressionEnv ? (int) $avifCompressionEnv : $this->get(self::KEY_IMAGE_COMPRESSION),
self::KEY_WEBP_ENABLED,
filter_var($this->getEnv('WEBP_ENABLED') ?? 'true', FILTER_VALIDATE_BOOLEAN),
);

$this->add(
ImageProcessor::class,
new ImageProcessor(
$this->get(FilesystemAdapter::class),
$this->get(UrlFilesystemAdapter::class),
$this->get(LoggerInterface::class),
$this->get(self::KEY_IMAGE_COMPRESSION),
$this->get(self::KEY_JPEG_COMPRESSION),
$this->get(self::KEY_AVIF_COMPRESSION),
$this->get(self::KEY_WEBP_COMPRESSION),
),
);
}
Expand Down
22 changes: 12 additions & 10 deletions src/Processor/ImageProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ public function __construct(
private readonly FilesystemAdapter $adapter,
private readonly UrlFilesystemAdapter $urlFilesystemAdapter,
private readonly LoggerInterface $logger,
private readonly int $imageCompression,
private readonly int $jpegCompression,
private readonly int $avifCompression,
private readonly int $webpCompression,
) {
}

Expand Down Expand Up @@ -60,17 +61,18 @@ public function process(
],
);

$quality = true === $outputAvif ? $this->avifCompression : $this->imageCompression;
$quality = match (true) {
$outputAvif => $this->avifCompression,
$outputWebp => $this->webpCompression,
default => $this->jpegCompression,
};
$glideParams = [...$params->toArray(), 'q' => $quality];

if (true === $outputAvif) {
$glideParams['fm'] = 'avif';
} elseif (true === $outputWebp) {
$glideParams['fm'] = 'webp';
} elseif (true === \in_array($extension, ['avif', 'heic'], true)) {
// Non-web-safe formats: always transcode to JPEG as browser-safe fallback
$glideParams['fm'] = 'jpg';
}
$glideParams['fm'] = match (true) {
$outputAvif => 'avif',
$outputWebp => 'webp',
default => 'jpg', // Always JPEG in fallback
};

$this->logger->info(
'Process image: {path} with params {params}',
Expand Down
51 changes: 51 additions & 0 deletions tests/Cdn/CdnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,42 @@ public function skipsSignatureCheckWhenSecretIsEmpty(): void
static::assertSame(Response::HTTP_OK, $response->getStatusCode());
}

#[Test]
public function avifDisabledIgnoresAvifAcceptHeader(): void
{
$request = Request::create('http://mycdn.com/' . static::TEST_BASE_URI);
$request->headers->set('Accept', 'image/avif,*/*');

$response = $this->getCdnWithFormats(avifEnabled: false, webpEnabled: true)->handleRequest($request);

static::assertSame(Response::HTTP_OK, $response->getStatusCode());
static::assertSame('image/jpeg', $response->headers->get('Content-Type'));
}

#[Test]
public function webpDisabledIgnoresWebpAcceptHeader(): void
{
$request = Request::create('http://mycdn.com/' . static::TEST_BASE_URI);
$request->headers->set('Accept', 'image/webp,*/*');

$response = $this->getCdnWithFormats(avifEnabled: true, webpEnabled: false)->handleRequest($request);

static::assertSame(Response::HTTP_OK, $response->getStatusCode());
static::assertSame('image/jpeg', $response->headers->get('Content-Type'));
}

#[Test]
public function avifDisabledFallsBackToWebpWhenBrowserSupportsBoths(): void
{
$request = Request::create('http://mycdn.com/' . static::TEST_BASE_URI);
$request->headers->set('Accept', 'image/avif,image/webp,*/*');

$response = $this->getCdnWithFormats(avifEnabled: false, webpEnabled: true)->handleRequest($request);

static::assertSame(Response::HTTP_OK, $response->getStatusCode());
static::assertSame('image/webp', $response->headers->get('Content-Type'));
}

private function getCdnWithSignatureSecret(string $secret): Cdn
{
return new Cdn(
Expand All @@ -516,4 +552,19 @@ private function getCdnWithSignatureSecret(string $secret): Cdn
new UrlSigner($secret),
);
}

private function getCdnWithFormats(bool $avifEnabled, bool $webpEnabled): Cdn
{
return new Cdn(
$this->getContainer('allowed_domains'),
$this->getContainer('domains_aliases'),
$this->getContainer(Storage::class),
$this->getContainer(ImageProcessor::class),
$this->getContainer(StaticAssetProcessor::class),
$this->getContainer(Cache::class),
$this->getContainer(LoggerInterface::class),
avifEnabled: $avifEnabled,
webpEnabled: $webpEnabled,
);
}
}
2 changes: 1 addition & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class TestCase extends BaseTestCase
protected const string TEST_FILENAME_MD5 = '18867d45576d8283d6fabb82406789c8.jpg';
protected const string TEST_EXTENSION = 'jpg';
protected const string TEST_ORIGINAL_PATH = 'example.com/original/' . self::TEST_FILENAME_MD5;
protected const string TEST_CACHE_PATH = './cache/image.jpg/4be3b730cab4c047525c594c7560cbf0';
protected const string TEST_CACHE_PATH = './cache/image.jpg/d2013cfdfb10b251425adf4149a28e50';
protected const string TEST_GIF_FILENAME = 'image.gif';
protected const string TEST_GIF_CACHE_PATH = './cache/image.gif';
protected const string TEST_GIF_WEBP_CACHE_PATH = './cache/image.webp';
Expand Down
Loading