1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the API Platform project. |
5
|
|
|
* |
6
|
|
|
* (c) Kévin Dunglas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace ApiPlatform\Core\EventListener; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\DataPersister\DataPersisterInterface; |
17
|
|
|
use Symfony\Component\HttpFoundation\Request; |
18
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Bridges persistense and the API system. |
22
|
|
|
* |
23
|
|
|
* @author Kévin Dunglas <[email protected]> |
24
|
|
|
* @author Baptiste Meyer <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
class WriteListener |
27
|
|
|
{ |
28
|
|
|
private $dataPersister; |
29
|
|
|
|
30
|
|
|
public function __construct(DataPersisterInterface $dataPersister) |
31
|
|
|
{ |
32
|
|
|
$this->dataPersister = $dataPersister; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Persists, updates or delete data return by the controller if applicable. |
37
|
|
|
*/ |
38
|
|
|
public function onKernelView(GetResponseForControllerResultEvent $event) |
39
|
|
|
{ |
40
|
|
|
$request = $event->getRequest(); |
41
|
|
|
if ($request->isMethodSafe(false) || !$request->attributes->has('_api_resource_class')) { |
42
|
|
|
return; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$controllerResult = $event->getControllerResult(); |
46
|
|
|
if (!$this->dataPersister->supports($controllerResult)) { |
47
|
|
|
return; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
switch ($request->getMethod()) { |
51
|
|
|
case Request::METHOD_PUT: |
52
|
|
|
case Request::METHOD_PATCH: |
53
|
|
|
case Request::METHOD_POST: |
54
|
|
|
$this->dataPersister->persist($controllerResult); |
55
|
|
|
break; |
56
|
|
|
case Request::METHOD_DELETE: |
57
|
|
|
$this->dataPersister->remove($controllerResult); |
58
|
|
|
$event->setControllerResult(null); |
59
|
|
|
break; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|