|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Rebolon\Request\ParamConverter; |
|
4
|
|
|
|
|
5
|
|
|
use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException; |
|
6
|
|
|
use Symfony\Component\Validator\ConstraintViolation; |
|
7
|
|
|
use Symfony\Component\Validator\ConstraintViolationList; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* |
|
11
|
|
|
* Class ItemAbstractConverter |
|
12
|
|
|
* @package Rebolon\Request\ParamConverter\Library |
|
13
|
|
|
*/ |
|
14
|
|
|
abstract class ItemAbstractConverter extends AbstractConverter |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @inheritdoc |
|
18
|
|
|
*/ |
|
19
|
4 |
|
public function initFromRequest($jsonOrArray, $propertyPath) |
|
20
|
|
|
{ |
|
21
|
4 |
|
$this->checkMandatoriesImplementations(); |
|
22
|
|
|
|
|
23
|
|
|
try { |
|
24
|
4 |
|
self::$propertyPath[] = $propertyPath; |
|
25
|
|
|
|
|
26
|
4 |
|
$json = $this->checkJsonOrArray($jsonOrArray); |
|
27
|
|
|
|
|
28
|
4 |
|
$idPropertyIsInJson = false; |
|
29
|
4 |
|
if (!is_array($json) |
|
30
|
4 |
|
|| ($idPropertyIsInJson = array_key_exists($this->getIdProperty(), $json)) |
|
31
|
|
|
) { |
|
32
|
|
|
/** |
|
33
|
|
|
* We don't care of other properties. We don't accept update on sub-entity, we can create or re-use |
|
34
|
|
|
* So here we just clean json and replace it with the id content |
|
35
|
|
|
*/ |
|
36
|
2 |
|
if ($idPropertyIsInJson) { |
|
37
|
1 |
|
$json = $json[$this->getIdProperty()]; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
2 |
|
array_pop(self::$propertyPath); |
|
41
|
|
|
|
|
42
|
2 |
|
return $this->getFromDatabase($json); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
$entity = $this->buildEntity($json); |
|
46
|
|
|
|
|
47
|
3 |
|
array_pop(self::$propertyPath); |
|
48
|
|
|
|
|
49
|
3 |
|
return $entity; |
|
50
|
1 |
|
} catch (ValidationException $e) { |
|
51
|
1 |
|
throw $e; |
|
52
|
|
|
} catch (\Exception $e) { |
|
53
|
|
|
$violationList = new ConstraintViolationList(); |
|
54
|
|
|
$violation = new ConstraintViolation($e->getMessage(), null, [], null, $this->getPropertyPath(), null); |
|
55
|
|
|
$violationList->add($violation); |
|
56
|
|
|
throw new ValidationException( |
|
57
|
|
|
$violationList, |
|
58
|
|
|
sprintf('Wrong parameter to create new %s (generic)', static::RELATED_ENTITY), |
|
59
|
|
|
420, |
|
60
|
|
|
$e |
|
61
|
|
|
); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|