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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added
- Locale-constrained Doctrine ORM filters (experimental):
`TranslationSearchFilter` and `TranslationOrderFilter` search and order
collections by translated fields in the locale resolved from the request,
e.g. `?locale=de&title=foo&order[title]=asc` (#24, #47, #57)

## [2.1.0] - 2026-11-03

See [UPGRADE-2.1.md](UPGRADE-2.1.md) for upgrade instructions.
Expand Down
80 changes: 72 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,14 +356,78 @@ existing translation so it is updated instead of replaced:
}
```

Limitations:
------------

- **Filtering and ordering by translated fields is not supported.** The
translated values live on the translation entity and are exposed through
virtual getters, so built-in API Platform filters (`SearchFilter`,
`OrderFilter`, ...) cannot target them on the resource. Filtering on
translation fields requires a custom filter joining the translation entity.
### Filter and order by translated fields

Translated values live on the translation entity, so built-in API Platform
filters cannot target them on the resource (a core `SearchFilter` on
`translations.title` works, but matches against **every** locale). The bundle
ships two experimental Doctrine ORM filters that are constrained to the
locale resolved from the request. Declare the translation entity's fields 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
{
// ...
}
```

```
GET /articles?locale=de&title=katze searches the de title only
GET /articles?locale=de&order[title]=asc orders by the de title
```

- `TranslationSearchFilter` supports the same strategies as the core
`SearchFilter`: `exact` (the default), `partial`, `start`, `end` and
`word_start`, each optionally prefixed with `i` for case-insensitive
matching. Multiple values for an `exact` property
(`?title[]=foo&title[]=bar`) become an `IN` clause. The `LIKE` wildcards
`%` and `_` in a searched value are matched literally.
- `TranslationOrderFilter` accepts `?order[title]=asc|desc`. A direction
configured in `properties` (e.g. `['title' => 'DESC']`) is the default
applied when the query parameter gives none; the parameter name is
customizable with `arguments: ['orderParameterName' => ...]`. Resources
without a translation in the current locale stay in the collection, ordered
by the database's null ordering.
- Omitting `properties` enables every field of the translation entity (except
its id and `locale`).
- Both filters match the resolved locale only: fallback-locale values are not
considered, so a resource whose `de` translation is missing does not match a
`de` search by its fallback value.

On large collections, index what you filter by on the translation entity:

```php
#[ORM\Entity]
#[ORM\Index(columns: ['locale', 'title'])]
class ArticleTranslation extends AbstractTranslation
{
// ...
}
```

- An index on `locale` plus the field serves the `exact` and `start`
strategies.
- `partial`, `end` and `word_start` start with a wildcard and the `i` variants
wrap the column in `LOWER()`, so a plain index cannot serve them; use what
your database offers for text search (on PostgreSQL, a `pg_trgm` index on
`LOWER(title)`).
- Ordering by a translated field sorts the whole filtered collection before
the page is cut, and no index avoids that. Measure it on realistic data
before you expose it on a large, unfiltered collection.

For service-based declaration (YAML/XML instead of the attribute), define a
child service of the abstract parent
`locastic_api_platform_translation.doctrine.orm.filter.translation_search` or
`locastic_api_platform_translation.doctrine.orm.filter.translation_order`,
pass `$properties`, and tag it `api_platform.filter`.

## Contribution

Expand Down
29 changes: 27 additions & 2 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use Locastic\ApiPlatformTranslationBundle\Doctrine\Orm\Extension\TranslationsEagerLoadingExtension;
use Locastic\ApiPlatformTranslationBundle\Doctrine\Orm\Filter\TranslationOrderFilter;
use Locastic\ApiPlatformTranslationBundle\Doctrine\Orm\Filter\TranslationSearchFilter;
use Locastic\ApiPlatformTranslationBundle\EventListener\AssignLocaleListener;
use Locastic\ApiPlatformTranslationBundle\Serializer\TranslatableItemDenormalizer;
use Locastic\ApiPlatformTranslationBundle\Translation\Translator;
Expand Down Expand Up @@ -39,8 +41,9 @@

$services->alias(TranslatableItemDenormalizer::class, 'locastic_api_platform_translation.serializer.translatable_denormalizer');

// Doctrine ORM: eager loading of translations (the interface lives in
// api-platform/doctrine-orm, which api-platform/symfony does not require)
// Doctrine ORM: eager loading and locale-constrained filters (the base
// classes live in api-platform/doctrine-orm, which api-platform/symfony
// does not require)
if (interface_exists(QueryCollectionExtensionInterface::class)) {
$services->set('locastic_api_platform_translation.doctrine.orm.query_extension.translations_eager_loading', TranslationsEagerLoadingExtension::class)
->args([
Expand All @@ -50,6 +53,28 @@
->tag('api_platform.doctrine.orm.query_extension.item', ['priority' => -8]);

$services->alias(TranslationsEagerLoadingExtension::class, 'locastic_api_platform_translation.doctrine.orm.query_extension.translations_eager_loading');

// Abstract parents the #[ApiFilter] attribute and user-defined filter
// services build upon; children carry the api_platform.filter tag.
$services->set('locastic_api_platform_translation.doctrine.orm.filter.translation_search', TranslationSearchFilter::class)
->abstract()
->args([
service('locastic_api_platform_translation.translation.translator'),
service('doctrine'),
service('logger')->ignoreOnInvalid(),
]);

$services->alias(TranslationSearchFilter::class, 'locastic_api_platform_translation.doctrine.orm.filter.translation_search');

$services->set('locastic_api_platform_translation.doctrine.orm.filter.translation_order', TranslationOrderFilter::class)
->abstract()
->args([
service('locastic_api_platform_translation.translation.translator'),
service('doctrine'),
service('logger')->ignoreOnInvalid(),
]);

$services->alias(TranslationOrderFilter::class, 'locastic_api_platform_translation.doctrine.orm.filter.translation_order');
}

// Filters
Expand Down
1 change: 1 addition & 0 deletions context7.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"PUT requires API Platform's standard_put to be disabled, either per operation via extraProperties: ['standard_put' => false] or globally under api_platform.defaults.extra_properties.",
"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.",
"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."
],
Expand Down
140 changes: 140 additions & 0 deletions src/Doctrine/Orm/Filter/AbstractTranslationFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?php

declare(strict_types=1);

namespace Locastic\ApiPlatformTranslationBundle\Doctrine\Orm\Filter;

use ApiPlatform\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Locastic\ApiPlatformTranslationBundle\Model\TranslatableInterface;
use Locastic\ApiPlatformTranslationBundle\Translation\Translator;
use Psr\Log\LoggerInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

/**
* Base of the filters working on translated fields: fields that live on the
* translation entity, addressed by their bare name (`title`, not
* `translations.title`) and constrained to the translation row of the locale
* resolved from the request.
*
* @experimental
*/
abstract class AbstractTranslationFilter extends AbstractFilter
{
/**
* @param array<string, mixed>|null $properties
*/
public function __construct(
protected readonly Translator $translator,
ManagerRegistry $managerRegistry,
?LoggerInterface $logger = null,
?array $properties = null,
?NameConverterInterface $nameConverter = null,
) {
parent::__construct($managerRegistry, $logger, $properties, $nameConverter);
}

/**
* The configured properties that are fields of the resource's translation
* entity; when no properties are configured, every translated field is
* enabled.
*
* @return array<string, mixed> property name to its configured options
*/
protected function getTranslatedProperties(string $resourceClass): array
{
$metadata = $this->getTranslationMetadata($resourceClass);
if (null === $metadata) {
return [];
}

$properties = $this->properties ?? array_fill_keys($metadata->getFieldNames(), null);

return array_filter(
$properties,
fn (string $property): bool => $this->isTranslatedField($property, $resourceClass),
\ARRAY_FILTER_USE_KEY,
);
}

/**
* Whether the property is a field of the resource's translation entity,
* excluding its identifier and the `locale` discriminator the filters
* already constrain.
*/
protected function isTranslatedField(string $property, string $resourceClass): bool
{
$metadata = $this->getTranslationMetadata($resourceClass);

return null !== $metadata
&& 'locale' !== $property
&& !\in_array($property, $metadata->getIdentifierFieldNames(), true)
&& $metadata->hasField($property);
}

/**
* Left-joins the translations of the resolved request locale and returns
* the join alias, reusing the join when another translation filter already
* added it to the query. The join is constrained and never selected: the
* eager-loading extension knows to leave conditioned joins alone, so the
* hydrated collections stay complete.
*/
protected function joinCurrentLocaleTranslations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $rootAlias): string
{
$locale = $this->translator->loadCurrentLocale();

/** @var array<string, Join[]> $joinParts */
$joinParts = $queryBuilder->getDQLPart('join');
foreach ($joinParts[$rootAlias] ?? [] as $join) {
$alias = $join->getAlias();
$condition = $join->getCondition();
if (\sprintf('%s.translations', $rootAlias) !== $join->getJoin()
|| Join::LEFT_JOIN !== $join->getJoinType()
|| null === $alias
|| null === $condition
) {
continue;
}

if (1 === preg_match('/^'.preg_quote($alias, '/').'\.locale = :(\w+)$/', (string) $condition, $matches)
&& $locale === $queryBuilder->getParameter($matches[1])?->getValue()
) {
return $alias;
}
}

$joinAlias = $queryNameGenerator->generateJoinAlias('translations');
$parameterName = $queryNameGenerator->generateParameterName('locale');
$queryBuilder
->leftJoin(\sprintf('%s.translations', $rootAlias), $joinAlias, Join::WITH, \sprintf('%s.locale = :%s', $joinAlias, $parameterName))
->setParameter($parameterName, $locale);

return $joinAlias;
}

/**
* @return ClassMetadata<object>|null
*/
private function getTranslationMetadata(string $resourceClass): ?ClassMetadata
{
if (!is_a($resourceClass, TranslatableInterface::class, true)) {
return null;
}

$manager = $this->managerRegistry?->getManagerForClass($resourceClass);
if (null === $manager) {
return null;
}

$metadata = $manager->getClassMetadata($resourceClass);
if (!$metadata->hasAssociation('translations')) {
return null;
}

return $manager->getClassMetadata($metadata->getAssociationTargetClass('translations'));
}
}
Loading
Loading