Completed
Push — master ( 10db52...80d8a4 )
by Julito
08:55
created

ResourceToIdentifierTransformer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 52
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A reverseTransform() 0 17 3
A __construct() 0 4 1
A transform() 0 10 2
1
<?php
2
3
namespace Chamilo\CoreBundle\Form\DataTransformer;
4
5
//use Sylius\Component\Resource\Repository\RepositoryInterface;
6
use Symfony\Component\Form\DataTransformerInterface;
7
use Symfony\Component\Form\Exception\TransformationFailedException;
8
use Symfony\Component\PropertyAccess\PropertyAccess;
9
use Webmozart\Assert\Assert;
10
11
final class ResourceToIdentifierTransformer implements DataTransformerInterface
12
{
13
    /** @var RepositoryInterface */
14
    private $repository;
15
16
    /** @var string */
17
    private $identifier;
18
19
    /**
20
     * @param string $identifier
21
     */
22
    public function __construct($repository, ?string $identifier = null)
23
    {
24
        $this->repository = $repository;
25
        $this->identifier = $identifier ?? 'id';
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function transform($value)
32
    {
33
        if (null === $value) {
34
            return null;
35
        }
36
37
        /** @psalm-suppress ArgumentTypeCoercion */
38
        Assert::isInstanceOf($value, $this->repository->getClassName());
39
40
        return PropertyAccess::createPropertyAccessor()->getValue($value, $this->identifier);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function reverseTransform($value)
47
    {
48
        if (null === $value) {
49
            return null;
50
        }
51
52
        $resource = $this->repository->findOneBy([$this->identifier => $value]);
53
        if (null === $resource) {
54
            throw new TransformationFailedException(sprintf(
55
                'Object "%s" with identifier "%s"="%s" does not exist.',
56
                $this->repository->getClassName(),
57
                $this->identifier,
58
                $value
59
            ));
60
        }
61
62
        return $resource;
63
    }
64
}
65