Completed
Push — master ( 296743...12eab9 )
by Kirill
36:17
created

DirectiveInvocationBuilder::onCompile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 13
cts 13
cp 1
rs 9.504
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
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\Reflection\Builder\Invocations;
11
12
use Railt\Parser\Ast\NodeInterface;
13
use Railt\Parser\Ast\RuleInterface;
14
use Railt\SDL\Base\Invocations\BaseDirectiveInvocation;
15
use Railt\SDL\Contracts\Definitions\DirectiveDefinition;
16
use Railt\SDL\Contracts\Definitions\TypeDefinition;
17
use Railt\SDL\Contracts\Dependent\ArgumentDefinition;
18
use Railt\SDL\Contracts\Document;
19
use Railt\SDL\Exceptions\TypeConflictException;
20
use Railt\SDL\Reflection\Builder\DocumentBuilder;
21
use Railt\SDL\Reflection\Builder\Process\Compilable;
22
use Railt\SDL\Reflection\Builder\Process\Compiler;
23
24
/**
25
 * Class DirectiveInvocationBuilder
26
 */
27
class DirectiveInvocationBuilder extends BaseDirectiveInvocation implements Compilable
28
{
29
    use Compiler;
30
31
    /**
32
     * DirectiveInvocationBuilder constructor.
33
     * @param NodeInterface $ast
34
     * @param DocumentBuilder|Document $document
35
     * @param TypeDefinition $parent
36
     * @throws \Railt\SDL\Exceptions\TypeConflictException
37
     */
38 894
    public function __construct(NodeInterface $ast, DocumentBuilder $document, TypeDefinition $parent)
39
    {
40 894
        $this->parent = $parent;
41 894
        $this->boot($ast, $document);
42 894
    }
43
44
    /**
45
     * @param NodeInterface $ast
46
     * @return bool
47
     * @throws \Railt\SDL\Exceptions\TypeConflictException
48
     */
49 894
    protected function onCompile(NodeInterface $ast): bool
50
    {
51 894
        if ($ast->is('Argument')) {
52 12
            [$name, $value] = $this->parseArgumentValue($ast);
0 ignored issues
show
Bug introduced by
The variable $name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $value does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
53
54
            /** @var DirectiveDefinition $definition */
55 12
            $definition = $this->getTypeDefinition();
56
            /** @var ArgumentDefinition|null $argument */
57 12
            $argument   = $definition->getArgument($name);
58
59 12
            if (! $argument) {
60 6
                $this->getCompiler()->getCallStack()->push($definition);
0 ignored issues
show
Bug introduced by
The method getCallStack does only exist in Railt\SDL\Schema\Configuration, but not in Railt\SDL\Schema\CompilerInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
61
62 6
                $error = \sprintf('Argument %s not defined in %s', $name, $definition);
63 6
                throw new TypeConflictException($error, $this->getCompiler()->getCallStack());
64
            }
65
66 6
            $typeName = $argument->getTypeDefinition()->getName();
67
68 6
            $this->arguments[$name] = $this->parseValue($value, $typeName);
69
70 6
            return true;
71
        }
72
73 894
        return false;
74
    }
75
76
    /**
77
     * @param NodeInterface|RuleInterface $ast
78
     * @return array
79
     */
80 12
    private function parseArgumentValue(NodeInterface $ast): array
81
    {
82 12
        [$key, $value] = [null, null];
0 ignored issues
show
Bug introduced by
The variable $key seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $value seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
83
84 12
        foreach ($ast->getChildren() as $child) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Ast\NodeInterface as the method getChildren() does only exist in the following implementations of said interface: Railt\Compiler\Grammar\Delegate\IncludeDelegate, Railt\Compiler\Grammar\Delegate\RuleDelegate, Railt\Compiler\Grammar\Delegate\TokenDelegate, Railt\Parser\Ast\Rule.

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...
85 12
            if ($child->is('Name')) {
86 12
                $key = $child->getChild(0)->getValue();
87 12
                continue;
88
            }
89
90 12
            if ($child->is('Value')) {
91 12
                $value = $child->getChild(0);
92 12
                continue;
93
            }
94
        }
95
96 12
        return [$key, $value];
0 ignored issues
show
Bug introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
97
    }
98
99
    /**
100
     * @return null|TypeDefinition
101
     */
102 900
    public function getTypeDefinition(): ?TypeDefinition
103
    {
104 900
        return $this->load($this->getName());
0 ignored issues
show
Bug introduced by
Consider using $this->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
105
    }
106
}
107