Issues (332)

Bridge/Doctrine/EventListener/WriteListener.php (1 issue)

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\Bridge\Doctrine\EventListener;
15
16
use ApiPlatform\Core\EventListener\WriteListener as BaseWriteListener;
17
use Doctrine\Common\Persistence\ManagerRegistry;
18
use Doctrine\Common\Persistence\ObjectManager;
19
use Symfony\Component\HttpKernel\Event\ViewEvent;
20
21
/**
22
 * Bridges Doctrine and the API system.
23
 *
24
 * @deprecated
25
 *
26
 * @author Kévin Dunglas <[email protected]>
27
 */
28
final class WriteListener
29
{
30
    private $managerRegistry;
31
32
    public function __construct(ManagerRegistry $managerRegistry)
33
    {
34
        @trigger_error(sprintf('The %s class is deprecated since version 2.2 and will be removed in 3.0. Use the %s class instead.', __CLASS__, BaseWriteListener::class), E_USER_DEPRECATED);
35
36
        $this->managerRegistry = $managerRegistry;
37
    }
38
39
    /**
40
     * Persists, updates or delete data return by the controller if applicable.
41
     */
42
    public function onKernelView(ViewEvent $event): void
43
    {
44
        $request = $event->getRequest();
45
        if ($request->isMethodSafe()) {
46
            return;
47
        }
48
49
        $resourceClass = $request->attributes->get('_api_resource_class');
50
        if (null === $resourceClass) {
51
            return;
52
        }
53
54
        $controllerResult = $event->getControllerResult();
55
        if (null === $objectManager = $this->getManager($resourceClass, $controllerResult)) {
56
            return;
57
        }
58
59
        switch ($request->getMethod()) {
60
            case 'POST':
61
                $objectManager->persist($controllerResult);
62
                break;
63
            case 'DELETE':
64
                $objectManager->remove($controllerResult);
65
                $event->setControllerResult(null);
66
                break;
67
        }
68
69
        $objectManager->flush();
70
    }
71
72
    /**
73
     * Gets the manager if applicable.
74
     */
75
    private function getManager(string $resourceClass, $data): ?ObjectManager
76
    {
77
        $objectManager = $this->managerRegistry->getManagerForClass($resourceClass);
78
        if (null === $objectManager || !\is_object($data)) {
79
            return null;
80
        }
81
82
        return $objectManager;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $objectManager returns the type Doctrine\Persistence\ObjectManager which includes types incompatible with the type-hinted return Doctrine\Common\Persistence\ObjectManager|null.
Loading history...
83
    }
84
}
85