Skip to content

Instantly share code, notes, and snippets.

@ger86
Last active October 9, 2018 18:35
Show Gist options
  • Save ger86/625bedcb8907521e0687e7127795a65f to your computer and use it in GitHub Desktop.
Save ger86/625bedcb8907521e0687e7127795a65f to your computer and use it in GitHub Desktop.
<?php
namespace App\Serializer;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use Sonata\MediaBundle\Provider\Pool;
use JMS\Serializer\VisitorInterface;
use Application\Sonata\MediaBundle\Entity\Media;
use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\XmlSerializationVisitor;
use Symfony\Component\HttpFoundation\RequestStack;
class MediaSerializer implements SubscribingHandlerInterface{
/**
* @param Sonata\MediaBundle\Provider\Pool $pool from sonata media
* @param Symfony\Component\HttpFoundation\RequestStack $requesStack
* @param AppBundle\Service\S3Service $s3Service
*/
public function __construct(Pool $mediaService, RequestStack $requestStack) {
$this->mediaService = $mediaService;
$this->requestStack = $requestStack;
}
public function serializeMedia(VisitorInterface $visitor, Media $media, array $type, Context $context) {
$provider = $this->mediaService->getProvider($media->getProviderName();
$format = $provider->getFormatName($media, 'reference');
$url = $provider->generatePublicUrl($media, $format);
$path = $visitor->visitString($url, $type, $context);
return $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost().$path;
}
public static function getSubscribingMethods() {
return [
[
'type' => Media::class,
'format' => 'json',
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'method' => 'serializeMedia',
],
[
'type' => Media::class,
'format' => 'xml',
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'method' => 'serializeMedia',
]
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment