Completed
Pull Request — develop (#273)
by Samuel
23:34 queued 09:33
created

MappingTransformer::transform()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 9.6667
c 1
b 0
f 1
cc 3
eloc 6
nc 3
nop 3
crap 12
1
<?php
2
/**
3
 * MappingTransformer
4
 */
5
6
namespace Graviton\ProxyBundle\Service;
7
8
use Symfony\Component\PropertyAccess\PropertyAccessor;
9
10
/**
11
 * This class transforms objects / arrays by applying a mapping on them.
12
 *
13
 * @author  List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
14
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
15
 * @link    http://swisscom.ch
16
 */
17
class MappingTransformer
18
{
19
20
    /**
21
     * @var PropertyAccessor
22
     */
23
    protected $propertyAccessor;
24
25
    /**
26
     * Constructor
27
     *
28
     * @param PropertyAccessor $propertyAccessor The Symfony PropertyAccessor for reading / writing the objects / arrays
29
     */
30
    public function __construct(PropertyAccessor $propertyAccessor)
31
    {
32
        $this->propertyAccessor = $propertyAccessor;
33
    }
34
35
    /**
36
     * Applies the given mapping on a given object or array.
37
     *
38
     * @param  object|array $raw         The input object or array
39
     * @param  array        $mapping     The mapping
40
     * @param  object|array $transformed The output object or array.
41
     * @return array
42
     */
43
    public function transform($raw, array $mapping, $transformed = [])
44
    {
45
        foreach ($mapping as $destination => $source) {
46
            $value = $this->propertyAccessor->isReadable($raw, $source) ?
47
                $this->propertyAccessor->getValue($raw, $source) : null;
48
            $this->propertyAccessor->setValue($transformed, $destination, $value);
49
        }
50
        return $transformed;
51
    }
52
}
53