Passed
Push — trunk ( ee04ee...d8d59f )
by Christian
13:00 queued 13s
created

TriggerFlowController::checkAppEventIsExist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 8
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Content\Flow\Controller;
4
5
use Shopware\Core\Content\Flow\Exception\CustomTriggerByNameNotFoundException;
6
use Shopware\Core\Framework\App\Event\CustomAppEvent;
7
use Shopware\Core\Framework\Context;
8
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
9
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
10
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
11
use Shopware\Core\Framework\Log\Package;
12
use Shopware\Core\Framework\Routing\Annotation\Since;
13
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
14
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
15
use Symfony\Component\HttpFoundation\JsonResponse;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\Routing\Annotation\Route;
19
20
#[Route(defaults: ['_routeScope' => ['api']])]
21
#[Package('business-ops')]
22
class TriggerFlowController extends AbstractController
23
{
24
    /**
25
     * @internal
26
     */
27
    public function __construct(
28
        private readonly EventDispatcherInterface $eventDispatcher,
29
        private readonly EntityRepository $appFlowEventRepository,
30
    ) {
31
    }
32
33
    /**
34
     * @Since("6.5.2.0")
35
     */
36
    #[Route(path: '/api/_action/trigger-event/{eventName}', name: 'api.action.trigger_event', methods: ['POST'])]
37
    public function trigger(string $eventName, Request $request, Context $context): JsonResponse
38
    {
39
        $data = $request->request->all();
40
41
        $this->checkAppEventIsExist($eventName, $context);
42
43
        $this->eventDispatcher->dispatch(new CustomAppEvent($eventName, $data, $context), $eventName);
44
45
        return new JsonResponse([
46
            'message' => \sprintf('The trigger `%s`successfully dispatched!', $eventName),
47
        ], Response::HTTP_OK);
48
    }
49
50
    private function checkAppEventIsExist(string $eventName, Context $context): void
51
    {
52
        $criteria = new Criteria();
53
        $criteria->setLimit(1);
54
        $criteria->addFilter(new EqualsFilter('name', $eventName));
55
        $criteria->addFilter(new EqualsFilter('app.active', 1));
56
57
        $this->appFlowEventRepository->search($criteria, $context)->first() ?? throw new CustomTriggerByNameNotFoundException($eventName);
58
    }
59
}
60