]> git.immae.eu Git - github/wallabag/wallabag.git/blob - vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ArrayToPartsTransformer.php
twig implementation
[github/wallabag/wallabag.git] / vendor / symfony / form / Symfony / Component / Form / Extension / Core / DataTransformer / ArrayToPartsTransformer.php
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Form\Extension\Core\DataTransformer;
13
14 use Symfony\Component\Form\DataTransformerInterface;
15 use Symfony\Component\Form\Exception\TransformationFailedException;
16
17 /**
18 * @author Bernhard Schussek <bschussek@gmail.com>
19 */
20 class ArrayToPartsTransformer implements DataTransformerInterface
21 {
22 private $partMapping;
23
24 public function __construct(array $partMapping)
25 {
26 $this->partMapping = $partMapping;
27 }
28
29 public function transform($array)
30 {
31 if (null === $array) {
32 $array = array();
33 }
34
35 if (!is_array($array) ) {
36 throw new TransformationFailedException('Expected an array.');
37 }
38
39 $result = array();
40
41 foreach ($this->partMapping as $partKey => $originalKeys) {
42 if (empty($array)) {
43 $result[$partKey] = null;
44 } else {
45 $result[$partKey] = array_intersect_key($array, array_flip($originalKeys));
46 }
47 }
48
49 return $result;
50 }
51
52 public function reverseTransform($array)
53 {
54 if (!is_array($array) ) {
55 throw new TransformationFailedException('Expected an array.');
56 }
57
58 $result = array();
59 $emptyKeys = array();
60
61 foreach ($this->partMapping as $partKey => $originalKeys) {
62 if (!empty($array[$partKey])) {
63 foreach ($originalKeys as $originalKey) {
64 if (isset($array[$partKey][$originalKey])) {
65 $result[$originalKey] = $array[$partKey][$originalKey];
66 }
67 }
68 } else {
69 $emptyKeys[] = $partKey;
70 }
71 }
72
73 if (count($emptyKeys) > 0) {
74 if (count($emptyKeys) === count($this->partMapping)) {
75 // All parts empty
76 return null;
77 }
78
79 throw new TransformationFailedException(
80 sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys)
81 ));
82 }
83
84 return $result;
85 }
86 }