Completed
Pull Request — develop (#177)
by A.
07:53 queued 03:30
created

getAllowedSecondFactorListService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * Copyright 2016 SURFnet B.V.
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\ManagementBundle\Controller;
20
21
use DateTime;
22
use Exception;
23
use Liip\FunctionalTestBundle\Validator\DataCollectingValidator;
24
use Rhumsaa\Uuid\Uuid;
25
use Surfnet\Stepup\Helper\JsonHelper;
26
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\AllowedSecondFactorListService;
27
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\InstitutionConfigurationOptionsService;
28
use Surfnet\StepupMiddleware\ApiBundle\Exception\BadCommandRequestException;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Command;
30
use Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Command\ReconfigureInstitutionConfigurationOptionsCommand;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
31
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\ForbiddenException;
32
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
33
use Surfnet\StepupMiddleware\ManagementBundle\Service\DBALConnectionHelper;
34
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Constraints\ValidReconfigureInstitutionsRequest;
35
use Symfony\Bridge\Monolog\Logger;
36
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
37
use Symfony\Component\HttpFoundation\JsonResponse;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
40
41
/**
42
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
43
 */
44
final class InstitutionConfigurationController extends Controller
45
{
46
    public function showAction()
47
    {
48
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
49
50
        $institutionConfigurationOptions = $this->getInstitutionConfigurationOptionsService()
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionConfigurationOptions exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
51
            ->findAllInstitutionConfigurationOptions();
52
53
        $allowedSecondFactorMap = $this->getAllowedSecondFactorListService()->getAllowedSecondFactorMap();
54
55
        $overview = [];
56
        foreach ($institutionConfigurationOptions as $options) {
57
            $overview[$options->institution->getInstitution()] = [
58
                'use_ra_locations' => $options->useRaLocationsOption,
59
                'show_raa_contact_information' => $options->showRaaContactInformationOption,
60
                'allowed_second_factors' => $allowedSecondFactorMap->getAllowedSecondFactorListFor(
61
                    $options->institution
62
                ),
63
            ];
64
        }
65
66
        return new JsonResponse($overview);
67
    }
68
69
    public function reconfigureAction(Request $request)
70
    {
71
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
72
73
        $configuration = JsonHelper::decode($request->getContent());
74
75
        $violations = $this->getValidator()->validate($configuration, new ValidReconfigureInstitutionsRequest());
76
        if ($violations->count() > 0) {
77
            throw BadCommandRequestException::withViolations('Invalid reconfigure institutions request', $violations);
78
        }
79
80
        if (empty($configuration)) {
81
            $this->getLogger()->notice(sprintf('No institutions to reconfigure: empty configuration received'));
82
83
            return new JsonResponse([
84
                'status'       => 'OK',
85
                'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
86
                'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
87
            ]);
88
        }
89
90
        $commands = [];
91
        foreach ($configuration as $institution => $options) {
92
            $command                                  = new ReconfigureInstitutionConfigurationOptionsCommand();
93
            $command->UUID                            = (string) Uuid::uuid4();
94
            $command->institution                     = $institution;
0 ignored issues
show
Documentation Bug introduced by
It seems like $institution can also be of type integer. However, the property $institution is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
95
            $command->useRaLocationsOption            = $options['use_ra_locations'];
96
            $command->showRaaContactInformationOption = $options['show_raa_contact_information'];
97
            $command->allowedSecondFactors            = $options['allowed_second_factors'];
98
99
            $commands[] = $command;
100
        }
101
102
        $this->getLogger()->notice(
103
            sprintf('Executing %s reconfigure institution configuration options commands', count($commands))
104
        );
105
106
        $this->handleCommands($commands);
107
108
        return new JsonResponse([
109
            'status'       => 'OK',
110
            'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
111
            'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
112
        ]);
113
    }
114
115
    /**
116
     * @param Command[] $commands
117
     * @throws Exception
118
     */
119
    private function handleCommands(array $commands)
120
    {
121
        $pipeline         = $this->getPipeline();
122
        $connectionHelper = $this->getConnectionHelper();
123
124
        $connectionHelper->beginTransaction();
125
126
        foreach ($commands as $command) {
127
            try {
128
                $pipeline->process($command);
129
            } catch (ForbiddenException $e) {
130
                $connectionHelper->rollBack();
131
132
                throw new AccessDeniedHttpException(
133
                    sprintf('Processing of command "%s" is forbidden for this client', $command),
134
                    $e
135
                );
136
            } catch (Exception $exception) {
137
                $connectionHelper->rollBack();
138
139
                throw $exception;
140
            }
141
        }
142
143
        $connectionHelper->commit();
144
    }
145
146
    /**
147
     * @return InstitutionConfigurationOptionsService
148
     */
149
    private function getInstitutionConfigurationOptionsService()
150
    {
151
        return $this->get('surfnet_stepup_middleware_api.service.institution_configuration_options');
152
    }
153
154
    /**
155
     * @return AllowedSecondFactorListService
156
     */
157
    private function getAllowedSecondFactorListService()
158
    {
159
        return $this->get('surfnet_stepup_middleware_api.service.allowed_second_factor_list');
160
    }
161
162
    /**
163
     * @return DataCollectingValidator
164
     */
165
    private function getValidator()
166
    {
167
        return $this->get('validator');
168
    }
169
170
    /**
171
     * @return Logger
172
     */
173
    private function getLogger()
174
    {
175
        return $this->get('logger');
176
    }
177
178
    /**
179
     * @return Pipeline
180
     */
181
    private function getPipeline()
182
    {
183
        return $this->get('pipeline');
184
    }
185
186
    /**
187
     * @return DBALConnectionHelper
188
     */
189
    private function getConnectionHelper()
190
    {
191
        return $this->get('surfnet_stepup_middleware_management.dbal_connection_helper');
192
    }
193
}
194