Completed
Push — feature/httplug ( f5571c )
by Maxime
10:26
created

FeatureContext::createFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
use Behat\Behat\Context\Context;
4
use Symfony\Component\Process\PhpExecutableFinder;
5
use Symfony\Component\Process\Process;
6
use Behat\Gherkin\Node\PyStringNode;
7
8
class FeatureContext implements Context
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
9
{
10
    private static $PARAMETERS = [
11
        '%base_host%' => 'localhost:8123',
12
    ];
13
14
    /**
15
     * @var string
16
     */
17
    private $workingDir;
18
19
    /**
20
     * @var string
21
     */
22
    private $phpBin;
23
24
    /**
25
     * @var Process
26
     */
27
    private $process;
28
29
    /**
30
     * @var Process
31
     */
32
    private $server;
33
34
    /**
35
     * @var Process
36
     */
37
    private $phantomjs;
38
39
    public function __construct()
40
    {
41
        $phpFinder = new PhpExecutableFinder();
42
        if (false === $php = $phpFinder->find()) {
43
            throw new \RuntimeException('Unable to find the PHP executable. The testsuite cannot run.');
44
        }
45
46
        $this->phpBin = $php;
47
    }
48
49
    /**
50
     * Cleans test folders in the temporary directory.
51
     *
52
     * @BeforeSuite
53
     * @AfterSuite
54
     */
55
    public static function cleanTestFolders()
56
    {
57
        if (is_dir($dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'behat')) {
58
            self::clearDirectory($dir);
59
        }
60
        if (is_dir($dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'friendly')) {
61
            self::clearDirectory($dir);
62
        }
63
    }
64
65
    /**
66
     * Prepares test folders in the temporary directory.
67
     *
68
     * @BeforeScenario
69
     */
70
    public function prepareTestFolders()
71
    {
72
        $this->workingDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'behat' . DIRECTORY_SEPARATOR . md5(microtime() . rand(0, 10000));
73
74
        $this->createDirectory($this->workingDir . '/features/bootstrap');
75
76
        $this->process = new Process(null);
77
        $this->process->setTimeout(20);
78
    }
79
80
    /**
81
     * @AfterScenario
82
     */
83
    public function stopServer()
84
    {
85
        if (null !== $this->server) {
86
            $this->server->stop();
87
        }
88
    }
89
90
    /**
91
     * @BeforeScenario @phantomjs
92
     */
93
    public function startPhantom()
94
    {
95
        if (PHP_OS === 'Darwin') {
96
            $phantomExec = 'phantomjs_mac';
97
        } else if (PHP_OS === 'Linux') {
98
            $phantomExec = 'phantomjs_linux';
99
        } else {
100
            throw new \Exception('This test suite cannot run on Windows, contribution in that way would be nice.');
101
        }
102
        $this->phantomjs = new Process(__DIR__ . '/../phantomjs/' . $phantomExec . ' --webdriver=4444');
103
        $this->phantomjs->start();
104
        sleep(1); // PhantomJS takes time to start
105
    }
106
107
    /**
108
     * @AfterScenario
109
     */
110
    public function stopPhantom()
111
    {
112
        if ($this->phantomjs) {
113
            $this->phantomjs->stop();
114
            $this->phantomjs = null;
115
        }
116
    }
117
118
    /**
119
     * Creates a file with specified name and context in current workdir.
120
     *
121
     * @Given /^(?:there is )?a file named "([^"]*)" with:$/
122
     *
123
     * @param string       $filename name of the file (relative path)
124
     * @param PyStringNode $content  PyString string instance
125
     */
126
    public function aFileNamedWith($filename, PyStringNode $content)
127
    {
128
        $content = strtr((string) $content, array("'''" => '"""'));
129
        $this->createFile($this->workingDir . '/' . $filename, $content);
130
    }
131
132
    private function createFile($filename, $content)
133
    {
134
        $path = dirname($filename);
135
        $this->createDirectory($path);
136
137
        file_put_contents($filename, $content);
138
    }
139
140
    private function createDirectory($path)
141
    {
142
        if (!is_dir($path)) {
143
            mkdir($path, 0777, true);
144
        }
145
    }
146
147
    private static function clearDirectory($path)
148
    {
149
        $files = scandir($path);
150
        array_shift($files);
151
        array_shift($files);
152
153
        foreach ($files as $file) {
154
            $file = $path . DIRECTORY_SEPARATOR . $file;
155
            if (is_dir($file)) {
156
                self::clearDirectory($file);
157
            } else {
158
                unlink($file);
159
            }
160
        }
161
162
        rmdir($path);
163
    }
164
165
    /**
166
     * @Given the homepage of my application is:
167
     */
168
    public function theHomepageOfMyApplicationIs(PyStringNode $string)
169
    {
170
        file_put_contents($this->workingDir . '/index.html', $string);
171
    }
172
173
    /**
174
     * @Given the file :file is:
175
     */
176
    public function theFileWith($file, PyStringNode $string)
177
    {
178
        file_put_contents($this->workingDir . DIRECTORY_SEPARATOR . $file, $string);
179
    }
180
181
    /**
182
     * @Given my application is running
183
     */
184
    public function myApplicationIsRunning()
185
    {
186
        $this->server = new Process('php -S ' . self::$PARAMETERS['%base_host%'] . ' -t ' . $this->workingDir);
187
        $this->server->start();
188
    }
189
190
    /**
191
     * @Given I have the following behat configuration:
192
     */
193
    public function iHaveTheFollowingBehatConfiguration(PyStringNode $string)
194
    {
195
        $string = $string->getRaw();
196
        $string = str_replace(array_keys(self::$PARAMETERS), array_values(self::$PARAMETERS), $string);
197
        file_put_contents($this->workingDir . '/behat.yml.dist', $string);
198
    }
199
200
    /**
201
     * Runs behat command with provided parameters
202
     *
203
     * @When /^I run "behat(?: ((?:\"|[^"])*))?"$/
204
     *
205
     * @param string $argumentsString
206
     */
207
    public function iRunBehat($argumentsString = '')
208
    {
209
        $argumentsString = strtr($argumentsString, array('\'' => '"'));
210
211
        $this->process->setWorkingDirectory($this->workingDir);
212
        $this->process->setCommandLine(
213
            sprintf(
214
                '%s %s %s',
215
                $this->phpBin,
216
                escapeshellarg(BEHAT_BIN_PATH),
217
                $argumentsString
218
            )
219
        );
220
221
        // Don't reset the LANG variable on HHVM, because it breaks HHVM itself
222
        $env = $this->process->getEnv();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 9 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...
223
        $env['LANG'] = 'en'; // Ensures that the default language is en, whatever the OS locale is.
224
        $this->process->setEnv($env);
225
226
        $this->process->run();
227
    }
228
229
    /**
230
     * Checks whether previously ran command passes|fails with provided output.
231
     *
232
     * @Then /^it should (fail|pass) with:$/
233
     *
234
     * @param string       $success "fail" or "pass"
235
     * @param PyStringNode $text    PyString text instance
236
     */
237
    public function itShouldPassWith($success, PyStringNode $text)
238
    {
239
        $this->itShouldFail($success);
240
        $this->theOutputShouldContain($text);
241
    }
242
243
    /**
244
     * Checks whether last command output contains provided string.
245
     *
246
     * @Then the output should contain:
247
     *
248
     * @param PyStringNode $text PyString text instance
249
     */
250
    public function theOutputShouldContain(PyStringNode $text)
251
    {
252
        expect($this->getOutput())->toContain($this->getExpectedOutput($text));
253
    }
254
255
    /**
256
     * Checks whether previously ran command failed|passed.
257
     *
258
     * @Then /^it should (fail|pass)$/
259
     *
260
     * @param string $success "fail" or "pass"
261
     */
262
    public function itShouldFail($success)
263
    {
264
        if ('fail' === $success) {
265 View Code Duplication
            if (0 === $this->getExitCode()) {
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...
266
                echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput();
267
            }
268
269
            expect($this->getExitCode())->toBe(0);
270
        } else {
271 View Code Duplication
            if (0 !== $this->getExitCode()) {
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...
272
                echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput();
273
            }
274
275
            expect($this->getExitCode())->toBe(0);
276
        }
277
    }
278
279
    private function getExpectedOutput(PyStringNode $expectedText)
280
    {
281
        $text = strtr($expectedText, array(
282
            '\'\'\'' => '"""',
283
            '%%TMP_DIR%%' => sys_get_temp_dir() . DIRECTORY_SEPARATOR,
284
            '%%WORKING_DIR%%' => realpath($this->workingDir . DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR,
285
            '%%DS%%' => DIRECTORY_SEPARATOR,
286
        ));
287
288
        // windows path fix
289
        if ('/' !== DIRECTORY_SEPARATOR) {
290
            $text = preg_replace_callback(
291
                '/[ "]features\/[^\n "]+/', function ($matches) {
292
                return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]);
293
            }, $text
294
            );
295
            $text = preg_replace_callback(
296
                '/\<span class\="path"\>features\/[^\<]+/', function ($matches) {
297
                return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]);
298
            }, $text
299
            );
300
            $text = preg_replace_callback(
301
                '/\+[fd] [^ ]+/', function ($matches) {
302
                return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]);
303
            }, $text
304
            );
305
        }
306
307
        return $text;
308
    }
309
310
    private function getExitCode()
311
    {
312
        return $this->process->getExitCode();
313
    }
314
315
    private function getOutput()
316
    {
317
        $output = $this->process->getErrorOutput() . $this->process->getOutput();
318
319
        // Normalize the line endings in the output
320
        if ("\n" !== PHP_EOL) {
321
            $output = str_replace(PHP_EOL, "\n", $output);
322
        }
323
324
        // Replace wrong warning message of HHVM
325
        $output = str_replace('Notice: Undefined index: ', 'Notice: Undefined offset: ', $output);
326
327
        return trim(preg_replace("/ +$/m", '', $output));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal / +$/m does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
328
    }
329
}
330