Test Setup Failed
Push — master ( e2ccdd...da0315 )
by Gerrit
09:14
created

EntityArgument   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 57.89%

Importance

Changes 0
Metric Value
dl 0
loc 72
ccs 11
cts 19
cp 0.5789
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 3
1
<?php
2
/**
3
 * Copyright (C) 2018 Gerrit Addiks.
4
 * This package (including this file) was released under the terms of the GPL-3.0.
5
 * You should have received a copy of the GNU General Public License along with this program.
6
 * If not, see <http://www.gnu.org/licenses/> or send me a mail so i can send you a copy.
7
 *
8
 * @license GPL-3.0
9
 *
10
 * @author Gerrit Addiks <[email protected]>
11
 */
12
13
namespace Addiks\SymfonyGenerics\Arguments;
14
15
use Addiks\SymfonyGenerics\Arguments\Argument;
16
use Doctrine\Persistence\ObjectManager;
17
use Doctrine\Persistence\ObjectRepository;
18
19
final class EntityArgument implements Argument
20
{
21
22
    /** @var class-string */
23
    private string $entityClass;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
24
25
    private Argument $id;
26
27
    private ObjectManager $objectManager;
28
29
    private ?ObjectRepository $repository;
30
31
    /** @var array<string, mixed> */
32
    private static $constantMap = array(
33
        'true' => true,
34
        'false' => false,
35
        'null' => null,
36
    );
37
38
    /** @param class-string $entityClass */
39
    public function __construct(
40
        ObjectManager $objectManager,
41
        string $entityClass,
42
        Argument $id
43
    ) {
44
        $this->entityClass = $entityClass;
45
        $this->id = $id;
46
        $this->objectManager = $objectManager;
47
    }
48
49 3
    public function resolve()
50
    {
51
        /** @var string $entityId */
52
        $entityId = $this->id->resolve();
53
54 3
        if (preg_match("/^\[([a-zA-Z0-9_-]+)\=(.*)\]$/is", $entityId, $matches)) {
55 3
            [, $column, $value] = $matches;
56 3
57 3
            if (isset(self::$constantMap[strtolower($value)])) {
58
                $value = self::$constantMap[strtolower($value)];
59 1
            }
60
61
            return $this->repository()->findOneBy([$column => $value]);
62 1
63
        } else {
64 1
            return $this->objectManager->find(
65
                $this->entityClass,
66
                $entityId
67
            );
68
        }
69
    }
70
71
    private function repository(): ObjectRepository
72
    {
73
        if (is_null($this->repository)) {
74 1
            $this->repository = $this->objectManager->getRepository($this->entityClass);
75 1
        }
76 1
77
        return $this->repository;
78
    }
79
80
}
81