Passed
Push — master ( 0e4f38...366f40 )
by Christian
13:45 queued 11s
created

ContactFormRoute::load()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 49
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 29
nc 24
nop 2
dl 0
loc 49
rs 8.8337
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Content\ContactForm\SalesChannel;
4
5
use OpenApi\Annotations as OA;
6
use Shopware\Core\Content\ContactForm\Event\ContactFormEvent;
7
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
8
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
9
use Shopware\Core\Framework\Event\EventData\MailRecipientStruct;
10
use Shopware\Core\Framework\Plugin\Exception\DecorationPatternException;
11
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
12
use Shopware\Core\Framework\Routing\Annotation\Since;
13
use Shopware\Core\Framework\Validation\DataBag\DataBag;
14
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
15
use Shopware\Core\Framework\Validation\DataValidationFactoryInterface;
16
use Shopware\Core\Framework\Validation\DataValidator;
17
use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
18
use Shopware\Core\System\SalesChannel\SalesChannelContext;
19
use Shopware\Core\System\SystemConfig\SystemConfigService;
20
use Symfony\Component\Routing\Annotation\Route;
21
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
22
23
/**
24
 * @RouteScope(scopes={"store-api"})
25
 */
26
class ContactFormRoute extends AbstractContactFormRoute
27
{
28
    /**
29
     * @var DataValidationFactoryInterface
30
     */
31
    private $contactFormValidationFactory;
32
33
    /**
34
     * @var DataValidator
35
     */
36
    private $validator;
37
38
    /**
39
     * @var EventDispatcherInterface
40
     */
41
    private $eventDispatcher;
42
43
    /**
44
     * @var SystemConfigService
45
     */
46
    private $systemConfigService;
47
48
    /**
49
     * @var EntityRepositoryInterface
50
     */
51
    private $cmsSlotRepository;
52
53
    /**
54
     * @var EntityRepositoryInterface
55
     */
56
    private $salutationRepository;
57
58
    public function __construct(
59
        DataValidationFactoryInterface $contactFormValidationFactory,
60
        DataValidator $validator,
61
        EventDispatcherInterface $eventDispatcher,
62
        SystemConfigService $systemConfigService,
63
        EntityRepositoryInterface $cmsSlotRepository,
64
        EntityRepositoryInterface $salutationRepository
65
    ) {
66
        $this->contactFormValidationFactory = $contactFormValidationFactory;
67
        $this->validator = $validator;
68
        $this->eventDispatcher = $eventDispatcher;
69
        $this->systemConfigService = $systemConfigService;
70
        $this->cmsSlotRepository = $cmsSlotRepository;
71
        $this->salutationRepository = $salutationRepository;
72
    }
73
74
    public function getDecorated(): AbstractContactFormRoute
75
    {
76
        throw new DecorationPatternException(self::class);
77
    }
78
79
    /**
80
     * @Since("6.2.0.0")
81
     * @OA\Post(
82
     *      path="/contact-form",
83
     *      summary="Send message throught contact form",
84
     *      operationId="sendContactMail",
85
     *      tags={"Store API", "Contact Mail"},
86
     *      @OA\RequestBody(
87
     *          required=true,
88
     *          @OA\JsonContent(
89
     *              @OA\Property(property="salutationId", description="Salutation ID", type="string"),
90
     *              @OA\Property(property="firstName", description="Firstname", type="string"),
91
     *              @OA\Property(property="lastName", description="Lastname", type="string"),
92
     *              @OA\Property(property="email", description="Email", type="string"),
93
     *              @OA\Property(property="phone", description="Phone", type="string"),
94
     *              @OA\Property(property="subject", description="Title", type="string"),
95
     *              @OA\Property(property="comment", description="Message", type="string"),
96
     *          )
97
     *      ),
98
     *      @OA\Response(
99
     *          response="200",
100
     *          description="Message sent"
101
     *     )
102
     * )
103
     * @Route("/store-api/v{version}/contact-form", name="store-api.contact.form", methods={"POST"})
104
     */
105
    public function load(RequestDataBag $data, SalesChannelContext $context): ContactFormRouteResponse
106
    {
107
        $receivers = [];
108
        $message = '';
109
        if ($data->has('slotId')) {
110
            $slotId = $data->get('slotId');
111
112
            if ($slotId) {
113
                $criteria = new Criteria([$slotId]);
114
                $slot = $this->cmsSlotRepository->search($criteria, $context->getContext());
115
116
                $receivers = $slot->getEntities()->first()->getTranslated()['config']['mailReceiver']['value'];
117
                $message = $slot->getEntities()->first()->getTranslated()['config']['confirmationText']['value'];
118
            }
119
        }
120
121
        if (empty($receivers)) {
122
            $receivers[] = $this->systemConfigService->get('core.basicInformation.email', $context->getSalesChannel()->getId());
123
        }
124
125
        $this->validateContactForm($data, $context);
126
127
        $salutationCriteria = new Criteria([$data->get('salutationId')]);
128
        $salutationSearchResult = $this->salutationRepository->search($salutationCriteria, $context->getContext());
129
130
        if ($salutationSearchResult->count() !== 0) {
131
            $data->set('salutation', $salutationSearchResult->first());
132
        }
133
134
        foreach ($receivers as $mail) {
135
            $event = new ContactFormEvent(
136
                $context->getContext(),
137
                $context->getSalesChannel()->getId(),
138
                new MailRecipientStruct([$mail => $mail]),
139
                $data
140
            );
141
142
            $this->eventDispatcher->dispatch(
143
                $event,
144
                ContactFormEvent::EVENT_NAME
0 ignored issues
show
Unused Code introduced by
The call to Symfony\Contracts\EventD...erInterface::dispatch() has too many arguments starting with Shopware\Core\Content\Co...ctFormEvent::EVENT_NAME. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

144
            $this->eventDispatcher->/** @scrutinizer ignore-call */ 
145
                                    dispatch(

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
145
            );
146
        }
147
148
        $result = new ContactFormRouteResponseStruct();
149
        $result->assign([
150
            'individualSuccessMessage' => $message ?? '',
151
        ]);
152
153
        return new ContactFormRouteResponse($result);
154
    }
155
156
    private function validateContactForm(DataBag $data, SalesChannelContext $context): void
157
    {
158
        $definition = $this->contactFormValidationFactory->create($context);
159
        $violations = $this->validator->getViolations($data->all(), $definition);
160
161
        if ($violations->count() > 0) {
162
            throw new ConstraintViolationException($violations, $data->all());
163
        }
164
    }
165
}
166