Added data transformers

This commit is contained in:
William DURAND 2011-05-02 07:54:44 +02:00
parent 0837af1bda
commit 87474437d4
2 changed files with 128 additions and 0 deletions

View file

@ -0,0 +1,54 @@
<?php
namespace Propel\PropelBundle\Form\DataTransformer;
use Propel\PropelBundle\Form\ChoiceList\ModelChoiceList;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\TransformationFailedException;
class ModelToIdTransformer implements DataTransformerInterface
{
private $choiceList;
public function __construct(ModelChoiceList $choiceList)
{
$this->choiceList = $choiceList;
}
public function transform($model)
{
if (null === $model || '' === $model) {
return '';
}
if (!is_object($model)) {
throw new UnexpectedTypeException($model, 'object');
}
if (count($this->choiceList->getIdentifier()) > 1) {
$availableModels = $this->choiceList->getModels();
return array_search($model, $availableModels);
}
return current($this->choiceList->getIdentifierValues($model));
}
public function reverseTransform($key)
{
if ('' === $key || null === $key) {
return null;
}
if (count($this->choiceList->getIdentifier()) > 1 && !is_numeric($key)) {
throw new UnexpectedTypeException($key, 'numeric');
}
if (!($model = $this->choiceList->getModel($key))) {
throw new TransformationFailedException('The model with key "%s" could not be found', $key);
}
return $model;
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Propel\PropelBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Propel\PropelBundle\Form\ChoiceList\ModelChoiceList;
use \PropelCollection;
class ModelsToArrayTransformer implements DataTransformerInterface
{
private $choiceList;
public function __construct(ModelChoiceList $choiceList)
{
$this->choiceList = $choiceList;
}
public function transform($collection)
{
if (null === $collection) {
return array();
}
if (!($collection instanceof PropelCollection)) {
throw new UnexpectedTypeException($collection, '\PropelCollection');
}
$array = array();
if (count($this->choiceList->getIdentifier()) > 1) {
$availableModels = $this->choiceList->getModels();
foreach ($collection as $model) {
$key = array_search($model, $availableModels);
$array[] = $key;
}
} else {
foreach ($collection as $model) {
$array[] = current($this->choiceList->getIdentifierValues($model));
}
}
return $array;
}
public function reverseTransform($keys)
{
$collection = new PropelCollection();
if ('' === $keys || null === $keys) {
return $collection;
}
if (!is_array($keys)) {
throw new UnexpectedTypeException($keys, 'array');
}
$notFound = array();
foreach ($keys as $key) {
if ($model = $this->choiceList->getModel($key)) {
$collection->append($model);
} else {
$notFound[] = $key;
}
}
if (count($notFound) > 0) {
throw new TransformationFailedException(sprintf('The models with keys "%s" could not be found', implode('", "', $notFound)));
}
return $collection;
}
}