|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Created by PhpStorm. |
|
4
|
|
|
* User: darkilliant |
|
5
|
|
|
* Date: 5/7/18 |
|
6
|
|
|
* Time: 8:20 PM. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Darkilliant\ImportBundle\TargetResolver; |
|
10
|
|
|
|
|
11
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @internal |
|
15
|
|
|
*/ |
|
16
|
|
|
class DoctrineTargetResolver |
|
17
|
|
|
{ |
|
18
|
|
|
/** @var EntityManagerInterface */ |
|
19
|
|
|
private $em; |
|
20
|
|
|
|
|
21
|
4 |
|
public function __construct(EntityManagerInterface $em) |
|
22
|
|
|
{ |
|
23
|
4 |
|
$this->em = $em; |
|
24
|
4 |
|
} |
|
25
|
|
|
|
|
26
|
4 |
|
public function resolve(array $config) |
|
27
|
|
|
{ |
|
28
|
4 |
|
$repository = $this->em->getRepository($config['entityClass']); |
|
29
|
4 |
|
$call = $this->factoryCall($config['strategy']['name'], $config['entityClass'], $config['strategy']['options']); |
|
30
|
|
|
|
|
31
|
|
|
// When not strategy found |
|
32
|
4 |
|
if (null === $call) { |
|
33
|
1 |
|
throw new \Exception('factory fail'); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
// When method of repository or entityManager with params |
|
37
|
3 |
|
$entity = call_user_func_array( |
|
38
|
|
|
[ |
|
39
|
3 |
|
('repository' === $call['in']) |
|
40
|
2 |
|
? $repository |
|
41
|
3 |
|
: $this->em, $call['method'], ], |
|
42
|
3 |
|
$call['params'] |
|
43
|
|
|
); |
|
44
|
|
|
|
|
45
|
|
|
// When not entity already exist in database |
|
46
|
3 |
|
if (null === $entity) { |
|
47
|
1 |
|
return ($config['create']) ? new $config['entityClass']() : null; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
2 |
|
return $entity; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
4 |
|
private function factoryCall(string $strategy, string $entityClass, array $options) |
|
54
|
|
|
{ |
|
55
|
|
|
switch ($strategy) { |
|
56
|
4 |
|
case 'findOneBy': |
|
57
|
2 |
|
return $this->factoryFindOneBy($options); |
|
58
|
|
|
break; |
|
|
|
|
|
|
59
|
2 |
|
case 'find': |
|
60
|
1 |
|
return $this->factoryFind($entityClass, $options); |
|
61
|
|
|
break; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
1 |
|
return null; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
2 |
|
private function factoryFindOneBy(array $options) |
|
68
|
|
|
{ |
|
69
|
|
|
return [ |
|
70
|
2 |
|
'in' => 'repository', |
|
71
|
2 |
|
'method' => 'findOneBy', |
|
72
|
2 |
|
'params' => [$options], |
|
73
|
|
|
]; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
private function factoryFind(string $entityClass, array $options) |
|
77
|
|
|
{ |
|
78
|
|
|
return [ |
|
79
|
1 |
|
'in' => 'entity_manager', |
|
80
|
1 |
|
'method' => 'getReference', |
|
81
|
1 |
|
'params' => [$entityClass, $options[0]], |
|
82
|
|
|
]; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|
The
breakstatement is not necessary if it is preceded for example by areturnstatement:If you would like to keep this construct to be consistent with other
casestatements, you can safely mark this issue as a false-positive.