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

validateInstitutionConfigurationOptions()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 25
rs 8.8571
c 1
b 0
f 1
cc 1
eloc 17
nc 1
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 GuzzleHttp;
24
use InvalidArgumentException as CoreInvalidArgumentException;
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 View Code Duplication
    public function validate($value, Constraint $constraint)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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 = array_filter($institutions, function ($institution) use ($configuredInstitutions) {
87
            return !in_array($institution, $configuredInstitutions);
88
        });
89
90
        if (!empty($nonExistentInstitutions)) {
91
            throw new InvalidArgumentException(
92
                sprintf('Cannot reconfigure non-existent institution(s): %s', implode(', ', $nonExistentInstitutions))
93
            );
94
        }
95
    }
96
97
    /**
98
     * @param array $options
99
     * @param string $institution
100
     */
101
    public function validateInstitutionConfigurationOptions($options, $institution)
102
    {
103
        $propertyPath = sprintf('Institution(%s)', $institution);
104
105
        Assertion::isArray($options, 'Invalid institution configuration, must be an object', $propertyPath);
106
107
        $acceptedOptions = ['use_ra_locations', 'show_raa_contact_information'];
108
        StepupAssert::keysMatch(
109
            $options,
110
            $acceptedOptions,
111
            sprintf('Expected only options "%s" for "%s"', join(', ', $acceptedOptions), $institution),
112
            $propertyPath
113
        );
114
115
        Assertion::boolean(
116
            $options['use_ra_locations'],
117
            sprintf('Option "use_ra_locations" for "%s" must be a boolean value', $institution),
118
            $propertyPath
119
        );
120
        Assertion::boolean(
121
            $options['show_raa_contact_information'],
122
            sprintf('Option "show_raa_contact_information" for "%s" must be a boolean value', $institution),
123
            $propertyPath
124
        );
125
    }
126
127
    /**
128
     * Accessor for configured institutions to be able to use an internal cache
129
     *
130
     * @return string[]
131
     */
132
    private function getConfiguredInstitutions()
133
    {
134
        if (!empty($this->configuredInstitutions)) {
135
            return $this->configuredInstitutions;
136
        }
137
138
        $this->configuredInstitutions = array_map(
139
            function (ConfiguredInstitution $configuredInstitution) {
140
                return $configuredInstitution->institution;
141
            },
142
            $this->configuredInstitutionsService->getAll()
143
        );
144
145
        return $this->configuredInstitutions;
146
    }
147
}
148