Completed
Push — master ( dbcf6b...d53ab6 )
by Peter
44:13 queued 37:37
created

EntityToIdTransformer::transform()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 6.6

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 6
cts 10
cp 0.6
rs 9.2568
c 0
b 0
f 0
cc 5
nc 4
nop 1
crap 6.6
1
<?php
2
3
namespace TreeHouse\IoBundle\Item\Modifier\Data\Transformer;
4
5
use Doctrine\Common\Persistence\Proxy;
6
use Doctrine\ORM\EntityManagerInterface;
7
use TreeHouse\Feeder\Exception\TransformationFailedException;
8
use TreeHouse\Feeder\Modifier\Data\Transformer\TransformerInterface;
9
10
class EntityToIdTransformer implements TransformerInterface
11
{
12
    /**
13
     * @var EntityManagerInterface
14
     */
15
    protected $entityManager;
16
17
    /**
18
     * @param EntityManagerInterface $entityManager
19
     */
20 6
    public function __construct(EntityManagerInterface $entityManager)
21
    {
22 6
        $this->entityManager = $entityManager;
23 6
    }
24
25 6
    public function transform($value)
26
    {
27
        // already transformed (or null)
28 6
        if (is_array($value) || is_null($value)) {
29
            return $value;
30
        }
31
32 6
        if (!is_object($value)) {
33
            throw new TransformationFailedException(
34
                sprintf('Expected an object to transform, got "%s"', json_encode($value))
35
            );
36
        }
37
38
        // load object if it's a Proxy
39 6
        if ($value instanceof Proxy) {
40
            $value->__load();
41
        }
42
43 6
        $meta = $this->entityManager->getClassMetadata(get_class($value));
44
45 6
        return $meta->getIdentifierValues($value);
46
    }
47
}
48