Completed
Push — feature/institution-configurat... ( d02be2...98944a )
by A.
04:12
created

reconfigureAction()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 50
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 50
rs 6.7272
cc 7
eloc 31
nc 6
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 GuzzleHttp;
23
use Liip\FunctionalTestBundle\Validator\DataCollectingValidator;
24
use Rhumsaa\Uuid\Uuid;
25
use Surfnet\StepupMiddleware\ApiBundle\Exception\BadCommandRequestException;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Command;
27
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...
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\ForbiddenException;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
30
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Constraints\ValidReconfigureInstitutionsRequest;
31
use Symfony\Bridge\Monolog\Logger;
32
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
33
use Symfony\Component\HttpFoundation\JsonResponse;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
36
37
/**
38
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
39
 */
40
final class InstitutionConfigurationController extends Controller
41
{
42
    public function reconfigureAction(Request $request)
43
    {
44
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
45
46
        $configuration = GuzzleHttp\json_decode($request->getContent(), true);
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, GuzzleHttp\json_decode() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
47
48
        $violations = $this->getValidator()->validate($configuration, new ValidReconfigureInstitutionsRequest());
49
        if ($violations->count() > 0) {
50
            throw BadCommandRequestException::withViolations(
51
                'Invalid reconfigure institutions request',
52
                $violations
53
            );
54
        }
55
56
        if (empty($configuration)) {
57
            $this->getLogger()->notice(sprintf('No institutions to reconfigure: empty configuration received'));
58
59
            return new JsonResponse([
60
                'status'       => 'OK',
61
                'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
62
                'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
63
            ]);
64
        }
65
66
        $commands = [];
67
        foreach ($configuration as $institution => $options) {
68
            $command                                  = new ReconfigureInstitutionConfigurationOptionsCommand();
69
            $command->UUID                            = (string) Uuid::uuid4();
70
            $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...
71
            $command->useRaLocationsOption            = $options['use_ra_locations'];
72
            $command->showRaaContactInformationOption = $options['show_raa_contact_information'];
73
74
            $commands[] = $command;
75
        }
76
77
        $this->getLogger()->notice(
78
            sprintf('Executing %s reconfigure institution configuration options commands', count($commands))
79
        );
80
81
        $pipeline = $this->getPipeline();
82
        foreach ($commands as $command) {
83
            $this->handleCommand($pipeline, $command);
84
        }
85
86
        return new JsonResponse([
87
            'status'       => 'OK',
88
            'processed_by' =>  $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR'),
89
            'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
90
        ]);
91
    }
92
93
    /**
94
     * @param Pipeline $pipeline
95
     * @param Command $command
96
     */
97
    private function handleCommand(Pipeline $pipeline, Command $command)
98
    {
99
        try {
100
            $pipeline->process($command);
101
        } catch (ForbiddenException $e) {
102
            throw new AccessDeniedHttpException(
103
                sprintf('Processing of command "%s" is forbidden for this client', $command),
104
                $e
105
            );
106
        }
107
    }
108
109
    /**
110
     * @return DataCollectingValidator
111
     */
112
    private function getValidator()
113
    {
114
        return $this->get('validator');
115
    }
116
117
    /**
118
     * @return Logger
119
     */
120
    private function getLogger()
121
    {
122
        return $this->get('logger');
123
    }
124
125
    /**
126
     * @return Pipeline
127
     */
128
    private function getPipeline()
129
    {
130
        return $this->get('pipeline');
131
    }
132
}
133