Completed
Push — master ( 22f213...24f6ce )
by Guilherme
17:25
created

DefaultController::contactAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 3
nop 2
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\CoreBundle\Controller;
12
13
use LoginCidadao\APIBundle\Entity\ActionLogRepository;
14
use LoginCidadao\CoreBundle\Model\SupportMessage;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
18
use Symfony\Component\Security\Core\User\UserInterface;
19
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
22
use LoginCidadao\CoreBundle\Entity\SentEmail;
23
use LoginCidadao\APIBundle\Entity\LogoutKey;
24
25
class DefaultController extends Controller
26
{
27
28
    /**
29
     * @Route("/help", name="lc_help")
30
     * @Template()
31
     */
32
    public function helpAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
33
    {
34
        return $this->render('LoginCidadaoCoreBundle:Info:help.html.twig');
35
    }
36
37
    /**
38
     * @Route("/contact/{correlationId}", defaults={"correlationId" = null}, name="lc_contact")
39
     * @Template()
40
     */
41
    public function contactAction(Request $request, $correlationId = null)
42
    {
43
        $data = new SupportMessage();
44
        $form = $this->createForm('contact_form_type', $data);
45
        $form->handleRequest($request);
46
        $translator = $this->get('translator');
47
        $message = $translator->trans('contact.form.sent');
48
49
        if ($form->isValid()) {
50
            $email = $this->getEmail($data, $correlationId);
51
            $swiftMail = $email->getSwiftMail();
52
            if ($this->get('mailer')->send($swiftMail)) {
53
                $em = $this->getDoctrine()->getManager();
54
                $em->persist($email);
55
                $em->flush();
56
                $this->get('session')->getFlashBag()->add('success', $message);
57
            }
58
59
            return $this->redirectToRoute('lc_contact');
60
        }
61
62
        return $this->render('LoginCidadaoCoreBundle:Info:contact.html.twig', ['form' => $form->createView()]);
63
    }
64
65
    /**
66
     * @Route("/dashboard", name="lc_dashboard")
67
     * @Template()
68
     */
69
    public function dashboardAction()
70
    {
71
        // badges
72
        $badgesHandler = $this->get('badges.handler');
73
        $badges = $badgesHandler->getAvailableBadges();
74
        $userBadges = $badgesHandler->evaluate($this->getUser())->getBadges();
75
76
        // logs
77
        $em = $this->getDoctrine()->getManager();
78
79
        /** @var ActionLogRepository $logRepo */
80
        $logRepo = $em->getRepository('LoginCidadaoAPIBundle:ActionLog');
81
        $logs['logins'] = $logRepo->findLoginsByPerson($this->getUser(), 5);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$logs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $logs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<LoginCidadao\Core...\Model\PersonInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
82
        $logs['activity'] = $logRepo->getActivityLogsByTarget($this->getUser(), 4);
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<LoginCidadao\Core...\Model\PersonInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
83
84
        $defaultClientUid = $this->container->getParameter('oauth_default_client.uid');
85
86
        return array(
87
            'allBadges' => $badges,
88
            'userBadges' => $userBadges,
89
            'logs' => $logs,
90
            'defaultClientUid' => $defaultClientUid,
91
        );
92
    }
93
94
    /**
95
     * @Route("/logout/if-not-remembered/{key}", name="lc_logout_not_remembered_safe")
96
     * @Template()
97
     */
98
    public function safeLogoutIfNotRememberedAction(Request $request, $key)
99
    {
100
        $em = $this->getDoctrine()->getManager();
101
        $logoutKeys = $em->getRepository('LoginCidadaoAPIBundle:LogoutKey');
102
        $logoutKey = $logoutKeys->findActiveByKey($key);
103
104
        if (!($logoutKey instanceof LogoutKey)) {
105
            throw new AccessDeniedException("Invalid logout key.");
106
        }
107
108
        $result['logged_out'] = false;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
109
        if ($this->getUser() instanceof UserInterface) {
110
            if ($request->cookies->has($this->getParameter('session.remember_me.name'))) {
111
                $result = array('logged_out' => false);
112
            } else {
113
                $this->get("request")->getSession()->invalidate();
114
                $this->get("security.token_storage")->setToken(null);
115
                $result['logged_out'] = true;
116
            }
117
        } else {
118
            $result['logged_out'] = true;
119
        }
120
121
        $response = new JsonResponse();
122
        $userAgent = $request->headers->get('User-Agent');
123
        if (preg_match('/(?i)msie [1-9]/', $userAgent)) {
124
            $response->headers->set('Content-Type', 'text/json');
125
        }
126
127
        $client = $logoutKey->getClient();
128
        $em->remove($logoutKey);
129
        $em->flush();
130
131
        $redirectUrl = $request->get('redirect_url');
132
        if ($redirectUrl !== null) {
133
            $host = parse_url($redirectUrl, PHP_URL_HOST);
134
            if ($client->ownsDomain($host)) {
135
                return $this->redirect($redirectUrl);
136
            } else {
137
                $result['error'] = "Invalid redirect_url domain. It doesn't appear to belong to {$client->getName()}";
138
            }
139
        }
140
141
        return $response->setData($result);
142
    }
143
144
    /**
145
     * @Route("/_home", name="lc_index")
146
     * @Template()
147
     */
148
    public function indexAction(Request $request, $lastUsername)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
149
    {
150
        ['last_username' => $lastUsername];
151
    }
152
153
    private function getEmail(SupportMessage $supportMessage, $correlationId = null)
154
    {
155
        $message = $supportMessage->getMessage();
156
        if ($correlationId !== null) {
157
            $message = "<p>$message</p><p>Correlation Id: {$correlationId}</p>";
158
        }
159
160
        $email = (new SentEmail())
161
            ->setType('contact-mail')
162
            ->setSubject('Fale conosco - '.$supportMessage->getName())
163
            ->setSender($supportMessage->getEmail())
164
            ->setReceiver($this->container->getParameter('contact_form.email'))
165
            ->setMessage($message);
166
167
        return $email;
168
    }
169
}
170