Completed
Push — bugfix/institution-casing-in-v... ( 82557c...0b0450 )
by A.
04:19
created

ReconfigureInstitutionRequestValidator::validate()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 19
rs 9.2
cc 4
eloc 11
nc 6
nop 2
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\Validator;
20
21
use Assert\Assertion;
22
use Assert\InvalidArgumentException as AssertionException;
23
use InvalidArgumentException as CoreInvalidArgumentException;
24
use Surfnet\StepupBundle\Value\SecondFactorType;
25
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Entity\ConfiguredInstitution;
26
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Service\ConfiguredInstitutionService;
27
use Surfnet\StepupMiddleware\ManagementBundle\Exception\InvalidArgumentException;
28
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Assert as StepupAssert;
29
use Symfony\Component\Validator\Constraint;
30
use Symfony\Component\Validator\ConstraintValidator;
31
32
final class ReconfigureInstitutionRequestValidator extends ConstraintValidator
33
{
34
    /**
35
     * @var ConfiguredInstitutionService
36
     */
37
    private $configuredInstitutionsService;
38
39
    /**
40
     * @var string[] internal cache, access through getConfiguredInstitutions()
41
     */
42
    private $configuredInstitutions;
43
44
    public function __construct(ConfiguredInstitutionService $configuredInstitutionsService)
45
    {
46
        $this->configuredInstitutionsService = $configuredInstitutionsService;
47
    }
48
49
    public function validate($value, Constraint $constraint)
50
    {
51
        /** @var \Symfony\Component\Validator\Violation\ConstraintViolationBuilder|false $violation */
52
        $violation = false;
53
54
        try {
55
            $this->validateRoot($value);
56
        } catch (AssertionException $exception) {
57
            // method is not in the interface yet, but the old method is deprecated.
58
            $violation = $this->context->buildViolation($exception->getMessage());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Valida...ecutionContextInterface as the method buildViolation() does only exist in the following implementations of said interface: Symfony\Component\Valida...ontext\ExecutionContext, Symfony\Component\Valida...\LegacyExecutionContext.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
59
            $violation->atPath($exception->getPropertyPath());
60
        } catch (CoreInvalidArgumentException $exception) {
61
            $violation = $this->context->buildViolation($exception->getMessage());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Valida...ecutionContextInterface as the method buildViolation() does only exist in the following implementations of said interface: Symfony\Component\Valida...ontext\ExecutionContext, Symfony\Component\Valida...\LegacyExecutionContext.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
62
        }
63
64
        if ($violation) {
65
            $violation->addViolation();
66
        }
67
    }
68
69
    public function validateRoot(array $configuration)
70
    {
71
        Assertion::isArray($configuration, 'Invalid body structure, must be an object', '(root)');
72
        $this->validateInstitutionsExist(array_keys($configuration));
73
74
        foreach ($configuration as $institution => $options) {
75
            $this->validateInstitutionConfigurationOptions($options, $institution);
76
        }
77
    }
78
79
    /**
80
     * @param array $institutions
81
     */
82
    public function validateInstitutionsExist(array $institutions)
83
    {
84
        $configuredInstitutions = $this->getConfiguredInstitutions();
85
86
        $nonExistentInstitutions = $this->determineNonExistentInstitutions($institutions, $configuredInstitutions);
87
88
        if (!empty($nonExistentInstitutions)) {
89
            throw new InvalidArgumentException(
90
                sprintf('Cannot reconfigure non-existent institution(s): %s', implode(', ', $nonExistentInstitutions))
91
            );
92
        }
93
    }
94
95
    /**
96
     * @param array $options
97
     * @param string $institution
98
     */
99
    public function validateInstitutionConfigurationOptions($options, $institution)
100
    {
101
        $propertyPath = sprintf('Institution(%s)', $institution);
102
103
        Assertion::isArray($options, 'Invalid institution configuration, must be an object', $propertyPath);
104
105
        $acceptedOptions = ['use_ra_locations', 'show_raa_contact_information', 'allowed_second_factors'];
106
        StepupAssert::keysMatch(
107
            $options,
108
            $acceptedOptions,
109
            sprintf('Expected only options "%s" for "%s"', join(', ', $acceptedOptions), $institution),
110
            $propertyPath
111
        );
112
113
        Assertion::boolean(
114
            $options['use_ra_locations'],
115
            sprintf('Option "use_ra_locations" for "%s" must be a boolean value', $institution),
116
            $propertyPath
117
        );
118
119
        Assertion::boolean(
120
            $options['show_raa_contact_information'],
121
            sprintf('Option "show_raa_contact_information" for "%s" must be a boolean value', $institution),
122
            $propertyPath
123
        );
124
125
        Assertion::isArray(
126
            $options['allowed_second_factors'],
127
            sprintf('Option "allowed_second_factors" for "%s" must be an array of strings', $institution),
128
            $propertyPath
129
        );
130
        Assertion::allString(
131
            $options['allowed_second_factors'],
132
            sprintf('Option "allowed_second_factors" for "%s" must be an array of strings', $institution),
133
            $propertyPath
134
        );
135
        Assertion::allInArray(
136
            $options['allowed_second_factors'],
137
            SecondFactorType::getAvailableSecondFactorTypes(),
138
            'Option "allowed_second_factors" for "%s" must contain valid second factor types',
139
            $propertyPath
140
        );
141
    }
142
143
    /**
144
     * Accessor for configured institutions to be able to use an internal cache
145
     *
146
     * @return string[]
147
     */
148
    private function getConfiguredInstitutions()
149
    {
150
        if (!empty($this->configuredInstitutions)) {
151
            return $this->configuredInstitutions;
152
        }
153
154
        $this->configuredInstitutions = array_map(
155
            function (ConfiguredInstitution $configuredInstitution) {
156
                return $configuredInstitution->institution->getInstitution();
157
            },
158
            $this->configuredInstitutionsService->getAll()
159
        );
160
161
        return $this->configuredInstitutions;
162
    }
163
164
    /**
165
     * @param string[] $institutions
166
     * @param $configuredInstitutions
167
     * @return string[]
168
     */
169
    public function determineNonExistentInstitutions(array $institutions, $configuredInstitutions)
170
    {
171
        $normalizedConfiguredInstitutions = array_map(
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $normalizedConfiguredInstitutions 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...
172
            function ($institution) {
173
                return strtolower($institution);
174
            },
175
            $configuredInstitutions
176
        );
177
178
        return array_filter(
179
            $institutions,
180
            function ($institution) use ($normalizedConfiguredInstitutions) {
181
                $normalizedInstitution = strtolower($institution);
182
183
                return !in_array($normalizedInstitution, $normalizedConfiguredInstitutions);
184
            }
185
        );
186
    }
187
}
188