1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Biurad opensource projects. |
5
|
|
|
* |
6
|
|
|
* @copyright 2019 Biurad Group (https://biurad.com/) |
7
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause License |
8
|
|
|
* |
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
10
|
|
|
* file that was distributed with this source code. |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace Flange\Database\Doctrine\Form\DataTransformer; |
14
|
|
|
|
15
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
16
|
|
|
use Doctrine\Common\Collections\Collection; |
17
|
|
|
use Symfony\Component\Form\DataTransformerInterface; |
18
|
|
|
use Symfony\Component\Form\Exception\TransformationFailedException; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @author Bernhard Schussek <[email protected]> |
22
|
|
|
*/ |
23
|
|
|
class CollectionToArrayTransformer implements DataTransformerInterface |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Transforms a collection into an array. |
27
|
|
|
* |
28
|
|
|
* @throws TransformationFailedException |
29
|
|
|
*/ |
30
|
|
|
public function transform(mixed $collection): mixed |
31
|
|
|
{ |
32
|
|
|
if (null === $collection) { |
33
|
|
|
return []; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
// For cases when the collection getter returns $collection->toArray() |
37
|
|
|
// in order to prevent modifications of the returned collection |
38
|
|
|
if (\is_array($collection)) { |
39
|
|
|
return $collection; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if (!$collection instanceof Collection) { |
43
|
|
|
throw new TransformationFailedException('Expected a Doctrine\Common\Collections\Collection object.'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $collection->toArray(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Transforms choice keys into entities. |
51
|
|
|
* |
52
|
|
|
* @param mixed $array An array of entities |
53
|
|
|
*/ |
54
|
|
|
public function reverseTransform(mixed $array): Collection |
55
|
|
|
{ |
56
|
|
|
if ('' === $array || null === $array) { |
57
|
|
|
$array = []; |
58
|
|
|
} else { |
59
|
|
|
$array = (array) $array; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return new ArrayCollection($array); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|