Conditionally displaying specific routes on OpenAPI (aka Swagger) documentation generated by API-Platform - symfony

I wish to limit the routes displayed by the API-Platform generated OpenAPI documentation based on each route's security attribute and the logged on user's roles (i.e. only ROLE_ADMIN can see the OpenApi documentation).
A similar question was earlier asked and this answer partially answered it but not completely:
This isn't supported out of the box (but it would be a nice
contribution). What you can do is to decorate the
DocumentationNormalizer to unset() the paths you don't want to appear
in the OpenAPI documentation.
More information:
https://api-platform.com/docs/core/swagger/#overriding-the-openapi-specification
It appears that DocumentationNormalizer is depreciated and that one should decorate OpenApiFactoryInterface instead.
Attempting to implement, I configured config/services.yaml to decorate OpenApiFactory as shown below.
The first issue is I am unable to "unset() the paths you don't want to appear". The paths exist within the \ApiPlatform\Core\OpenApi\Model\Paths property of \ApiPlatform\Core\OpenApi\OpenApi, but there is only the ability to add additional paths to Paths and not remove them. I've come up with a solution which is shown in the below code which creates new objects and only adds back properties if they do not require admin access, but I suspect that doing so is not the "right way" to do this. Also, I just realized while it removed the documentation from SwaggerUI's routes, it did not remove it from the Schema displayed below the routes.
The second issue is how to determine which paths to display, and I temporarily hardcoded them in my getRemovedPaths() method. First, I will need to add a logon form to the SwaggerUi page so that we know the user's role which is fairly straightforward. Next, however, I will need to obtain the security attributes associated with each route so that I could determine whether a given route should be displayed, however, I have no idea how to do so. I expected the necessary data to be in each ApiPlatform\Core\OpenApi\Model\PathItem, however, there does not appear to be any methods to retrieve it and the properties are private. I also attempted to access the information by using \App\Kernel::getContainer()->get('router'), but was not successful locating the route security attributes.
In summary, how should one prevent routes from being displayed by the API-Platform generated OpenAPI documentation if the user does not have authority to access the route?
config/services.yaml
services:
App\OpenApi\OpenApiFactory:
decorates: 'api_platform.openapi.factory'
arguments: [ '#App\OpenApi\OpenApiFactory.inner' ]
autoconfigure: false
App/OpenApi/OpenApiFactory
<?php
namespace App\OpenApi;
use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\Core\OpenApi\OpenApi;
use ApiPlatform\Core\OpenApi\Model\Paths;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Kernel;
class OpenApiFactory implements OpenApiFactoryInterface {
private $decorated, $tokenStorage, $kernel;
public function __construct(OpenApiFactoryInterface $decorated, TokenStorageInterface $tokenStorage, Kernel $kernel)
{
$this->decorated = $decorated;
$this->tokenStorage = $tokenStorage;
$this->kernel = $kernel;
}
public function __invoke(array $context = []): OpenApi
{
//$this->debug($context);
$openApi = $this->decorated->__invoke($context);
$removedPaths = $this->getRemovedPaths();
$paths = new Paths;
$pathArray = $openApi->getPaths()->getPaths();
foreach($openApi->getPaths()->getPaths() as $path=>$pathItem) {
if(!isset($removedPaths[$path])) {
// No restrictions
$paths->addPath($path, $pathItem);
}
elseif($removedPaths[$path]!=='*') {
// Remove one or more operation
foreach($removedPaths[$path] as $operation) {
$method = 'with'.ucFirst($operation);
$pathItem = $pathItem->$method(null);
}
$paths->addPath($path, $pathItem);
}
// else don't add this route to the documentation
}
$openApiTest = $openApi->withPaths($paths);
return $openApi->withPaths($paths);
}
private function getRemovedPaths():array
{
/*
Instead of hardcoding removed paths, remove all paths which $user does not have access to based on the route's security attributes and the user's credentials.
This hack returns an array with the path as the key, and either "*" to remove all operations or an array to remove specific operations.
*/
$user = $this->tokenStorage->getToken()->getUser();
return [
'/guids'=>'*', // Remove all operations
'/guids/{guid}'=>'*', // Remove all operations
'/accounts'=>['post'], // Remove only post operation
'/accounts/{uuid}'=>['delete'], // Remove only delete operation
];
}
private function debug(array $context = [])
{
$this->display($context, '$context');
$openApi = $this->decorated->__invoke($context);
$this->displayGetters($openApi);
$pathObject = $openApi->getPaths();
$this->displayGetters($pathObject, null, ['getPath', 'getPaths']);
$pathsArray = $pathObject->getPaths();
$this->display($pathsArray, '$openApi->getPaths()->getPaths()', true);
$pathItem = $pathsArray['/accounts'];
$this->displayGetters($pathItem);
$getGet = $pathItem->getGet();
$this->displayGetters($getGet, '$pathItem->getGet()', ['getResponses']);
$this->display($getGet->getTags(), '$getGet->getTags()');
$this->display($getGet->getParameters(), '$getGet->getParameters()');
$this->display($getGet->getSecurity(), '$getGet->getSecurity()');
$this->display($getGet->getExtensionProperties(), '$getGet->getExtensionProperties()');
$this->displayGetters($this->kernel, null, ['getBundles', 'getBundle']);
$container = $this->kernel->getContainer();
$this->displayGetters($container, null, ['getRemovedIds', 'getParameter', 'get', 'getServiceIds']);
$router = $container->get('router');
$this->displayGetters($router, null, ['getOption']);
$routeCollection = $router->getRouteCollection();
$this->displayGetters($routeCollection, null, ['get']);
$this->displayGetters($this, '$this');
$this->displayGetters($this->decorated, '$this->decorated');
$components = $openApi->getComponents ();
$this->displayGetters($components, null, []);
}
private function displayGetters($obj, ?string $notes=null, array $exclude=[])
{
echo('-----------------------------------------------------------'.PHP_EOL);
if($notes) {
echo($notes.PHP_EOL);
}
echo(get_class($obj).PHP_EOL);
echo('get_object_vars'.PHP_EOL);
print_r(array_keys(get_object_vars($obj)));
echo('get_class_methods'.PHP_EOL);
print_r(get_class_methods($obj));
foreach(get_class_methods($obj) as $method) {
if(substr($method, 0, 3)==='get') {
if(!in_array($method, $exclude)) {
$rs = $obj->$method();
$type = gettype($rs);
switch($type) {
case 'object':
printf('type: %s path: %s method: %s'.PHP_EOL, $type, $method, get_class($rs));
print_r(get_class_methods($rs));
break;
case 'array':
printf('type: %s method: %s'.PHP_EOL, $type, $method);
print_r($rs);
break;
default:
printf('type: %s method: %s, value: %s'.PHP_EOL, $type, $method, $rs);
}
}
else {
echo('Exclude method: '.$method.PHP_EOL);
}
}
}
}
private function display($rs, string $notes, bool $keysOnly = false)
{
echo('-----------------------------------------------------------'.PHP_EOL);
echo($notes.PHP_EOL);
print_r($keysOnly?array_keys($rs):$rs);
}
}

Related

How to configure the Symfony serializer to link relational fields when deserialising?

Objective:
I'm importing a bunch of JSON files data into the database. Keeping the id fields the same as in the json files and link the relational id's to existing rows.
Problem:
When deserialising relational fields, the serialiser is inserting new empty records rather than linking them to existing rows.
Context:
I'm deserialising the files into respective entity objects.
Let's focus on one called Region.json which has an entity called Region and has a ManyToOne relation to Country.
Here is a snippet from Region.json the fields are the same as the entity properties.
[
{
"id": 1,
"name": "Aera",
"code": AR",
"country": 1, // relational field
"isActive": true,
},
{
"id": 2,
"name": "Mauw",
"code": "MW",
"country": 8, // relational field
"isActive": true,
}
]
The deserialisation process is as follows:
public function getDeserializeData(): mixed
{
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizers = [new ObjectNormalizer( classMetadataFactory: $classMetadataFactory,propertyTypeExtractor: new ReflectionExtractor()), new GetSetMethodNormalizer(), new ArrayDenormalizer()];
$encoders = [new JsonEncoder(), new XmlEncoder(), new CsvEncoder()];
$serializer = new Serializer(
normalizers: $normalizers,
encoders: $encoders
);
return $serializer->deserialize(
$this->staticDataFile->getContents(),
$this->getEntityNamespace() . '[]',
$this->staticDataFile->getExtension()
);
}
I'm using the ReflectionExtractor because are you can see the json data files have pre-defined ids and this can not be changed.
If I try to change the generated value strategy from 'IDENTITY' to 'NONE' I get the following error:
Entity of type App\Entity\Country is missing an assigned ID for field 'id'. The identifier generation strategy for this
entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically genera
ted identifiers instead you need to adjust the metadata mapping accordingly.
You will likely need a custom (De-)Normalizer for this, designed for each specific entity, e.g. for Region. Then you know, which fields contain associated data like country and how to search for that data. Your normalizer will take the id from the input, get the country from the database and add it in place of the number. It could look roughly like this:
class RegionDenormalizer implements DenormalizerInterface
{
public function __construct(
private CountryRepository $countryRepository,
) {}
public functionsupportsDenormalization(mixed $data, string $type, string $format = null /* , array $context = [] */)
{
return $type === Region::class;
}
public function denormalize(mixed $data, string $type, string $format = null, array $context = [])
{
$country = $this->countryRepository->find($data[’country’];
if (!$country instanceof Country)
{
// throw an Exception probably
}
$region = $context[AbstractNormalizer::OBJECT_TO_POPULATE];
$region->setCountry($country);
// Probably also set the other fields
}
}
You can also use $context to prevent your Denormalizer from being called twice, replace the id with the country in data and then use the original ObjectNormalizer. This is a bit more complicated, but I prefer this:
class RegionDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
public function __construct(
private CountryRepository $countryRepository,
) {}
public functionsupportsDenormalization(mixed $data, string $type, string $format = null /* , array $context = [] */)
{
return $type === Region::class
&& !in_array($data[‘id’], $context[‘visited_regions’] ?? []);
}
public function denormalize(mixed $data, string $type, string $format = null, array $context = [])
{
$innerContext = $context;
$innerContext[‘visited_regions’][] = $data[‘id’];
$country = $this->countryRepository->find($data[’country’];
if (!$country instanceof Country)
{
// throw an Exception probably
}
$innerContext = $context;
// By setting this inner context, we prevent this listener from being called again for this region
$innerContext[‘visited_regions’][] = $data[‘id’];
// By replacing the country in data, we now have the expected country instead of the id or a new entity
$data[‘country’] = $country;
return $this->denormalizer->denormalize($data, $type, $innerContext);
}
}
I prefer this, because I don’t have to care about how to deserialize the region itself, only about replacing the country-id with the actual instance, but handling the context is more difficult.
Note: the single quotes in the code samples are wrong, because I am typing this on an iPad. You will have to replace them.

How to cache a JSON response in the Silverstripe Controller?

We have a Silverstripe 4 project which acts as a headless CMS returning a group of complex data models formatted as JSON.
Here's an example of the code:
class APIController extends ContentController
{
public function index(HTTPRequest $request)
{
$dataArray['model1'] = AccessPointController::getModel1();
$dataArray['model2'] = AccessPointController::getModel2();
$dataArray['model3'] = AccessPointController::getModel3();
$dataArray['model4'] = AccessPointController::getModel4();
$dataArray['model5'] = AccessPointController::getModel5();
$dataArray['model6'] = AccessPointController::getModel6();
$this->response->addHeader('Content-Type', 'application/json');
$this->response->addHeader('Access-Control-Allow-Origin', '*');
return json_encode($dataArray);
}
The problem we're having is the data models have got so complex the generation time for the JSON is running into seconds.
The JSON should only change when site content has been updates so ideally we'd like to cache the JSON & rather than dynamically generating it for each call.
What is the best way to cache the JSON in the above example?
Have you looked at the silverstripe docs about caching?
They do provide a programmatic way to store things in cache. And configuration options what back-ends are to be used to store the cache.
A simple example might be:
I've extended the cache live time here, but still you should note that this cache is not intended for storing generated static content, but rather to reduce load. Your application will still have to compute the api response every 86400 seconds (24 hours).
# app/_config/apiCache.yml
---
Name: apicacheconfig
---
# [... rest of your config config ...]
SilverStripe\Core\Injector\Injector:
Psr\SimpleCache\CacheInterface.apiResponseCache:
factory: SilverStripe\Core\Cache\CacheFactory
constructor:
namespace: "apiResponseCache"
defaultLifetime: 86400
<?php // app/src/FooController.php
class FooController extends \SilverStripe\Control\Controller {
public function getCache() {
return Injector::inst()->get('Psr\SimpleCache\CacheInterface.apiResponseCache');
// or your own cache (see below):
// return new MyCache();
}
protected function hasDataBeenChanged() {
// alternative to this method, you could also simply include Page::get()->max('LastEdited') or whatever in your cache key inside index(), but if you are using your own cache system, you need to handle deleting of old unused cache files. If you are using SilverStripe's cache, it will do that for you
$c = $this->getCache();
$lastCacheTime = $c->has('cacheTime') ? (int)$c->get('cacheTime') : 0;
$lastDataChangeTime = strtotime(Page::get()->max('LastEdited'));
return $lastDataChangeTime > $lastCacheTime;
}
public function index() {
$c = $this->getCache();
$cacheKey = 'indexActionResponse';
if ($c->has($cacheKey) && !$this->hasDataBeenChanged()) {
$data = $c->get($cacheKey);
} else {
$dataArray['model1'] = AccessPointController::getModel1();
$dataArray['model2'] = AccessPointController::getModel2();
$dataArray['model3'] = AccessPointController::getModel3();
$dataArray['model4'] = AccessPointController::getModel4();
$dataArray['model5'] = AccessPointController::getModel5();
$dataArray['model6'] = AccessPointController::getModel6();
$data = json_encode($dataArray);
$c->set($cacheKey, $data);
$c->set('cacheTime', time());
}
$this->response->addHeader('Content-Type', 'application/json');
$this->response->addHeader('Access-Control-Allow-Origin', '*');
return json_encode($dataArray);
}
}
If you are looking for a permanent/persistent cache, that will only ever update when data changed, I suggest you look for a different back-end or just implement a simple cache yourself and use that instead of the silverstripe cache.
class MyCache {
protected function fileName($key) {
if (strpos($key, '/') !== false || strpos($key, '\\') !== false) {
throw new \Exception("Invalid cache key '$key'");
}
return BASE_PATH . "/api-cache/$key.json";
}
public function get($key) {
if ($this->has($key)) {
return file_get_contents($this->fileName($key));
}
return null;
}
public function set($key, $val) {
file_put_contents($this->fileName($key), $val);
}
public function has($key) {
$f = $this->fileName($key);
return #file_exists($f);
}

what is the correct way to pass not services to the constructor of a custom normalize in symfony

I'm creating my own Normalizer, based on the tutorial on the Symfony documentation page https://symfony.com/doc/current/serializer/custom_normalizer.html, which I find incomplete because it tells you how to create it but not apply it, that's the first point.
Then based on my little experience in Symfony I'm trying to guess how to pass data to the normalizer to be the proper calculations, the data I'm trying to pass are not services, which can be a String or a Request object, but none of this data allows me, really I need to understand or I need to refactor to get what I want?
I put my normalizer code to understand well what I am looking for.
Normalizer:
<?php
namespace App\Serializer;
use App\Entity\Task;
use App\Traits\TaskControl;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class TaskNormalizer implements NormalizerInterface
{
use TaskControl;
private $normalizer;
private $rangeDate;
public function __construct(ObjectNormalizer $normalizer, $rangeDate )
{
$this->normalizer = $normalizer;
$this->rangeDate = $rangeDate;
}
public function normalize($task, $format = null, array $context = [])
{
$data = $this->normalizer->normalize($task, $format, $context);
dd($this->rangeDate);
$data['totalWork'] = $this->timeTask($task,$this->rangeDate);
return $data;
}
public function supportsNormalization($task, $format = null, array $context = []): bool
{
return $task instanceof Task;
}
}
Applying the normalizer:
Passing the variable $rangeDate that is dynamic from object Request.
$rangeDate = $request->request->get('range','all');
$serializer = new Serializer([new TaskNormalizer($normalizer,$rangeDate)]);
$data = $serializer->normalize($attendances, null, ['attributes' => $attributes]);
and this is the error I get:
Cannot autowire service "App\Serializer\TaskNormalizer": argument "$rangeDate" of method "__construct()" has no type-hint, you should configure its value explicitly.
Why would you pass your range date as constructor argument?
Normalizer is a service dependency, rangeDate is a dynamic value.
You can pass it as an argument for the method normalize instead either as a new argument, or in the context array:
$rangeDate = $request->request->get('range','all');
$serializer = new Serializer([new TaskNormalizer($normalizer)]);
$data = $serializer->normalize($attendances, null, ['attributes' => $attributes, 'rangeDate' => $rangeDate]);
You'll have t odeclare your service explicitely... something like this should do the trick:
## services.yml
App\Serializer\TaskNormalizer :
arguments:
$normalizer: '#serializer.normalizer.object' ## check the alias ...
$rangeDate: '%range_date%'
Keep in mind that it is better depend on interface than class, for the sake of dependency inversion principle. So you should think about changing the constructor to :
## your class
public function __construct(NormalizerInterface $normalizer, $rangeDate )
{
$this->normalizer = $normalizer;
$this->rangeDate = $rangeDate;
}

Symfony 3, detect browser language

I use Symfony 3.
My website is in 2 languages, French and English and people can switch via a select form.
Default language is French.
Main URL are:
example.com/fr for French version and example.com/en for English version
Well, now, I will like when the user arrives to the website to detect his browser language and redirect to the correct language automatically.
Exemple, if the browser is in French, he is redirected to the French version : example.com/fr
Else he is redirected to the English version: example.com/en
Is there a way to do that properly?
Thank you for your help
If you don't want to rely on other bundles like JMSI18nRoutingBundle
you have to make yourself familiar with Symfony's Event system, e.g. by reading up on the HttpKernel.
For your case you want to hook into the kernel.request event.
Typical Purposes: To add more information to the Request, initialize parts of the system, or return a Response if possible (e.g. a security layer that denies access).
In your custom EventListener you can listen to that event add information to the Request-object used in your router. It could look something like this:
class LanguageListener implements EventSubscriberInterface
{
private $supportedLanguages;
public function __construct(array $supportedLanguages)
{
if (empty($supportedLanguages)) {
throw new \InvalidArgumentException('At least one supported language must be given.');
}
$this->supportedLanguages = $supportedLanguages;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['redirectToLocalizedHomepage', 100],
];
}
public function redirectToLocalizedHomepage(GetResponseEvent $event)
{
// Do not modify sub-requests
if (KernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
// Assume all routes except the frontpage use the _locale parameter
if ($event->getRequest()->getPathInfo() !== '/') {
return;
}
$language = $this->supportedLanguages[0];
if (null !== $acceptLanguage = $event->getRequest()->headers->get('Accept-Language')) {
$negotiator = new LanguageNegotiator();
$best = $negotiator->getBest(
$event->getRequest()->headers->get('Accept-Language'),
$this->supportedLanguages
);
if (null !== $best) {
$language = $best->getType();
}
}
$response = new RedirectResponse('/' . $language);
$event->setResponse($response);
}
}
This listener will check the Accept-Language header of the request and use the Negotiation\LanguageNegotiator to determine the best locale. Be careful as I didn't add the use statements, but they should be fairly obvious.
For a more advanced version you can just read the source for the LocaleChoosingListener from JMSI18nRoutingBundle.
Doing this is usually only required for the frontpage, which is why both the example I posted and the one from the JMSBundle exclude all other paths. For those you can just use the special parameter _locale as described in the documentation:
https://symfony.com/doc/current/translation/locale.html#the-locale-and-the-url
The Symfony documentation also contains an example how to read the locale and make it sticky in a session using a Listener: https://symfony.com/doc/current/session/locale_sticky_session.html
This example also shows how to register the Listener in your services.yml.
Slight changes to #dbrumann's answer to work with my use case and setup:
List of available locales are defined in services.yml file:
parameters:
available_locales:
- nl
- en
- cs
I wanted to determine the locale on any landing page of the website. In case the parsing fails, it fallbacks to _locale parameter or the default one.
class LocaleDetermineSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $parameterBag;
private $logger;
public function __construct(ParameterBagInterface $parameterBag,
LoggerInterface $logger,
$defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
$this->parameterBag = $parameterBag;
$this->logger = $logger;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
//do this on first request only
if ($request->hasPreviousSession()) {
return;
}
$allowedLocales = $this->parameterBag->get('available_locales'); //defined in services.yml
$determinedLocale = null;
// use locale from the user preference header
$acceptLanguage = $event->getRequest()->headers->get('Accept-Language');
if ($acceptLanguage != null) {
$negotiator = new LanguageNegotiator();
try {
$best = $negotiator->getBest($acceptLanguage, $allowedLocales);
if ($best != null) {
$language = $best->getType();
$request->setLocale($language);
$determinedLocale = $language;
}
} catch (Exception $e) {
$this->logger->warning("Failed to determine language from Accept-Language header " . $e);
}
}
//check if locale is set with _locale parameter if user preference header parsing not happened
if($determinedLocale == null) {
if ($locale = $request->attributes->get('_locale')) {
if(in_array($locale, $allowedLocales)) {
$request->getSession()->set('_locale', $locale);
} else {
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
} else {
//fallback to default
$request->setLocale($this->defaultLocale);
}
}
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 25]],
];
}
}
It uses the willdurand/negotiation package, so it needs to be installed first:
composer require willdurand/negotiation
https://packagist.org/packages/willdurand/negotiation

Callback Constraint doesn't show paylod (Symfony Validator Component)

My controller code:
public function postFilesAction(Request $request)
{
$validator = $this->get('validator');
$requestCredentials = RequestCredentials::fromRequest($request);
$errors = $validator->validate($requestCredentials);
...
validate method in RequestCredentials (Callback constraint).
/**
* #Assert\Callback(payload = {"errorCode" = "FILE_FILE_URL"})
*/
public function validate(ExecutionContextInterface $context)
{
if (! ($this->fileExistsAndValid() || $this->fileUrlExistsAndValid())) {
$context->buildViolation('Neither file nor file_url is present.')->addViolation();
}
}
Callback works as expected, but the value of $constraintViolation->$constraint->$payload is null.
When I'm trying to use payload in other Constraints (NotBlank, for example), it works (I can see it in ConstraintViolation object).
Is it Symfony bug or am I doing somethings wrong? Should I use some other solution to my problem? (I need to check if there's at least one of two fields (file or file_url) present in request).
In Symfony 3.0 you cannot easily access the payload in the callback when using the Callback constraint. Starting with Symfony 3.1, the payload will be passed as an additional argument to the callback (see https://github.com/symfony/symfony/issues/15092 and https://github.com/symfony/symfony/pull/16909).
I managed to solve this problem with following code in the assertion:
/**
* #Assert\Callback(payload = {"error_code" = "1"}, callback = "validate", groups = {"Default", "RequestCredentials"})
*/
public function validate(ExecutionContextInterface $context)
{
// some validation code
}
I think the problem was because of the Symfony Callback constraint constructor:
public function __construct($options = null)
{
// Invocation through annotations with an array parameter only
if (is_array($options) && 1 === count($options) && isset($options['value'])) {
$options = $options['value'];
}
if (is_array($options) && !isset($options['callback']) && !isset($options['groups'])) {
$options = array('callback' => $options);
}
parent::__construct($options);
}
When it is given $options = ['payload' => [...]] (what happened in my case) it turns it into $options = ['callback' => ['payload' => [...]]]
and then '$payload' data becomes inacessable in ConstraintViolation object.
But I'm still not sure whether it's Symfony imperfection or me not getting something and using it wrong.

Resources