CustomerRegistrationFormSubscriber   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 5
dl 0
loc 51
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 6 1
B preSubmit() 0 22 6
1
<?php
2
3
/*
4
 * This file is part of AppName.
5
 *
6
 * (c) Monofony
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
namespace App\Form\EventSubscriber;
13
14
use App\Entity\Customer\CustomerInterface;
15
use Sylius\Component\Resource\Repository\RepositoryInterface;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\Form\Exception\UnexpectedTypeException;
18
use Symfony\Component\Form\FormEvent;
19
use Symfony\Component\Form\FormEvents;
20
21
final class CustomerRegistrationFormSubscriber implements EventSubscriberInterface
22
{
23
    /**
24
     * @var RepositoryInterface
25
     */
26
    private $customerRepository;
27
28
    /**
29
     * @param RepositoryInterface $customerRepository
30
     */
31
    public function __construct(RepositoryInterface $customerRepository)
32
    {
33
        $this->customerRepository = $customerRepository;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public static function getSubscribedEvents()
40
    {
41
        return [
42
            FormEvents::PRE_SUBMIT => 'preSubmit',
43
        ];
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function preSubmit(FormEvent $event): void
50
    {
51
        $rawData = $event->getData();
52
        $form = $event->getForm();
53
        $data = $form->getData();
54
55
        if (!$data instanceof CustomerInterface) {
56
            throw new UnexpectedTypeException($data, CustomerInterface::class);
57
        }
58
59
        // if email is not filled in, go on
60
        if (!isset($rawData['email']) || empty($rawData['email'])) {
61
            return;
62
        }
63
        $existingCustomer = $this->customerRepository->findOneBy(['email' => $rawData['email']]);
64
        if (null === $existingCustomer || null !== $existingCustomer->getUser()) {
65
            return;
66
        }
67
68
        $existingCustomer->setUser($data->getUser());
69
        $form->setData($existingCustomer);
70
    }
71
}
72