]> git.immae.eu Git - github/wallabag/wallabag.git/blame - vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php
gitignore vendor
[github/wallabag/wallabag.git] / vendor / symfony / form / Symfony / Component / Form / Extension / Core / DataTransformer / ValueToDuplicatesTransformer.php
CommitLineData
4f5b44bd
NL
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
12namespace Symfony\Component\Form\Extension\Core\DataTransformer;
13
14use Symfony\Component\Form\DataTransformerInterface;
15use Symfony\Component\Form\Exception\TransformationFailedException;
16
17/**
18 * @author Bernhard Schussek <bschussek@gmail.com>
19 */
20class ValueToDuplicatesTransformer implements DataTransformerInterface
21{
22 private $keys;
23
24 public function __construct(array $keys)
25 {
26 $this->keys = $keys;
27 }
28
29 /**
30 * Duplicates the given value through the array.
31 *
32 * @param mixed $value The value
33 *
34 * @return array The array
35 */
36 public function transform($value)
37 {
38 $result = array();
39
40 foreach ($this->keys as $key) {
41 $result[$key] = $value;
42 }
43
44 return $result;
45 }
46
47 /**
48 * Extracts the duplicated value from an array.
49 *
50 * @param array $array
51 *
52 * @return mixed The value
53 *
54 * @throws TransformationFailedException If the given value is not an array or
55 * if the given array can not be transformed.
56 */
57 public function reverseTransform($array)
58 {
59 if (!is_array($array)) {
60 throw new TransformationFailedException('Expected an array.');
61 }
62
63 $result = current($array);
64 $emptyKeys = array();
65
66 foreach ($this->keys as $key) {
67 if (!empty($array[$key])) {
68 if ($array[$key] !== $result) {
69 throw new TransformationFailedException(
70 'All values in the array should be the same'
71 );
72 }
73 } else {
74 $emptyKeys[] = $key;
75 }
76 }
77
78 if (count($emptyKeys) > 0) {
79 if (count($emptyKeys) == count($this->keys)) {
80 // All keys empty
81 return null;
82 }
83
84 throw new TransformationFailedException(
85 sprintf('The keys "%s" should not be empty', implode('", "', $emptyKeys)
86 ));
87 }
88
89 return $result;
90 }
91}