SmartReader::readEnvironmentCallees()   B
last analyzed

Complexity

Conditions 6
Paths 3

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 26
rs 8.439
cc 6
eloc 15
nc 3
nop 1
1
<?php
2
3
namespace Knp\FriendlyContexts\Reader;
4
5
use Behat\Behat\Definition\Call;
6
use Behat\Behat\Definition\Call\DefinitionCall;
7
use Behat\Behat\Definition\Exception\SearchException;
8
use Behat\Behat\Definition\SearchResult;
9
use Behat\Behat\Tester\Result\ExecutedStepResult;
10
use Behat\Behat\Tester\Result\SkippedStepResult;
11
use Behat\Behat\Tester\Result\UndefinedStepResult;
12
use Behat\Gherkin\Gherkin;
13
use Behat\Gherkin\Node\FeatureNode;
14
use Behat\Gherkin\Node\StepNode;
15
use Behat\Testwork\Environment\Environment;
16
use Behat\Testwork\Environment\Reader\EnvironmentReader;
17
use Behat\Testwork\Specification\Locator\SpecificationLocator;
18
use Behat\Testwork\Suite\SuiteRepository;
19
use Knp\FriendlyContexts\Call\CallCenter;
20
use Knp\FriendlyContexts\Definition\DefinitionFinder;
21
22
class SmartReader implements EnvironmentReader
23
{
24
    public function __construct(Gherkin $gherkin, SuiteRepository $registry, SpecificationLocator $locator, DefinitionFinder $definitionFinder, CallCenter $callCenter, $smartTag)
25
    {
26
        $this->gherkin          = $gherkin;
0 ignored issues
show
Bug introduced by
The property gherkin does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
27
        $this->registry         = $registry;
0 ignored issues
show
Bug introduced by
The property registry does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
28
        $this->locator          = $locator;
0 ignored issues
show
Bug introduced by
The property locator does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
29
        $this->definitionFinder = $definitionFinder;
0 ignored issues
show
Bug introduced by
The property definitionFinder does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
30
        $this->callCenter       = $callCenter;
0 ignored issues
show
Bug introduced by
The property callCenter does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
31
        $this->smartTag         = $smartTag;
0 ignored issues
show
Bug introduced by
The property smartTag does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
32
    }
33
34
    public function supportsEnvironment(Environment $environment)
35
    {
36
        return true;
37
    }
38
39
    public function readEnvironmentCallees(Environment $environment)
40
    {
41
        $callees = [];
42
43
        foreach ($this->extractScenarios() as $data) {
44
            list($feature, $scenarios) = $data;
45
            foreach ($scenarios as $scenario) {
46
                $callable = function () use ($environment, $feature, $scenario) {
47
                    $steps = $scenario->getSteps();
48
                    foreach ($steps as $step) {
49
                        $result = $this->testStep($environment, $feature, $step);
50
51
                        if ($result instanceof SkippedStepResult) {
52
                            throw new \RuntimeException('Step has been skipped.');
53
                        } elseif (true === $result->hasException()) {
0 ignored issues
show
Bug introduced by
The method hasException does only exist in Behat\Behat\Tester\Result\ExecutedStepResult, but not in Behat\Behat\Tester\Result\UndefinedStepResult.

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...
54
                            throw $result->getException();
0 ignored issues
show
Bug introduced by
The method getException does only exist in Behat\Behat\Tester\Result\ExecutedStepResult, but not in Behat\Behat\Tester\Result\UndefinedStepResult.

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...
55
                        }
56
                    }
57
                };
58
59
                $callees = array_merge($callees, $this->buildCallee($feature, $scenario, $callable));
60
            }
61
        }
62
63
        return $callees;
64
    }
65
66
    public function extractScenarios()
67
    {
68
        $scenarios = [];
69
70
        foreach ($this->registry->getSuites() as $suite) {
71
            foreach ($this->locator->locateSpecifications($suite, '') as $feature) {
72
                $collection = array_filter($feature->getScenarios(), function ($e) { return $e->hasTag($this->smartTag); });
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
73
                $scenarios[] = [ $feature, $collection ];
74
            }
75
        }
76
77
        return $scenarios;
78
    }
79
80
    protected function buildCallee($feature, $scenario, $callable)
81
    {
82
        $description = sprintf('%s:%s', $feature->getFile(), $scenario->getLine());
83
84
        return [
85
            new Call\Given(sprintf('/^%s$/', $scenario->getTitle()), $callable, $description),
86
        ];
87
    }
88
89
    protected function testStep(Environment $environment, FeatureNode $feature, StepNode $step, $skip = false)
90
    {
91
        try {
92
            $search = $this->searchDefinition($environment, $feature, $step);
93
            $result = $this->testDefinition($environment, $feature, $step, $search, $skip);
94
        } catch (SearchException $exception) {
95
            $result = new UndefinedStepResult();
96
        }
97
98
        return $result;
99
    }
100
101
    private function searchDefinition(Environment $environment, FeatureNode $feature, StepNode $step)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
102
    {
103
        return $this->definitionFinder->findDefinition($environment, $feature, $step);
104
    }
105
106
    private function testDefinition(Environment $environment, FeatureNode $feature, StepNode $step, SearchResult $search, $skip = false)
107
    {
108
        if ($skip || !$search->hasMatch()) {
109
            return new SkippedStepResult($search, null, null);
0 ignored issues
show
Unused Code introduced by
The call to SkippedStepResult::__construct() has too many arguments starting with null.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
110
        }
111
112
        $call = $this->createDefinitionCall($environment, $feature, $search, $step);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
113
        $result = $this->callCenter->makeCall($call);
114
115
        return new ExecutedStepResult($search, $result);
116
    }
117
118
    private function createDefinitionCall(Environment $environment, FeatureNode $feature, SearchResult $search, StepNode $step)
119
    {
120
        $definition = $search->getMatchedDefinition();
121
        $arguments = $search->getMatchedArguments();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
122
123
        return new DefinitionCall($environment, $feature, $step, $definition, $arguments);
0 ignored issues
show
Bug introduced by
It seems like $definition defined by $search->getMatchedDefinition() on line 120 can be null; however, Behat\Behat\Definition\C...tionCall::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $arguments defined by $search->getMatchedArguments() on line 121 can also be of type null; however, Behat\Behat\Definition\C...tionCall::__construct() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
124
    }
125
}
126