Test Failed
Push — master ( 08713d...9fa0b4 )
by Kirill
03:13
created

DirectiveBuilder   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 88
Duplicated Lines 11.36 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 10
loc 88
ccs 0
cts 48
cp 0
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 15 1
A loadDefinition() 5 13 2
A buildArguments() 5 18 3
A validateUncompletedArguments() 0 14 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\SDL\Compiler\Builder\Invocation;
11
12
use Railt\Parser\Ast\RuleInterface;
13
use Railt\Reflection\Contracts\Definition;
14
use Railt\Reflection\Definition\DirectiveDefinition;
15
use Railt\Reflection\Invocation\DirectiveInvocation as Invocation;
16
use Railt\SDL\Compiler\Ast\Invocation\DirectiveArgumentNode;
17
use Railt\SDL\Compiler\Ast\Invocation\DirectiveNode;
18
use Railt\SDL\Compiler\Builder\Builder;
19
use Railt\SDL\Exception\TypeConflictException;
20
21
/**
22
 * Class DirectiveInvocationBuilder
23
 */
24
class DirectiveBuilder extends Builder
25
{
26
    /**
27
     * @param RuleInterface|DirectiveNode $rule
28
     * @param Definition $parent
29
     * @return Definition
30
     */
31
    public function build(RuleInterface $rule, Definition $parent): Definition
32
    {
33
        $directive = new Invocation($parent->getDocument(), $rule->getDirectiveName());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Ast\RuleInterface as the method getDirectiveName() does only exist in the following implementations of said interface: Railt\SDL\Compiler\Ast\Invocation\DirectiveNode.

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...
Compatibility introduced by
$parent->getDocument() of type object<Railt\Reflection\Contracts\Document> is not a sub-type of object<Railt\Reflection\Document>. It seems like you assume a concrete implementation of the interface Railt\Reflection\Contracts\Document to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
34
        $directive->withOffset($rule->getOffset());
35
36
        $this->when->resolving(function () use ($rule, $directive): void {
37
            $definition = $this->loadDefinition($directive, $rule);
38
39
            $this->buildArguments($directive, $definition, $rule);
40
41
            $this->validateUncompletedArguments($directive, $definition);
42
        });
43
44
        return $directive;
45
    }
46
47
    /**
48
     * @param Invocation $directive
49
     * @param RuleInterface $rule
50
     * @return DirectiveDefinition
51
     * @throws \Railt\Io\Exception\ExternalFileException
52
     */
53
    private function loadDefinition(Invocation $directive, RuleInterface $rule): DirectiveDefinition
54
    {
55
        /** @var DirectiveDefinition $definition */
56
        $definition = $directive->getDefinition();
57
58 View Code Duplication
        if (! ($definition instanceof Definition\DirectiveDefinition)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
59
            $error = '%s should be a Directive, but %s given';
60
            throw (new TypeConflictException(\sprintf($error, $directive,
61
                $definition)))->throwsIn($directive->getFile(), $rule->getOffset());
62
        }
63
64
        return $definition;
65
    }
66
67
    /**
68
     * @param Invocation $call
69
     * @param DirectiveDefinition $def
70
     * @param RuleInterface|DirectiveNode $rule
71
     * @throws \Railt\Io\Exception\ExternalFileException
72
     */
73
    private function buildArguments(Invocation $call, DirectiveDefinition $def, RuleInterface $rule): void
74
    {
75
        /** @var DirectiveArgumentNode $ast */
76
        foreach ($rule->getDirectiveArguments() as $ast) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Ast\RuleInterface as the method getDirectiveArguments() does only exist in the following implementations of said interface: Railt\SDL\Compiler\Ast\Invocation\DirectiveNode.

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...
77
            $name = $ast->getArgumentName();
78
            $argument = $def->getArgument($name);
79
80 View Code Duplication
            if ($argument === null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
81
                $error = 'Directive %s does not provide argument %s';
82
                throw (new TypeConflictException(\sprintf($error, $def, $name)))->throwsIn($call->getFile(),
83
                        $ast->getOffset());
84
            }
85
86
            $value = $this->valueOf($argument, $ast->getArgumentValue());
87
88
            $call->withArgument($name, $value);
89
        }
90
    }
91
92
    /**
93
     * @param Invocation $directive
94
     * @param DirectiveDefinition $definition
95
     * @throws \Railt\Io\Exception\ExternalFileException
96
     */
97
    private function validateUncompletedArguments(Invocation $directive, DirectiveDefinition $definition): void
98
    {
99
        foreach ($definition->getArguments() as $argument) {
100
            if ($directive->hasArgument($argument->getName())) {
101
                continue;
102
            }
103
104
            if (! $argument->hasDefaultValue()) {
105
                $error = 'Missing value for required argument %s of %s';
106
                throw (new TypeConflictException(\sprintf($error, $argument,
107
                    $directive)))->throwsIn($directive->getFile(), $directive->getLine(), $directive->getColumn());
108
            }
109
        }
110
    }
111
}
112