diff --git a/CHANGELOG.md b/CHANGELOG.md index d9d88d0..d1e0807 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- Instructions and four skills for coding agents, installed by + [Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html) + (`vendor/bin/mate discover`): create a translatable resource, search and + sort by translated fields, write translations over HTTP, and use a DTO as + the API resource. The bundle does not require Mate + ## [2.3.0] - 2026-11-18 ### Changed diff --git a/INSTRUCTIONS.md b/INSTRUCTIONS.md new file mode 100644 index 0000000..d647ffb --- /dev/null +++ b/INSTRUCTIONS.md @@ -0,0 +1,22 @@ +## locastic/api-platform-translation-bundle + +Entity translations for API Platform and Doctrine ORM: one translation row for +each locale, with the locale resolved from each request. This extension has no +Mate tools. Its skills hold the complete setup, payloads and checks, so load +the skill for your task: + +| Task | Skill | +|---|---| +| Make an entity translatable, or add a translated field | `api-translation-resource` | +| Search or sort a collection by a translated field | `api-translation-filters` | +| Send, edit or replace translations through the API (POST, PATCH, PUT) | `api-translation-writes` | +| Use a DTO class as the API resource of a translatable entity | `api-translation-dto` | + +Installed skill names start with `mate-`. + +### Rules + +- Virtual getters on the translatable delegate to getTranslation(), which resolves the current locale and falls back to the fallback locale; virtual setters delegate to getOrCreateTranslation(), which targets the exact locale and creates the translation when missing. +- Set auto_create_translations: false so reads never write to the database; the default (true) keeps the legacy behavior where getTranslation() attaches an empty translation for a missing locale, which cascade persist can insert on the next flush. The default flips to false in 3.0. +- Prefer PATCH (application/merge-patch+json) for editing translations: it updates only the submitted locales. PUT is a full replace and removes locales absent from the payload. +- With a DTO as the API resource (stateOptions: new Options(entityClass: ...)), reads need nothing extra, but the bundle does not match submitted translations to their existing rows: in your state processor, call getOrCreateTranslation($locale) on the managed entity for each submitted locale (or match by locale in an Object Mapper transformer). The 'translation.groups' filter and the 'translations' group do not apply to a DTO; expose the translations as a DTO property keyed by locale. diff --git a/README.md b/README.md index fd00977..4256e43 100644 --- a/README.md +++ b/README.md @@ -438,6 +438,23 @@ child service of the abstract parent `locastic_api_platform_translation.doctrine.orm.filter.translation_order`, pass `$properties`, and tag it `api_platform.filter`. +Coding agents: +-------------- +The bundle ships instructions and skills for coding agents through +[Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html). +In a project that uses Mate, `vendor/bin/mate discover` adds the bundle's +rules to the agent instructions (`mate/AGENT_INSTRUCTIONS.md`) and installs +four skills: + +- `mate-api-translation-resource`: create a translatable entity, or add a + translated field. +- `mate-api-translation-filters`: search and sort by translated fields. +- `mate-api-translation-writes`: send translations with POST, PATCH and PUT. +- `mate-api-translation-dto`: use a DTO class as the API resource. + +The bundle does not require Mate. The same files are in the package: +`INSTRUCTIONS.md` and the `skills/` directory. + ## Contribution If you have an idea on how to improve this bundle, feel free to contribute. If you have problems or you found some bugs, please open an issue. diff --git a/composer.json b/composer.json index 8618700..9e25682 100644 --- a/composer.json +++ b/composer.json @@ -45,6 +45,9 @@ "api-platform/core": "^3.4 || ^4.0 || ^5.0", "symfony/http-client": "^6.4 || ^7.0 || ^8.0" }, + "suggest": { + "symfony/ai-mate": "Installs this bundle's agent instructions and skills for coding agents" + }, "prefer-stable": true, "autoload": { "psr-4": { @@ -59,6 +62,10 @@ "extra": { "branch-alias": { "dev-master": "2.x-dev" + }, + "ai-mate": { + "instructions": "INSTRUCTIONS.md", + "skills": ["skills"] } }, "config": { diff --git a/context7.json b/context7.json index a2b885c..e9d30cc 100644 --- a/context7.json +++ b/context7.json @@ -10,11 +10,13 @@ "tests", "config", "bin", - "vendor" + "vendor", + "skills" ], "excludeFiles": [ "CONTRIBUTING.md", - "SECURITY.md" + "SECURITY.md", + "INSTRUCTIONS.md" ], "rules": [ "A translatable resource extends AbstractTranslatable, implements createTranslation(), and maps translations as OneToMany with indexBy: 'locale', cascade: ['persist'], orphanRemoval: true.", @@ -28,8 +30,9 @@ "When editing via PUT, include each existing translation's 'id' so its row is updated in place instead of replaced.", "Clients select the locale with the ?locale= query parameter or the Accept-Language header, and can request all translations at once with ?groups[]=translations (the bundle's 'translation.groups' filter).", "Filter and order collections by translated fields with the bundle's TranslationSearchFilter and TranslationOrderFilter (e.g. #[ApiFilter(TranslationSearchFilter::class, properties: ['title' => 'ipartial'])]); declare the translation entity's fields by their bare name ('title', not 'translations.title'). They match only the locale resolved from the request, unlike a core SearchFilter on 'translations.title', which matches every locale.", + "With a DTO as the API resource (stateOptions: new Options(entityClass: ...)), reads need nothing extra, but the bundle does not match submitted translations to their existing rows: in your state processor, call getOrCreateTranslation($locale) on the managed entity for each submitted locale (or match by locale in an Object Mapper transformer). The 'translation.groups' filter and the 'translations' group do not apply to a DTO; expose the translations as a DTO property keyed by locale.", "Restrict accepted locales with framework.enabled_locales or the bundle's api_platform_translation.enabled_locales option (which takes precedence); unlisted locales fall back to the default locale.", - "Version 2.x requires PHP >= 8.2, API Platform ^3.4 || ^4.0, and Doctrine ORM ^3.0; use PHP 8 attributes, not Doctrine annotations, in mappings." + "Version 2.x requires PHP >= 8.2, API Platform ^3.4 || ^4.0 || ^5.0, and Doctrine ORM ^3.0; use PHP 8 attributes, not Doctrine annotations, in mappings." ], "previousVersions": [ "v2.0.1", diff --git a/skills/api-translation-dto/SKILL.md b/skills/api-translation-dto/SKILL.md new file mode 100644 index 0000000..0fc4727 --- /dev/null +++ b/skills/api-translation-dto/SKILL.md @@ -0,0 +1,292 @@ +--- +name: api-translation-dto +description: Expose a translatable Doctrine entity of locastic/api-platform-translation-bundle through a DTO class as the API Platform resource (stateOptions with entityClass, a state provider and processor, or the Symfony Object Mapper). Use when the API resource is not the entity itself and it must read and write translations by locale without duplicate or lost translation rows. +--- + +# DTO as the API resource of a translatable entity + +In this setup, a plain class (the DTO) has `#[ApiResource]`, and the state +layer maps between the DTO and the Doctrine entity. The entity stays as the +skill `api-translation-resource` (`mate-api-translation-resource` when Mate +installed it) shows, but without `#[ApiResource]` and without serialization +groups. + +What changes against an entity resource: + +- **Reads need nothing extra.** The bundle sets the current and fallback + locale on each translatable entity when Doctrine loads it. The translated + getters return the request locale when you map the entity to the DTO. +- **Writes need your own match by locale.** The bundle matches submitted + translations to their rows only when the resource is the entity. With a DTO, + your code must do it. Otherwise each write creates new translation rows or + loses the existing ones. +- The translation filters and `eager_load_translations` work. Put the + `#[ApiFilter]` attributes on the DTO class. +- The `translation.groups` filter and the `translations` serialization group + do not apply. The DTO has a `translations` property instead. + +## Variant selection + +| Variant | Use when | +|---|---| +| State provider and processor (this file) | any supported API Platform version, or you need PUT as a full replace | +| Symfony Object Mapper ([references/object-mapper.md](references/object-mapper.md)) | API Platform 4.2 or later with `symfony/object-mapper` 7.4 or later, and PATCH is enough | + +## Procedure: state provider and processor + +### Step 1: install the docblock packages + +The serializer reads the `array` type from the +docblock only with these two packages. Without them, the entries reach your +code as plain arrays: + +```bash +composer require phpstan/phpdoc-parser phpdocumentor/type-resolver +``` + +### Step 2: create the DTO for one translation + +```php +// src/ApiResource/ArticleTranslationDto.php +namespace App\ApiResource; + +final class ArticleTranslationDto +{ + public ?string $title = null; + public ?string $locale = null; +} +``` + +### Step 3: create the resource class + +`stateOptions` tells API Platform's Doctrine services which entity is behind +the resource: + +```php +// src/ApiResource/ArticleResource.php +namespace App\ApiResource; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use App\Entity\Article; +use App\State\ArticleResourceProcessor; +use App\State\ArticleResourceProvider; + +#[ApiResource( + shortName: 'Article', + // The entity behind this resource, for API Platform's Doctrine services. + stateOptions: new Options(entityClass: Article::class), + operations: [ + new Get(), + new GetCollection(), + new Post(), + new Patch(), + // PUT needs standard_put off, see the note below. + new Put(extraProperties: ['standard_put' => false]), + new Delete(), + ], + provider: ArticleResourceProvider::class, + processor: ArticleResourceProcessor::class, +)] +final class ArticleResource +{ + public ?int $id = null; + + /** + * Translated value in the requested (or fallback) locale. The processor + * does not write it: writes go through `translations`. + */ + public ?string $title = null; + + /** + * All translations, keyed by locale. + * + * @var array + */ + public array $translations = []; + + public static function fromEntity(Article $article): self + { + $resource = new self(); + $resource->id = $article->getId(); + $resource->title = $article->getTitle(); + + foreach ($article->getTranslations() as $translation) { + $dto = new ArticleTranslationDto(); + $dto->title = $translation->getTitle(); + $dto->locale = $translation->getLocale(); + $resource->translations[$dto->locale] = $dto; + } + + return $resource; + } +} +``` + +### Step 4: create the provider + +The provider calls API Platform's Doctrine providers, so pagination and +filters keep working. Then it maps each entity to the DTO: + +```php +// src/State/ArticleResourceProvider.php +namespace App\State; + +use ApiPlatform\Metadata\CollectionOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\State\Pagination\PaginatorInterface; +use ApiPlatform\State\Pagination\TraversablePaginator; +use ApiPlatform\State\ProviderInterface; +use App\ApiResource\ArticleResource; +use App\Entity\Article; +use Symfony\Component\DependencyInjection\Attribute\Autowire; + +final readonly class ArticleResourceProvider implements ProviderInterface +{ + public function __construct( + #[Autowire(service: 'api_platform.doctrine.orm.state.item_provider')] + private ProviderInterface $itemProvider, + #[Autowire(service: 'api_platform.doctrine.orm.state.collection_provider')] + private ProviderInterface $collectionProvider, + ) { + } + + public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null + { + if ($operation instanceof CollectionOperationInterface) { + $articles = $this->collectionProvider->provide($operation, $uriVariables, $context); + + $resources = []; + foreach ($articles as $article) { + $resources[] = ArticleResource::fromEntity($article); + } + + if ($articles instanceof PaginatorInterface) { + return new TraversablePaginator( + new \ArrayIterator($resources), + $articles->getCurrentPage(), + $articles->getItemsPerPage(), + $articles->getTotalItems(), + ); + } + + return $resources; + } + + $article = $this->itemProvider->provide($operation, $uriVariables, $context); + + return $article instanceof Article ? ArticleResource::fromEntity($article) : null; + } +} +``` + +### Step 5: create the processor + +For each submitted locale, the processor calls +`getOrCreateTranslation($locale)` on the managed entity. That method returns +the translation of exactly that locale, or creates and attaches a new one. +For PUT, the processor removes the locales that are not in the payload: + +```php +// src/State/ArticleResourceProcessor.php +namespace App\State; + +use ApiPlatform\Metadata\DeleteOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\State\ProcessorInterface; +use ApiPlatform\State\ProviderInterface; +use App\ApiResource\ArticleResource; +use App\Entity\Article; +use App\Entity\ArticleTranslation; +use Symfony\Component\DependencyInjection\Attribute\Autowire; + +final readonly class ArticleResourceProcessor implements ProcessorInterface +{ + public function __construct( + #[Autowire(service: 'api_platform.doctrine.orm.state.item_provider')] + private ProviderInterface $itemProvider, + #[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')] + private ProcessorInterface $persistProcessor, + #[Autowire(service: 'api_platform.doctrine.orm.state.remove_processor')] + private ProcessorInterface $removeProcessor, + ) { + } + + public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?ArticleResource + { + if ($operation instanceof DeleteOperationInterface) { + $article = $this->itemProvider->provide($operation, $uriVariables, $context); + $this->removeProcessor->process($article, $operation, $uriVariables, $context); + + return null; + } + + \assert($data instanceof ArticleResource); + + // A new entity for POST, the managed one for PATCH and PUT. + $article = [] === $uriVariables + ? new Article() + : $this->itemProvider->provide($operation, $uriVariables, $context); + + foreach ($data->translations as $locale => $translationDto) { + // Exact locale, no fallback: the existing row, or a new one. + $translation = $article->getOrCreateTranslation($locale); + \assert($translation instanceof ArticleTranslation); + + if (null !== $translationDto->title) { + $translation->setTitle($translationDto->title); + } + } + + // PUT is a full replace: remove the locales absent from the payload. + if ('PUT' === $operation->getMethod()) { + foreach ($article->getTranslationLocales() as $existingLocale) { + if (!isset($data->translations[$existingLocale])) { + $article->removeTranslationWithLocale($existingLocale); + } + } + } + + $article = $this->persistProcessor->process($article, $operation, $uriVariables, $context); + + return ArticleResource::fromEntity($article); + } +} +``` + +### Step 6: verify + +Do the checks in "Verify" below. + +## Rules + +- In the processor, always load the managed entity for PATCH and PUT, and + match translations by locale with `getOrCreateTranslation($locale)`. Never + build new translation entities for locales that already exist. +- Never write translations through the translated setter of the entity (for + example `setTitle()`). It writes into the request locale, not into the + submitted locale. +- PUT needs `extraProperties: ['standard_put' => false]` in this setup too. + With `standard_put` on, the request fails with "Given object is not an + instance of the class this property was declared in". + +## Verify + +The paths below assume the resource at `/articles`. Add the API prefix of +the project, for example `/api/articles`. + +1. POST a resource with `en` and `de` translations. The response must contain + both under `translations`. +2. `GET /articles/{id}?locale=de` must return the `de` title. A locale without + a translation must return the fallback title. +3. PATCH only `de`. The `de` translation row must keep its id (check it in the + database), and `en` must stay unchanged. +4. PUT only `en` (provider and processor variant). The `de` row must be gone. +5. `GET /articles` must return pages as before, and the translation filters + must work on the DTO class. diff --git a/skills/api-translation-dto/references/object-mapper.md b/skills/api-translation-dto/references/object-mapper.md new file mode 100644 index 0000000..6897ba5 --- /dev/null +++ b/skills/api-translation-dto/references/object-mapper.md @@ -0,0 +1,180 @@ +# Variant: Symfony Object Mapper + +Requirements: API Platform 4.2 or later, `symfony/object-mapper` 7.4 or later. +This variant has no provider and no processor. It also needs the two docblock +packages (step 1) and the `ArticleTranslationDto` class (step 2) from the main +file of this skill. + +```bash +composer require symfony/object-mapper +``` + +On an update, API Platform maps the submitted DTO onto the managed entity. It +gives that entity to the transformer as `$target`, so one transformer service +can match the translations by locale. + +## Step 1: create the resource class + +The translated `title` maps only from the entity to the DTO. If it mapped +back, it would go through the virtual setter of the entity and write into one +locale. + +```php +// src/ApiResource/ArticleResource.php +namespace App\ApiResource; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Patch; +use ApiPlatform\Metadata\Post; +use App\Entity\Article; +use App\State\ArticleTranslationsTransformer; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[ApiResource( + shortName: 'Article', + stateOptions: new Options(entityClass: Article::class), + operations: [ + new Get(), + new GetCollection(), + new Post(), + new Patch(), + new Delete(), + ], +)] +#[Map(source: Article::class)] +final class ArticleResource +{ + public ?int $id = null; + + /** + * Translated value in the requested (or fallback) locale. Mapped from the + * entity only: mapped back, it would go through the entity's virtual + * setter and write into a single locale. Writes go through `translations`. + */ + #[Map(if: [self::class, 'onlyFromEntity'])] + public ?string $title = null; + + /** + * All translations, keyed by locale. + * + * @var array + */ + #[Map(source: 'translations', transform: ArticleTranslationsTransformer::class)] + public array $translations = []; + + public static function onlyFromEntity(mixed $value, object $source): bool + { + return $source instanceof Article; + } +} +``` + +## Step 2: create the transformer + +In the write direction, the transformer must return the existing translations +plus the submitted ones. The Object Mapper applies the returned list to the +entity, so a list with only the submitted locales removes all other locales: + +```php +// src/State/ArticleTranslationsTransformer.php +namespace App\State; + +use App\ApiResource\ArticleResource; +use App\ApiResource\ArticleTranslationDto; +use App\Entity\Article; +use App\Entity\ArticleTranslation; +use Locastic\ApiPlatformTranslationBundle\Model\AbstractTranslatable; +use Symfony\Component\ObjectMapper\TransformCallableInterface; + +/** + * Maps the `translations` property in both directions: + * - entity to resource: translation entities to DTOs keyed by locale; + * - resource to entity: matches the submitted locales to the existing + * translations of the entity (update in place, create only new locales). + */ +final class ArticleTranslationsTransformer implements TransformCallableInterface +{ + public function __invoke(mixed $value, object $source, ?object $target): mixed + { + if ($source instanceof Article) { + return $this->toDtos($source); + } + + \assert($source instanceof ArticleResource); + + return $this->toTranslations($value, $target); + } + + /** + * @return array + */ + private function toDtos(Article $article): array + { + $dtos = []; + + foreach ($article->getTranslations() as $translation) { + $dto = new ArticleTranslationDto(); + $dto->title = $translation->getTitle(); + $dto->locale = $translation->getLocale(); + $dtos[$dto->locale] = $dto; + } + + return $dtos; + } + + /** + * Returns the complete set (existing plus submitted). The returned list + * is applied to the entity through addTranslation()/removeTranslation(), + * so a list with only the submitted locales would remove the others. + * + * @param array $value + * + * @return list + */ + private function toTranslations(array $value, ?object $target): array + { + $existing = []; + + // On POST the target is a new entity that was created without its + // constructor, so the translations collection is not initialized yet. + if ($target instanceof Article && $this->isInitialized($target)) { + foreach ($target->getTranslations() as $translation) { + $existing[(string) $translation->getLocale()] = $translation; + } + } + + foreach ($value as $locale => $dto) { + $translation = $existing[$locale] ?? null; + + if (null === $translation) { + $translation = new ArticleTranslation(); + $translation->setLocale($locale); + $existing[$locale] = $translation; + } + + if (null !== $dto->title) { + $translation->setTitle($dto->title); + } + } + + return array_values($existing); + } + + private function isInitialized(Article $article): bool + { + return (new \ReflectionProperty(AbstractTranslatable::class, 'translations')) + ->isInitialized($article); + } +} +``` + +## Operations + +GET, POST, PATCH and DELETE work with no other code. This variant has no PUT: +with `standard_put` on, the request fails, and with it off, this transformer +merges like PATCH and keeps the locales that are not in the payload. For a +full replace, use the provider and processor variant. diff --git a/skills/api-translation-filters/SKILL.md b/skills/api-translation-filters/SKILL.md new file mode 100644 index 0000000..4d1113e --- /dev/null +++ b/skills/api-translation-filters/SKILL.md @@ -0,0 +1,130 @@ +--- +name: api-translation-filters +description: Add search and sort by translated fields to an API Platform collection with TranslationSearchFilter and TranslationOrderFilter from locastic/api-platform-translation-bundle. Use when clients must filter or order a translatable resource by a field of its translation entity in the requested locale, for example ?title=cat or ?order[title]=asc, or when a filter on translations.title returns matches from other locales. +--- + +# Search and sort by translated fields + +The translated values are on the translation entity, not on the resource. The +bundle has two Doctrine ORM filters that use only the locale of the request +(`?locale=` or `Accept-Language`): + +- `TranslationSearchFilter` filters by a translated field. +- `TranslationOrderFilter` sorts by a translated field. + +Both filters are experimental. Do not use API Platform's core `SearchFilter` +or `OrderFilter` on `translations.title`: they match the values of every +locale. + +## Before you start + +The resource must be mapped as the skill `api-translation-resource` shows +(`mate-api-translation-resource` when Mate installed it): + +- `translations` is a `OneToMany` with `mappedBy: 'translatable'` and + `indexBy: 'locale'`. +- The translation entity has a `ManyToOne` `$translatable` with + `inversedBy: 'translations'`. +- The translation entity has a unique constraint on (`translatable_id`, + `locale`). + +The filters rely on one translation for each resource and locale. Without the +bidirectional mapping, the filters still work, but they use a slower join on +the `translations` association. + +## Procedure + +1. Add the filters to the resource class. Give the fields of the translation + entity by their bare name: `title`, not `translations.title`. + + ```php + use ApiPlatform\Metadata\ApiFilter; + use Locastic\ApiPlatformTranslationBundle\Doctrine\Orm\Filter\TranslationOrderFilter; + use Locastic\ApiPlatformTranslationBundle\Doctrine\Orm\Filter\TranslationSearchFilter; + + #[ApiResource] + #[ApiFilter(TranslationSearchFilter::class, properties: ['title' => 'ipartial'])] + #[ApiFilter(TranslationOrderFilter::class, properties: ['title'])] + class Article extends AbstractTranslatable + { + // ... + } + ``` + + If the API resource is a DTO class, put the `#[ApiFilter]` attributes on + the DTO class. + +2. Select the search strategy for each field: + + | Strategy | Matches | + |---|---| + | `exact` (the default) | the whole value. Several values (`?title[]=a&title[]=b`) become an `IN` clause. | + | `partial` | the value anywhere in the field | + | `start` | the start of the field | + | `end` | the end of the field | + | `word_start` | the start of any word in the field | + + Add the prefix `i` (for example `ipartial`) for a match that ignores case. + The filter matches `%` and `_` in a searched value as literal characters. + +3. For the order filter, give a default direction in `properties` if the + collection must be sorted when the request has no `order` parameter, for + example `properties: ['title' => 'DESC']`. To change the parameter name, + add `arguments: ['orderParameterName' => 'sort']`. + +4. Add indexes to the translation entity for large collections: + + ```php + #[ORM\Entity] + #[ORM\UniqueConstraint(columns: ['translatable_id', 'locale'])] + #[ORM\Index(columns: ['locale', 'title'])] + class ArticleTranslation extends AbstractTranslation + ``` + + - The index on (`locale`, field) serves `exact` and `start`. + - `partial`, `end`, `word_start` and every `i` strategy cannot use a plain + index. On PostgreSQL, use a `pg_trgm` index on `LOWER(title)`. + +5. Create the database migration the way the project does it. +6. Do the checks in "Verify" below. + +If you omit `properties`, the filter enables every field of the translation +entity, except its id and `locale`. Give the list of fields explicitly. + +## Service declaration + +To declare a filter in YAML or PHP service configuration instead of the +attribute, define a child service of one of these abstract services, pass +`$properties`, and tag it `api_platform.filter`: + +- `locastic_api_platform_translation.doctrine.orm.filter.translation_search` +- `locastic_api_platform_translation.doctrine.orm.filter.translation_order` + +Then add the service ID to the `filters` of the resource. + +## What the filters do not do + +- They do not use the fallback locale. A resource that has no `de` + translation does not match a `de` search by its fallback value. +- The order filter keeps resources that have no translation in the request + locale. The database puts them first or last (its null ordering). +- Sorting joins the translation of every resource in the filtered collection + before the page is cut. The cost grows with the size of the collection. + Measure it on real data before you allow sorting on a very large collection + without other filters. + +## Verify + +The paths below assume the resource at `/articles`. Add the API prefix of +the project, for example `/api/articles`. + +Create resources with `en` and `de` translations whose titles differ, for +example `Cat` / `Katze` and `Dog` / `Hund`. Then: + +1. `GET /articles?locale=de&title=katz` must return only the resource with + `Katze`. +2. `GET /articles?locale=en&title=katz` must return no resource. +3. `GET /articles?locale=de&order[title]=asc` must return `Hund` before + `Katze`. +4. `GET /articles?locale=de&title=katz&groups[]=translations` must return the + resource with all its translations, not only `de`. diff --git a/skills/api-translation-resource/SKILL.md b/skills/api-translation-resource/SKILL.md new file mode 100644 index 0000000..57affd5 --- /dev/null +++ b/skills/api-translation-resource/SKILL.md @@ -0,0 +1,272 @@ +--- +name: api-translation-resource +description: Create a translatable Doctrine entity for API Platform with locastic/api-platform-translation-bundle, or add a translated field to an existing one. Use when a resource needs text in more than one language, when a new field must have a different value for each locale, or when a translatable entity does not save or return its translations. +--- + +# Translatable resource + +A translatable resource is two Doctrine entities: + +- The **translatable** entity (for example `Article`) is the API resource. It + holds the fields that are the same in all locales, plus a `translations` + collection. +- The **translation** entity (for example `ArticleTranslation`) holds the + translated fields and a `locale`. The database has one row for each locale. + +The bundle resolves the locale of each request (`?locale=de` or +`Accept-Language`). The translatable entity shows the translated fields in that +locale through virtual getters. + +## Procedure: new translatable resource + +1. Make sure that `config/packages/api_platform_translation.yaml` exists and + sets `auto_create_translations: false`. Without this option, a read of a + missing locale attaches an empty translation, and the next flush can insert + it. To restrict locales, `framework.enabled_locales` is enough: the bundle + uses it when its own `enabled_locales` is empty. Set + `api_platform_translation.enabled_locales` only when the API must accept a + different list. + + ```yaml + api_platform_translation: + auto_create_translations: false + ``` + +2. Create the translation entity. Name it after the translatable entity plus + `Translation`. Extend `AbstractTranslation`. The base class defines the + `$translatable` and `$locale` properties. Declare them again only to add + the mapping attributes, and keep their names and `protected` visibility. + Select the column type of each translated field: `#[ORM\Column]` on a + string is `VARCHAR(255)`. For long text, use + `#[ORM\Column(type: Types::TEXT)]` (`Doctrine\DBAL\Types\Types`). + + ```php + use Doctrine\ORM\Mapping as ORM; + use Locastic\ApiPlatformTranslationBundle\Model\AbstractTranslation; + use Locastic\ApiPlatformTranslationBundle\Model\TranslatableInterface; + use Symfony\Component\Serializer\Attribute\Groups; + + #[ORM\Entity] + #[ORM\UniqueConstraint(columns: ['translatable_id', 'locale'])] + class ArticleTranslation extends AbstractTranslation + { + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + #[Groups(['translations'])] + private ?int $id = null; + + #[ORM\ManyToOne(targetEntity: Article::class, inversedBy: 'translations')] + protected ?TranslatableInterface $translatable = null; + + #[ORM\Column] + #[Groups(['article_read', 'article_write', 'translations'])] + private ?string $title = null; + + #[ORM\Column] + #[Groups(['article_write', 'translations'])] + protected ?string $locale = null; + + public function getId(): ?int + { + return $this->id; + } + + public function getTitle(): ?string + { + return $this->title; + } + + public function setTitle(string $title): void + { + $this->title = $title; + } + } + ``` + +3. Create the translatable entity, or change the existing entity. Extend + `AbstractTranslatable`. Map `translations` exactly as shown: + `mappedBy: 'translatable'`, `indexBy: 'locale'`, `cascade: ['persist']`, + `orphanRemoval: true`. Implement `createTranslation()`. + + ```php + use ApiPlatform\Metadata\ApiResource; + use ApiPlatform\Metadata\Get; + use ApiPlatform\Metadata\GetCollection; + use ApiPlatform\Metadata\Patch; + use ApiPlatform\Metadata\Post; + use ApiPlatform\Metadata\Put; + use Doctrine\Common\Collections\Collection; + use Doctrine\ORM\Mapping as ORM; + use Locastic\ApiPlatformTranslationBundle\Model\AbstractTranslatable; + use Locastic\ApiPlatformTranslationBundle\Model\TranslationInterface; + use Symfony\Component\Serializer\Attribute\Groups; + + #[ORM\Entity] + #[ApiResource( + operations: [ + new Get(), + new GetCollection(), + new Post(normalizationContext: ['groups' => ['translations']]), + new Patch(normalizationContext: ['groups' => ['translations']]), + new Put( + normalizationContext: ['groups' => ['translations']], + extraProperties: ['standard_put' => false], + ), + ], + normalizationContext: ['groups' => ['article_read']], + denormalizationContext: ['groups' => ['article_write']], + filters: ['translation.groups'], + )] + class Article extends AbstractTranslatable + { + #[ORM\Id] + #[ORM\GeneratedValue] + #[ORM\Column] + private ?int $id = null; + + #[ORM\OneToMany( + targetEntity: ArticleTranslation::class, + mappedBy: 'translatable', + fetch: 'EXTRA_LAZY', + indexBy: 'locale', + cascade: ['persist'], + orphanRemoval: true, + )] + #[Groups(['article_write', 'translations'])] + protected Collection $translations; + + public function getId(): ?int + { + return $this->id; + } + + #[Groups(['article_read'])] + public function getTitle(): ?string + { + return $this->getTranslation()->getTitle(); + } + + public function setTitle(string $title): void + { + $this->getOrCreateTranslation()->setTitle($title); + } + + protected function createTranslation(): TranslationInterface + { + return new ArticleTranslation(); + } + } + ``` + +4. Check the serialization groups. They decide what the API reads and writes: + + | Where | Groups | + |---|---| + | `translations` collection | the write group, `translations` | + | each translated field on the translation entity | the read group, the write group, `translations` | + | `locale` on the translation entity | the write group, `translations` | + | `id` on the translation entity | `translations` | + | virtual getter on the translatable entity | the read group | + | field on the translatable entity that is the same in all locales (for example `name`) | the read group, the write group, `translations` | + +5. Add `'groups' => ['translations']` to the `normalizationContext` of POST, + PUT and PATCH. Then a write returns all translations. A field that has + only the read group does not appear in write responses. For this reason, + the table above gives the `translations` group to the fields that are the + same in all locales. +6. Add validation. Put `#[Assert\Valid]` on the `translations` collection, + and constraints such as `#[Assert\NotBlank]` on the translated fields. + Without `#[Assert\Valid]`, API Platform does not validate the + translations, and a missing value fails in the database with HTTP 500, not + with HTTP 422. +7. Keep `filters: ['translation.groups']` on the resource. Then a client can + request all translations with `?groups[]=translations`. +8. Keep `extraProperties: ['standard_put' => false]` on PUT, or remove the PUT + operation. With `standard_put` on, a PUT fails with a `LogicException`. +9. Create the database migration the way the project does it (for example + `bin/console make:migration`). Do the next step only after the schema is + up to date. +10. Do the checks in "Verify" below. + +## Procedure: add a translated field + +A translated field needs five members in two classes: + +1. On the translation entity: the property with `#[ORM\Column]` (select the + column type as in step 2), the groups from step 4, the validation from + step 6, a getter, and a setter. +2. On the translatable entity: a virtual getter with the read group, which + calls `$this->getTranslation()->getX()`. +3. On the translatable entity: a virtual setter, which calls + `$this->getOrCreateTranslation()->setX($value)`. +4. Create the database migration. A new column on existing rows must be + nullable or have a default. +5. Do the checks in "Verify" below. + +To move an existing field into the translations, write the migration in +this order: add the column to the translation table, write the old values +into the translation of the default locale (insert that row where a resource +has none), then remove the old column. + +## Rules + +- Getters call `getTranslation()`. It returns the translation of the request + locale, or of the fallback locale when the request locale has none. The + fallback locale is `api_platform_translation.fallback_locale`, or + `framework.default_locale` when that option is empty. +- Setters call `getOrCreateTranslation()`. It returns the translation of the + exact locale and creates it when it is missing. Never call + `getTranslation()` in a setter: it can return the fallback translation, and + the setter then changes the wrong locale. +- Use PHP attributes. Do not use Doctrine annotations. +- Keep the translations embedded in the resource. Do not make the translation + entity a separate API resource: the bundle matches submitted translations + to their rows by locale only when they are embedded objects, not IRIs. +- The unique constraint on (`translatable_id`, `locale`) keeps one + translation for each resource and locale. The translation filters rely on + it. + +## Verify + +The paths below assume the resource at `/articles`. Add the API prefix of +the project, for example `/api/articles`. + +1. Run `bin/console doctrine:schema:validate`. The mapping section must be + correct. +2. Create a resource with two locales: + + ```http + POST /articles + Content-Type: application/ld+json + + {"translations": {"en": {"title": "Cat", "locale": "en"}, "de": {"title": "Katze", "locale": "de"}}} + ``` + + The response must contain both entries under `translations`, each with an + `id`. +3. `GET /articles/{id}?locale=de` must return `"title": "Katze"`. +4. Select a locale that the project accepts but that the resource has no + translation for, for example `fr`. If `enabled_locales` is set, the locale + must be in that list: the bundle replaces a locale outside the list with + the default locale, and the fallback is then not tested. + `GET /articles/{id}?locale=fr` must return the title of the fallback + locale, and the database must still have two translation rows for the + resource. +5. `GET /articles/{id}?groups[]=translations` must return all translations. +6. Edit one locale: + + ```http + PATCH /articles/{id} + Content-Type: application/merge-patch+json + + {"translations": {"de": {"title": "Kater", "locale": "de"}}} + ``` + + The `de` translation must keep its `id`, and the `en` translation must stay + unchanged. + +For more about POST, PATCH and PUT payloads, load the skill +`api-translation-writes`. To search or sort by a translated field, load the +skill `api-translation-filters`. When Mate installed the skills, their names +start with `mate-`, for example `mate-api-translation-writes`. diff --git a/skills/api-translation-writes/SKILL.md b/skills/api-translation-writes/SKILL.md new file mode 100644 index 0000000..b2f70b7 --- /dev/null +++ b/skills/api-translation-writes/SKILL.md @@ -0,0 +1,121 @@ +--- +name: api-translation-writes +description: Send translations of a translatable API Platform resource through HTTP with locastic/api-platform-translation-bundle - create with POST, edit some locales with PATCH, replace all with PUT - and read one or all locales. Use when you write client code, API tests, HTTP fixtures or API documentation for a translatable resource, or when a PUT fails, removes translations or creates duplicate translation rows. +--- + +# Write and read translations through the API + +The resource embeds its translations as an object keyed by locale. The bundle +matches each submitted locale to the existing translation row of that locale +and updates the row in place. The row keeps its `id`. + +The examples assume the resource at `/articles`. Add the API prefix of the +project, for example `/api/articles`. + +## Payload shape + +`translations` is an object keyed by locale. Each entry repeats its `locale` +field: + +```json +{ + "translations": { + "en": {"title": "Cat", "locale": "en"}, + "de": {"title": "Katze", "locale": "de"} + } +} +``` + +- Do not send `translations` as a list of IRIs or mix IRIs and objects. The + bundle matches only embedded objects. API Platform handles other shapes, + without the match by locale. +- Fields that are the same in all locales go next to `translations`, at the + top level. + +## Create: POST + +```http +POST /articles +Content-Type: application/ld+json + +{"translations": {"en": {"title": "Cat", "locale": "en"}, "de": {"title": "Katze", "locale": "de"}}} +``` + +## Edit some locales: PATCH (recommended) + +PATCH updates the submitted locales and keeps all other locales unchanged. It +needs no `id`. + +```http +PATCH /articles/1 +Content-Type: application/merge-patch+json + +{"translations": {"de": {"title": "Kater", "locale": "de"}}} +``` + +- A locale that the resource does not have yet is created. +- Use the content type `application/merge-patch+json`. + +## Replace all: PUT + +PUT is a full replace. The bundle removes every locale that is not in the +payload. Send the `id` of each existing translation: + +```http +PUT /articles/1 +Content-Type: application/ld+json + +{"translations": {"en": {"id": 2, "title": "Cat", "locale": "en"}, "de": {"id": 3, "title": "Kater", "locale": "de"}}} +``` + +PUT works only when API Platform's `standard_put` is off for the operation: + +```php +new Put(extraProperties: ['standard_put' => false]) +``` + +or for the whole API: + +```yaml +api_platform: + defaults: + extra_properties: + standard_put: false +``` + +With `standard_put` on, the request fails with HTTP 500. The bundle throws a +`LogicException` whose message starts with "PUT operations on translatable +resources require standard_put to be disabled" (the response shows it in +debug mode). Turn `standard_put` off, or use PATCH. + +To remove one locale, send a PUT without that locale. + +## Read + +- One locale: `GET /articles/1?locale=de`, or the header + `Accept-Language: de`. The translated fields show the `de` values. When the + resource has no `de` translation, they show the values of the fallback + locale. +- All locales: `GET /articles/1?groups[]=translations`. This needs + `filters: ['translation.groups']` on the resource. +- If the project sets `enabled_locales` (in `framework` or in + `api_platform_translation`), a locale that is not in the list falls back to + the default locale. +- A write returns all translations only when the operation has + `'groups' => ['translations']` in its `normalizationContext`. + +## Rules + +- Prefer PATCH for edits. Use PUT only when the client sends the complete + resource and wants the missing locales removed. +- Never send a PUT with only the changed locale. PUT removes all other + locales. + +## Verify + +After a write, read the resource with `?groups[]=translations` and check: + +1. Every submitted locale has the submitted values. +2. An updated locale keeps its `id`. +3. After PATCH, the locales that were not in the payload are unchanged. +4. After PUT, only the locales in the payload remain. diff --git a/tests/AgentFilesTest.php b/tests/AgentFilesTest.php new file mode 100644 index 0000000..2b3099a --- /dev/null +++ b/tests/AgentFilesTest.php @@ -0,0 +1,156 @@ +assertFileExists(self::ROOT.'/'.$aiMate['instructions']); + $this->assertNotEmpty($aiMate['skills']); + + foreach ($aiMate['skills'] as $directory) { + $this->assertDirectoryExists(self::ROOT.'/'.$directory); + } + } + + #[DataProvider('provideSkills')] + public function testSkillHasValidFrontMatter(string $directory): void + { + $frontMatter = self::frontMatter($directory.'/SKILL.md'); + $name = $frontMatter['name'] ?? ''; + $description = $frontMatter['description'] ?? ''; + + $this->assertSame(basename($directory), $name, 'The skill name must match its directory.'); + $this->assertMatchesRegularExpression('/^[a-z0-9]+(-[a-z0-9]+)*$/', $name); + $this->assertLessThanOrEqual(64, \strlen($name)); + $this->assertNotSame('', $description); + $this->assertLessThanOrEqual(1024, \strlen($description)); + } + + #[DataProvider('provideSkills')] + public function testSkillLinksStayInsideTheSkill(string $directory): void + { + $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS)); + $skillRoot = (string) realpath($directory); + $badLinks = []; + + foreach ($files as $file) { + if ('md' !== $file->getExtension()) { + continue; + } + + preg_match_all('/\]\(([^)#\s]+)(?:#[^)]*)?\)/', (string) file_get_contents($file->getPathname()), $matches); + + foreach ($matches[1] as $link) { + if (preg_match('#^[a-z]+://#i', $link)) { + continue; + } + + // Mate copies each skill directory alone, so a link must + // resolve to a file inside it. + $target = realpath($file->getPath().'/'.$link); + if (false === $target || !str_starts_with($target, $skillRoot.'/')) { + $badLinks[] = $file->getFilename().': '.$link; + } + } + } + + $this->assertSame([], $badLinks); + } + + public function testInstructionsListEverySkill(): void + { + $instructions = (string) file_get_contents(self::ROOT.'/'.self::aiMateConfig()['instructions']); + + preg_match_all('/`(api-translation-[a-z-]+)`/', $instructions, $matches); + $listed = array_values(array_unique($matches[1])); + sort($listed); + + $shipped = array_map('basename', array_column(self::provideSkills(), 0)); + sort($shipped); + + $this->assertSame($shipped, $listed); + } + + /** + * INSTRUCTIONS.md stays short (Mate merges it into every project's agent + * instructions), so it repeats only some rules, word for word. + */ + public function testInstructionsRulesAreContext7Rules(): void + { + $context7 = json_decode((string) file_get_contents(self::ROOT.'/context7.json'), true, 512, \JSON_THROW_ON_ERROR); + $instructions = (string) file_get_contents(self::ROOT.'/'.self::aiMateConfig()['instructions']); + + $this->assertSame(1, preg_match('/^### Rules\n\n((?:- .+\n)+)/m', $instructions, $matches), 'INSTRUCTIONS.md needs a "### Rules" list.'); + + $rules = array_map( + static fn (string $line): string => substr($line, 2), + explode("\n", rtrim($matches[1])), + ); + + $this->assertSame([], array_values(array_diff($rules, $context7['rules'])), 'Each rule in INSTRUCTIONS.md must be a context7.json rule, word for word.'); + } + + /** + * @return array + */ + public static function provideSkills(): array + { + $skills = []; + + foreach (self::aiMateConfig()['skills'] as $skillsDirectory) { + foreach (glob(self::ROOT.'/'.$skillsDirectory.'/*', \GLOB_ONLYDIR) ?: [] as $directory) { + $skills[basename($directory)] = [$directory]; + } + } + + return $skills; + } + + /** + * @return array{instructions: string, skills: list} + */ + private static function aiMateConfig(): array + { + $composer = json_decode((string) file_get_contents(self::ROOT.'/composer.json'), true, 512, \JSON_THROW_ON_ERROR); + + return $composer['extra']['ai-mate']; + } + + /** + * Reads the single-line `key: value` pairs of a Markdown front matter. + * + * @return array + */ + private static function frontMatter(string $file): array + { + $content = (string) file_get_contents($file); + + if (1 !== preg_match('/\A---\n(.*?)\n---\n/s', $content, $matches)) { + return []; + } + + $values = []; + foreach (explode("\n", $matches[1]) as $line) { + if (1 === preg_match('/^([a-z-]+):\s*(.+)$/', $line, $pair)) { + $values[$pair[1]] = trim($pair[2]); + } + } + + return $values; + } +}