Completed
Push — feature/show-institution-confi... ( 41abf0 )
by A.
07:04
created

handleCommands()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.5806
cc 4
eloc 16
nc 4
nop 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 GuzzleHttp;
24
use Liip\FunctionalTestBundle\Validator\DataCollectingValidator;
25
use Rhumsaa\Uuid\Uuid;
26
use Surfnet\Stepup\Helper\JsonHelper;
27
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Entity\InstitutionConfigurationOptions;
28
use Surfnet\StepupMiddleware\ApiBundle\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
        $response = array_map(
50
            function (InstitutionConfigurationOptions $options) {
51
                return [
52
                    $options->institution->getInstitution() => [
53
                        'use_ra_locations'             => $options->useRaLocationsOption->isEnabled(),
54
                        'show_raa_contact_information' => $options->showRaaContactInformationOption->isEnabled(),
55
                    ],
56
                ];
57
            },
58
            $this->getInstitutionConfigurationOptionsService()->findAllInstitutionConfigurationOptions()
59
        );
60
61
        return new JsonResponse($response);
62
    }
63
64
    public function reconfigureAction(Request $request)
65
    {
66
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
67
68
        $configuration = JsonHelper::decode($request->getContent());
69
70
        $violations = $this->getValidator()->validate($configuration, new ValidReconfigureInstitutionsRequest());
71
        if ($violations->count() > 0) {
72
            throw BadCommandRequestException::withViolations('Invalid reconfigure institutions request', $violations);
73
        }
74
75
        if (empty($configuration)) {
76
            $this->getLogger()->notice(sprintf('No institutions to reconfigure: empty configuration received'));
77
78
            return new JsonResponse([
79
                'status'       => 'OK',
80
                'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
81
                'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
82
            ]);
83
        }
84
85
        $commands = [];
86
        foreach ($configuration as $institution => $options) {
87
            $command                                  = new ReconfigureInstitutionConfigurationOptionsCommand();
88
            $command->UUID                            = (string) Uuid::uuid4();
89
            $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...
90
            $command->useRaLocationsOption            = $options['use_ra_locations'];
91
            $command->showRaaContactInformationOption = $options['show_raa_contact_information'];
92
93
            $commands[] = $command;
94
        }
95
96
        $this->getLogger()->notice(
97
            sprintf('Executing %s reconfigure institution configuration options commands', count($commands))
98
        );
99
100
        $this->handleCommands($commands);
101
102
        return new JsonResponse([
103
            'status'       => 'OK',
104
            'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
105
            'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
106
        ]);
107
    }
108
109
    /**
110
     * @param Command[] $commands
111
     * @throws Exception
112
     */
113
    private function handleCommands(array $commands)
114
    {
115
        $pipeline         = $this->getPipeline();
116
        $connectionHelper = $this->getConnectionHelper();
117
118
        $connectionHelper->beginTransaction();
119
120
        foreach ($commands as $command) {
121
            try {
122
                $pipeline->process($command);
123
            } catch (ForbiddenException $e) {
124
                $connectionHelper->rollBack();
125
126
                throw new AccessDeniedHttpException(
127
                    sprintf('Processing of command "%s" is forbidden for this client', $command),
128
                    $e
129
                );
130
            } catch (Exception $exception) {
131
                $connectionHelper->rollBack();
132
133
                throw $exception;
134
            }
135
        }
136
137
        $connectionHelper->commit();
138
    }
139
140
    /**
141
     * @return InstitutionConfigurationOptionsService
142
     */
143
    private function getInstitutionConfigurationOptionsService()
144
    {
145
        return $this->get('surfnet_stepup_middleware_api.service.institution_configuration_options');
146
    }
147
148
    /**
149
     * @return DataCollectingValidator
150
     */
151
    private function getValidator()
152
    {
153
        return $this->get('validator');
154
    }
155
156
    /**
157
     * @return Logger
158
     */
159
    private function getLogger()
160
    {
161
        return $this->get('logger');
162
    }
163
164
    /**
165
     * @return Pipeline
166
     */
167
    private function getPipeline()
168
    {
169
        return $this->get('pipeline');
170
    }
171
172
    /**
173
     * @return DBALConnectionHelper
174
     */
175
    private function getConnectionHelper()
176
    {
177
        return $this->get('surfnet_stepup_middleware_management.dbal_connection_helper');
178
    }
179
}
180