Completed
Push — master ( 1dbefb...c77374 )
by Jeroen
32s queued 11s
created

FormHandler::dispatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 11
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 11
loc 11
ccs 0
cts 9
cp 0
c 0
b 0
f 0
rs 9.9
cc 2
nc 2
nop 2
crap 6
1
<?php
2
3
namespace Kunstmaan\FormBundle\Helper;
4
5
use ArrayObject;
6
use Doctrine\ORM\EntityManager;
7
use Kunstmaan\FormBundle\Entity\FormAdaptorInterface;
8
use Kunstmaan\FormBundle\Entity\FormSubmission;
9
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
10
use Kunstmaan\FormBundle\Event\FormEvents;
11
use Kunstmaan\FormBundle\Event\SubmissionEvent;
12
use Kunstmaan\NodeBundle\Helper\RenderContext;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
15
use Symfony\Component\Form\Extension\Core\Type\FormType;
16
use Symfony\Component\Form\FormBuilderInterface;
17
use Symfony\Component\HttpFoundation\RedirectResponse;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Routing\RouterInterface;
20
21
/**
22
 * The form handler handles everything from creating the form to handling the submitted form
23
 */
24
class FormHandler implements FormHandlerInterface
25
{
26
    /**
27
     * @var ContainerInterface
28
     */
29
    private $container;
30
31
    /**
32
     * @param ContainerInterface $container
33
     */
34
    public function __construct(ContainerInterface $container)
35
    {
36
        $this->container = $container;
37
    }
38
39
    /**
40
     * @param FormPageInterface $page    The form page
41
     * @param Request           $request The request
42
     * @param RenderContext     $context The render context
43
     *
44
     * @return RedirectResponse|void|null
45
     */
46
    public function handleForm(FormPageInterface $page, Request $request, RenderContext $context)
47
    {
48
        /* @var EntityManager $em */
49
        $em = $this->container->get('doctrine.orm.entity_manager');
50
        /* @var FormBuilderInterface $formBuilder */
51
        $formBuilder = $this->container->get('form.factory')->createBuilder(FormType::class);
52
        /* @var RouterInterface $router */
53
        $router = $this->container->get('router');
54
        /* @var ArrayObject $fields */
55
        $fields = new ArrayObject();
56
        $pageParts = $em->getRepository('KunstmaanPagePartBundle:PagePartRef')->getPageParts($page, $page->getFormElementsContext());
0 ignored issues
show
Bug introduced by Daan Poron
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getPageParts() does only exist in the following implementations of said interface: Kunstmaan\PagePartBundle...y\PagePartRefRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
57
        foreach ($pageParts as $sequence => $pagePart) {
58
            if ($pagePart instanceof FormAdaptorInterface) {
59
                $pagePart->adaptForm($formBuilder, $fields, $sequence);
60
            }
61
        }
62
63
        $form = $formBuilder->getForm();
64
        if ($request->getMethod() == 'POST') {
65
            $form->handleRequest($request);
66
            if ($form->isSubmitted() && $form->isValid()) {
67
                $formSubmission = new FormSubmission();
68
                $formSubmission->setIpAddress($request->getClientIp());
69
                $formSubmission->setNode($em->getRepository('KunstmaanNodeBundle:Node')->getNodeFor($page));
0 ignored issues
show
Bug introduced by Daan Poron
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getNodeFor() does only exist in the following implementations of said interface: Kunstmaan\NodeBundle\Repository\NodeRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
70
                $formSubmission->setLang($request->getLocale());
71
                $em->persist($formSubmission);
72
73
                /* @var FormSubmissionField $field */
74
                foreach ($fields as $field) {
75
                    $field->setSubmission($formSubmission);
76
                    $field->onValidPost($form, $formBuilder, $request, $this->container);
77
                    $em->persist($field);
78
                }
79
80
                $em->flush();
81
                $em->refresh($formSubmission);
82
83
                $event = new SubmissionEvent($formSubmission, $page);
84
                $this->dispatch($event, FormEvents::ADD_SUBMISSION);
85
86
                return new RedirectResponse($page->generateThankYouUrl($router, $context));
87
            }
88
        }
89
        $context['frontendform'] = $form->createView();
90
        $context['frontendformobject'] = $form;
91
92
        return null;
93
    }
94
95
    /**
96
     * @param object $event
97
     * @param string $eventName
98
     *
99
     * @return object
100
     */
101 View Code Duplication
    private function dispatch($event, string $eventName)
0 ignored issues
show
Duplication introduced by Jeroen Thora
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        $eventDispatcher = $this->container->get('event_dispatcher');
104
        if (class_exists(LegacyEventDispatcherProxy::class)) {
105
            $eventDispatcher = LegacyEventDispatcherProxy::decorate($eventDispatcher);
106
107
            return $eventDispatcher->dispatch($event, $eventName);
108
        }
109
110
        return $eventDispatcher->dispatch($eventName, $event);
111
    }
112
}
113