1<?php 2 3declare(strict_types=1); 4 5namespace JMS\Serializer\Twig; 6 7use JMS\Serializer\SerializationContext; 8use JMS\Serializer\SerializerInterface; 9 10/** 11 * Serializer helper twig extension 12 * 13 * Basically provides access to JMSSerializer from Twig 14 */ 15class SerializerExtension extends \Twig_Extension 16{ 17 /** 18 * @var SerializerInterface 19 */ 20 protected $serializer; 21 22 /** 23 * @return string 24 * 25 * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint 26 */ 27 public function getName() 28 { 29 return 'jms_serializer'; 30 } 31 32 public function __construct(SerializerInterface $serializer) 33 { 34 $this->serializer = $serializer; 35 } 36 37 /** 38 * @return \Twig_Filter[] 39 * 40 * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint 41 */ 42 public function getFilters() 43 { 44 return [ 45 new \Twig_SimpleFilter('serialize', [$this, 'serialize']), 46 ]; 47 } 48 49 /** 50 * @return \Twig_Function[] 51 * 52 * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint 53 */ 54 public function getFunctions() 55 { 56 return [ 57 new \Twig_SimpleFunction('serialization_context', '\JMS\Serializer\SerializationContext::create'), 58 ]; 59 } 60 61 public function serialize(object $object, string $type = 'json', ?SerializationContext $context = null): string 62 { 63 return $this->serializer->serialize($object, $type, $context); 64 } 65} 66