Completed
Push — feature/institutions-with-pers... ( 5416f5 )
by A.
04:32
created

validateInstitutionsWithPersonalRaDetailsConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 1
eloc 9
nc 1
nop 2
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
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 as Assert;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Surfnet\StepupMiddleware...Bundle\Validator\Assert.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
22
use Assert\InvalidArgumentException as AssertionException;
23
use GuzzleHttp;
24
use InvalidArgumentException as CoreInvalidArgumentException;
25
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Assert as StepupAssert;
26
use Symfony\Component\Validator\Constraint;
27
use Symfony\Component\Validator\ConstraintValidator;
28
29
/**
30
 * Once the Assert 2.0 library has been built this should be converted to the lazy assertions so we can report
31
 * all errors at once.
32
 */
33
class ConfigurationStructureValidator extends ConstraintValidator
34
{
35
    /**
36
     * @var GatewayConfigurationValidator
37
     */
38
    private $gatewayConfigurationValidator;
39
40
    /**
41
     * @var EmailTemplatesConfigurationValidator
42
     */
43
    private $emailTemplatesConfigurationValidator;
44
45
    public function __construct(
46
        GatewayConfigurationValidator $gatewayConfigurationValidator,
47
        EmailTemplatesConfigurationValidator $emailTemplatesConfigurationValidator
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $emailTemplatesConfigurationValidator 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...
48
    ) {
49
        $this->gatewayConfigurationValidator = $gatewayConfigurationValidator;
50
        $this->emailTemplatesConfigurationValidator = $emailTemplatesConfigurationValidator;
51
    }
52
53
    public function validate($value, Constraint $constraint)
54
    {
55
        /** @var \Symfony\Component\Validator\Violation\ConstraintViolationBuilder|false $violation */
56
        $violation = false;
57
58
        try {
59
            $decoded = $this->decodeJson($value);
60
            $this->validateRoot($decoded);
61
        } catch (AssertionException $exception) {
62
            // method is not in the interface yet, but the old method is deprecated.
63
            $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...
64
            $violation->atPath($exception->getPropertyPath());
65
        } catch (CoreInvalidArgumentException $exception) {
66
            $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...
67
        }
68
69
        if ($violation) {
70
            // ensure we have a sensible path.
71
            $violation->addViolation();
72
        }
73
    }
74
75
    private function decodeJson($rawValue)
76
    {
77
        return GuzzleHttp\json_decode($rawValue, true);
78
    }
79
80
    public function validateRoot($configuration)
81
    {
82
        Assert::isArray($configuration, 'Invalid body structure, must be an object', '(root)');
83
84
        $acceptedProperties = ['gateway', 'sraa', 'email_templates', 'institutions_with_personal_ra_details'];
85
        StepupAssert::keysMatch(
86
            $configuration,
87
            $acceptedProperties,
88
            sprintf("Expected only properties '%s'", join(',', $acceptedProperties)),
89
            '(root)'
90
        );
91
92
        $this->validateGatewayConfiguration($configuration, 'gateway');
93
        $this->validateSraaConfiguration($configuration, 'sraa');
94
        $this->validateEmailTemplatesConfiguration($configuration, 'email_templates');
95
        $this->validateInstitutionsWithPersonalRaDetailsConfiguration(
96
            $configuration,
97
            'institutions_with_personal_ra_details'
98
        );
99
    }
100
101
    private function validateGatewayConfiguration($configuration, $propertyPath)
102
    {
103
        Assert::isArray($configuration['gateway'], 'Property "gateway" must have an object as value', $propertyPath);
104
105
        $this->gatewayConfigurationValidator->validate($configuration['gateway'], $propertyPath);
106
    }
107
108
    private function validateSraaConfiguration($configuration, $propertyPath)
109
    {
110
        Assert::isArray(
111
            $configuration['sraa'],
112
            'Property sraa must have an array of name_ids (string) as value',
113
            $propertyPath
114
        );
115
116
        foreach ($configuration['sraa'] as $index => $value) {
117
            Assert::string(
118
                $value,
119
                'value must be a string (the name_id of the SRAA)',
120
                $propertyPath . '[' . $index. ']'
121
            );
122
        }
123
    }
124
125
    private function validateEmailTemplatesConfiguration($configuration, $propertyPath)
126
    {
127
        Assert::isArray(
128
            $configuration['email_templates'],
129
            'Property "email_templates" must have an object as value',
130
            $propertyPath
131
        );
132
133
        $this->emailTemplatesConfigurationValidator->validate($configuration['email_templates'], $propertyPath);
134
    }
135
136
    private function validateInstitutionsWithPersonalRaDetailsConfiguration($configuration, $propertyPath)
137
    {
138
        Assert::isArray(
139
            $configuration[$propertyPath],
140
            sprintf('Property "%s" must be an array of institutions', $propertyPath),
141
            $propertyPath
142
        );
143
144
        Assert::allString(
145
            $configuration[$propertyPath],
146
            sprintf('The institutions configured under property "%s" should be strings', $propertyPath),
147
            $propertyPath
148
        );
149
    }
150
}
151