1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PommProject\PommBundle\Request\ParamConverter; |
4
|
|
|
|
5
|
|
|
use PommProject\Foundation\Pomm; |
6
|
|
|
use PommProject\ModelManager\Model\Model; |
7
|
|
|
use Symfony\Component\HttpFoundation\Request; |
8
|
|
|
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; |
9
|
|
|
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface; |
10
|
|
|
|
11
|
|
|
class EntityParamConverter implements ParamConverterInterface |
12
|
|
|
{ |
13
|
|
|
private $pomm; |
14
|
|
|
|
15
|
|
|
public function __construct(Pomm $pomm) |
16
|
|
|
{ |
17
|
|
|
$this->pomm = $pomm; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function supports(ParamConverter $configuration) |
21
|
|
|
{ |
22
|
|
|
if ($configuration->getClass() === null) { |
23
|
|
|
return false; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
$reflection = new \ReflectionClass($configuration->getClass()); |
27
|
|
|
|
28
|
|
|
return $reflection->implementsInterface( |
29
|
|
|
"PommProject\\ModelManager\\Model\\FlexibleEntity\\FlexibleEntityInterface" |
30
|
|
|
); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function apply(Request $request, ParamConverter $configuration) |
34
|
|
|
{ |
35
|
|
|
$name = $configuration->getName(); |
36
|
|
|
$options = $this->getOptions($configuration); |
37
|
|
|
|
38
|
|
|
$model = $options['session']->getModel($options['model']); |
39
|
|
|
|
40
|
|
|
$entity = null; |
41
|
|
|
|
42
|
|
|
try { |
43
|
|
|
$entity = $model->findByPk($this->getPk($model, $request)); |
44
|
|
|
} catch (\LogicException $e) { |
45
|
|
|
if ($options["optional"] === false) { |
46
|
|
|
throw $e; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$request->attributes->set($name, $entity); |
51
|
|
|
|
52
|
|
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function getOptions(ParamConverter $configuration) |
56
|
|
|
{ |
57
|
|
|
$options = array_replace([ |
58
|
|
|
'model' => $configuration->getClass() . 'Model', |
59
|
|
|
], $configuration->getOptions()); |
60
|
|
|
|
61
|
|
|
if (isset($options['session'])) { |
62
|
|
|
$options['session'] = $this->pomm[$options['session']]; |
63
|
|
|
} else { |
64
|
|
|
$options['session'] = $this->pomm->getDefaultSession(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$options["optional"] = $configuration->isOptional(); |
68
|
|
|
|
69
|
|
|
return $options; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function getPk(Model $model, Request $request) |
73
|
|
|
{ |
74
|
|
|
$values = []; |
75
|
|
|
$primaryKeys = $model->getStructure() |
76
|
|
|
->getPrimaryKey(); |
77
|
|
|
|
78
|
|
|
foreach ($primaryKeys as $key) { |
79
|
|
|
if (!$request->attributes->has($key)) { |
80
|
|
|
throw new \LogicException("Missing primary key element '$key'"); |
81
|
|
|
} |
82
|
|
|
$values[$key] = $request->attributes->get($key); |
83
|
|
|
} |
84
|
|
|
return $values; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|