CollectionToArrayTransformer   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 40
ccs 0
cts 13
cp 0
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 17 4
A reverseTransform() 0 9 3
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