Skip to content

Instantly share code, notes, and snippets.

@vasilvestre
Created August 22, 2022 08:22
Show Gist options
  • Save vasilvestre/2ef15f2e98bdac442a40453d6fbd46e9 to your computer and use it in GitHub Desktop.
Save vasilvestre/2ef15f2e98bdac442a40453d6fbd46e9 to your computer and use it in GitHub Desktop.
API Platform + Sylius + LiipImagine path resolver
<?php
namespace App\Serializer;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Sylius\Component\Core\Model\ImageInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
final class FilePathNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'FILE_PATH_NORMALIZER_ALREADY_CALLED';
public function __construct(private CacheManager $cacheManager)
{
}
public function normalize($object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$context[self::ALREADY_CALLED] = true;
$object->setPath($this->cacheManager->getBrowserPath($object->getPath(), 'sylius_small'));
return $this->normalizer->normalize($object, $format, $context);
}
public function supportsNormalization($data, ?string $format = null, array $context = []): bool
{
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
return $data instanceof ImageInterface;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment