Completed
Push — master ( 586888...6f962e )
by Kamil
14s
created

ObjectToIdentifierTransformer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\SettingsBundle\Transformer;
13
14
use Doctrine\Common\Persistence\ObjectRepository;
15
use Symfony\Component\PropertyAccess\PropertyAccess;
16
17
/**
18
 * @author Paweł Jędrzejewski <[email protected]>
19
 */
20
final class ObjectToIdentifierTransformer implements ParameterTransformerInterface
21
{
22
    /**
23
     * @var ObjectRepository
24
     */
25
    private $repository;
26
27
    /**
28
     * @var string
29
     */
30
    private $identifier;
31
32
    /**
33
     * @param ObjectRepository $repository
34
     * @param string $identifier
35
     */
36
    public function __construct(ObjectRepository $repository, $identifier = 'id')
37
    {
38
        $this->repository = $repository;
39
        $this->identifier = $identifier;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function transform($value)
46
    {
47
        if (!is_object($value)) {
48
            return null;
49
        }
50
51
        $accessor = PropertyAccess::createPropertyAccessor();
52
53
        return $accessor->getValue($value, $this->identifier);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function reverseTransform($value)
60
    {
61
        if (empty($value)) {
62
            return null;
63
        }
64
65
        if ('id' === $this->identifier) {
66
            return $this->repository->find($value);
67
        }
68
69
        return $this->repository->findOneBy([$this->identifier => $value]);
70
    }
71
}
72