From 48c47ac40c78fefb41e0733ab3a8a672a882535c Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Tue, 24 Nov 2026 17:15:06 +0100 Subject: [PATCH] feat: normalised media and a CDN for the uploads (0.5) - NormalizedMedia: a file in one shape whatever its kind (url, sizes, srcset, alt, caption, dimensions, duration, focal point from pollora/media) - GET /wp-json/headless/v1/media/{id}; headless_featured_media field of posts, computed only when _fields names it (OptInField) - MediaUrls and MediaCdn: the uploads served from a CDN in the address, srcset and content, not in the administration - A file attached to a draft is visible to those who can see the draft --- CHANGELOG.md | 1 + README.md | 16 ++ api-surface.json | 3 +- config/headless.php | 9 + src/Domain/Media/FocalPoint.php | 37 ++++ src/Domain/Media/MediaCatalog.php | 16 ++ src/Domain/Media/MediaKind.php | 26 +++ src/Domain/Media/MediaUrls.php | 54 +++++ src/Infrastructure/Config/Settings.php | 23 +++ src/Infrastructure/WordPress/Bootstrap.php | 9 + src/Infrastructure/WordPress/MediaCdn.php | 49 +++++ src/Infrastructure/WordPress/MediaRoutes.php | 73 +++++++ .../WordPress/NormalizedMedia.php | 109 ++++++++++ src/Infrastructure/WordPress/OptInField.php | 24 +++ tests/Integration/MediaTest.php | 193 ++++++++++++++++++ tests/Unit/Domain/MediaTest.php | 77 +++++++ .../MediaInfrastructureTest.php | 128 ++++++++++++ tests/Unit/Infrastructure/ModulesTest.php | 4 +- 18 files changed, 848 insertions(+), 3 deletions(-) create mode 100644 src/Domain/Media/FocalPoint.php create mode 100644 src/Domain/Media/MediaCatalog.php create mode 100644 src/Domain/Media/MediaKind.php create mode 100644 src/Domain/Media/MediaUrls.php create mode 100644 src/Infrastructure/WordPress/MediaCdn.php create mode 100644 src/Infrastructure/WordPress/MediaRoutes.php create mode 100644 src/Infrastructure/WordPress/NormalizedMedia.php create mode 100644 src/Infrastructure/WordPress/OptInField.php create mode 100644 tests/Integration/MediaTest.php create mode 100644 tests/Unit/Domain/MediaTest.php create mode 100644 tests/Unit/Infrastructure/MediaInfrastructureTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f3c4ae..b773fdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,4 +23,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - Revalidation: signed notifications of changes (posts, terms, menus, site options, files) to the front end, merged, off the request (Action Scheduler or WP-Cron), with retries; `wp headless revalidate ping`. - Site manifest: `GET /wp-json/headless/v1/site` (site, languages, menus as trees, locations, front page, content types and taxonomies). - Redirects: rules managed with `wp headless redirect`, the old slugs of renamed posts, `GET /wp-json/headless/v1/redirects` and `/redirects/resolve`. +- Media: `GET /wp-json/headless/v1/media/{id}` (one shape for every kind, with the focal point of `pollora/media`), the `headless_featured_media` field, and `media.cdn_url` to serve the uploads from a CDN. - mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer. diff --git a/README.md b/README.md index 302c91a..93f761d 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo | Revalidation | When a post is published, updated, unpublished or deleted, or a term, a menu, a site option or a file changes, the front end is told: one signed POST, merged with the other changes of the last seconds, sent off the request, tried again if it fails. See [Revalidation](#telling-your-front-end-what-changed). | | Site manifest | `GET /wp-json/headless/v1/site`: the site and its languages, the menus as trees with front-end paths, the menu locations, the front page and the content types with their REST routes, in one public, cacheable answer. | | Redirects | The redirects of the site for a front end: the ones you manage (`wp headless redirect add /old/ /new/`, patterns, 410 for a page that is gone) and the old addresses WordPress remembers for renamed posts, at `GET /wp-json/headless/v1/redirects` (every rule) and `/redirects/resolve?path=/old/` (one path). | +| Media | A file of the library in one shape whatever its kind (`GET /wp-json/headless/v1/media/{id}`: url, sizes, srcset, alt, caption, the focal point set with `pollora/media`), the featured image of a post in full without a second request, and the uploads served from a CDN. | | URL mapper | `UrlMapper::toFront()` turns a URL of the WordPress site into the URL of the same page on the front end. It is the one place every URL the package hands out goes through. | Nothing changes on the public site until you set the front-end URL: a site that is not told where its front end lives is never locked. @@ -172,6 +173,21 @@ const { redirect } = await (await fetch(`https://cms.example.com/wp-json/headles An exact rule wins over a pattern, and the rules you write win over the old slugs. A rule is checked when it is made (a path, a destination that is a path or an absolute http(s) URL, a status of 301, 302, 307, 308 or 410, a pattern that compiles, no loop). Changing the rules is announced to the front end with the `option:headless_redirects` tag. +## Media + +```js +const image = await (await fetch('https://cms.example.com/wp-json/headless/v1/media/42')).json(); +// { id, kind: 'image', mime, url, title, alt, caption, description, width, height, filesize, duration, +// focal_point: { x: 0.25, y: 0.75 } | null, sizes: { medium: { url, width, height }, …, full: {…} }, srcset, modified_gmt } + +// The featured image of a post, in the same request (a field that costs something is computed only when you name it) +const post = await (await fetch('https://cms.example.com/wp-json/wp/v2/posts/12?_fields=id,title,headless_featured_media')).json(); +``` + +`focal_point` is the part of the image to keep whatever the crop (use it as `object-position: 25% 75%`); it comes from [`pollora/media`](https://github.com/Pollora/media) and is `null` without it. A file attached to a draft answers 404 to a visitor. + +To serve the uploads from a CDN or an image proxy, set `media.cdn_url` (or `HEADLESS_MEDIA_CDN_URL` on Pollora): `https://cdn.example.com` replaces `https://cms.example.com/wp-content/uploads` in the address of every file, in `srcset` and in the HTML of the content. The administration keeps the WordPress addresses, so that an editor sees a file they have just uploaded. + ## Roadmap `0.1` core · `0.2` CORS, REST security and speed, URL mapping, Polylang and WPML, API tokens · `0.3` content preview · `0.4` revalidation webhooks (this release) · `0.5` site manifest, media, blocks as JSON, redirects · `0.6` SEO (Yoast, Rank Math, AIOSEO, SEOPress, The SEO Framework) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract. diff --git a/api-surface.json b/api-surface.json index f68545a..e459fcf 100644 --- a/api-surface.json +++ b/api-surface.json @@ -3,6 +3,7 @@ "surface": { "config:headless": "unreadable without the application", "hook:pollora/headless/flush": "hook", - "hook:pollora/headless/retry": "hook" + "hook:pollora/headless/retry": "hook", + "hook:pollora/media/focal_point": "filter" } } diff --git a/config/headless.php b/config/headless.php index 8fda248..45b5901 100644 --- a/config/headless.php +++ b/config/headless.php @@ -129,4 +129,13 @@ 'enabled' => true, 'old_slugs' => true, ], + + // GET /wp-json/headless/v1/media/{id}: a file in one shape (url, sizes, srcset, alt, focal point from pollora/media…), and the + // field `headless_featured_media` of a post when _fields asks for it. `cdn_url` serves the uploads from a CDN or an image proxy: + // https://cdn.example.com replaces https://cms.example.com/wp-content/uploads in the addresses of files, in srcset and in the content + // (not in the administration). The routes are active once a front-end URL is set; the CDN once its address is. + 'media' => [ + 'enabled' => true, + 'cdn_url' => env('HEADLESS_MEDIA_CDN_URL', ''), + ], ]; diff --git a/src/Domain/Media/FocalPoint.php b/src/Domain/Media/FocalPoint.php new file mode 100644 index 0000000..e19a017 --- /dev/null +++ b/src/Domain/Media/FocalPoint.php @@ -0,0 +1,37 @@ + 0.25, 'y' => 0.75]`); anything else is no point. */ + public static function tryFrom(mixed $stored): ?self + { + if (! is_array($stored) || ! is_numeric($stored['x'] ?? null) || ! is_numeric($stored['y'] ?? null)) { + return null; + } + + $x = (float) $stored['x']; + $y = (float) $stored['y']; + + return $x >= 0.0 && $x <= 1.0 && $y >= 0.0 && $y <= 1.0 ? new self($x, $y) : null; + } + + /** + * @return array{x: float, y: float} + */ + public function toArray(): array + { + return ['x' => $this->x, 'y' => $this->y]; + } +} diff --git a/src/Domain/Media/MediaCatalog.php b/src/Domain/Media/MediaCatalog.php new file mode 100644 index 0000000..3f55e37 --- /dev/null +++ b/src/Domain/Media/MediaCatalog.php @@ -0,0 +1,16 @@ +|null null when there is no such file, or the visitor may not see it + */ + public function for(int $id): ?array; +} diff --git a/src/Domain/Media/MediaKind.php b/src/Domain/Media/MediaKind.php new file mode 100644 index 0000000..7aef505 --- /dev/null +++ b/src/Domain/Media/MediaKind.php @@ -0,0 +1,26 @@ + self::Image, + 'video' => self::Video, + 'audio' => self::Audio, + default => self::File, + }; + } +} diff --git a/src/Domain/Media/MediaUrls.php b/src/Domain/Media/MediaUrls.php new file mode 100644 index 0000000..035f805 --- /dev/null +++ b/src/Domain/Media/MediaUrls.php @@ -0,0 +1,54 @@ +uploads = rtrim((string) preg_replace('#\Ahttps?:#i', '', $uploadsBase), '/'); + $this->cdn = rtrim($cdnBase, '/'); + } + + public function toCdn(string $url): string + { + $bare = (string) preg_replace('#\Ahttps?:#i', '', $url); + + if ($this->uploads === '' || ($bare !== $this->uploads && ! str_starts_with($bare, $this->uploads.'/'))) { + return $url; + } + + return $this->cdn.substr($bare, strlen($this->uploads)); + } + + /** Every address of an uploaded file in a piece of HTML (an image, a link, a source set). */ + public function rewriteHtml(string $html): string + { + if ($this->uploads === '' || ! str_contains($html, ltrim($this->uploads, '/'))) { + return $html; + } + + return (string) preg_replace_callback( + '#https?:'.preg_quote($this->uploads, '#').'(?=[/"\'\s,?]|\z)#i', + fn (): string => $this->cdn, + $html, + ); + } +} diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index 9f11446..ef6ebd9 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -62,6 +62,8 @@ private function __construct( public bool $manifest, public bool $redirects, public bool $oldSlugRedirects, + public bool $mediaRoutes, + public ?string $mediaCdn, ) {} /** @@ -73,6 +75,7 @@ public static function fromArray(array $config, string $backendUrl): self $backend = Origin::fromUrl($backendUrl); $preview = is_array($config['preview'] ?? null) ? $config['preview'] : []; $revalidation = is_array($config['revalidation'] ?? null) ? $config['revalidation'] : []; + $media = is_array($config['media'] ?? null) ? $config['media'] : []; $frontUrl = self::string($config, 'frontend_url'); $front = $frontUrl === '' ? null : Origin::fromUrl($frontUrl); @@ -122,6 +125,8 @@ public static function fromArray(array $config, string $backendUrl): self manifest: $front instanceof Origin && self::bool(is_array($config['manifest'] ?? null) ? $config['manifest'] : [], 'enabled', true), redirects: $front instanceof Origin && self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'enabled', true), oldSlugRedirects: self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'old_slugs', true), + mediaRoutes: $front instanceof Origin && self::bool($media, 'enabled', true), + mediaCdn: self::mediaCdn($media), ); } @@ -249,6 +254,24 @@ private static function targets(array $config): array return $targets; } + /** + * The address the CDN serves the uploads from, without its trailing slash; null when there is none. + * + * @param array $config + */ + private static function mediaCdn(array $config): ?string + { + $url = rtrim(self::string($config, 'cdn_url'), '/'); + + if ($url === '') { + return null; + } + + Origin::fromUrl($url); + + return $url; + } + private static function mode(string $value, bool $hasFront): FrontMode { if ($value === '') { diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index d49df74..bbe9167 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -13,6 +13,7 @@ use Pollora\Headless\Domain\Front\UrlMapper; use Pollora\Headless\Domain\Language\Languages; use Pollora\Headless\Domain\Language\LanguageUrls; +use Pollora\Headless\Domain\Media\MediaUrls; use Pollora\Headless\Infrastructure\Config\Settings; use Pollora\Headless\Infrastructure\Config\SettingsLoader; use Pollora\Headless\Infrastructure\Language\LanguagesFactory; @@ -108,6 +109,14 @@ public static function modules(Settings $settings, ?Languages $languages = null) $modules[] = new RedirectRoutes(new RedirectCatalog([new OptionRedirectStore, ...($settings->oldSlugRedirects ? [new OldSlugRedirects($urls)] : [])])); } + if ($settings->mediaRoutes) { + $modules[] = new MediaRoutes(new NormalizedMedia); + } + + if ($settings->mediaCdn !== null) { + $modules[] = new MediaCdn(new MediaUrls((string) (wp_upload_dir(null, false)['baseurl'] ?? ''), $settings->mediaCdn)); + } + if ($settings->restCache instanceof RestCachePolicy || $settings->perPageMax !== null) { $modules[] = new RestPerformance($settings->restCache, $settings->perPageMax); } diff --git a/src/Infrastructure/WordPress/MediaCdn.php b/src/Infrastructure/WordPress/MediaCdn.php new file mode 100644 index 0000000..9b22b39 --- /dev/null +++ b/src/Infrastructure/WordPress/MediaCdn.php @@ -0,0 +1,49 @@ +addFilter('wp_get_attachment_url', [$this, 'url']); + $hooks->addFilter('wp_calculate_image_srcset', [$this, 'srcset']); + $hooks->addFilter('the_content', [$this, 'html'], 20); + } + + public function url(mixed $url): mixed + { + return is_string($url) && ! is_admin() ? $this->urls->toCdn($url) : $url; + } + + public function srcset(mixed $sources): mixed + { + if (! is_array($sources) || is_admin()) { + return $sources; + } + + foreach ($sources as $width => $source) { + if (is_array($source) && is_string($source['url'] ?? null)) { + $sources[$width]['url'] = $this->urls->toCdn($source['url']); + } + } + + return $sources; + } + + public function html(mixed $html): mixed + { + return is_string($html) && ! is_admin() ? $this->urls->rewriteHtml($html) : $html; + } +} diff --git a/src/Infrastructure/WordPress/MediaRoutes.php b/src/Infrastructure/WordPress/MediaRoutes.php new file mode 100644 index 0000000..6609057 --- /dev/null +++ b/src/Infrastructure/WordPress/MediaRoutes.php @@ -0,0 +1,73 @@ +addAction('rest_api_init', [$this, 'routes']); + } + + public function routes(): void + { + register_rest_route(self::NAMESPACE, '/media/(?P\d+)', [ + 'methods' => 'GET', + 'callback' => [$this, 'show'], + // Public on purpose: a file a visitor can already see on the front end. A file attached to a post they may not read answers 404. + 'permission_callback' => '__return_true', + 'args' => ['id' => ['type' => 'integer', 'required' => true]], + ]); + + foreach (get_post_types(['show_in_rest' => true, 'public' => true]) as $type) { + if (post_type_supports($type, 'thumbnail')) { + register_rest_field($type, self::FIELD, [ + 'get_callback' => [$this, 'featured'], + 'schema' => ['description' => 'The featured image in full (ask for it in _fields).', 'type' => ['object', 'null'], 'context' => ['view', 'edit']], + ]); + } + } + } + + /** + * @param \WP_REST_Request> $request + */ + public function show(\WP_REST_Request $request): \WP_REST_Response|\WP_Error + { + $media = $this->media->for((int) $request->get_param('id')); + + return $media === null ? new \WP_Error('media_not_found', 'No such file.', ['status' => 404]) : rest_ensure_response($media); + } + + /** + * @param array $post the post as the REST controller prepared it + * @param \WP_REST_Request> $request + * @return array|null + */ + public function featured(array $post, string $field, \WP_REST_Request $request): ?array + { + if (! OptInField::requested($request, self::FIELD)) { + return null; + } + + $id = (int) get_post_thumbnail_id((int) ($post['id'] ?? 0)); + + return $id > 0 ? $this->media->for($id) : null; + } +} diff --git a/src/Infrastructure/WordPress/NormalizedMedia.php b/src/Infrastructure/WordPress/NormalizedMedia.php new file mode 100644 index 0000000..f15927a --- /dev/null +++ b/src/Infrastructure/WordPress/NormalizedMedia.php @@ -0,0 +1,109 @@ +post_type !== 'attachment' || ! $this->isVisible($post)) { + return null; + } + + $mime = (string) get_post_mime_type($post); + $kind = MediaKind::fromMime($mime); + $url = (string) wp_get_attachment_url($id); + $metadata = wp_get_attachment_metadata($id); + $metadata = is_array($metadata) ? $metadata : []; + + $isImage = $kind === MediaKind::Image; + + return [ + 'id' => $id, + 'kind' => $kind->value, + 'mime' => $mime, + 'url' => $url, + 'title' => $post->post_title, + 'alt' => (string) get_post_meta($id, '_wp_attachment_image_alt', true), + 'caption' => $post->post_excerpt, + 'description' => $post->post_content, + 'width' => $isImage && isset($metadata['width']) ? (int) $metadata['width'] : null, + 'height' => $isImage && isset($metadata['height']) ? (int) $metadata['height'] : null, + 'filesize' => isset($metadata['filesize']) ? (int) $metadata['filesize'] : null, + 'duration' => ! $isImage && isset($metadata['length']) ? (int) $metadata['length'] : null, + 'focal_point' => $isImage ? $this->focalPoint($id) : null, + 'sizes' => $isImage ? $this->sizes($url, $metadata) : [], + 'srcset' => $isImage ? (wp_get_attachment_image_srcset($id, 'full') ?: null) : null, + 'modified_gmt' => str_replace(' ', 'T', $post->post_modified_gmt), + ]; + } + + /** + * Who may see a file: anyone for a file of the library, and for a file attached to a post, whoever may see that post. + * (`read_post` is no use here: it refuses an attachment's own "inherit" status to a visitor.) + */ + private function isVisible(\WP_Post $file): bool + { + if ($file->post_status === 'private') { + return current_user_can('read_post', $file->ID); + } + + $parent = $file->post_parent > 0 ? get_post($file->post_parent) : null; + + return ! $parent instanceof \WP_Post || is_post_publicly_viewable($parent) || current_user_can('read_post', $parent->ID); + } + + /** + * @return array{x: float, y: float}|null + */ + private function focalPoint(int $id): ?array + { + $stored = FocalPoint::tryFrom(get_post_meta($id, self::FOCAL_META, true)); + $filtered = apply_filters('pollora/media/focal_point', $stored?->toArray(), $id); + + return (FocalPoint::tryFrom($filtered) ?? $stored)?->toArray(); + } + + /** + * @param array $metadata + * @return array + */ + private function sizes(string $url, array $metadata): array + { + $directory = substr($url, 0, (int) strrpos($url, '/')); + $sizes = []; + + foreach (is_array($metadata['sizes'] ?? null) ? $metadata['sizes'] : [] as $name => $size) { + if (is_array($size) && is_string($size['file'] ?? null)) { + $sizes[(string) $name] = ['url' => $directory.'/'.$size['file'], 'width' => (int) ($size['width'] ?? 0), 'height' => (int) ($size['height'] ?? 0)]; + } + } + + ksort($sizes); + + if (isset($metadata['width'], $metadata['height'])) { + $sizes['full'] = ['url' => $url, 'width' => (int) $metadata['width'], 'height' => (int) $metadata['height']]; + } + + return $sizes; + } +} diff --git a/src/Infrastructure/WordPress/OptInField.php b/src/Infrastructure/WordPress/OptInField.php new file mode 100644 index 0000000..68fe12a --- /dev/null +++ b/src/Infrastructure/WordPress/OptInField.php @@ -0,0 +1,24 @@ +> $request + */ + public static function requested(\WP_REST_Request $request, string $field): bool + { + $fields = $request->get_param('_fields'); + $fields = is_array($fields) ? $fields : explode(',', (string) $fields); + + return in_array($field, array_map(trim(...), array_map(strval(...), $fields)), true); + } +} diff --git a/tests/Integration/MediaTest.php b/tests/Integration/MediaTest.php new file mode 100644 index 0000000..0b809a2 --- /dev/null +++ b/tests/Integration/MediaTest.php @@ -0,0 +1,193 @@ +register(new WordPressHooks); + + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); +} + +function imageAttachment(int $parent = 0, string $name = 'headless-test'): int +{ + $id = wp_insert_attachment([ + 'post_title' => 'A test image', + 'post_excerpt' => 'Caption of it', + 'post_mime_type' => 'image/png', + 'post_status' => 'inherit', + 'post_parent' => $parent, + ], "2026/11/$name.png"); + + update_post_meta($id, '_wp_attachment_image_alt', 'An alternative text'); + wp_update_attachment_metadata($id, [ + 'width' => 1200, + 'height' => 800, + 'file' => "2026/11/$name.png", + 'filesize' => 54321, + 'sizes' => [ + 'thumbnail' => ['file' => "$name-150x150.png", 'width' => 150, 'height' => 150, 'mime-type' => 'image/png'], + 'medium' => ['file' => "$name-300x200.png", 'width' => 300, 'height' => 200, 'mime-type' => 'image/png'], + ], + ]); + + return $id; +} + +afterEach(function (): void { + foreach (array_keys($GLOBALS['wp_filter']) as $hook) { + foreach ($GLOBALS['wp_filter'][$hook]->callbacks as $priority => $callbacks) { + foreach ($callbacks as $callback) { + $function = $callback['function']; + + if (is_array($function) && is_object($function[0]) && str_starts_with($function[0]::class, 'Pollora\\Headless\\')) { + remove_filter($hook, $function, $priority); + } + } + } + } + + remove_all_filters('pollora/media/focal_point'); + wp_set_current_user(0); +}); + +it('describes an image in one shape: sizes, srcset, alt, caption', function (): void { + mediaServer(); + $id = imageAttachment(); + + $response = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$id")); + $data = $response->get_data(); + wp_delete_attachment($id, true); + + expect($response->get_status())->toBe(200) + ->and($data)->toMatchArray(['id' => $id, 'kind' => 'image', 'mime' => 'image/png', 'title' => 'A test image', 'alt' => 'An alternative text', 'caption' => 'Caption of it', 'width' => 1200, 'height' => 800, 'filesize' => 54321, 'duration' => null, 'focal_point' => null]) + ->and($data['url'])->toEndWith('/2026/11/headless-test.png') + ->and(array_keys($data['sizes']))->toBe(['medium', 'thumbnail', 'full']) + ->and($data['sizes']['medium'])->toMatchArray(['width' => 300, 'height' => 200]) + ->and($data['sizes']['medium']['url'])->toEndWith('/2026/11/headless-test-300x200.png') + ->and($data['sizes']['full']['url'])->toBe($data['url']) + ->and($data['srcset'])->toContain('headless-test-300x200.png 300w') + ->and($data['modified_gmt'])->toMatch('/\A\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\z/'); +}); + +it('gives the focal point the editor set with pollora/media, and lets its filter have the last word', function (): void { + mediaServer(); + $id = imageAttachment(); + update_post_meta($id, '_pollora_focal_point', ['x' => 0.25, 'y' => 0.75]); + + $stored = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$id"))->get_data()['focal_point']; + + add_filter('pollora/media/focal_point', static fn (mixed $point, int $attachment): array => ['x' => 0.5, 'y' => 0.5], 10, 2); + $filtered = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$id"))->get_data()['focal_point']; + remove_all_filters('pollora/media/focal_point'); + + update_post_meta($id, '_pollora_focal_point', ['x' => 9, 'y' => 'nope']); + $broken = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$id"))->get_data()['focal_point']; + wp_delete_attachment($id, true); + + expect($stored)->toBe(['x' => 0.25, 'y' => 0.75]) + ->and($filtered)->toBe(['x' => 0.5, 'y' => 0.5]) + ->and($broken)->toBeNull(); +}); + +it('describes a document without image fields', function (): void { + mediaServer(); + $id = wp_insert_attachment(['post_title' => 'A report', 'post_mime_type' => 'application/pdf', 'post_status' => 'inherit'], '2026/11/report.pdf'); + + $data = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$id"))->get_data(); + wp_delete_attachment($id, true); + + expect($data['kind'])->toBe('file') + ->and($data['width'])->toBeNull() + ->and($data['sizes'])->toBe([]) + ->and($data['srcset'])->toBeNull() + ->and($data['focal_point'])->toBeNull(); +}); + +it('answers 404 for a file that is not there, a post that is not a file, and a file of a draft to a visitor', function (): void { + mediaServer(); + $draft = wp_insert_post(['post_title' => 'Draft', 'post_status' => 'draft']); + $attached = imageAttachment($draft, 'attached-to-draft'); + $post = wp_insert_post(['post_title' => 'Not a file', 'post_status' => 'publish']); + + wp_set_current_user(0); + $visitor = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$attached")); + $missing = rest_do_request(new WP_REST_Request('GET', '/headless/v1/media/999999')); + $notFile = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$post")); + wp_set_current_user(get_users(['role' => 'administrator', 'number' => 1])[0]->ID); + $editor = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$attached")); + wp_set_current_user(0); + wp_delete_attachment($attached, true); + wp_delete_post($draft, true); + wp_delete_post($post, true); + + expect($visitor->get_status())->toBe(404) + ->and($visitor->get_data()['code'])->toBe('media_not_found') + ->and($missing->get_status())->toBe(404) + ->and($notFile->get_status())->toBe(404) + ->and($editor->get_status())->toBe(200); +}); + +it('gives the featured image of a post in full, only when _fields asks for it', function (): void { + mediaServer(); + $image = imageAttachment(); + $post = wp_insert_post(['post_title' => 'With image', 'post_status' => 'publish']); + set_post_thumbnail($post, $image); + + $ask = static function (string $fields) use ($post): array { + $request = new WP_REST_Request('GET', "/wp/v2/posts/$post"); + $request->set_param('_fields', $fields); + + return rest_do_request($request)->get_data(); + }; + + $with = $ask('id,headless_featured_media'); + $without = $ask('id,featured_media'); + $all = rest_do_request(new WP_REST_Request('GET', "/wp/v2/posts/$post"))->get_data(); + wp_delete_post($post, true); + wp_delete_attachment($image, true); + + expect($with['headless_featured_media'])->toMatchArray(['id' => $image, 'kind' => 'image', 'width' => 1200]) + ->and($without)->not->toHaveKey('headless_featured_media') + ->and($all['headless_featured_media'])->toBeNull(); +}); + +it('serves the files from the CDN, in the address, the srcset and the content, and not in the administration', function (): void { + $uploads = wp_upload_dir(null, false)['baseurl']; + (new MediaCdn(new MediaUrls($uploads, 'https://cdn.example.com')))->register(new WordPressHooks); + mediaServer(); + $id = imageAttachment(); + + $url = wp_get_attachment_url($id); + $srcset = wp_get_attachment_image_srcset($id, 'full'); + $content = apply_filters('the_content', '

p

'); + $api = rest_do_request(new WP_REST_Request('GET', "/headless/v1/media/$id"))->get_data(); + // is_admin() reads the screen: the one of the administration + require_once ABSPATH.'wp-admin/includes/class-wp-screen.php'; + require_once ABSPATH.'wp-admin/includes/screen.php'; + set_current_screen('dashboard'); + $inAdmin = wp_get_attachment_url($id); + unset($GLOBALS['current_screen']); + $GLOBALS['current_screen'] = WP_Screen::get('front'); + wp_delete_attachment($id, true); + + expect($url)->toBe('https://cdn.example.com/2026/11/headless-test.png') + ->and($srcset)->toContain('https://cdn.example.com/2026/11/headless-test-300x200.png 300w') + ->and($srcset)->not->toContain($uploads) + ->and($content)->toContain('src="https://cdn.example.com/2026/11/headless-test.png"') + ->and($content)->toContain('href="'.home_url('/page/').'"') + ->and($api['url'])->toBe('https://cdn.example.com/2026/11/headless-test.png') + ->and($api['sizes']['medium']['url'])->toBe('https://cdn.example.com/2026/11/headless-test-300x200.png') + ->and($inAdmin)->toBe($uploads.'/2026/11/headless-test.png'); +}); diff --git a/tests/Unit/Domain/MediaTest.php b/tests/Unit/Domain/MediaTest.php new file mode 100644 index 0000000..9c0cdf8 --- /dev/null +++ b/tests/Unit/Domain/MediaTest.php @@ -0,0 +1,77 @@ +toCdn('https://cms.example.com/wp-content/uploads/2026/11/a.jpg'))->toBe('https://cdn.example.com/2026/11/a.jpg') + ->and($urls->toCdn('http://cms.example.com/wp-content/uploads/2026/11/a.jpg?x=1'))->toBe('https://cdn.example.com/2026/11/a.jpg?x=1') + ->and($urls->toCdn('https://cms.example.com/wp-content/uploads'))->toBe('https://cdn.example.com'); +}); + +it('can serve the uploads under a path of the CDN', function (): void { + $urls = new MediaUrls('https://cms.example.com/wp-content/uploads', 'https://cdn.example.com/media'); + + expect($urls->toCdn('https://cms.example.com/wp-content/uploads/a.jpg'))->toBe('https://cdn.example.com/media/a.jpg'); +}); + +it('leaves alone what is not an uploaded file', function (string $url): void { + $urls = new MediaUrls('https://cms.example.com/wp-content/uploads', 'https://cdn.example.com'); + + expect($urls->toCdn($url))->toBe($url); +})->with([ + 'a page' => 'https://cms.example.com/about/', + 'a theme file' => 'https://cms.example.com/wp-content/themes/x/a.css', + 'another host' => 'https://other.example.org/wp-content/uploads/a.jpg', + 'a look-alike directory' => 'https://cms.example.com/wp-content/uploads-old/a.jpg', + 'not an address' => 'a.jpg', + 'nothing' => '', +]); + +it('does nothing without an uploads address', function (): void { + expect((new MediaUrls('', 'https://cdn.example.com'))->toCdn('https://cms.example.com/a.jpg'))->toBe('https://cms.example.com/a.jpg') + ->and((new MediaUrls('', 'https://cdn.example.com'))->rewriteHtml(''))->toBe(''); +}); + +it('rewrites every uploaded file of a piece of HTML, in src, srcset and links', function (): void { + $urls = new MediaUrls('https://cms.example.com/wp-content/uploads', 'https://cdn.example.com'); + $html = '' + .'fpo'; + + expect($urls->rewriteHtml($html))->toBe( + '' + .'fpo', + )->and($urls->rewriteHtml('

No file here

'))->toBe('

No file here

'); +}); + +it('reads a focal point, and nothing else', function (mixed $stored, ?array $expected): void { + expect(FocalPoint::tryFrom($stored)?->toArray())->toBe($expected); +})->with([ + [['x' => 0.25, 'y' => 0.75], ['x' => 0.25, 'y' => 0.75]], + [['x' => '0.5', 'y' => 1], ['x' => 0.5, 'y' => 1.0]], + [['x' => 0, 'y' => 0], ['x' => 0.0, 'y' => 0.0]], + [['x' => 1.2, 'y' => 0.5], null], + [['x' => -0.1, 'y' => 0.5], null], + [['x' => 0.5], null], + [['x' => 'left', 'y' => 'top'], null], + ['0.5,0.5', null], + [null, null], + ['', null], +]); + +it('tells what a front end does with a file', function (string $mime, MediaKind $kind): void { + expect(MediaKind::fromMime($mime))->toBe($kind); +})->with([ + ['image/jpeg', MediaKind::Image], + ['image/svg+xml', MediaKind::Image], + ['video/mp4', MediaKind::Video], + ['audio/mpeg', MediaKind::Audio], + ['application/pdf', MediaKind::File], + ['', MediaKind::File], + ['nonsense', MediaKind::File], +]); diff --git a/tests/Unit/Infrastructure/MediaInfrastructureTest.php b/tests/Unit/Infrastructure/MediaInfrastructureTest.php new file mode 100644 index 0000000..a0321f4 --- /dev/null +++ b/tests/Unit/Infrastructure/MediaInfrastructureTest.php @@ -0,0 +1,128 @@ +shouldReceive('get_param')->with('_fields')->andReturn($fields); + + return $request; +} + +it('knows whether a request asked for a field by name', function (mixed $fields, bool $expected): void { + expect(OptInField::requested(fieldsRequest($fields), 'headless_blocks'))->toBe($expected); +})->with([ + ['id,headless_blocks', true], + ['id, headless_blocks ,title', true], + [['id', 'headless_blocks'], true], + ['id,title', false], + ['headless_blocks_other', false], + ['', false], + [null, false], +]); + +it('registers the media route, and a featured-media field on the types that have a thumbnail', function (): void { + Actions\expectAdded('rest_api_init')->once(); + $routes = new MediaRoutes(new NormalizedMedia); + $routes->register(new WordPressHooks); + + Functions\when('get_post_types')->justReturn(['post', 'page', 'event']); + Functions\when('post_type_supports')->alias(static fn (string $type, string $feature): bool => $type !== 'page' && $feature === 'thumbnail'); + Functions\expect('register_rest_route')->once()->with('headless/v1', '/media/(?P\d+)', Mockery::type('array')); + Functions\expect('register_rest_field')->twice()->with(Mockery::anyOf('post', 'event'), 'headless_featured_media', Mockery::type('array')); + + $routes->routes(); +}); + +it('computes the featured image only when asked for it', function (): void { + $media = Mockery::mock(MediaCatalog::class); + $media->shouldReceive('for')->once()->with(55)->andReturn(['id' => 55]); + $routes = new MediaRoutes($media); + Functions\when('get_post_thumbnail_id')->alias(static fn (int $id): int => $id === 12 ? 55 : 0); + + expect($routes->featured(['id' => 12], 'headless_featured_media', fieldsRequest('id,headless_featured_media')))->toBe(['id' => 55]) + ->and($routes->featured(['id' => 12], 'headless_featured_media', fieldsRequest('id,title')))->toBeNull() + ->and($routes->featured(['id' => 13], 'headless_featured_media', fieldsRequest('headless_featured_media')))->toBeNull(); +}); + +it('answers 404 for a file that is not there, and the file otherwise', function (): void { + $media = Mockery::mock(MediaCatalog::class); + $media->shouldReceive('for')->with(1)->andReturn(null); + $media->shouldReceive('for')->with(2)->andReturn(['id' => 2]); + Functions\when('rest_ensure_response')->alias(static function (array $data): WP_REST_Response { + $response = Mockery::mock('WP_REST_Response'); + $response->shouldReceive('get_data')->andReturn($data); + + return $response; + }); + $routes = new MediaRoutes($media); + $ask = static function (int $id): WP_REST_Request { + $request = Mockery::mock('WP_REST_Request'); + $request->shouldReceive('get_param')->with('id')->andReturn($id); + + return $request; + }; + + $missing = $routes->show($ask(1)); + + expect($missing)->toBeInstanceOf(WP_Error::class) + ->and($missing->get_error_code())->toBe('media_not_found') + ->and($missing->get_error_data())->toBe(['status' => 404]) + ->and($routes->show($ask(2))->get_data())->toBe(['id' => 2]); +}); + +it('hooks the address of a file, its srcset and the content', function (): void { + Filters\expectAdded('wp_get_attachment_url')->once(); + Filters\expectAdded('wp_calculate_image_srcset')->once(); + Filters\expectAdded('the_content')->once()->with(Mockery::type('array'), 20); + + (new MediaCdn(new MediaUrls('https://cms.example.com/wp-content/uploads', 'https://cdn.example.com')))->register(new WordPressHooks); +}); + +it('moves files to the CDN outside the administration, and leaves the administration alone', function (): void { + $cdn = new MediaCdn(new MediaUrls('https://cms.example.com/wp-content/uploads', 'https://cdn.example.com')); + $sources = [300 => ['url' => 'https://cms.example.com/wp-content/uploads/a-300.jpg', 'descriptor' => 'w', 'value' => 300], 600 => 'not a source']; + + Functions\when('is_admin')->justReturn(false); + + expect($cdn->url('https://cms.example.com/wp-content/uploads/a.jpg'))->toBe('https://cdn.example.com/a.jpg') + ->and($cdn->url(false))->toBeFalse() + ->and($cdn->srcset($sources)[300]['url'])->toBe('https://cdn.example.com/a-300.jpg') + ->and($cdn->srcset($sources)[600])->toBe('not a source') + ->and($cdn->srcset(false))->toBeFalse() + ->and($cdn->html(''))->toBe('') + ->and($cdn->html(['not html']))->toBe(['not html']); + + Functions\when('is_admin')->justReturn(true); + + expect($cdn->url('https://cms.example.com/wp-content/uploads/a.jpg'))->toBe('https://cms.example.com/wp-content/uploads/a.jpg') + ->and($cdn->srcset($sources))->toBe($sources) + ->and($cdn->html(''))->toBe(''); +}); + +it('reads the media settings', function (): void { + $on = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'media' => ['cdn_url' => 'https://cdn.example.com/']], 'https://cms.example.com'); + $off = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'media' => ['enabled' => false]], 'https://cms.example.com'); + $bare = Settings::fromArray([], 'https://cms.example.com'); + + expect($on->mediaRoutes)->toBeTrue()->and($on->mediaCdn)->toBe('https://cdn.example.com') + ->and($off->mediaRoutes)->toBeFalse()->and($off->mediaCdn)->toBeNull() + ->and($bare->mediaRoutes)->toBeFalse()->and($bare->mediaCdn)->toBeNull(); +}); + +it('refuses a CDN address that is not one', function (): void { + Settings::fromArray(['media' => ['cdn_url' => 'cdn.example.com']], 'https://cms.example.com'); +})->throws(InvalidArgumentException::class); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 2fb7af6..041fb62 100644 --- a/tests/Unit/Infrastructure/ModulesTest.php +++ b/tests/Unit/Infrastructure/ModulesTest.php @@ -120,10 +120,10 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate Functions\when('wp_salt')->justReturn('salt'); $settings = Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com'); - expect(Bootstrap::modules($settings))->toHaveCount(12); + expect(Bootstrap::modules($settings))->toHaveCount(13); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->times(4); + Actions\expectAdded('rest_api_init')->times(5); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once();