HydratorStrategy::extract()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 3
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasDoctrine\Hydrator\Strategy;
6
7
use Arp\Entity\EntityInterface;
8
use Arp\LaminasDoctrine\Repository\EntityRepositoryInterface;
9
use Laminas\Hydrator\Strategy\Exception\InvalidArgumentException;
10
use Laminas\Hydrator\Strategy\HydratorStrategy as LaminasHydratorStrategy;
11
12
final class HydratorStrategy extends AbstractHydratorStrategy
13
{
14
    private LaminasHydratorStrategy $hydratorStrategy;
15
16
    /**
17
     * @param EntityRepositoryInterface<EntityInterface> $repository
18
     * @param LaminasHydratorStrategy                    $hydratorStrategy
19
     */
20
    public function __construct(EntityRepositoryInterface $repository, LaminasHydratorStrategy $hydratorStrategy)
21
    {
22
        parent::__construct($repository);
23
24
        $this->hydratorStrategy = $hydratorStrategy;
25
    }
26
27
    /**
28
     * @param mixed       $value
29
     * @param object|null $object
30
     *
31
     * @return mixed|null
32
     *
33
     * @throws InvalidArgumentException
34
     */
35
    public function extract($value, ?object $object = null)
36
    {
37
        if (null !== $value) {
38
            try {
39
                return $this->hydratorStrategy->extract($value, $object);
40
            } catch (\Throwable $e) {
41
                throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
42
            }
43
        }
44
        return null;
45
    }
46
47
    /**
48
     * @param mixed             $value
49
     * @param array<mixed>|null $data
50
     *
51
     * @return object|string|null
52
     *
53
     * @throws InvalidArgumentException
54
     */
55
    public function hydrate($value, ?array $data)
56
    {
57
        $id = $this->resolveId($value);
58
59
        if (!empty($id)) {
60
            try {
61
                $entity = $this->repository->findOneBy(['id' => $id]);
62
63
                $targetClassName = $this->repository->getClassName();
64
                if ($entity instanceof $targetClassName) {
65
                    return $entity;
66
                }
67
            } catch (\Throwable $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
68
            }
69
70
            $value = [
71
                'id' => $value,
72
            ];
73
        }
74
75
        try {
76
            return $this->hydratorStrategy->hydrate($value, $data);
77
        } catch (\Throwable $e) {
78
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
79
        }
80
    }
81
}
82