GherkinSnippets::__construct()   F
last analyzed

Complexity

Conditions 13
Paths 468

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 468
nop 2
dl 0
loc 58
rs 3.1888
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Codeception\Lib\Generator;
3
4
use Behat\Gherkin\Node\StepNode;
5
use Codeception\Test\Loader\Gherkin;
6
use Codeception\Util\Template;
7
use Symfony\Component\Finder\Finder;
8
9
class GherkinSnippets
10
{
11
    protected $template = <<<EOF
12
    /**
13
     * @{{type}} {{text}}
14
     */
15
     public function {{methodName}}({{params}})
16
     {
17
         throw new \Codeception\Exception\Incomplete("Step `{{text}}` is not defined");
18
     }
19
20
EOF;
21
22
    protected $snippets = [];
23
    protected $processed = [];
24
    protected $features = [];
25
26
    public function __construct($settings, $test = null)
27
    {
28
        $loader = new Gherkin($settings);
29
        $pattern = $loader->getPattern();
30
        $path = $settings['path'];
31
        if (!empty($test)) {
32
            $path = $settings['path'].'/'.$test;
33
            if (preg_match($pattern, $test)) {
34
                $path = dirname($path);
35
                $pattern = basename($test);
36
            }
37
        }
38
39
        $finder = Finder::create()
40
            ->files()
41
            ->sortByName()
42
            ->in($path)
43
            ->followLinks()
44
            ->name($pattern);
45
46
        foreach ($finder as $file) {
47
            $pathname = str_replace("//", "/", $file->getPathname());
48
            $loader->loadTests($pathname);
49
        }
50
        $availableSteps = $loader->getSteps();
51
        $allSteps = [];
52
        foreach ($availableSteps as $stepGroup) {
53
            $allSteps = array_merge($allSteps, $stepGroup);
54
        }
55
        foreach ($loader->getTests() as $test) {
56
            /** @var $test \Codeception\Test\Gherkin  **/
57
            $steps = $test->getScenarioNode()->getSteps();
58
            if ($test->getFeatureNode()->hasBackground()) {
59
                $steps = array_merge($steps, $test->getFeatureNode()->getBackground()->getSteps());
60
            }
61
            foreach ($steps as $step) {
62
                $matched = false;
63
                $text = $step->getText();
64
                if (self::stepHasPyStringArgument($step)) {
65
                    // pretend it is inline argument
66
                    $text .= ' ""';
67
                }
68
                foreach (array_keys($allSteps) as $pattern) {
69
                    if (preg_match($pattern, $text)) {
70
                        $matched = true;
71
                        break;
72
                    }
73
                }
74
                if (!$matched) {
75
                    $this->addSnippet($step);
76
                    $file = str_ireplace($settings['path'], '', $test->getFeatureNode()->getFile());
77
                    if (!in_array($file, $this->features)) {
78
                        $this->features[] = $file;
79
                    }
80
                }
81
            }
82
        }
83
    }
84
85
    public function addSnippet(StepNode $step)
86
    {
87
        $args = [];
88
        $pattern = $step->getText();
89
90
        // match numbers (not in quotes)
91 View Code Duplication
        if (preg_match_all('~([\d\.])(?=([^"]*"[^"]*")*[^"]*$)~', $pattern, $matches)) {
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...
92
            foreach ($matches[1] as $num => $param) {
93
                $num++;
94
                $args[] = '$num' . $num;
95
                $pattern = str_replace($param, ":num$num", $pattern);
96
            }
97
        }
98
99
        // match quoted string
100 View Code Duplication
        if (preg_match_all('~"(.*?)"~', $pattern, $matches)) {
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...
101
            foreach ($matches[1] as $num => $param) {
102
                $num++;
103
                $args[] = '$arg' . $num;
104
                $pattern = str_replace('"'.$param.'"', ":arg$num", $pattern);
105
            }
106
        }
107
        // Has multiline argument at the end of step?
108
        if (self::stepHasPyStringArgument($step)) {
109
            $num = count($args) + 1;
110
            $pattern .= " :arg$num";
111
            $args[] = '$arg' . $num;
112
        }
113
        if (in_array($pattern, $this->processed)) {
114
            return;
115
        }
116
117
        $methodName = preg_replace('~(\s+?|\'|\"|\W)~', '', ucwords(preg_replace('~"(.*?)"|\d+~', '', $step->getText())));
118
        if (empty($methodName)) {
119
            $methodName = 'step_' . substr(sha1($pattern), 0, 9);
120
        }
121
122
        $this->snippets[] = (new Template($this->template))
123
            ->place('type', $step->getKeywordType())
124
            ->place('text', $pattern)
125
            ->place('methodName', lcfirst($methodName))
126
            ->place('params', implode(', ', $args))
127
            ->produce();
128
129
        $this->processed[] = $pattern;
130
    }
131
132
    public function getSnippets()
133
    {
134
        return $this->snippets;
135
    }
136
137
    public function getFeatures()
138
    {
139
        return $this->features;
140
    }
141
142
    public static function stepHasPyStringArgument(StepNode $step)
143
    {
144
        if ($step->hasArguments()) {
145
            $stepArgs = $step->getArguments();
146
            if ($stepArgs[count($stepArgs) - 1]->getNodeType() == "PyString") {
147
                return true;
148
            }
149
        }
150
        return false;
151
    }
152
}
153