Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace AppBundle\Form\DataTransformer;
- use AppBundle\Entity\Entity;
- use AppBundle\Entity\EntityRepository;
- use Symfony\Component\Form\DataTransformerInterface;
- use Symfony\Component\Form\Exception\TransformationFailedException;
- class EntitiesToIdsDataTransformer implements DataTransformerInterface
- {
- /**
- * @var EntityRepository
- */
- private $entityRepository;
- public function __construct(EntityRepository $entity)
- {
- $this->entityRepository = $entity;
- }
- /**
- * @param array|\Traversable|null $value
- * @return array|string
- * @throws TransformationFailedException
- */
- public function transform($value)
- {
- if (null === $value) {
- // as the DataTransformerInterface suggests
- return '';
- }
- if (!is_array($value) && !$value instanceof \Traversable) {
- throw new TransformationFailedException(sprintf(
- 'Array or Traversable expected, %s given',
- gettype($value)
- ));
- }
- $ids = [];
- foreach ($value as $entity) {
- if (!$entity instanceof Entity) {
- throw new TransformationFailedException(sprintf(
- '%s expected, %s given',
- Entity::class,
- gettype($entity)
- ));
- }
- $ids[] = $entity->getId();
- }
- return $ids;
- }
- /**
- * @param array|null $value
- * @return \AppBundle\Entity\Entity[]|null
- * @throws TransformationFailedException
- */
- public function reverseTransform($value)
- {
- if (empty($value)) {
- // as the DataTransformerInterface suggests
- return null;
- }
- if (!is_array($value)) {
- throw new TransformationFailedException(sprintf(
- 'Array expected, %s given',
- gettype($value)
- ));
- }
- return $this->entityRepository->findByIds($value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment