Completed
Push — develop ( b0b139...6288f9 )
by A.
9s
created

ConfigurationStructureValidator::validateInstitutionsWithRaLocationsConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
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 InvalidArgumentException as CoreInvalidArgumentException;
24
use Surfnet\Stepup\Helper\JsonHelper;
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 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...
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 JsonHelper::decode($rawValue);
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'];
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
    }
96
97
    private function validateGatewayConfiguration($configuration, $propertyPath)
98
    {
99
        Assert::isArray($configuration['gateway'], 'Property "gateway" must have an object as value', $propertyPath);
100
101
        $this->gatewayConfigurationValidator->validate($configuration['gateway'], $propertyPath);
102
    }
103
104
    private function validateSraaConfiguration($configuration, $propertyPath)
105
    {
106
        Assert::isArray(
107
            $configuration['sraa'],
108
            'Property sraa must have an array of name_ids (string) as value',
109
            $propertyPath
110
        );
111
112
        foreach ($configuration['sraa'] as $index => $value) {
113
            Assert::string(
114
                $value,
115
                'value must be a string (the name_id of the SRAA)',
116
                $propertyPath . '[' . $index. ']'
117
            );
118
        }
119
    }
120
121
    private function validateEmailTemplatesConfiguration($configuration, $propertyPath)
122
    {
123
        Assert::isArray(
124
            $configuration['email_templates'],
125
            'Property "email_templates" must have an object as value',
126
            $propertyPath
127
        );
128
129
        $this->emailTemplatesConfigurationValidator->validate($configuration['email_templates'], $propertyPath);
130
    }
131
}
132