/** * Transform submitted data to model data * * @param FormEvent $event */ public function preSubmit(FormEvent $event) { $values = $event->getData(); $entities = array('all' => array(), 'owner' => array()); foreach (array_keys($entities) as $type) { if (isset($values[$type]) && !empty($values[$type])) { try { if (!is_array($values[$type])) { $values[$type] = json_decode($values[$type]); } $names[$type] = array(); foreach ($values[$type] as $value) { if (!empty($value->name)) { // new tag $names[$type][] = $value->name; } } $entities[$type] = $this->manager->loadOrCreateTags($names[$type]); } catch (\Exception $e) { $entities[$type] = array(); } } } $event->setData($entities); }
/** * @dataProvider getTagNames * @param array $names * @param int|bool $shouldWorkWithDB * @param int $resultCount * @param array $tagsFromDB */ public function testLoadOrCreateTags($names, $shouldWorkWithDB, $resultCount, array $tagsFromDB) { $repo = $this->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock(); $this->em->expects($this->exactly((int) $shouldWorkWithDB))->method('getRepository')->will($this->returnValue($repo)); $repo->expects($this->exactly((int) $shouldWorkWithDB))->method('findBy')->will($this->returnValue($tagsFromDB)); $result = $this->manager->loadOrCreateTags($names); $this->assertCount($resultCount, $result); if ($shouldWorkWithDB) { $this->assertContainsOnlyInstancesOf('Oro\\Bundle\\TagBundle\\Entity\\Tag', $result); } }
/** * {@inheritdoc} */ protected function onSuccess($entity) { $targetEntity = $entity['target']; /** @var ArrayCollection $tags */ $tags = $entity['tags']; $names = array_map(function ($tag) { return $tag['name']; }, $tags->getValues()); $tags = $this->tagManager->loadOrCreateTags($names); $this->tagManager->setTags($targetEntity, new ArrayCollection($tags)); $this->tagManager->saveTagging($targetEntity); }
/** * {@inheritdoc} */ public function reverseTransform($value) { if (!$value) { return new ArrayCollection(); } $tags = explode(';;', $value); $names = []; foreach ($tags as $tag) { $tag = json_decode($tag, true); if ($tag && array_key_exists('name', $tag) === true) { $names[] = $tag['name']; } } if (!empty($names)) { return new ArrayCollection($this->tagManager->loadOrCreateTags($names)); } return new ArrayCollection(); }