Skip to content

Instantly share code, notes, and snippets.

@saksmt
Created August 21, 2014 12:18
Show Gist options
  • Save saksmt/7b24f2411a66b85310ce to your computer and use it in GitHub Desktop.
Save saksmt/7b24f2411a66b85310ce to your computer and use it in GitHub Desktop.
DataTransformer
<?php
namespace ForaSoft\ImproveClassBundle\Form\Transformer;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ObjectManager;
use ForaSoft\ImproveClassBundle\Entity\Tag;
use Symfony\Component\Form\DataTransformerInterface;
class TagsTransformer implements DataTransformerInterface
{
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
public function transform($tags)
{
return implode(',', $this->extractStrings($tags->toArray()));
}
public function reverseTransform($string)
{
$strings = explode(',',$string);
$tags = $this->manager->getRepository('ForaSoftImproveClassBundle:Tag')->findBy(array('tag'=>$strings));
$existingTags = $this->extractStrings($tags);
$newTags = array_diff($strings,$existingTags);
foreach ($newTags as $tag) {
$newTag = new Tag();
$newTag->setTag($tag);
$tags[] = $newTag;
}
return $tags;
}
public static function extractStrings(array $tags)
{
return array_map(function (Tag $item) {
return $item->getTag();
},$tags);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment