Test Failed
Push — main ( eafc82...249bd3 )
by Daniel
04:23
created

PositionRemoveEventListener::onPreWrite()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 16
rs 9.2222
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[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 Silverback\ApiComponentsBundle\EventListener\Api;
15
16
use Doctrine\Persistence\ManagerRegistry;
17
use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent;
18
use Silverback\ApiComponentsBundle\Entity\Core\ComponentPosition;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpKernel\Event\ViewEvent;
21
22
/**
23
 * @author Daniel West <[email protected]>
24
 */
25
class PositionRemoveEventListener
26
{
27
    private ManagerRegistry $registry;
28
29
    public function __construct(ManagerRegistry $registry)
30
    {
31
        $this->registry = $registry;
32
    }
33
34
    public function onPreWrite(ViewEvent $event): void
35
    {
36
        $request = $event->getRequest();
37
        $data = $request->attributes->get('data');
38
        if (!$data instanceof AbstractComponent || !$request->isMethod(Request::METHOD_DELETE)) {
39
            return;
40
        }
41
42
        $positions = $data->getComponentPositions();
43
        $manager = $this->registry->getManagerForClass(ComponentPosition::class);
44
        if (!$manager) {
45
            return;
46
        }
47
        foreach ($positions as $position) {
48
            if (!$position->pageDataProperty) {
49
                $manager->remove($position);
50
            }
51
        }
52
    }
53
}
54