Completed
Pull Request — master (#1464)
by
unknown
03:21
created

DataPersister::remove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
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\Common;
15
16
use ApiPlatform\Core\DataPersister\DataPersisterInterface;
17
use ApiPlatform\Core\Util\ClassInfoTrait;
18
use Doctrine\Common\Persistence\ManagerRegistry;
19
use Doctrine\Common\Persistence\ObjectManager as DoctrineObjectManager;
20
21
/**
22
 * Data persister for Doctrine.
23
 *
24
 * @author Baptiste Meyer <[email protected]>
25
 */
26
final class DataPersister implements DataPersisterInterface
27
{
28
    use ClassInfoTrait;
29
30
    private $managerRegistry;
31
32
    public function __construct(ManagerRegistry $managerRegistry)
33
    {
34
        $this->managerRegistry = $managerRegistry;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function supports($data): bool
41
    {
42
        return null !== $this->getManager($data);
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function persist($data)
49
    {
50
        if (!$manager = $this->getManager($data)) {
51
            return;
52
        }
53
54
        $manager->persist($data);
55
        $manager->flush();
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function remove($data)
62
    {
63
        if (!$manager = $this->getManager($data)) {
64
            return;
65
        }
66
67
        $manager->remove($data);
68
        $manager->flush();
69
    }
70
71
    /**
72
     * Gets the Doctrine object manager associated with given data.
73
     *
74
     * @param mixed $data
75
     *
76
     * @return DoctrineObjectManager|null
77
     */
78
    private function getManager($data)
79
    {
80
        return is_object($data) ? $this->managerRegistry->getManagerForClass($this->getObjectClass($data)) : null;
81
    }
82
}
83