Completed
Push — feature/sf-subset/management-g... ( c8f831 )
by A.
04:24
created

InstitutionConfigurationController   C

Complexity

Total Complexity 18

Size/Duplication

Total Lines 148
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 19
dl 0
loc 148
rs 6.875
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A showAction() 0 20 2
B reconfigureAction() 0 45 6
B handleCommands() 0 26 4
A getInstitutionConfigurationOptionsService() 0 4 1
A getAllowedSecondFactorListService() 0 4 1
A getValidator() 0 4 1
A getLogger() 0 4 1
A getPipeline() 0 4 1
A getConnectionHelper() 0 4 1
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\Configuration\Value\AllowedSecondFactorList;
26
use Surfnet\Stepup\Helper\JsonHelper;
27
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\AllowedSecondFactorListService;
28
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\InstitutionConfigurationOptionsService;
29
use Surfnet\StepupMiddleware\ApiBundle\Exception\BadCommandRequestException;
30
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Command;
31
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...
32
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\ForbiddenException;
33
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
34
use Surfnet\StepupMiddleware\ManagementBundle\Service\DBALConnectionHelper;
35
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Constraints\ValidReconfigureInstitutionsRequest;
36
use Symfony\Bridge\Monolog\Logger;
37
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
38
use Symfony\Component\HttpFoundation\JsonResponse;
39
use Symfony\Component\HttpFoundation\Request;
40
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
41
42
/**
43
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
44
 */
45
final class InstitutionConfigurationController extends Controller
46
{
47
    public function showAction()
48
    {
49
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
50
51
        $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...
52
            ->findAllInstitutionConfigurationOptions();
53
54
        $allowedSecondFactorMap = $this->getAllowedSecondFactorListService()->getAllowedSecondFactorMap();
55
56
        $overview = [];
57
        foreach ($institutionConfigurationOptions as $options) {
58
            $overview[$options->institution->getInstitution()] = [
59
                'use_ra_locations' => $options->useRaLocationsOption,
60
                'show_raa_contact_information' => $options->showRaaContactInformationOption,
61
                'allowed_second_factors' => $allowedSecondFactorMap->getSecondFactorListFor($options->institution),
62
            ];
63
        }
64
65
        return new JsonResponse($overview);
66
    }
67
68
    public function reconfigureAction(Request $request)
69
    {
70
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
71
72
        $configuration = JsonHelper::decode($request->getContent());
73
74
        $violations = $this->getValidator()->validate($configuration, new ValidReconfigureInstitutionsRequest());
75
        if ($violations->count() > 0) {
76
            throw BadCommandRequestException::withViolations('Invalid reconfigure institutions request', $violations);
77
        }
78
79
        if (empty($configuration)) {
80
            $this->getLogger()->notice(sprintf('No institutions to reconfigure: empty configuration received'));
81
82
            return new JsonResponse([
83
                'status'       => 'OK',
84
                'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
85
                'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
86
            ]);
87
        }
88
89
        $commands = [];
90
        foreach ($configuration as $institution => $options) {
91
            $command                                  = new ReconfigureInstitutionConfigurationOptionsCommand();
92
            $command->UUID                            = (string) Uuid::uuid4();
93
            $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...
94
            $command->useRaLocationsOption            = $options['use_ra_locations'];
95
            $command->showRaaContactInformationOption = $options['show_raa_contact_information'];
96
            $command->allowedSecondFactors            = $options['allowed_second_factors'];
97
98
            $commands[] = $command;
99
        }
100
101
        $this->getLogger()->notice(
102
            sprintf('Executing %s reconfigure institution configuration options commands', count($commands))
103
        );
104
105
        $this->handleCommands($commands);
106
107
        return new JsonResponse([
108
            'status'       => 'OK',
109
            'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
110
            'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
111
        ]);
112
    }
113
114
    /**
115
     * @param Command[] $commands
116
     * @throws Exception
117
     */
118
    private function handleCommands(array $commands)
119
    {
120
        $pipeline         = $this->getPipeline();
121
        $connectionHelper = $this->getConnectionHelper();
122
123
        $connectionHelper->beginTransaction();
124
125
        foreach ($commands as $command) {
126
            try {
127
                $pipeline->process($command);
128
            } catch (ForbiddenException $e) {
129
                $connectionHelper->rollBack();
130
131
                throw new AccessDeniedHttpException(
132
                    sprintf('Processing of command "%s" is forbidden for this client', $command),
133
                    $e
134
                );
135
            } catch (Exception $exception) {
136
                $connectionHelper->rollBack();
137
138
                throw $exception;
139
            }
140
        }
141
142
        $connectionHelper->commit();
143
    }
144
145
    /**
146
     * @return InstitutionConfigurationOptionsService
147
     */
148
    private function getInstitutionConfigurationOptionsService()
149
    {
150
        return $this->get('surfnet_stepup_middleware_api.service.institution_configuration_options');
151
    }
152
153
    /**
154
     * @return AllowedSecondFactorListService
155
     */
156
    private function getAllowedSecondFactorListService()
157
    {
158
        return $this->get('surfnet_stepup_middleware_api.service.allowed_second_factor_list');
159
    }
160
161
    /**
162
     * @return DataCollectingValidator
163
     */
164
    private function getValidator()
165
    {
166
        return $this->get('validator');
167
    }
168
169
    /**
170
     * @return Logger
171
     */
172
    private function getLogger()
173
    {
174
        return $this->get('logger');
175
    }
176
177
    /**
178
     * @return Pipeline
179
     */
180
    private function getPipeline()
181
    {
182
        return $this->get('pipeline');
183
    }
184
185
    /**
186
     * @return DBALConnectionHelper
187
     */
188
    private function getConnectionHelper()
189
    {
190
        return $this->get('surfnet_stepup_middleware_management.dbal_connection_helper');
191
    }
192
}
193