UuidToItemTransformer::transform()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 15
ccs 0
cts 9
cp 0
crap 20
rs 9.9666
1
<?php
2
namespace App\Form\DataTransformer;
3
4
use App\Entity\Item;
5
use App\Repository\Exception\ItemNotFoundException;
6
use App\Repository\ItemRepository;
7
use Symfony\Component\Form\DataTransformerInterface;
8
use Symfony\Component\Form\Exception\TransformationFailedException;
9
use Ramsey\Uuid\UuidInterface;
10
use Ramsey\Uuid\Uuid;
11
use Ramsey\Uuid\Exception\InvalidUuidStringException;
12
13
class UuidToItemTransformer implements DataTransformerInterface
14
{
15
    private $itemRepository;
16
17
    public function __construct(ItemRepository $itemRepository)
18
    {
19
        $this->itemRepository = $itemRepository;
20
    }
21
22
    /**
23
     * Transforms an object (item) to a UuidInterface
24
     *
25
     * @param  Item|null $item
26
     * @return UuidInterface|string
27
     */
28
    public function reverseTransform($item)
29
    {
30
        if (null === $item) {
31
            return '';
32
        }
33
34
        return $item->getId();
35
    }
36
37
    /**
38
     * Transforms a UuidInterface to an object (Item).
39
     *
40
     * @param  string|null $itemId
41
     * @return Item|null
42
     * @throws TransformationFailedException if object (Item) is not found.
43
     */
44
    public function transform($itemId)
45
    {
46
        if (!$itemId) {
47
            return null;
48
        }
49
50
        try {
51
            $item = $this->itemRepository->getItem(Uuid::fromString($itemId));
52
        } catch (ItemNotFoundException $e) {
53
            throw new TransformationFailedException(sprintf('Item "%s" not found !', $itemId));
54
        } catch (InvalidUuidStringException $e) {
55
            throw new TransformationFailedException(sprintf('Invalid UUID "%s" !', $itemId));
56
        }
57
58
        return $item;
59
    }
60
}