Passed
Push — master ( a6dc76...6d79cb )
by Guilherme
01:12 queued 11s
created

AdminBlocklistController::newAction()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 3
nop 1
dl 0
loc 28
rs 9.7
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\PhoneVerificationBundle\Controller;
12
13
use libphonenumber\NumberParseException;
14
use libphonenumber\PhoneNumber;
15
use libphonenumber\PhoneNumberType;
16
use libphonenumber\PhoneNumberUtil;
17
use LoginCidadao\CoreBundle\Entity\PersonRepository;
18
use LoginCidadao\CoreBundle\Helper\GridHelper;
19
use LoginCidadao\PhoneVerificationBundle\Entity\BlockedPhoneNumber;
20
use LoginCidadao\PhoneVerificationBundle\Entity\BlockedPhoneNumberRepository;
21
use LoginCidadao\PhoneVerificationBundle\Form\BlockPhoneFormType;
22
use LoginCidadao\PhoneVerificationBundle\Form\SearchPhoneNumberType;
23
use LoginCidadao\PhoneVerificationBundle\Model\BlockedPhoneNumberInterface;
24
use LoginCidadao\PhoneVerificationBundle\Model\BlockPhoneNumberRequest;
25
use LoginCidadao\PhoneVerificationBundle\Service\BlocklistInterface;
26
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpFoundation\Session\Session;
29
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
use Symfony\Component\Routing\Annotation\Route;
32
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
34
35
/**
36
 * Class AdminBlocklistController
37
 * @package LoginCidadao\PhoneVerificationBundle\Controller
38
 *
39
 * @Security("has_role('ROLE_EDIT_BLOCKED_PHONES')")
40
 * @codeCoverageIgnore
41
 */
42
class AdminBlocklistController extends Controller
43
{
44
    /**
45
     * @Route("/admin/phones/blocklist", name="phone_blocklist_list")
46
     * @Template()
47
     */
48
    public function listAction(Request $request)
49
    {
50
        $form = $this->createForm(SearchPhoneNumberType::class);
51
52
        $form->handleRequest($request);
53
        if ($form->isSubmitted() && $form->isValid()) {
54
            $data = $form->getData();
55
56
            $grid = new GridHelper();
57
            $grid->setId('person-grid');
58
            $grid->setPerPage(5);
59
            $grid->setMaxResult(5);
60
            $grid->setInfiniteGrid(true);
61
            $grid->setRoute('lc_admin_person_grid');
62
            $grid->setRouteParams([$form->getName()]);
63
64
            if ($data['phone']) {
65
                /** @var BlockedPhoneNumberRepository $blockedPhoneRepo */
66
                $blockedPhoneRepo = $this->getDoctrine()->getRepository(BlockedPhoneNumber::class);
67
                $query = $blockedPhoneRepo->getSearchByPartialPhoneQuery($data['phone']);
68
                $grid->setQueryBuilder($query);
0 ignored issues
show
Deprecated Code introduced by
The function LoginCidadao\CoreBundle\...lper::setQueryBuilder() has been deprecated: since version 1.1.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

68
                /** @scrutinizer ignore-deprecated */ $grid->setQueryBuilder($query);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
69
            }
70
71
            $gridView = $grid->createView($request);
72
        }
73
74
        return [
75
            'form' => $form->createView(),
76
            'grid' => $gridView ?? null,
77
        ];
78
    }
79
80
    /**
81
     * @Route("/admin/phones/blocklist/new", name="phone_blocklist_new")
82
     * @Template()
83
     */
84
    public function newAction(Request $request)
85
    {
86
        $blockRequest = new BlockPhoneNumberRequest($this->getUser());
0 ignored issues
show
Bug introduced by
It seems like $this->getUser() can also be of type null; however, parameter $blockedBy of LoginCidadao\PhoneVerifi...rRequest::__construct() does only seem to accept LoginCidadao\CoreBundle\Model\PersonInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

86
        $blockRequest = new BlockPhoneNumberRequest(/** @scrutinizer ignore-type */ $this->getUser());
Loading history...
87
88
        $blockedPhones = [];
89
        $form = $this->createForm(BlockPhoneFormType::class, $blockRequest);
90
91
        $form->handleRequest($request);
92
        if ($form->isSubmitted() && $form->isValid()) {
93
            $phoneNumber = $blockRequest->phoneNumber;
94
95
            $blocklist = $this->getBlocklistService();
96
            $blockedPhoneNumber = $blocklist->addBlockedPhoneNumber($phoneNumber, $blockRequest->getBlockedBy());
97
            $blockedPhones = $blocklist->checkPhoneNumber($blockedPhoneNumber->getPhoneNumber());
98
99
            /** @var Session $session */
100
            $session = $request->getSession();
101
            $session->getFlashBag()->add('success', "Phone number successfully banned.");
102
            if (($count = count($blockedPhones)) > 0) {
103
                $session->getFlashBag()->add('success', "{$count} accounts were blocked blocked.");
104
            }
105
106
            return $this->redirectToRoute('phone_blocklist_list');
107
        }
108
109
        return [
110
            'form' => $form->createView(),
111
            'blockedPhones' => $blockedPhones,
112
        ];
113
    }
114
115
    /**
116
     * @Route("/admin/phones/blocklist/{phone}", name="phone_blocklist_details", requirements={"phone": "[0-9+]+"})
117
     * @Template()
118
     */
119
    public function detailsAction(Request $request, string $phone)
120
    {
121
        $phoneNumber = $this->parsePhone($phone);
122
        $blockedPhone = $this->getOr404($phoneNumber);
123
124
        return [
125
            'blockedPhone' => $blockedPhone,
126
            'grid' => $this->getUsersByPhoneGrid($request, $phoneNumber),
127
        ];
128
    }
129
130
    /**
131
     * @return BlocklistInterface
132
     */
133
    private function getBlocklistService(): BlocklistInterface
134
    {
135
        /** @var BlocklistInterface $blocklistService */
136
        $blocklistService = $this->get('phone_verification.blocklist');
137
138
        return $blocklistService;
139
    }
140
141
    private function parsePhone($phone): PhoneNumber
142
    {
143
        $phoneUtils = PhoneNumberUtil::getInstance();
144
        try {
145
            return $phoneUtils->parse($phone);
146
        } catch (NumberParseException $e) {
147
            throw new BadRequestHttpException("Invalid phone number");
148
        }
149
    }
150
151
    private function getOr404(PhoneNumber $phoneNumber): BlockedPhoneNumberInterface
152
    {
153
        $blocklistService = $this->getBlocklistService();
154
        $blockedPhone = $blocklistService->getBlockedPhoneNumberByPhone($phoneNumber);
155
156
        if (null === $blockedPhone) {
157
            throw new NotFoundHttpException("Blocked Phone Number not found");
158
        }
159
160
        return $blockedPhone;
161
    }
162
163
    private function getUsersByPhoneGrid(Request $request, PhoneNumber $phoneNumber)
164
    {
165
        $grid = new GridHelper();
166
        $grid->setId('person-grid');
167
        $grid->setPerPage(5);
168
        $grid->setMaxResult(5);
169
        $grid->setInfiniteGrid(true);
170
        $grid->setRoute('phone_blocklist_details');
171
        $grid->setRouteParams(['phone']);
172
173
        /** @var PersonRepository $repo */
174
        $repo = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Person');
175
        $query = $repo->getPhoneSearchQuery($phoneNumber);
176
        $grid->setQueryBuilder($query);
0 ignored issues
show
Deprecated Code introduced by
The function LoginCidadao\CoreBundle\...lper::setQueryBuilder() has been deprecated: since version 1.1.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

176
        /** @scrutinizer ignore-deprecated */ $grid->setQueryBuilder($query);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
177
178
        return $grid->createView($request);
179
    }
180
}
181