Skip to content

Instantly share code, notes, and snippets.

@taiebb
Last active March 15, 2016 09:38
Show Gist options
  • Save taiebb/fccfbb6c3f609369b613 to your computer and use it in GitHub Desktop.
Save taiebb/fccfbb6c3f609369b613 to your computer and use it in GitHub Desktop.
<?php
class CompetenceTransformer implements DataTransformerInterface {
/**
* @var ObjectManager
*/
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om) {
$this->om = $om;
}
/**
* Transforms an object (Competence) to a string (name).
*
* @param Competence|null $competence
* @return string
*/
public function transform($competence) {
if (null === $competence) {
return "";
}
return $competence->getName();
}
/**
* Transforms a string (name) to an object (Competence).
*
* @param string $name
* @return Competence|null
* @throws TransformationFailedException if object (Competence) is not found.
*/
public function reverseTransform($name) {
if (!$name) {
return null;
}
$competence = $this->om
->getRepository('AppBundle:Competence')
->findOneByName($name);
if (null === $competence) {
try {
// create a new compentence
$competence = new Competence();
$competence->setName($name);
$this->om->persist($competence);
$this->om->flush();
} catch (\Exception $ex) {
throw new TransformationFailedException(sprintf(
'Problème de transformation', $ex . getMessage()
));
}
}
return $competence;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment