From 4f5b44bd3bd490309eb2ba7b44df4769816ba729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20L=C5=93uillet?= Date: Sat, 3 Aug 2013 19:26:54 +0200 Subject: twig implementation --- .../DataTransformer/ArrayToPartsTransformer.php | 86 ++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ArrayToPartsTransformer.php (limited to 'vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ArrayToPartsTransformer.php') diff --git a/vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ArrayToPartsTransformer.php new file mode 100644 index 00000000..fc080f25 --- /dev/null +++ b/vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\Core\DataTransformer; + +use Symfony\Component\Form\DataTransformerInterface; +use Symfony\Component\Form\Exception\TransformationFailedException; + +/** + * @author Bernhard Schussek + */ +class ArrayToPartsTransformer implements DataTransformerInterface +{ + private $partMapping; + + public function __construct(array $partMapping) + { + $this->partMapping = $partMapping; + } + + public function transform($array) + { + if (null === $array) { + $array = array(); + } + + if (!is_array($array) ) { + throw new TransformationFailedException('Expected an array.'); + } + + $result = array(); + + foreach ($this->partMapping as $partKey => $originalKeys) { + if (empty($array)) { + $result[$partKey] = null; + } else { + $result[$partKey] = array_intersect_key($array, array_flip($originalKeys)); + } + } + + return $result; + } + + public function reverseTransform($array) + { + if (!is_array($array) ) { + throw new TransformationFailedException('Expected an array.'); + } + + $result = array(); + $emptyKeys = array(); + + foreach ($this->partMapping as $partKey => $originalKeys) { + if (!empty($array[$partKey])) { + foreach ($originalKeys as $originalKey) { + if (isset($array[$partKey][$originalKey])) { + $result[$originalKey] = $array[$partKey][$originalKey]; + } + } + } else { + $emptyKeys[] = $partKey; + } + } + + if (count($emptyKeys) > 0) { + if (count($emptyKeys) === count($this->partMapping)) { + // All parts empty + return null; + } + + throw new TransformationFailedException( + sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys) + )); + } + + return $result; + } +} -- cgit v1.2.3