Skip to content

Instantly share code, notes, and snippets.

@TimoBakx
Created March 10, 2020 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TimoBakx/f66947e88f9ebffe9e475029ced38471 to your computer and use it in GitHub Desktop.
Save TimoBakx/f66947e88f9ebffe9e475029ced38471 to your computer and use it in GitHub Desktop.
Add a dynamic property to API Platform documentation
<?php
declare(strict_types=1);
namespace App\Api;
use ArrayObject;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class Documentation implements NormalizerInterface
{
/**
* @var NormalizerInterface
*/
private $decorated;
public function __construct(NormalizerInterface $decorated)
{
$this->decorated = $decorated;
}
public function supportsNormalization($data, string $format = null): bool
{
return $this->decorated->supportsNormalization($data, $format);
}
public function normalize($object, string $format = null, array $context = [])
{
/** @var ArrayObject[] $docs */
$docs = $this->decorated->normalize($object, $format, $context);
// Use your object shorthand instead of MyObject and the dynamic property name instead of myDynamicProperty
$docs['definitions']['MyObject']['properties']['myDynamicProperty'] = [
'type' => 'string',
'example' => 'Example code here',
];
return $docs;
}
}
services:
_defaults:
autowire: true
autoconfigure: true
App\Api\Documentation:
decorates: 'api_platform.swagger.normalizer.api_gateway'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment