Completed
Push — feature/institution-configurat... ( 219d9c )
by A.
05:39
created

reconfigureAction()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 44
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 44
rs 8.439
c 1
b 0
f 0
cc 6
eloc 28
nc 17
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\CommandHandlingBundle\Command\Command;
26
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...
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\ForbiddenException;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\TransactionAwarePipeline;
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
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
37
use Symfony\Component\Validator\ConstraintViolation;
38
39
final class InstitutionConfigurationController extends Controller
40
{
41
    public function reconfigureAction(Request $request)
42
    {
43
        $this->denyAccessUnlessGranted(['ROLE_MANAGEMENT']);
44
45
        $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...
46
47
        $violations = $this->getValidator()->validate($configuration, new ValidReconfigureInstitutionsRequest());
48
        if ($violations->count() > 0) {
49
            $errors = array_map(function (ConstraintViolation $violation) {
50
                return sprintf('%s: %s', $violation->getPropertyPath(), $violation->getMessage());
51
            }, iterator_to_array($violations));
52
53
            return new JsonResponse(['errors' => $errors], 400);
54
        }
55
56
        $commands = [];
57
        foreach ($configuration as $institution => $options) {
58
            $command                                  = new ReconfigureInstitutionConfigurationOptionsCommand();
59
            $command->UUID                            = (string) Uuid::uuid4();
60
            $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...
61
            $command->useRaLocationsOption            = $options['use_ra_locations'];
62
            $command->showRaaContactInformationOption = $options['show_raa_contact_information'];
63
64
            $commands[] = $command;
65
        }
66
67
        if (empty($commands)) {
68
            $this->getLogger()->notice('Institution configuration will not be reconfigured: no commands to execute.');
69
        }
70
71
        $pipeline = $this->getPipeline();
72
        foreach ($commands as $command) {
73
            $this->handleCommand($pipeline, $command);
74
        }
75
76
        $serverName = $request->server->get('SERVER_NAME') ?: $request->server->get('SERVER_ADDR');
77
        $response   = new JsonResponse([
78
            'status'       => 'OK',
79
            'processed_by' => $serverName,
80
            'applied_at'   => (new DateTime())->format(DateTime::ISO8601),
81
        ]);
82
83
        return $response;
84
    }
85
86
    /**
87
     * @param Pipeline $pipeline
88
     * @param Command $command
89
     * @return JsonResponse
0 ignored issues
show
Documentation introduced by
Should the return type not be JsonResponse|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
90
     */
91
    private function handleCommand(Pipeline $pipeline, Command $command)
92
    {
93
        try {
94
            $pipeline->process($command);
95
        } catch (ForbiddenException $e) {
96
            throw new AccessDeniedHttpException(
97
                sprintf('Processing of command "%s" is forbidden for this client', $command),
98
                $e
99
            );
100
        }
101
    }
102
103
    /**
104
     * @return DataCollectingValidator
105
     */
106
    private function getValidator()
107
    {
108
        return $this->container->get('validator');
109
    }
110
111
    /**
112
     * @return Logger
113
     */
114
    private function getLogger()
115
    {
116
        return $this->get('logger');
117
    }
118
119
    /**
120
     * @return TransactionAwarePipeline
121
     */
122
    private function getPipeline()
123
    {
124
        return $this->get('pipeline');
125
    }
126
}
127