ConnectionController::checkAction()   F
last analyzed

Complexity

Conditions 11
Paths 326

Size

Total Lines 96
Code Lines 63

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 96
rs 3.8181
cc 11
eloc 63
nc 326
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Oro\Bundle\ImapBundle\Controller;
4
5
use FOS\RestBundle\Util\Codes;
6
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
14
use Oro\Bundle\EmailBundle\Mailer\DirectMailer;
15
use Oro\Bundle\EmailBundle\Entity\Mailbox;
16
use Oro\Bundle\ImapBundle\Connector\ImapConfig;
17
use Oro\Bundle\ImapBundle\Entity\UserEmailOrigin;
18
use Oro\Bundle\ImapBundle\Manager\ImapEmailFolderManager;
19
use Oro\Bundle\UserBundle\Entity\User;
20
use Oro\Bundle\OrganizationBundle\Entity\Organization;
21
22
class ConnectionController extends Controller
23
{
24
    /**
25
     * @var ImapEmailFolderManager
26
     */
27
    protected $manager;
28
29
    /**
30
     * @Route("/connection/check", name="oro_imap_connection_check", methods={"POST"})
31
     */
32
    public function checkAction(Request $request)
33
    {
34
        $responseCode = Codes::HTTP_BAD_REQUEST;
35
36
        $data = null;
37
        $id = $request->get('id', false);
38
        if (false !== $id) {
39
            $data = $this->getDoctrine()->getRepository('OroImapBundle:UserEmailOrigin')->find($id);
40
        }
41
42
        $form = $this->createForm('oro_imap_configuration', null, ['csrf_protection' => false,]);
43
        $form->setData($data);
44
        $form->submit($request);
45
        /** @var UserEmailOrigin $origin */
46
        $origin = $form->getData();
47
48
        if ($form->isValid() && null !== $origin) {
49
            $response = [];
50
            $password = $this->get('oro_security.encoder.mcrypt')->decryptData($origin->getPassword());
51
52
            if ($origin->getImapHost() !== null) {
53
                $response['imap'] = [];
54
55
                $config = new ImapConfig(
56
                    $origin->getImapHost(),
57
                    $origin->getImapPort(),
58
                    $origin->getImapEncryption(),
59
                    $origin->getUser(),
60
                    $password
61
                );
62
63
                try {
64
                    $connector = $this->get('oro_imap.connector.factory')->createImapConnector($config);
65
                    $this->manager = new ImapEmailFolderManager(
66
                        $connector,
67
                        $this->getDoctrine()->getManager(),
0 ignored issues
show
Compatibility introduced by
$this->getDoctrine()->getManager() of type object<Doctrine\Common\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
68
                        $origin
69
                    );
70
71
                    $emailFolders = $this->manager->getFolders();
72
                    $origin->setFolders($emailFolders);
73
74
                    $entity = $request->get('for_entity', 'user');
75
                    $organizationId = $request->get('organization');
76
                    $organization = $this->getOrganization($organizationId);
77
                    if ($entity === 'user') {
78
                        $user = new User();
79
                        $user->setImapConfiguration($origin);
80
                        $user->setOrganization($organization);
0 ignored issues
show
Bug introduced by
It seems like $organization defined by $this->getOrganization($organizationId) on line 76 can also be of type object; however, Oro\Bundle\UserBundle\En...User::setOrganization() does only seem to accept null|object<Oro\Bundle\O...\OrganizationInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
81
                        $userForm = $this->get('oro_user.form.user');
82
                        $userForm->setData($user);
83
84
                        $response['imap']['folders'] = $this->renderView('OroImapBundle:Connection:check.html.twig', [
85
                            'form' => $userForm->createView(),
86
                        ]);
87
                    } elseif ($entity === 'mailbox') {
88
                        $mailbox = new Mailbox();
89
                        $mailbox->setOrigin($origin);
90
                        if ($organization) {
91
                            $mailbox->setOrganization($organization);
92
                        }
93
                        $mailboxForm = $this->createForm('oro_email_mailbox');
94
                        $mailboxForm->setData($mailbox);
95
96
                        $response['imap']['folders'] = $this->renderView(
97
                            'OroImapBundle:Connection:checkMailbox.html.twig',
98
                            [
99
                                'form' => $mailboxForm->createView(),
100
                            ]
101
                        );
102
                    }
103
                } catch (\Exception $e) {
104
                    $response['imap']['error'] = $e->getMessage();
105
                }
106
            }
107
108
            if ($origin->getSmtpHost() !== null) {
109
                $response['smtp'] = [];
110
111
                try {
112
                    /** @var DirectMailer $mailer */
113
                    $mailer = $this->get('oro_email.direct_mailer');
114
                    // Prepare Smtp Transport
115
                    $mailer->prepareSmtpTransport($origin);
116
                    $transport = $mailer->getTransport();
117
                    $transport->start();
118
                } catch (\Exception $e) {
119
                    $response['smtp']['error'] = $e->getMessage();
120
                }
121
            }
122
123
            return new JsonResponse($response);
124
        }
125
126
        return new Response('', $responseCode);
127
    }
128
129
    /**
130
     * @Route("imap/connection/account/change", name="oro_imap_change_account_type", methods={"POST"})
131
     */
132
    public function getFormAction()
133
    {
134
        $request = $this->container->get('request_stack')->getCurrentRequest();
135
        $type = $request->get('type');
136
        $token = $request->get('accessToken');
137
        $formParentName = $request->get('formParentName');
138
139
        $connectionControllerManager = $this->container->get('oro_imap.manager.controller.connection');
140
        $form = $connectionControllerManager->getImapConnectionForm($type, $token, $formParentName);
141
142
        if ($token) {
143
            $html = $this->renderView('OroImapBundle:Form:accountTypeGmail.html.twig', [
144
                'form' => $form->createView(),
145
            ]);
146
        } else {
147
            $html = $this->renderView('OroImapBundle:Form:accountTypeOther.html.twig', [
148
                'form' => $form->createView(),
149
            ]);
150
        }
151
152
        $response = ['html' => $html];
153
154
        return new JsonResponse($response);
155
    }
156
157
    /**
158
     * @param int|null $id
159
     *
160
     * @return Organization|null
161
     */
162
    protected function getOrganization($id)
163
    {
164
        if (!$id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
165
            return null;
166
        }
167
168
        return $this->getDoctrine()->getRepository('OroOrganizationBundle:Organization')->find($id);
169
    }
170
}
171