Commit fe99830c by Mathieu Poisbeau

#22: API Prestataire -> le media est désormais exposé

en lecture (GET) seulement
parent f0598687
...@@ -480,3 +480,7 @@ services: ...@@ -480,3 +480,7 @@ services:
decorates: 'api_platform.swagger.normalizer.api_gateway' decorates: 'api_platform.swagger.normalizer.api_gateway'
arguments: [ '@App\Swagger\SwaggerDecorator.inner' ] arguments: [ '@App\Swagger\SwaggerDecorator.inner' ]
autoconfigure: false autoconfigure: false
App\Serializer\ApiNormalizer:
decorates: 'api_platform.serializer.normalizer.item'
arguments: [ '@App\Serializer\ApiNormalizer.inner' ]
<?php
namespace App\Serializer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Sonata\MediaBundle\Provider\Pool;
use App\Entity\Prestataire;
/**
* This class allows to expose the media of a Prestataire in ApiPlatform
* (because it's not possible with a Media from SonataMediaBundle)
*/
final class ApiNormalizer implements NormalizerInterface, SerializerAwareInterface
{
private $decorated;
private $pool;
public function __construct(NormalizerInterface $decorated, Pool $pool)
{
$this->decorated = $decorated;
$this->pool = $pool;
}
public function supportsNormalization($data, $format = null)
{
return $this->decorated->supportsNormalization($data, $format);
}
public function normalize($object, $format = null, array $context = [])
{
$data = $this->decorated->normalize($object, $format, $context);
// In the case of normalizing a Prestataire...
if (! $object instanceof Prestataire) {
return $data;
}
// ... we retrieve its associated Sonata Media (from the Sonata Media's provider, from the providers pool)
if (is_array($data) && $media = $object->getMedia()) {
if ($provider = $this->pool->getProvider($media->getProviderName())) {
$data['media'] = $provider->getHelperProperties($media, 'reference');
}
}
return $data;
}
public function setSerializer(SerializerInterface $serializer)
{
if($this->decorated instanceof SerializerAwareInterface) {
$this->decorated->setSerializer($serializer);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment