/
php.js
107 lines (91 loc) · 2.33 KB
/
php.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict';
var spawn = require('child_process').spawn;
var http = require('http');
var open = require('opn');
var binVersionCheck = require('bin-version-check');
var getPort = require('get-port');
module.exports = function (grunt) {
var checkServerTries = 0;
function checkServer(hostname, port, cb) {
setTimeout(function () {
http.request({
method: 'HEAD',
hostname: hostname,
port: port
}, function (res) {
var statusCodeType = Number(res.statusCode.toString()[0]);
if ([2, 3, 4].indexOf(statusCodeType) !== -1) {
return cb();
} else if (statusCodeType === 5) {
grunt.fail.warn(
'Server docroot returned 500-level response. Please check ' +
'your configuration for possible errors.'
);
return cb();
}
checkServer(hostname, port, cb);
}).on('error', function (err) {
// back off after 1s
if (++checkServerTries > 20) {
return cb();
}
grunt.verbose.writeln('PHP server not started. Retrying...');
checkServer(hostname, port, cb);
}).end();
}, 50);
}
grunt.registerMultiTask('php', 'Start a PHP-server', function () {
var cb = this.async();
var options = this.options({
port: 8000,
hostname: '127.0.0.1',
base: '.',
keepalive: false,
open: false,
bin: 'php'
});
getPort(function (err, port) {
if (err) {
grunt.warn(err);
cb();
return;
}
if (options.port === '?') {
options.port = port;
}
var host = options.hostname + ':' + options.port;
var args = ['-S', host];
if (options.ini) {
args.push('-c', options.ini);
}
if (options.router) {
args.push(options.router);
}
binVersionCheck(options.bin, '>=5.4', function (err) {
if (err) {
grunt.warn(err);
cb();
return;
}
var cp = spawn(options.bin, args, {
cwd: options.base,
stdio: 'inherit'
});
// quit PHP when grunt is done
process.on('exit', function () {
cp.kill();
});
// check when the server is ready. tried doing it by listening
// to the child process `data` event, but it's not triggered...
checkServer(options.hostname, options.port, function () {
if (!this.flags.keepalive && !options.keepalive) {
cb();
}
if (options.open) {
open('http://' + host);
}
}.bind(this));
}.bind(this));
}.bind(this));
});
};