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

PositionRemoveEventListener   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 25
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A onPreWrite() 0 16 6
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