Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

src/Kunstmaan/FormBundle/Helper/FormHandler.php (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\Form\Extension\Core\Type\FormType;
15
use Symfony\Component\Form\FormBuilderInterface;
16
use Symfony\Component\HttpFoundation\RedirectResponse;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\Routing\RouterInterface;
19
20
/**
21
 * The form handler handles everything from creating the form to handling the submitted form
22
 */
23
class FormHandler implements FormHandlerInterface
24
{
25
    /**
26
     * @var ContainerInterface
27
     */
28
    private $container;
29
30
    /**
31
     * @param ContainerInterface $container
32
     */
33
    public function __construct(ContainerInterface $container)
34
    {
35
        $this->container = $container;
36
    }
37
38
    /**
39
     * @param FormPageInterface $page    The form page
40
     * @param Request           $request The request
41
     * @param RenderContext     $context The render context
42
     *
43
     * @return RedirectResponse|void|null
44
     */
45
    public function handleForm(FormPageInterface $page, Request $request, RenderContext $context)
46
    {
47
        /* @var EntityManager $em */
48
        $em = $this->container->get('doctrine.orm.entity_manager');
49
        /* @var FormBuilderInterface $formBuilder */
50
        $formBuilder = $this->container->get('form.factory')->createBuilder(FormType::class);
51
        /* @var RouterInterface $router */
52
        $router = $this->container->get('router');
53
        /* @var ArrayObject $fields */
54
        $fields = new ArrayObject();
55
        $pageParts = $em->getRepository('KunstmaanPagePartBundle:PagePartRef')->getPageParts($page, $page->getFormElementsContext());
0 ignored issues
show
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...
56
        foreach ($pageParts as $sequence => $pagePart) {
57
            if ($pagePart instanceof FormAdaptorInterface) {
58
                $pagePart->adaptForm($formBuilder, $fields, $sequence);
59
            }
60
        }
61
62
        $form = $formBuilder->getForm();
63
        if ($request->getMethod() == 'POST') {
64
            $form->handleRequest($request);
65
            if ($form->isSubmitted() && $form->isValid()) {
66
                $formSubmission = new FormSubmission();
67
                $formSubmission->setIpAddress($request->getClientIp());
68
                $formSubmission->setNode($em->getRepository('KunstmaanNodeBundle:Node')->getNodeFor($page));
0 ignored issues
show
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...
69
                $formSubmission->setLang($request->getLocale());
70
                $em->persist($formSubmission);
71
72
                /* @var FormSubmissionField $field */
73
                foreach ($fields as $field) {
74
                    $field->setSubmission($formSubmission);
75
                    $field->onValidPost($form, $formBuilder, $request, $this->container);
76
                    $em->persist($field);
77
                }
78
79
                $em->flush();
80
                $em->refresh($formSubmission);
81
82
                $event = new SubmissionEvent($formSubmission, $page);
83
                $this->container->get('event_dispatcher')->dispatch(FormEvents::ADD_SUBMISSION, $event);
84
85
                return new RedirectResponse($page->generateThankYouUrl($router, $context));
86
            }
87
        }
88
        $context['frontendform'] = $form->createView();
89
        $context['frontendformobject'] = $form;
90
91
        return null;
92
    }
93
}
94