Skip to content

feat: add support for Symfony's TranslatableInterface #2472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 24, 2025
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# CHANGELOG

## 5.3.0
Added support for Symfony's `TranslatableInterface`

## 5.2.1
Fixed a bug where using abstract controllers would ignore various attributes like ``#[OA\Tag]`` & ``#[Security]`` on child classes

Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"symfony/serializer": "^6.4 || ^7.1",
"symfony/stopwatch": "^6.4 || ^7.1",
"symfony/templating": "^6.4 || ^7.1",
"symfony/translation": "^6.4 || ^7.1",
"symfony/twig-bundle": "^6.4 || ^7.1",
"symfony/uid": "^6.4 || ^7.1",
"symfony/validator": "^6.4 || ^7.1",
Expand Down
4 changes: 4 additions & 0 deletions config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@
<tag name="nelmio_api_doc.object_model.property_describer" />
</service>

<service id="nelmio_api_doc.object_model.property_describers.translatable" class="Nelmio\ApiDocBundle\PropertyDescriber\TranslatablePropertyDescriber" public="false">
<tag name="nelmio_api_doc.object_model.property_describer" />
</service>

<!-- Form Type Extensions -->

<service id="nelmio_api_doc.form.documentation_extension" class="Nelmio\ApiDocBundle\Form\Extension\DocumentationExtension">
Expand Down
4 changes: 0 additions & 4 deletions src/DependencyInjection/NelmioApiDocExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,6 @@ public function load(array $configs, ContainerBuilder $container): void
$container->registerForAutoconfiguration(ModelDescriberInterface::class)
->addTag('nelmio_api_doc.model_describer');

if (!class_exists(\Symfony\Component\Uid\AbstractUid::class)) {
$container->removeDefinition('nelmio_api_doc.object_model.property_describers.uuid');
}

// Import services needed for each library
$loader->load('php_doc.xml');

Expand Down
34 changes: 34 additions & 0 deletions src/PropertyDescriber/TranslatablePropertyDescriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the NelmioApiDocBundle package.
*
* (c) Nelmio
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Nelmio\ApiDocBundle\PropertyDescriber;

use OpenApi\Annotations as OA;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Contracts\Translation\TranslatableInterface;

final class TranslatablePropertyDescriber implements PropertyDescriberInterface
{
/**
* @param array<string, mixed> $context Context options for describing the property
*/
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'string';
}

public function supports(array $types, array $context = []): bool
{
return 1 === \count($types)
&& Type::BUILTIN_TYPE_OBJECT === $types[0]->getBuiltinType()
&& is_a($types[0]->getClassName(), TranslatableInterface::class, true);
}
}
7 changes: 7 additions & 0 deletions src/TypeDescriber/ClassDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\ObjectType;
use Symfony\Component\Uid\AbstractUid;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
* @implements TypeDescriberInterface<ObjectType>
Expand All @@ -47,6 +48,12 @@ public function describe(Type $type, Schema $schema, array $context = []): void
return;
}

if (is_a($type->getClassName(), TranslatableInterface::class, true)) {
$schema->type = 'string';

return;
}

// Ensure that the schema gets describe in oneOf for nullable objects
if (true === $schema->nullable) {
$weakContext = Util::createWeakContext($schema->_context);
Expand Down
13 changes: 13 additions & 0 deletions tests/Functional/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Nelmio\ApiDocBundle\Tests\Functional\Entity\EntityWithNullableSchemaSet;
use Nelmio\ApiDocBundle\Tests\Functional\Entity\EntityWithObjectType;
use Nelmio\ApiDocBundle\Tests\Functional\Entity\EntityWithRef;
use Nelmio\ApiDocBundle\Tests\Functional\Entity\EntityWithTranslatable;
use Nelmio\ApiDocBundle\Tests\Functional\Entity\EntityWithUuid;
use Nelmio\ApiDocBundle\Tests\Functional\Entity\RangeInteger;
use Nelmio\ApiDocBundle\Tests\Functional\Entity\SymfonyConstraints;
Expand Down Expand Up @@ -352,6 +353,18 @@ public function entityWithUuid()
{
}

#[Route('/entity-with-translatable', methods: ['GET', 'POST'])]
#[OA\Response(
response: 200,
description: 'success',
content: new OA\JsonContent(
ref: new Model(type: EntityWithTranslatable::class),
),
)]
public function entityWithTranslatable()
{
}

#[Route('/form-with-alternate-type', methods: ['POST'])]
#[OA\Response(
response: 204,
Expand Down
27 changes: 27 additions & 0 deletions tests/Functional/Entity/EntityWithTranslatable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

/*
* This file is part of the NelmioApiDocBundle package.
*
* (c) Nelmio
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Nelmio\ApiDocBundle\Tests\Functional\Entity;

use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;

class EntityWithTranslatable
{
public TranslatableInterface $translatable;
public TranslatableMessage $translatableMessage;

public function __construct(TranslatableInterface $translatable, TranslatableMessage $translatableMessage)
{
$this->translatable = $translatable;
$this->translatableMessage = $translatableMessage;
}
}
17 changes: 17 additions & 0 deletions tests/Functional/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,23 @@ public function testEntityWithUuid(): void
], json_decode($this->getModel('EntityWithUuid')->toJson(), true));
}

public function testEntityWithTranslatable(): void
{
self::assertEquals([
'schema' => 'EntityWithTranslatable',
'type' => 'object',
'required' => ['translatable', 'translatableMessage'],
'properties' => [
'translatable' => [
'type' => 'string',
],
'translatableMessage' => [
'type' => 'string',
],
],
], json_decode($this->getModel('EntityWithTranslatable')->toJson(), true));
}

public function testEntityWithIgnoredProperty(): void
{
self::assertEquals([
Expand Down
23 changes: 23 additions & 0 deletions tests/Functional/ModelDescriber/Fixtures/TranslatedInvoice.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"required": [
"id",
"title",
"description",
"type"
],
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"type": {
"type": "string"
}
},
"type": "object"
}
43 changes: 43 additions & 0 deletions tests/Functional/ModelDescriber/Fixtures/TranslatedInvoice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Nelmio\ApiDocBundle\Tests\Functional\ModelDescriber\Fixtures;

use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

enum InvoiceType: string implements TranslatableInterface
{
case INVOICE = 'invoice';
case CREDIT_NOTE = 'credit_note';

public function trans(TranslatorInterface $translator, ?string $locale = null): string
{
return 'invoice.type.'.$this->value;
}
}

final class TranslatableTitle implements TranslatableInterface
{
private string $title;

public function __construct(string $title)
{
$this->title = $title;
}

public function trans(TranslatorInterface $translator, ?string $locale = null): string
{
return $translator->trans('invoice.title.'.$this->title, [], 'messages', $locale);
}
}

final class TranslatedInvoice
{
public int $id;

public TranslatableTitle $title;

public string $description;

public InvoiceType $type;
}
62 changes: 62 additions & 0 deletions tests/PropertyDescriber/TranslatablePropertyDescriberTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

/*
* This file is part of the NelmioApiDocBundle package.
*
* (c) Nelmio
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Nelmio\ApiDocBundle\Tests\PropertyDescriber;

use Nelmio\ApiDocBundle\PropertyDescriber\TranslatablePropertyDescriber;
use PHPUnit\Framework\TestCase;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Contracts\Translation\TranslatableInterface;

class TranslatablePropertyDescriberTest extends TestCase
{
public function testSupportsTranslatablePropertyType(): void
{
$type = new Type(Type::BUILTIN_TYPE_OBJECT, false, TranslatableInterface::class);

$describer = new TranslatablePropertyDescriber();

self::assertTrue($describer->supports([$type]));
}

public function testSupportsNoIntPropertyType(): void
{
$type = new Type(Type::BUILTIN_TYPE_INT, false);

$describer = new TranslatablePropertyDescriber();

self::assertFalse($describer->supports([$type]));
}

public function testSupportsNoDifferentObjectPropertyType(): void
{
$type = new Type(Type::BUILTIN_TYPE_OBJECT, false, \DateTimeInterface::class);

$describer = new TranslatablePropertyDescriber();

self::assertFalse($describer->supports([$type]));
}

public function testDescribeTranslatablePropertyType(): void
{
$property = $this->initProperty();

$describer = new TranslatablePropertyDescriber();
$describer->describe([], $property, []);

self::assertSame('string', $property->type);
}

private function initProperty(): \OpenApi\Annotations\Property
{
return new \OpenApi\Attributes\Property(); // union types, used in schema attribute require PHP >= 8.0.0
}
}