repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
kakserpom/phpdaemon
PHPDaemon/Servers/HTTP/Connection.php
Connection.onFinish
public function onFinish() { Timer::remove($this->keepaliveTimer); if ($this->req !== null && $this->req instanceof Generic) { if (!$this->req->isFinished()) { $this->req->abort(); } } $this->req = null; }
php
public function onFinish() { Timer::remove($this->keepaliveTimer); if ($this->req !== null && $this->req instanceof Generic) { if (!$this->req->isFinished()) { $this->req->abort(); } } $this->req = null; }
[ "public", "function", "onFinish", "(", ")", "{", "Timer", "::", "remove", "(", "$", "this", "->", "keepaliveTimer", ")", ";", "if", "(", "$", "this", "->", "req", "!==", "null", "&&", "$", "this", "->", "req", "instanceof", "Generic", ")", "{", "if",...
Called when connection is finished @return void
[ "Called", "when", "connection", "is", "finished" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/HTTP/Connection.php#L406-L415
kakserpom/phpdaemon
PHPDaemon/Servers/HTTP/Connection.php
Connection.badRequest
public function badRequest($req) { $this->state = self::STATE_ROOT; $this->write("400 Bad Request\r\n\r\n<html><head><title>400 Bad Request</title></head><body bgcolor=\"white\"><center><h1>400 Bad Request</h1></center></body></html>"); $this->finish(); }
php
public function badRequest($req) { $this->state = self::STATE_ROOT; $this->write("400 Bad Request\r\n\r\n<html><head><title>400 Bad Request</title></head><body bgcolor=\"white\"><center><h1>400 Bad Request</h1></center></body></html>"); $this->finish(); }
[ "public", "function", "badRequest", "(", "$", "req", ")", "{", "$", "this", "->", "state", "=", "self", "::", "STATE_ROOT", ";", "$", "this", "->", "write", "(", "\"400 Bad Request\\r\\n\\r\\n<html><head><title>400 Bad Request</title></head><body bgcolor=\\\"white\\\"><ce...
Send Bad request @return void
[ "Send", "Bad", "request" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/HTTP/Connection.php#L421-L426
kakserpom/phpdaemon
PHPDaemon/Config/Entry/Time.php
Time.humanToPlain
public static function humanToPlain($value) { $time = 0; preg_replace_callback('~(\d+(\.\d+)?)\s*([smhd])\s*|(.+)~i', function ($m) use (&$time) { if (isset($m[4]) && ($m[4] !== '')) { $time = false; } if ($time === false) { return; } if (!empty($m[2])) { $n = (float)$m[1]; } else { $n = (int)$m[1]; } $l = strtolower($m[3]); if ($l === 's') { $time += $n; } elseif ($l === 'm') { $time += $n * 60; } elseif ($l === 'h') { $time += $n * 60 * 60; } elseif ($l === 'd') { $time += $n * 60 * 60 * 24; } }, $value); return $time; }
php
public static function humanToPlain($value) { $time = 0; preg_replace_callback('~(\d+(\.\d+)?)\s*([smhd])\s*|(.+)~i', function ($m) use (&$time) { if (isset($m[4]) && ($m[4] !== '')) { $time = false; } if ($time === false) { return; } if (!empty($m[2])) { $n = (float)$m[1]; } else { $n = (int)$m[1]; } $l = strtolower($m[3]); if ($l === 's') { $time += $n; } elseif ($l === 'm') { $time += $n * 60; } elseif ($l === 'h') { $time += $n * 60 * 60; } elseif ($l === 'd') { $time += $n * 60 * 60 * 24; } }, $value); return $time; }
[ "public", "static", "function", "humanToPlain", "(", "$", "value", ")", "{", "$", "time", "=", "0", ";", "preg_replace_callback", "(", "'~(\\d+(\\.\\d+)?)\\s*([smhd])\\s*|(.+)~i'", ",", "function", "(", "$", "m", ")", "use", "(", "&", "$", "time", ")", "{", ...
Converts human-readable value to plain @param $value @return int
[ "Converts", "human", "-", "readable", "value", "to", "plain" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Config/Entry/Time.php#L20-L53
kakserpom/phpdaemon
PHPDaemon/Servers/IRCBouncer/Connection.php
Connection.onReady
public function onReady() { $conn = $this; $this->keepaliveTimer = setTimeout(function ($timer) use ($conn) { $conn->ping(); }, 10e6); }
php
public function onReady() { $conn = $this; $this->keepaliveTimer = setTimeout(function ($timer) use ($conn) { $conn->ping(); }, 10e6); }
[ "public", "function", "onReady", "(", ")", "{", "$", "conn", "=", "$", "this", ";", "$", "this", "->", "keepaliveTimer", "=", "setTimeout", "(", "function", "(", "$", "timer", ")", "use", "(", "$", "conn", ")", "{", "$", "conn", "->", "ping", "(", ...
Called when the connection is handshaked (at low-level), and peer is ready to recv. data @return void
[ "Called", "when", "the", "connection", "is", "handshaked", "(", "at", "low", "-", "level", ")", "and", "peer", "is", "ready", "to", "recv", ".", "data" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/IRCBouncer/Connection.php#L55-L61
kakserpom/phpdaemon
PHPDaemon/Clients/Mongo/Connection.php
Connection.onRead
public function onRead() { start: if ($this->freed) { return; } if ($this->state === self::STATE_ROOT) { if (false === ($hdr = $this->readExact(16))) { return; // we do not have a header } $this->hdr = unpack('Vlen/VreqId/VresponseTo/VopCode', $hdr); $this->hdr['plen'] = $this->hdr['len'] - 16; $this->setWatermark($this->hdr['plen'], $this->hdr['plen']); $this->state = self::STATE_PACKET; } if ($this->state === self::STATE_PACKET) { if (false === ($pct = $this->readExact($this->hdr['plen']))) { return; //we do not have a whole packet } $this->state = self::STATE_ROOT; $this->setWatermark(16, 0xFFFFFF); if ($this->hdr['opCode'] === Pool::OP_REPLY) { $r = unpack('Vflag/VcursorID1/VcursorID2/Voffset/Vlength', mb_orig_substr($pct, 0, 20)); $r['cursorId'] = mb_orig_substr($pct, 4, 8); $id = (int)$this->hdr['responseTo']; if (isset($this->requests[$id])) { $req = $this->requests[$id]; if (sizeof($req) === 1) { // get more $r['cursorId'] = $req[0]; } } else { $req = false; } $flagBits = str_pad(strrev(decbin($r['flag'])), 8, '0', STR_PAD_LEFT); $curId = ($r['cursorId'] !== "\x00\x00\x00\x00\x00\x00\x00\x00" ? 'c' . $r['cursorId'] : 'r' . $this->hdr['responseTo']); if ($req && isset($req[2]) && ($req[2] === false) && !isset($this->cursors[$curId])) { $cur = new Cursor($curId, $req[0], $this); $this->cursors[$curId] = $cur; $cur->failure = $flagBits[1] === '1'; $cur->await = $flagBits[3] === '1'; $cur->callback = $req[1]; $cur->parseOplog = isset($req[3]) && $req[3]; $cur->tailable = isset($req[4]) && $req[4]; } else { $cur = isset($this->cursors[$curId]) ? $this->cursors[$curId] : false; } if ($cur && (($r['length'] === 0) || (mb_orig_substr($curId, 0, 1) === 'r'))) { if ($cur->tailable) { if ($cur->finished = ($flagBits[0] === '1')) { $cur->destroy(); } } else { $cur->finished = true; } } $p = 20; $items = []; while ($p < $this->hdr['plen']) { $dl = unpack('Vlen', mb_orig_substr($pct, $p, 4)); $doc = bson_decode(mb_orig_substr($pct, $p, $dl['len'])); if ($cur) { if ($cur->parseOplog && isset($doc['ts'])) { $tsdata = unpack('Vsec/Vinc', mb_orig_substr($pct, $p + 8, 8)); $doc['ts'] = $tsdata['sec'] . ' ' . $tsdata['inc']; } $cur->items[] = $doc; ++$cur->counter; } else { $items[] = $doc; } $p += $dl['len']; } $this->setFree(true); if (isset($req[2]) && $req[2] && $req[1]) { $req[1](sizeof($items) ? $items[0] : false); if ($cur) { if ($cur instanceof Cursor) { $cur->destroy(); } else { unset($this->cursors[$curId]); } } } elseif ($cur) { $func = $cur->callback; $func($cur); } unset($this->requests[$id]); $req = null; } } goto start; }
php
public function onRead() { start: if ($this->freed) { return; } if ($this->state === self::STATE_ROOT) { if (false === ($hdr = $this->readExact(16))) { return; // we do not have a header } $this->hdr = unpack('Vlen/VreqId/VresponseTo/VopCode', $hdr); $this->hdr['plen'] = $this->hdr['len'] - 16; $this->setWatermark($this->hdr['plen'], $this->hdr['plen']); $this->state = self::STATE_PACKET; } if ($this->state === self::STATE_PACKET) { if (false === ($pct = $this->readExact($this->hdr['plen']))) { return; //we do not have a whole packet } $this->state = self::STATE_ROOT; $this->setWatermark(16, 0xFFFFFF); if ($this->hdr['opCode'] === Pool::OP_REPLY) { $r = unpack('Vflag/VcursorID1/VcursorID2/Voffset/Vlength', mb_orig_substr($pct, 0, 20)); $r['cursorId'] = mb_orig_substr($pct, 4, 8); $id = (int)$this->hdr['responseTo']; if (isset($this->requests[$id])) { $req = $this->requests[$id]; if (sizeof($req) === 1) { // get more $r['cursorId'] = $req[0]; } } else { $req = false; } $flagBits = str_pad(strrev(decbin($r['flag'])), 8, '0', STR_PAD_LEFT); $curId = ($r['cursorId'] !== "\x00\x00\x00\x00\x00\x00\x00\x00" ? 'c' . $r['cursorId'] : 'r' . $this->hdr['responseTo']); if ($req && isset($req[2]) && ($req[2] === false) && !isset($this->cursors[$curId])) { $cur = new Cursor($curId, $req[0], $this); $this->cursors[$curId] = $cur; $cur->failure = $flagBits[1] === '1'; $cur->await = $flagBits[3] === '1'; $cur->callback = $req[1]; $cur->parseOplog = isset($req[3]) && $req[3]; $cur->tailable = isset($req[4]) && $req[4]; } else { $cur = isset($this->cursors[$curId]) ? $this->cursors[$curId] : false; } if ($cur && (($r['length'] === 0) || (mb_orig_substr($curId, 0, 1) === 'r'))) { if ($cur->tailable) { if ($cur->finished = ($flagBits[0] === '1')) { $cur->destroy(); } } else { $cur->finished = true; } } $p = 20; $items = []; while ($p < $this->hdr['plen']) { $dl = unpack('Vlen', mb_orig_substr($pct, $p, 4)); $doc = bson_decode(mb_orig_substr($pct, $p, $dl['len'])); if ($cur) { if ($cur->parseOplog && isset($doc['ts'])) { $tsdata = unpack('Vsec/Vinc', mb_orig_substr($pct, $p + 8, 8)); $doc['ts'] = $tsdata['sec'] . ' ' . $tsdata['inc']; } $cur->items[] = $doc; ++$cur->counter; } else { $items[] = $doc; } $p += $dl['len']; } $this->setFree(true); if (isset($req[2]) && $req[2] && $req[1]) { $req[1](sizeof($items) ? $items[0] : false); if ($cur) { if ($cur instanceof Cursor) { $cur->destroy(); } else { unset($this->cursors[$curId]); } } } elseif ($cur) { $func = $cur->callback; $func($cur); } unset($this->requests[$id]); $req = null; } } goto start; }
[ "public", "function", "onRead", "(", ")", "{", "start", ":", "if", "(", "$", "this", "->", "freed", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "state", "===", "self", "::", "STATE_ROOT", ")", "{", "if", "(", "false", "===", "(", ...
Called when new data received @return void
[ "Called", "when", "new", "data", "received" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Connection.php#L88-L183
kakserpom/phpdaemon
PHPDaemon/Clients/Mongo/Connection.php
Connection.onFinish
public function onFinish() { foreach ($this->cursors as $curId => $cur) { if ($cur instanceof Cursor) { $cur->destroy(true); } } $this->cursors = null; $this->requests = null; parent::onFinish(); }
php
public function onFinish() { foreach ($this->cursors as $curId => $cur) { if ($cur instanceof Cursor) { $cur->destroy(true); } } $this->cursors = null; $this->requests = null; parent::onFinish(); }
[ "public", "function", "onFinish", "(", ")", "{", "foreach", "(", "$", "this", "->", "cursors", "as", "$", "curId", "=>", "$", "cur", ")", "{", "if", "(", "$", "cur", "instanceof", "Cursor", ")", "{", "$", "cur", "->", "destroy", "(", "true", ")", ...
onFinish @return void
[ "onFinish" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Connection.php#L189-L199
kakserpom/phpdaemon
PHPDaemon/SockJS/Methods/Welcome.php
Welcome.init
public function init() { parent::init(); $this->header('Cache-Control: max-age=31536000, public, pre-check=0, post-check=0'); $this->header('Expires: ' . date('r', strtotime('+1 year'))); echo "Welcome to SockJS!\n"; $this->finish(); }
php
public function init() { parent::init(); $this->header('Cache-Control: max-age=31536000, public, pre-check=0, post-check=0'); $this->header('Expires: ' . date('r', strtotime('+1 year'))); echo "Welcome to SockJS!\n"; $this->finish(); }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "$", "this", "->", "header", "(", "'Cache-Control: max-age=31536000, public, pre-check=0, post-check=0'", ")", ";", "$", "this", "->", "header", "(", "'Expires: '", ".", "date", ...
Constructor @return void
[ "Constructor" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/SockJS/Methods/Welcome.php#L18-L25
kakserpom/phpdaemon
PHPDaemon/Structures/StackCallbacks.php
StackCallbacks.executeOne
public function executeOne(...$args) { if ($this->isEmpty()) { return false; } $cb = $this->shift(); if ($cb) { $cb(...$args); if ($cb instanceof CallbackWrapper) { $cb->cancel(); } } return true; }
php
public function executeOne(...$args) { if ($this->isEmpty()) { return false; } $cb = $this->shift(); if ($cb) { $cb(...$args); if ($cb instanceof CallbackWrapper) { $cb->cancel(); } } return true; }
[ "public", "function", "executeOne", "(", "...", "$", "args", ")", "{", "if", "(", "$", "this", "->", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "$", "cb", "=", "$", "this", "->", "shift", "(", ")", ";", "if", "(", "$", "cb", ...
Executes one callback from the top with given arguments @param mixed ...$args Arguments @return boolean
[ "Executes", "one", "callback", "from", "the", "top", "with", "given", "arguments" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Structures/StackCallbacks.php#L28-L41
kakserpom/phpdaemon
PHPDaemon/Structures/StackCallbacks.php
StackCallbacks.executeAndKeepOne
public function executeAndKeepOne(...$args) { if ($this->isEmpty()) { return false; } $cb = $this->shift(); $this->unshift($cb); if ($cb) { $cb(...$args); } return true; }
php
public function executeAndKeepOne(...$args) { if ($this->isEmpty()) { return false; } $cb = $this->shift(); $this->unshift($cb); if ($cb) { $cb(...$args); } return true; }
[ "public", "function", "executeAndKeepOne", "(", "...", "$", "args", ")", "{", "if", "(", "$", "this", "->", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "$", "cb", "=", "$", "this", "->", "shift", "(", ")", ";", "$", "this", "->", ...
Executes one callback from the top with given arguments without taking it out @param mixed ...$args Arguments @return boolean
[ "Executes", "one", "callback", "from", "the", "top", "with", "given", "arguments", "without", "taking", "it", "out" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Structures/StackCallbacks.php#L48-L59
kakserpom/phpdaemon
PHPDaemon/Structures/StackCallbacks.php
StackCallbacks.executeAll
public function executeAll(...$args) { if ($this->isEmpty()) { return 0; } $n = 0; do { if ($cb = $this->shift()) { $cb(...$args); ++$n; if ($cb instanceof CallbackWrapper) { $cb->cancel(); } } } while (!$this->isEmpty()); return $n; }
php
public function executeAll(...$args) { if ($this->isEmpty()) { return 0; } $n = 0; do { if ($cb = $this->shift()) { $cb(...$args); ++$n; if ($cb instanceof CallbackWrapper) { $cb->cancel(); } } } while (!$this->isEmpty()); return $n; }
[ "public", "function", "executeAll", "(", "...", "$", "args", ")", "{", "if", "(", "$", "this", "->", "isEmpty", "(", ")", ")", "{", "return", "0", ";", "}", "$", "n", "=", "0", ";", "do", "{", "if", "(", "$", "cb", "=", "$", "this", "->", "...
Executes all callbacks with given arguments @param array $args @return int
[ "Executes", "all", "callbacks", "with", "given", "arguments" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Structures/StackCallbacks.php#L76-L93
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.hash
public static function hash($str, $salt = '', $plain = false) { $size = 512; $rounds = 1; if (strncmp($salt, '$', 1) === 0) { $e = explode('$', $salt, 3); $ee = explode('=', $e[1]); if (ctype_digit($ee[0])) { $size = (int)$e[1]; } if (isset($ee[1]) && ctype_digit($e[1])) { $size = (int)$e[1]; } } $hash = $str . $salt; if ($rounds < 1) { $rounds = 1; } elseif ($rounds > 128) { $rounds = 128; } for ($i = 0; $i < $rounds; ++$i) { $hash = \keccak_hash($hash, $size); } if ($plain) { return $hash; } return base64_encode($hash); }
php
public static function hash($str, $salt = '', $plain = false) { $size = 512; $rounds = 1; if (strncmp($salt, '$', 1) === 0) { $e = explode('$', $salt, 3); $ee = explode('=', $e[1]); if (ctype_digit($ee[0])) { $size = (int)$e[1]; } if (isset($ee[1]) && ctype_digit($e[1])) { $size = (int)$e[1]; } } $hash = $str . $salt; if ($rounds < 1) { $rounds = 1; } elseif ($rounds > 128) { $rounds = 128; } for ($i = 0; $i < $rounds; ++$i) { $hash = \keccak_hash($hash, $size); } if ($plain) { return $hash; } return base64_encode($hash); }
[ "public", "static", "function", "hash", "(", "$", "str", ",", "$", "salt", "=", "''", ",", "$", "plain", "=", "false", ")", "{", "$", "size", "=", "512", ";", "$", "rounds", "=", "1", ";", "if", "(", "strncmp", "(", "$", "salt", ",", "'$'", "...
Generate keccak hash for string with salt @param string $str Data @param string $salt Salt @param boolean $plain Is plain text? @return string @deprecated
[ "Generate", "keccak", "hash", "for", "string", "with", "salt" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L26-L53
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.randomString
public static function randomString($len = null, $chars = null, $cb = null, $pri = 0, $hang = false) { if ($len === null) { $len = 64; } if ($chars === null) { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.'; } if ($cb === null) { Daemon::log('[CODE WARN] \\PHPDaemon\\Utils\\Crypt::randomString: non-callback way is not secure.' . ' Please rewrite your code with callback function in third argument' . PHP_EOL . Debug::backtrace()); $r = ''; $m = mb_orig_strlen($chars) - 1; for ($i = 0; $i < $len; ++$i) { $r .= $chars[mt_rand(0, $m)]; } return $r; } $charsLen = mb_orig_strlen($chars); $mask = static::getMinimalBitMask($charsLen - 1); $iterLimit = max($len, $len * 64); static::randomInts(2 * $len, function ($ints) use ($cb, $chars, $charsLen, $len, $mask, &$iterLimit) { if ($ints === false) { $cb(false); return; } $r = ''; for ($i = 0, $s = sizeof($ints); $i < $s; ++$i) { // This is wasteful, but RNGs are fast and doing otherwise adds complexity and bias $c = $ints[$i] & $mask; // Only use the random number if it is in range, otherwise try another (next iteration) if ($c < $charsLen) { $r .= static::stringIdx($chars, $c); } // Guarantee termination if (--$iterLimit <= 0) { return false; } } $d = $len - mb_orig_strlen($r); if ($d > 0) { static::randomString($d, $chars, function ($r2) use ($r, $cb) { $cb($r . $r2); }); return; } $cb($r); }, $pri, $hang); }
php
public static function randomString($len = null, $chars = null, $cb = null, $pri = 0, $hang = false) { if ($len === null) { $len = 64; } if ($chars === null) { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.'; } if ($cb === null) { Daemon::log('[CODE WARN] \\PHPDaemon\\Utils\\Crypt::randomString: non-callback way is not secure.' . ' Please rewrite your code with callback function in third argument' . PHP_EOL . Debug::backtrace()); $r = ''; $m = mb_orig_strlen($chars) - 1; for ($i = 0; $i < $len; ++$i) { $r .= $chars[mt_rand(0, $m)]; } return $r; } $charsLen = mb_orig_strlen($chars); $mask = static::getMinimalBitMask($charsLen - 1); $iterLimit = max($len, $len * 64); static::randomInts(2 * $len, function ($ints) use ($cb, $chars, $charsLen, $len, $mask, &$iterLimit) { if ($ints === false) { $cb(false); return; } $r = ''; for ($i = 0, $s = sizeof($ints); $i < $s; ++$i) { // This is wasteful, but RNGs are fast and doing otherwise adds complexity and bias $c = $ints[$i] & $mask; // Only use the random number if it is in range, otherwise try another (next iteration) if ($c < $charsLen) { $r .= static::stringIdx($chars, $c); } // Guarantee termination if (--$iterLimit <= 0) { return false; } } $d = $len - mb_orig_strlen($r); if ($d > 0) { static::randomString($d, $chars, function ($r2) use ($r, $cb) { $cb($r . $r2); }); return; } $cb($r); }, $pri, $hang); }
[ "public", "static", "function", "randomString", "(", "$", "len", "=", "null", ",", "$", "chars", "=", "null", ",", "$", "cb", "=", "null", ",", "$", "pri", "=", "0", ",", "$", "hang", "=", "false", ")", "{", "if", "(", "$", "len", "===", "null"...
Returns string of pseudo random characters @param integer $len Length of desired string @param string $chars String of allowed characters @param callable $cb Callback @param integer $pri Priority of EIO operation @param boolean $hang If true, we shall use /dev/random instead of /dev/urandom and it may cause a delay @return string
[ "Returns", "string", "of", "pseudo", "random", "characters" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L64-L113
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.stringIdx
public static function stringIdx($str, $idx) { // FIXME: Make the const-time hack below work for all integer sizes, or // check it properly $l = mb_orig_strlen($str); if ($l > 65535 || $idx > $l) { return false; } $r = 0; for ($i = 0; $i < $l; ++$i) { $x = $i ^ $idx; $mask = (((($x | ($x >> 16)) & 0xFFFF) + 0xFFFF) >> 16) - 1; $r |= ord($str[$i]) & $mask; } return chr($r); }
php
public static function stringIdx($str, $idx) { // FIXME: Make the const-time hack below work for all integer sizes, or // check it properly $l = mb_orig_strlen($str); if ($l > 65535 || $idx > $l) { return false; } $r = 0; for ($i = 0; $i < $l; ++$i) { $x = $i ^ $idx; $mask = (((($x | ($x >> 16)) & 0xFFFF) + 0xFFFF) >> 16) - 1; $r |= ord($str[$i]) & $mask; } return chr($r); }
[ "public", "static", "function", "stringIdx", "(", "$", "str", ",", "$", "idx", ")", "{", "// FIXME: Make the const-time hack below work for all integer sizes, or", "// check it properly", "$", "l", "=", "mb_orig_strlen", "(", "$", "str", ")", ";", "if", "(", "$", ...
Returns the character at index $idx in $str in constant time @param string $str String @param integer $idx Index @return string
[ "Returns", "the", "character", "at", "index", "$idx", "in", "$str", "in", "constant", "time" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L121-L136
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.randomBytes
public static function randomBytes($len, $cb, $pri = 0, $hang = false) { $cb = CallbackWrapper::wrap($cb); FileSystem::open('/dev/' . ($hang ? '' : 'u') . 'random', 'r', function ($file) use ($len, $cb, $pri) { if (!$file) { $cb(false); return; } $file->read($len, 0, function ($file, $data) use ($cb) { $cb($data); }, $pri); }, null, $pri); }
php
public static function randomBytes($len, $cb, $pri = 0, $hang = false) { $cb = CallbackWrapper::wrap($cb); FileSystem::open('/dev/' . ($hang ? '' : 'u') . 'random', 'r', function ($file) use ($len, $cb, $pri) { if (!$file) { $cb(false); return; } $file->read($len, 0, function ($file, $data) use ($cb) { $cb($data); }, $pri); }, null, $pri); }
[ "public", "static", "function", "randomBytes", "(", "$", "len", ",", "$", "cb", ",", "$", "pri", "=", "0", ",", "$", "hang", "=", "false", ")", "{", "$", "cb", "=", "CallbackWrapper", "::", "wrap", "(", "$", "cb", ")", ";", "FileSystem", "::", "o...
Returns string of pseudo random bytes @param integer $len Length of desired string @param callable $cb Callback @param integer $pri Priority of EIO operation @param boolean $hang If true, we shall use /dev/random instead of /dev/urandom and it may cause a delay @return integer
[ "Returns", "string", "of", "pseudo", "random", "bytes" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L146-L158
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.randomInts
public static function randomInts($numInts, $cb, $pri = 0, $hang = false) { static::randomBytes(PHP_INT_SIZE * $numInts, function ($bytes) use ($cb, $numInts) { if ($bytes === false) { $cb(false); return; } $ints = []; for ($i = 0; $i < $numInts; ++$i) { $thisInt = 0; for ($j = 0; $j < PHP_INT_SIZE; ++$j) { $thisInt = ($thisInt << 8) | (ord($bytes[$i * PHP_INT_SIZE + $j]) & 0xFF); } // Absolute value in two's compliment (with min int going to zero) $thisInt = $thisInt & PHP_INT_MAX; $ints[] = $thisInt; } $cb($ints); }, $pri, $hang); }
php
public static function randomInts($numInts, $cb, $pri = 0, $hang = false) { static::randomBytes(PHP_INT_SIZE * $numInts, function ($bytes) use ($cb, $numInts) { if ($bytes === false) { $cb(false); return; } $ints = []; for ($i = 0; $i < $numInts; ++$i) { $thisInt = 0; for ($j = 0; $j < PHP_INT_SIZE; ++$j) { $thisInt = ($thisInt << 8) | (ord($bytes[$i * PHP_INT_SIZE + $j]) & 0xFF); } // Absolute value in two's compliment (with min int going to zero) $thisInt = $thisInt & PHP_INT_MAX; $ints[] = $thisInt; } $cb($ints); }, $pri, $hang); }
[ "public", "static", "function", "randomInts", "(", "$", "numInts", ",", "$", "cb", ",", "$", "pri", "=", "0", ",", "$", "hang", "=", "false", ")", "{", "static", "::", "randomBytes", "(", "PHP_INT_SIZE", "*", "$", "numInts", ",", "function", "(", "$"...
Returns array of pseudo random integers of machine-dependent size @param integer $numInts Number of integers @param callable $cb Callback @param integer $pri Priority of EIO operation @param boolean $hang If true, we shall use /dev/random instead of /dev/urandom and it may cause a delay @return integer
[ "Returns", "array", "of", "pseudo", "random", "integers", "of", "machine", "-", "dependent", "size" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L168-L187
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.randomInts32
public static function randomInts32($numInts, $cb, $pri = 0, $hang = false) { static::randomBytes(4 * $numInts, function ($bytes) use ($cb, $numInts) { if ($bytes === false) { $cb(false); return; } $ints = []; for ($i = 0; $i < $numInts; ++$i) { $thisInt = 0; for ($j = 0; $j < 4; ++$j) { $thisInt = ($thisInt << 8) | (ord($bytes[$i * 4 + $j]) & 0xFF); } // Absolute value in two's compliment (with min int going to zero) $thisInt = $thisInt & 0xFFFFFFFF; $ints[] = $thisInt; } $cb($ints); }, $pri, $hang); }
php
public static function randomInts32($numInts, $cb, $pri = 0, $hang = false) { static::randomBytes(4 * $numInts, function ($bytes) use ($cb, $numInts) { if ($bytes === false) { $cb(false); return; } $ints = []; for ($i = 0; $i < $numInts; ++$i) { $thisInt = 0; for ($j = 0; $j < 4; ++$j) { $thisInt = ($thisInt << 8) | (ord($bytes[$i * 4 + $j]) & 0xFF); } // Absolute value in two's compliment (with min int going to zero) $thisInt = $thisInt & 0xFFFFFFFF; $ints[] = $thisInt; } $cb($ints); }, $pri, $hang); }
[ "public", "static", "function", "randomInts32", "(", "$", "numInts", ",", "$", "cb", ",", "$", "pri", "=", "0", ",", "$", "hang", "=", "false", ")", "{", "static", "::", "randomBytes", "(", "4", "*", "$", "numInts", ",", "function", "(", "$", "byte...
Returns array of pseudo random 32-bit integers @param integer $numInts Number of integers @param callable $cb Callback @param integer $pri Priority of EIO operation @param boolean $hang If true, we shall use /dev/random instead of /dev/urandom and it may cause a delay @return integer
[ "Returns", "array", "of", "pseudo", "random", "32", "-", "bit", "integers" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L197-L216
kakserpom/phpdaemon
PHPDaemon/Utils/Crypt.php
Crypt.getMinimalBitMask
protected static function getMinimalBitMask($toRepresent) { if ($toRepresent < 1) { return false; } $mask = 0x1; while ($mask < $toRepresent) { $mask = ($mask << 1) | 1; } return $mask; }
php
protected static function getMinimalBitMask($toRepresent) { if ($toRepresent < 1) { return false; } $mask = 0x1; while ($mask < $toRepresent) { $mask = ($mask << 1) | 1; } return $mask; }
[ "protected", "static", "function", "getMinimalBitMask", "(", "$", "toRepresent", ")", "{", "if", "(", "$", "toRepresent", "<", "1", ")", "{", "return", "false", ";", "}", "$", "mask", "=", "0x1", ";", "while", "(", "$", "mask", "<", "$", "toRepresent",...
Returns the smallest bit mask of all 1s such that ($toRepresent & mask) = $toRepresent @param integer $toRepresent must be an integer greater than or equal to 1 @return integer
[ "Returns", "the", "smallest", "bit", "mask", "of", "all", "1s", "such", "that", "(", "$toRepresent", "&", "mask", ")", "=", "$toRepresent" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/Crypt.php#L223-L233
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Connection/ConnectionStartFrame.php
ConnectionStartFrame.create
public static function create( $versionMajor = null, $versionMinor = null, $serverProperties = null, $mechanisms = null, $locales = null ) { $frame = new self(); if (null !== $versionMajor) { $frame->versionMajor = $versionMajor; } if (null !== $versionMinor) { $frame->versionMinor = $versionMinor; } if (null !== $serverProperties) { $frame->serverProperties = $serverProperties; } if (null !== $mechanisms) { $frame->mechanisms = $mechanisms; } if (null !== $locales) { $frame->locales = $locales; } return $frame; }
php
public static function create( $versionMajor = null, $versionMinor = null, $serverProperties = null, $mechanisms = null, $locales = null ) { $frame = new self(); if (null !== $versionMajor) { $frame->versionMajor = $versionMajor; } if (null !== $versionMinor) { $frame->versionMinor = $versionMinor; } if (null !== $serverProperties) { $frame->serverProperties = $serverProperties; } if (null !== $mechanisms) { $frame->mechanisms = $mechanisms; } if (null !== $locales) { $frame->locales = $locales; } return $frame; }
[ "public", "static", "function", "create", "(", "$", "versionMajor", "=", "null", ",", "$", "versionMinor", "=", "null", ",", "$", "serverProperties", "=", "null", ",", "$", "mechanisms", "=", "null", ",", "$", "locales", "=", "null", ")", "{", "$", "fr...
longstr
[ "longstr" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Connection/ConnectionStartFrame.php#L24-L47
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.getFrameType
public function getFrameType($type) { if (is_int($type)) { return $type; } if ($type === null) { $type = 'STRING'; } $frametype = @constant(get_class($this) . '::' . $type); if ($frametype === null) { Daemon::log(__METHOD__ . ' : Undefined frametype "' . $type . '"'); } return $frametype; }
php
public function getFrameType($type) { if (is_int($type)) { return $type; } if ($type === null) { $type = 'STRING'; } $frametype = @constant(get_class($this) . '::' . $type); if ($frametype === null) { Daemon::log(__METHOD__ . ' : Undefined frametype "' . $type . '"'); } return $frametype; }
[ "public", "function", "getFrameType", "(", "$", "type", ")", "{", "if", "(", "is_int", "(", "$", "type", ")", ")", "{", "return", "$", "type", ";", "}", "if", "(", "$", "type", "===", "null", ")", "{", "$", "type", "=", "'STRING'", ";", "}", "$...
Get real frame type identificator @param $type @return integer
[ "Get", "real", "frame", "type", "identificator" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L115-L128
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.onInheritanceFromRequest
public function onInheritanceFromRequest($req) { $this->state = self::STATE_HEADERS; $this->addr = $req->attrs->server['REMOTE_ADDR']; $this->server = $req->attrs->server; $this->get = $req->attrs->get; $this->prependInput("\r\n"); $this->onRead(); }
php
public function onInheritanceFromRequest($req) { $this->state = self::STATE_HEADERS; $this->addr = $req->attrs->server['REMOTE_ADDR']; $this->server = $req->attrs->server; $this->get = $req->attrs->get; $this->prependInput("\r\n"); $this->onRead(); }
[ "public", "function", "onInheritanceFromRequest", "(", "$", "req", ")", "{", "$", "this", "->", "state", "=", "self", "::", "STATE_HEADERS", ";", "$", "this", "->", "addr", "=", "$", "req", "->", "attrs", "->", "server", "[", "'REMOTE_ADDR'", "]", ";", ...
Called when connection is inherited from HTTP request @param object $req @return void
[ "Called", "when", "connection", "is", "inherited", "from", "HTTP", "request" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L136-L144
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.onFinish
public function onFinish() { $this->sendFrame('', 'CONNCLOSE'); if ($this->route) { $this->route->onFinish(); } $this->route = null; }
php
public function onFinish() { $this->sendFrame('', 'CONNCLOSE'); if ($this->route) { $this->route->onFinish(); } $this->route = null; }
[ "public", "function", "onFinish", "(", ")", "{", "$", "this", "->", "sendFrame", "(", "''", ",", "'CONNCLOSE'", ")", ";", "if", "(", "$", "this", "->", "route", ")", "{", "$", "this", "->", "route", "->", "onFinish", "(", ")", ";", "}", "$", "thi...
Event of Connection. @return void
[ "Event", "of", "Connection", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L163-L171
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.onFrame
public function onFrame($data, $type) { if (!isset($this->route)) { return false; } try { $this->route->onWakeup(); $this->route->onFrame($data, $type); } catch (\Exception $e) { Daemon::uncaughtExceptionHandler($e); } if ($this->route) { $this->route->onSleep(); } return true; }
php
public function onFrame($data, $type) { if (!isset($this->route)) { return false; } try { $this->route->onWakeup(); $this->route->onFrame($data, $type); } catch (\Exception $e) { Daemon::uncaughtExceptionHandler($e); } if ($this->route) { $this->route->onSleep(); } return true; }
[ "public", "function", "onFrame", "(", "$", "data", ",", "$", "type", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "route", ")", ")", "{", "return", "false", ";", "}", "try", "{", "$", "this", "->", "route", "->", "onWakeup", "(", ...
Called when new frame received. @param string $data Frame's data. @param string $type Frame's type ("STRING" OR "BINARY"). @return boolean Success.
[ "Called", "when", "new", "frame", "received", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L192-L207
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.gracefulShutdown
public function gracefulShutdown() { if ((!$this->route) || $this->route->gracefulShutdown()) { $this->finish(); return true; } return false; }
php
public function gracefulShutdown() { if ((!$this->route) || $this->route->gracefulShutdown()) { $this->finish(); return true; } return false; }
[ "public", "function", "gracefulShutdown", "(", ")", "{", "if", "(", "(", "!", "$", "this", "->", "route", ")", "||", "$", "this", "->", "route", "->", "gracefulShutdown", "(", ")", ")", "{", "$", "this", "->", "finish", "(", ")", ";", "return", "tr...
Called when the worker is going to shutdown. @return boolean Ready to shutdown ?
[ "Called", "when", "the", "worker", "is", "going", "to", "shutdown", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L213-L220
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.handshake
public function handshake() { $this->route = $this->pool->getRoute($this->server['DOCUMENT_URI'], $this); if (!$this->route) { Daemon::$process->log(get_class($this) . '::' . __METHOD__ . ' : Cannot handshake session for client "' . $this->addr . '"'); $this->finish(); return false; } if (method_exists($this->route, 'onBeforeHandshake')) { $this->route->onWakeup(); $ret = $this->route->onBeforeHandshake(function () { $this->handshakeAfter(); }); if ($this->route) { $this->route->onSleep(); } if ($ret !== false) { return true; } } return $this->handshakeAfter(); }
php
public function handshake() { $this->route = $this->pool->getRoute($this->server['DOCUMENT_URI'], $this); if (!$this->route) { Daemon::$process->log(get_class($this) . '::' . __METHOD__ . ' : Cannot handshake session for client "' . $this->addr . '"'); $this->finish(); return false; } if (method_exists($this->route, 'onBeforeHandshake')) { $this->route->onWakeup(); $ret = $this->route->onBeforeHandshake(function () { $this->handshakeAfter(); }); if ($this->route) { $this->route->onSleep(); } if ($ret !== false) { return true; } } return $this->handshakeAfter(); }
[ "public", "function", "handshake", "(", ")", "{", "$", "this", "->", "route", "=", "$", "this", "->", "pool", "->", "getRoute", "(", "$", "this", "->", "server", "[", "'DOCUMENT_URI'", "]", ",", "$", "this", ")", ";", "if", "(", "!", "$", "this", ...
Called when we're going to handshake. @return boolean Handshake status
[ "Called", "when", "we", "re", "going", "to", "handshake", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L227-L250
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.httpReadFirstline
protected function httpReadFirstline() { if (($l = $this->readline()) === null) { return null; } $e = explode(' ', $l); $u = isset($e[1]) ? parse_url($e[1]) : false; if ($u === false) { $this->badRequest(); return false; } if (!isset($u['path'])) { $u['path'] = null; } if (isset($u['host'])) { $this->server['HTTP_HOST'] = $u['host']; } $srv = &$this->server; $srv['REQUEST_METHOD'] = $e[0]; $srv['REQUEST_TIME'] = time(); $srv['REQUEST_TIME_FLOAT'] = microtime(true); $srv['REQUEST_URI'] = $u['path'] . (isset($u['query']) ? '?' . $u['query'] : ''); $srv['DOCUMENT_URI'] = $u['path']; $srv['PHP_SELF'] = $u['path']; $srv['QUERY_STRING'] = isset($u['query']) ? $u['query'] : null; $srv['SCRIPT_NAME'] = $srv['DOCUMENT_URI'] = isset($u['path']) ? $u['path'] : '/'; $srv['SERVER_PROTOCOL'] = isset($e[2]) ? $e[2] : 'HTTP/1.1'; $srv['REMOTE_ADDR'] = $this->addr; $srv['REMOTE_PORT'] = $this->port; return true; }
php
protected function httpReadFirstline() { if (($l = $this->readline()) === null) { return null; } $e = explode(' ', $l); $u = isset($e[1]) ? parse_url($e[1]) : false; if ($u === false) { $this->badRequest(); return false; } if (!isset($u['path'])) { $u['path'] = null; } if (isset($u['host'])) { $this->server['HTTP_HOST'] = $u['host']; } $srv = &$this->server; $srv['REQUEST_METHOD'] = $e[0]; $srv['REQUEST_TIME'] = time(); $srv['REQUEST_TIME_FLOAT'] = microtime(true); $srv['REQUEST_URI'] = $u['path'] . (isset($u['query']) ? '?' . $u['query'] : ''); $srv['DOCUMENT_URI'] = $u['path']; $srv['PHP_SELF'] = $u['path']; $srv['QUERY_STRING'] = isset($u['query']) ? $u['query'] : null; $srv['SCRIPT_NAME'] = $srv['DOCUMENT_URI'] = isset($u['path']) ? $u['path'] : '/'; $srv['SERVER_PROTOCOL'] = isset($e[2]) ? $e[2] : 'HTTP/1.1'; $srv['REMOTE_ADDR'] = $this->addr; $srv['REMOTE_PORT'] = $this->port; return true; }
[ "protected", "function", "httpReadFirstline", "(", ")", "{", "if", "(", "(", "$", "l", "=", "$", "this", "->", "readline", "(", ")", ")", "===", "null", ")", "{", "return", "null", ";", "}", "$", "e", "=", "explode", "(", "' '", ",", "$", "l", ...
Read first line of HTTP request @return boolean|null Success
[ "Read", "first", "line", "of", "HTTP", "request" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L295-L325
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.httpReadHeaders
protected function httpReadHeaders() { while (($l = $this->readLine()) !== null) { if ($l === '') { return true; } $e = explode(': ', $l); if (isset($e[1])) { $this->currentHeader = 'HTTP_' . strtoupper(strtr($e[0], Generic::$htr)); $this->server[$this->currentHeader] = $e[1]; } elseif (($e[0][0] === "\t" || $e[0][0] === "\x20") && $this->currentHeader) { // multiline header continued $this->server[$this->currentHeader] .= $e[0]; } else { // whatever client speaks is not HTTP anymore $this->badRequest(); return false; } } return null; }
php
protected function httpReadHeaders() { while (($l = $this->readLine()) !== null) { if ($l === '') { return true; } $e = explode(': ', $l); if (isset($e[1])) { $this->currentHeader = 'HTTP_' . strtoupper(strtr($e[0], Generic::$htr)); $this->server[$this->currentHeader] = $e[1]; } elseif (($e[0][0] === "\t" || $e[0][0] === "\x20") && $this->currentHeader) { // multiline header continued $this->server[$this->currentHeader] .= $e[0]; } else { // whatever client speaks is not HTTP anymore $this->badRequest(); return false; } } return null; }
[ "protected", "function", "httpReadHeaders", "(", ")", "{", "while", "(", "(", "$", "l", "=", "$", "this", "->", "readLine", "(", ")", ")", "!==", "null", ")", "{", "if", "(", "$", "l", "===", "''", ")", "{", "return", "true", ";", "}", "$", "e"...
Read headers line-by-line @return boolean|null Success
[ "Read", "headers", "line", "-", "by", "-", "line" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L331-L351
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.onRead
protected function onRead() { if (!$this->policyReqNotFound) { $d = $this->drainIfMatch("<policy-file-request/>\x00"); if ($d === null) { // partially match return; } if ($d) { if (($FP = \PHPDaemon\Servers\FlashPolicy\Pool::getInstance($this->pool->config->fpsname->value, false)) && $FP->policyData ) { $this->write($FP->policyData . "\x00"); } $this->finish(); return; } else { $this->policyReqNotFound = true; } } start: if ($this->finished) { return; } if ($this->state === self::STATE_STANDBY) { $this->state = self::STATE_FIRSTLINE; } if ($this->state === self::STATE_FIRSTLINE) { if (!$this->httpReadFirstline()) { return; } $this->state = self::STATE_HEADERS; } if ($this->state === self::STATE_HEADERS) { if (!$this->httpReadHeaders()) { return; } if (!$this->httpProcessHeaders()) { $this->finish(); return; } $this->state = self::STATE_CONTENT; } if ($this->state === self::STATE_CONTENT) { $this->state = self::STATE_PREHANDSHAKE; } }
php
protected function onRead() { if (!$this->policyReqNotFound) { $d = $this->drainIfMatch("<policy-file-request/>\x00"); if ($d === null) { // partially match return; } if ($d) { if (($FP = \PHPDaemon\Servers\FlashPolicy\Pool::getInstance($this->pool->config->fpsname->value, false)) && $FP->policyData ) { $this->write($FP->policyData . "\x00"); } $this->finish(); return; } else { $this->policyReqNotFound = true; } } start: if ($this->finished) { return; } if ($this->state === self::STATE_STANDBY) { $this->state = self::STATE_FIRSTLINE; } if ($this->state === self::STATE_FIRSTLINE) { if (!$this->httpReadFirstline()) { return; } $this->state = self::STATE_HEADERS; } if ($this->state === self::STATE_HEADERS) { if (!$this->httpReadHeaders()) { return; } if (!$this->httpProcessHeaders()) { $this->finish(); return; } $this->state = self::STATE_CONTENT; } if ($this->state === self::STATE_CONTENT) { $this->state = self::STATE_PREHANDSHAKE; } }
[ "protected", "function", "onRead", "(", ")", "{", "if", "(", "!", "$", "this", "->", "policyReqNotFound", ")", "{", "$", "d", "=", "$", "this", "->", "drainIfMatch", "(", "\"<policy-file-request/>\\x00\"", ")", ";", "if", "(", "$", "d", "===", "null", ...
Called when new data received. @return void
[ "Called", "when", "new", "data", "received", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L357-L403
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.httpProcessHeaders
protected function httpProcessHeaders() { $this->state = self::STATE_PREHANDSHAKE; if (isset($this->server['HTTP_SEC_WEBSOCKET_EXTENSIONS'])) { $str = strtolower($this->server['HTTP_SEC_WEBSOCKET_EXTENSIONS']); $str = preg_replace($this->extensionsCleanRegex, '', $str); $this->extensions = explode(', ', $str); } if (!isset($this->server['HTTP_CONNECTION']) || (!preg_match('~(?:^|\W)Upgrade(?:\W|$)~i', $this->server['HTTP_CONNECTION'])) // "Upgrade" is not always alone (ie. "Connection: Keep-alive, Upgrade") || !isset($this->server['HTTP_UPGRADE']) || (strtolower($this->server['HTTP_UPGRADE']) !== 'websocket') // Lowercase comparison iss important ) { $this->finish(); return false; } if (isset($this->server['HTTP_COOKIE'])) { Generic::parseStr(strtr($this->server['HTTP_COOKIE'], Generic::$hvaltr), $this->cookie); } if (isset($this->server['QUERY_STRING'])) { Generic::parseStr($this->server['QUERY_STRING'], $this->get); } // ---------------------------------------------------------- // Protocol discovery, based on HTTP headers... // ---------------------------------------------------------- if (isset($this->server['HTTP_SEC_WEBSOCKET_VERSION'])) { // HYBI if ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] === '8') { // Version 8 (FF7, Chrome14) $this->switchToProtocol('V13'); } elseif ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] === '13') { // newest protocol $this->switchToProtocol('V13'); } else { Daemon::$process->log(get_class($this) . '::' . __METHOD__ . " : Websocket protocol version " . $this->server['HTTP_SEC_WEBSOCKET_VERSION'] . ' is not yet supported for client "' . $this->addr . '"'); $this->finish(); return false; } } elseif (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY1']) || !isset($this->server['HTTP_SEC_WEBSOCKET_KEY2'])) { $this->switchToProtocol('VE'); } else { // Defaulting to HIXIE (Safari5 and many non-browser clients...) $this->switchToProtocol('V0'); } // ---------------------------------------------------------- // End of protocol discovery // ---------------------------------------------------------- return true; }
php
protected function httpProcessHeaders() { $this->state = self::STATE_PREHANDSHAKE; if (isset($this->server['HTTP_SEC_WEBSOCKET_EXTENSIONS'])) { $str = strtolower($this->server['HTTP_SEC_WEBSOCKET_EXTENSIONS']); $str = preg_replace($this->extensionsCleanRegex, '', $str); $this->extensions = explode(', ', $str); } if (!isset($this->server['HTTP_CONNECTION']) || (!preg_match('~(?:^|\W)Upgrade(?:\W|$)~i', $this->server['HTTP_CONNECTION'])) // "Upgrade" is not always alone (ie. "Connection: Keep-alive, Upgrade") || !isset($this->server['HTTP_UPGRADE']) || (strtolower($this->server['HTTP_UPGRADE']) !== 'websocket') // Lowercase comparison iss important ) { $this->finish(); return false; } if (isset($this->server['HTTP_COOKIE'])) { Generic::parseStr(strtr($this->server['HTTP_COOKIE'], Generic::$hvaltr), $this->cookie); } if (isset($this->server['QUERY_STRING'])) { Generic::parseStr($this->server['QUERY_STRING'], $this->get); } // ---------------------------------------------------------- // Protocol discovery, based on HTTP headers... // ---------------------------------------------------------- if (isset($this->server['HTTP_SEC_WEBSOCKET_VERSION'])) { // HYBI if ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] === '8') { // Version 8 (FF7, Chrome14) $this->switchToProtocol('V13'); } elseif ($this->server['HTTP_SEC_WEBSOCKET_VERSION'] === '13') { // newest protocol $this->switchToProtocol('V13'); } else { Daemon::$process->log(get_class($this) . '::' . __METHOD__ . " : Websocket protocol version " . $this->server['HTTP_SEC_WEBSOCKET_VERSION'] . ' is not yet supported for client "' . $this->addr . '"'); $this->finish(); return false; } } elseif (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY1']) || !isset($this->server['HTTP_SEC_WEBSOCKET_KEY2'])) { $this->switchToProtocol('VE'); } else { // Defaulting to HIXIE (Safari5 and many non-browser clients...) $this->switchToProtocol('V0'); } // ---------------------------------------------------------- // End of protocol discovery // ---------------------------------------------------------- return true; }
[ "protected", "function", "httpProcessHeaders", "(", ")", "{", "$", "this", "->", "state", "=", "self", "::", "STATE_PREHANDSHAKE", ";", "if", "(", "isset", "(", "$", "this", "->", "server", "[", "'HTTP_SEC_WEBSOCKET_EXTENSIONS'", "]", ")", ")", "{", "$", "...
Process headers @return bool
[ "Process", "headers" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L409-L454
kakserpom/phpdaemon
PHPDaemon/Servers/WebSocket/Connection.php
Connection.header
public function header($s, $replace = true, $code = false) { if ($code) { $this->status($code); } if ($this->headers_sent) { throw new RequestHeadersAlreadySent; } $s = strtr($s, "\r\n", ' '); $e = explode(':', $s, 2); if (!isset($e[1])) { $e[0] = 'STATUS'; if (strncmp($s, 'HTTP/', 5) === 0) { $s = substr($s, 9); } } $k = strtr(strtoupper($e[0]), Generic::$htr); if ($k === 'CONTENT_TYPE') { Generic::parseStr(strtolower($e[1]), $ctype, true); if (!isset($ctype['charset'])) { $ctype['charset'] = $this->upstream->pool->config->defaultcharset->value; $s = $e[0] . ': '; $i = 0; foreach ($ctype as $k => $v) { $s .= ($i > 0 ? '; ' : '') . $k . ($v !== '' ? '=' . $v : ''); ++$i; } } } if ($k === 'SET_COOKIE') { $k .= '_' . ++$this->cookieNum; } elseif (!$replace && isset($this->headers[$k])) { return false; } $this->headers[$k] = $s; if ($k === 'CONTENT_LENGTH') { $this->contentLength = (int)$e[1]; } elseif ($k === 'LOCATION') { $this->status(301); } if (Daemon::$compatMode) { is_callable('header_native') ? header_native($s) : header($s); } return true; }
php
public function header($s, $replace = true, $code = false) { if ($code) { $this->status($code); } if ($this->headers_sent) { throw new RequestHeadersAlreadySent; } $s = strtr($s, "\r\n", ' '); $e = explode(':', $s, 2); if (!isset($e[1])) { $e[0] = 'STATUS'; if (strncmp($s, 'HTTP/', 5) === 0) { $s = substr($s, 9); } } $k = strtr(strtoupper($e[0]), Generic::$htr); if ($k === 'CONTENT_TYPE') { Generic::parseStr(strtolower($e[1]), $ctype, true); if (!isset($ctype['charset'])) { $ctype['charset'] = $this->upstream->pool->config->defaultcharset->value; $s = $e[0] . ': '; $i = 0; foreach ($ctype as $k => $v) { $s .= ($i > 0 ? '; ' : '') . $k . ($v !== '' ? '=' . $v : ''); ++$i; } } } if ($k === 'SET_COOKIE') { $k .= '_' . ++$this->cookieNum; } elseif (!$replace && isset($this->headers[$k])) { return false; } $this->headers[$k] = $s; if ($k === 'CONTENT_LENGTH') { $this->contentLength = (int)$e[1]; } elseif ($k === 'LOCATION') { $this->status(301); } if (Daemon::$compatMode) { is_callable('header_native') ? header_native($s) : header($s); } return true; }
[ "public", "function", "header", "(", "$", "s", ",", "$", "replace", "=", "true", ",", "$", "code", "=", "false", ")", "{", "if", "(", "$", "code", ")", "{", "$", "this", "->", "status", "(", "$", "code", ")", ";", "}", "if", "(", "$", "this",...
Send the header @param string $s Header. Example: 'Location: http://php.net/' @param boolean $replace Optional. Replace? @param boolean $code Optional. HTTP response code @throws \PHPDaemon\Request\RequestHeadersAlreadySent @return boolean Success
[ "Send", "the", "header" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Connection.php#L497-L552
kakserpom/phpdaemon
PHPDaemon/Examples/GameMonitor.php
GameMonitor.init
public function init() { if ($this->isEnabled()) { $this->client = \PHPDaemon\Clients\Valve\Pool::getInstance(); $this->db = \MongoClient::getInstance(); $this->servers = $this->db->{$this->config->dbname->value . '.servers'}; } }
php
public function init() { if ($this->isEnabled()) { $this->client = \PHPDaemon\Clients\Valve\Pool::getInstance(); $this->db = \MongoClient::getInstance(); $this->servers = $this->db->{$this->config->dbname->value . '.servers'}; } }
[ "public", "function", "init", "(", ")", "{", "if", "(", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "$", "this", "->", "client", "=", "\\", "PHPDaemon", "\\", "Clients", "\\", "Valve", "\\", "Pool", "::", "getInstance", "(", ")", ";", "$", ...
Constructor. @return void
[ "Constructor", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/GameMonitor.php#L23-L30
kakserpom/phpdaemon
PHPDaemon/Examples/GameMonitor.php
GameMonitor.onReady
public function onReady() { if ($this->isEnabled()) { $this->updateTimer = setTimeout(function ($timer) { $this->updateAllServers(); $timer->timeout(2e6); }, 1); } }
php
public function onReady() { if ($this->isEnabled()) { $this->updateTimer = setTimeout(function ($timer) { $this->updateAllServers(); $timer->timeout(2e6); }, 1); } }
[ "public", "function", "onReady", "(", ")", "{", "if", "(", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "$", "this", "->", "updateTimer", "=", "setTimeout", "(", "function", "(", "$", "timer", ")", "{", "$", "this", "->", "updateAllServers", "...
Called when the worker is ready to go. @return void
[ "Called", "when", "the", "worker", "is", "ready", "to", "go", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/GameMonitor.php#L47-L55
kakserpom/phpdaemon
PHPDaemon/Examples/GameMonitor.php
GameMonitorHTTPRequest.init
public function init() { $req = $this; $job = $this->job = new \PHPDaemon\Core\ComplexJob(function () use ($req) { // called when job is done $req->wakeup(); // wake up the request immediately }); $job('getServers', function ($name, $job) use ($req) { // registering job named 'pingjob' $req->appInstance->servers->find(function ($cursor) use ($name, $job) { $job->setResult($name, $cursor->items); }); }); $job(); // let the fun begin $this->sleep(5); // setting timeout }
php
public function init() { $req = $this; $job = $this->job = new \PHPDaemon\Core\ComplexJob(function () use ($req) { // called when job is done $req->wakeup(); // wake up the request immediately }); $job('getServers', function ($name, $job) use ($req) { // registering job named 'pingjob' $req->appInstance->servers->find(function ($cursor) use ($name, $job) { $job->setResult($name, $cursor->items); }); }); $job(); // let the fun begin $this->sleep(5); // setting timeout }
[ "public", "function", "init", "(", ")", "{", "$", "req", "=", "$", "this", ";", "$", "job", "=", "$", "this", "->", "job", "=", "new", "\\", "PHPDaemon", "\\", "Core", "\\", "ComplexJob", "(", "function", "(", ")", "use", "(", "$", "req", ")", ...
Constructor. @return void
[ "Constructor", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/GameMonitor.php#L206-L226
kakserpom/phpdaemon
PHPDaemon/Clients/Redis/Examples/SimpleRequest.php
SimpleRequest.init
public function init() { $job = $this->job = new \PHPDaemon\Core\ComplexJob(function ($job) { // called when job is done // prevent cleaning up results $job->keep(); // wake up the request immediately $this->wakeup(); }); // just pushing something $this->appInstance->redis->lpush('mylist', microtime(true)); // registering job named 'testquery' $job('testquery', function ($name, $job) { $this->appInstance->redis->lrange('mylist', 0, 10, function ($conn) use ($name, $job) { // calling lrange Redis command // setting job result $job->setResult($name, $conn->result); }); }); // let the fun begin $job(); // setting timeout $this->sleep(1, true); }
php
public function init() { $job = $this->job = new \PHPDaemon\Core\ComplexJob(function ($job) { // called when job is done // prevent cleaning up results $job->keep(); // wake up the request immediately $this->wakeup(); }); // just pushing something $this->appInstance->redis->lpush('mylist', microtime(true)); // registering job named 'testquery' $job('testquery', function ($name, $job) { $this->appInstance->redis->lrange('mylist', 0, 10, function ($conn) use ($name, $job) { // calling lrange Redis command // setting job result $job->setResult($name, $conn->result); }); }); // let the fun begin $job(); // setting timeout $this->sleep(1, true); }
[ "public", "function", "init", "(", ")", "{", "$", "job", "=", "$", "this", "->", "job", "=", "new", "\\", "PHPDaemon", "\\", "Core", "\\", "ComplexJob", "(", "function", "(", "$", "job", ")", "{", "// called when job is done", "// prevent cleaning up results...
Constructor. @return void
[ "Constructor", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Redis/Examples/SimpleRequest.php#L22-L53
kakserpom/phpdaemon
PHPDaemon/Core/EventLoop.php
EventLoop.run
public function run() { $this->stopped = false; while (!$this->stopped) { $this->callbacks->executeAll($this); if (!$this->base->dispatch()) { break; } } }
php
public function run() { $this->stopped = false; while (!$this->stopped) { $this->callbacks->executeAll($this); if (!$this->base->dispatch()) { break; } } }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "stopped", "=", "false", ";", "while", "(", "!", "$", "this", "->", "stopped", ")", "{", "$", "this", "->", "callbacks", "->", "executeAll", "(", "$", "this", ")", ";", "if", "(", "!"...
Run
[ "Run" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/EventLoop.php#L144-L153
kakserpom/phpdaemon
PHPDaemon/Examples/ExampleWithMySQL.php
ExampleWithMySQLRequest.init
public function init() { $job = $this->job = new \PHPDaemon\Core\ComplexJob(function ($job) { // called when job is done $job->keep(); $this->wakeup(); // wake up the request immediately }); $job('select', function ($name, $job) { // registering job named 'select' $this->appInstance->sql->getConnection(function ($sql) use ($name, $job) { if (!$sql->isConnected()) { $job->setResult($name, null); return null; } $sql->query('SELECT 123, "string"', function ($sql, $success) use ($job, $name) { $job('showdbs', function ($name, $job) use ($sql) { // registering job named 'showdbs' $sql->query('SHOW DATABASES', function ($sql, $t) use ($job, $name) { $job->setResult($name, $sql->resultRows); }); }); $job->setResult($name, $sql->resultRows); }); return null; }); }); $job(); // let the fun begin $this->sleep(5, true); // setting timeout }
php
public function init() { $job = $this->job = new \PHPDaemon\Core\ComplexJob(function ($job) { // called when job is done $job->keep(); $this->wakeup(); // wake up the request immediately }); $job('select', function ($name, $job) { // registering job named 'select' $this->appInstance->sql->getConnection(function ($sql) use ($name, $job) { if (!$sql->isConnected()) { $job->setResult($name, null); return null; } $sql->query('SELECT 123, "string"', function ($sql, $success) use ($job, $name) { $job('showdbs', function ($name, $job) use ($sql) { // registering job named 'showdbs' $sql->query('SHOW DATABASES', function ($sql, $t) use ($job, $name) { $job->setResult($name, $sql->resultRows); }); }); $job->setResult($name, $sql->resultRows); }); return null; }); }); $job(); // let the fun begin $this->sleep(5, true); // setting timeout }
[ "public", "function", "init", "(", ")", "{", "$", "job", "=", "$", "this", "->", "job", "=", "new", "\\", "PHPDaemon", "\\", "Core", "\\", "ComplexJob", "(", "function", "(", "$", "job", ")", "{", "// called when job is done", "$", "job", "->", "keep",...
Constructor. @return void
[ "Constructor", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleWithMySQL.php#L56-L88
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Confirm/ConfirmSelectFrame.php
ConfirmSelectFrame.create
public static function create( $nowait = null ) { $frame = new self(); if (null !== $nowait) { $frame->nowait = $nowait; } return $frame; }
php
public static function create( $nowait = null ) { $frame = new self(); if (null !== $nowait) { $frame->nowait = $nowait; } return $frame; }
[ "public", "static", "function", "create", "(", "$", "nowait", "=", "null", ")", "{", "$", "frame", "=", "new", "self", "(", ")", ";", "if", "(", "null", "!==", "$", "nowait", ")", "{", "$", "frame", "->", "nowait", "=", "$", "nowait", ";", "}", ...
bit
[ "bit" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Confirm/ConfirmSelectFrame.php#L20-L31
kakserpom/phpdaemon
PHPDaemon/Examples/ExampleComplexJob.php
ExampleComplexJob.onReady
public function onReady() { // Adding listener // ComplexJob - STATE_WAITING $job = new \PHPDaemon\Core\ComplexJob(function ($job) { // ComplexJob - STATE_DONE /*array ( 'bar' => array ( 'job' => 'bar', 'success' => false, 'line' => 63, ), 'foo' => array ( 'job' => 'foo', 'success' => true, 'line' => 84, 'arg' => array ( 'param' => 'value', ), ), 'baz' => array ( 'job' => 'baz', 'success' => false, 'line' => 94, ), )*/ \PHPDaemon\Core\Daemon::log($job->results); }); // Adding listener // ComplexJob - STATE_WAITING $job->addListener(function ($job) { // ComplexJob - STATE_DONE }); // Adding async job foo $job('foo', $this->foo(['param' => 'value'])); // Adding with 1 sec delay \PHPDaemon\Core\Timer::add(function ($event) use ($job) { // Adding async job bar $job('bar', function ($jobname, $job) { \PHPDaemon\Core\Timer::add(function ($event) use ($jobname, $job) { // Job done $job->setResult($jobname, ['job' => 'bar', 'success' => false, 'line' => __LINE__]); $event->finish(); }, 1e3 * 50); }); // Adding async job baz. Equal $job('baz', $this->baz()); $job->addJob('baz', $this->baz()); // Run jobs. All listeners will be called when the jobs done // ComplexJob - STATE_RUNNING $job(); $event->finish(); }, 1e6 * 1); }
php
public function onReady() { // Adding listener // ComplexJob - STATE_WAITING $job = new \PHPDaemon\Core\ComplexJob(function ($job) { // ComplexJob - STATE_DONE /*array ( 'bar' => array ( 'job' => 'bar', 'success' => false, 'line' => 63, ), 'foo' => array ( 'job' => 'foo', 'success' => true, 'line' => 84, 'arg' => array ( 'param' => 'value', ), ), 'baz' => array ( 'job' => 'baz', 'success' => false, 'line' => 94, ), )*/ \PHPDaemon\Core\Daemon::log($job->results); }); // Adding listener // ComplexJob - STATE_WAITING $job->addListener(function ($job) { // ComplexJob - STATE_DONE }); // Adding async job foo $job('foo', $this->foo(['param' => 'value'])); // Adding with 1 sec delay \PHPDaemon\Core\Timer::add(function ($event) use ($job) { // Adding async job bar $job('bar', function ($jobname, $job) { \PHPDaemon\Core\Timer::add(function ($event) use ($jobname, $job) { // Job done $job->setResult($jobname, ['job' => 'bar', 'success' => false, 'line' => __LINE__]); $event->finish(); }, 1e3 * 50); }); // Adding async job baz. Equal $job('baz', $this->baz()); $job->addJob('baz', $this->baz()); // Run jobs. All listeners will be called when the jobs done // ComplexJob - STATE_RUNNING $job(); $event->finish(); }, 1e6 * 1); }
[ "public", "function", "onReady", "(", ")", "{", "// Adding listener", "// ComplexJob - STATE_WAITING", "$", "job", "=", "new", "\\", "PHPDaemon", "\\", "Core", "\\", "ComplexJob", "(", "function", "(", "$", "job", ")", "{", "// ComplexJob - STATE_DONE", "/*array (...
Called when the worker is ready to go @return void
[ "Called", "when", "the", "worker", "is", "ready", "to", "go" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleComplexJob.php#L20-L84
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Connection/ConnectionOpenOkFrame.php
ConnectionOpenOkFrame.create
public static function create( $knownHosts = null ) { $frame = new self(); if (null !== $knownHosts) { $frame->knownHosts = $knownHosts; } return $frame; }
php
public static function create( $knownHosts = null ) { $frame = new self(); if (null !== $knownHosts) { $frame->knownHosts = $knownHosts; } return $frame; }
[ "public", "static", "function", "create", "(", "$", "knownHosts", "=", "null", ")", "{", "$", "frame", "=", "new", "self", "(", ")", ";", "if", "(", "null", "!==", "$", "knownHosts", ")", "{", "$", "frame", "->", "knownHosts", "=", "$", "knownHosts",...
shortstr
[ "shortstr" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Connection/ConnectionOpenOkFrame.php#L20-L31
kakserpom/phpdaemon
PHPDaemon/PubSub/PubSubEvent.php
PubSubEvent.sub
public function sub($obj, $cb) { $act = $this->count() === 0; $this->attach($obj, $cb); if ($act) { if (($func = $this->actCb) !== null) { $func($this); } } return $this; }
php
public function sub($obj, $cb) { $act = $this->count() === 0; $this->attach($obj, $cb); if ($act) { if (($func = $this->actCb) !== null) { $func($this); } } return $this; }
[ "public", "function", "sub", "(", "$", "obj", ",", "$", "cb", ")", "{", "$", "act", "=", "$", "this", "->", "count", "(", ")", "===", "0", ";", "$", "this", "->", "attach", "(", "$", "obj", ",", "$", "cb", ")", ";", "if", "(", "$", "act", ...
Subscribe @param object $obj Subcriber object @param callable $cb Callback @return this
[ "Subscribe" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/PubSub/PubSubEvent.php#L82-L92
kakserpom/phpdaemon
PHPDaemon/PubSub/PubSubEvent.php
PubSubEvent.unsub
public function unsub($obj) { $this->detach($obj); if ($this->count() === 0) { if (($func = $this->deactCb) !== null) { $func($this); } } return $this; }
php
public function unsub($obj) { $this->detach($obj); if ($this->count() === 0) { if (($func = $this->deactCb) !== null) { $func($this); } } return $this; }
[ "public", "function", "unsub", "(", "$", "obj", ")", "{", "$", "this", "->", "detach", "(", "$", "obj", ")", ";", "if", "(", "$", "this", "->", "count", "(", ")", "===", "0", ")", "{", "if", "(", "(", "$", "func", "=", "$", "this", "->", "d...
Unsubscripe @param object $obj Subscriber object @return this
[ "Unsubscripe" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/PubSub/PubSubEvent.php#L99-L108
kakserpom/phpdaemon
PHPDaemon/PubSub/PubSubEvent.php
PubSubEvent.pub
public function pub($data) { foreach ($this as $obj) { $func = $this->getInfo(); $func($data); } return $this; }
php
public function pub($data) { foreach ($this as $obj) { $func = $this->getInfo(); $func($data); } return $this; }
[ "public", "function", "pub", "(", "$", "data", ")", "{", "foreach", "(", "$", "this", "as", "$", "obj", ")", "{", "$", "func", "=", "$", "this", "->", "getInfo", "(", ")", ";", "$", "func", "(", "$", "data", ")", ";", "}", "return", "$", "thi...
Publish @param mixed $data Data @return this
[ "Publish" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/PubSub/PubSubEvent.php#L115-L122
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Queue/QueueDeleteOkFrame.php
QueueDeleteOkFrame.create
public static function create( $messageCount = null ) { $frame = new self(); if (null !== $messageCount) { $frame->messageCount = $messageCount; } return $frame; }
php
public static function create( $messageCount = null ) { $frame = new self(); if (null !== $messageCount) { $frame->messageCount = $messageCount; } return $frame; }
[ "public", "static", "function", "create", "(", "$", "messageCount", "=", "null", ")", "{", "$", "frame", "=", "new", "self", "(", ")", ";", "if", "(", "null", "!==", "$", "messageCount", ")", "{", "$", "frame", "->", "messageCount", "=", "$", "messag...
long
[ "long" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Queue/QueueDeleteOkFrame.php#L20-L31
kakserpom/phpdaemon
PHPDaemon/SockJS/Methods/JsonpSend.php
JsonpSend.run
public function run() { if ($this->stage++ > 0) { $this->header('500 Too Busy'); return; } $this->noncache(); if (isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] === 'application/x-www-form-urlencoded') { if (!isset($_POST['d']) || !is_string($_POST['d']) || !mb_orig_strlen($_POST['d'])) { $this->header('500 Internal Server Error'); echo 'Payload expected.'; return; } if (!json_decode($_POST['d'], true)) { $this->header('500 Internal Server Error'); echo 'Broken JSON encoding.'; return; } $payload = $_POST['d']; } else { if ($this->attrs->raw === '') { $this->header('500 Internal Server Error'); echo 'Payload expected.'; return; } if (!json_decode($this->attrs->raw, true)) { $this->header('500 Internal Server Error'); echo 'Broken JSON encoding.'; return; } $payload = $this->attrs->raw; } $this->appInstance->publish('c2s:' . $this->sessId, $payload, function ($redis) { if ($redis->result === 0) { $this->header('404 Not Found'); } else { echo 'ok'; } $this->finish(); }); $this->sleep(30); }
php
public function run() { if ($this->stage++ > 0) { $this->header('500 Too Busy'); return; } $this->noncache(); if (isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] === 'application/x-www-form-urlencoded') { if (!isset($_POST['d']) || !is_string($_POST['d']) || !mb_orig_strlen($_POST['d'])) { $this->header('500 Internal Server Error'); echo 'Payload expected.'; return; } if (!json_decode($_POST['d'], true)) { $this->header('500 Internal Server Error'); echo 'Broken JSON encoding.'; return; } $payload = $_POST['d']; } else { if ($this->attrs->raw === '') { $this->header('500 Internal Server Error'); echo 'Payload expected.'; return; } if (!json_decode($this->attrs->raw, true)) { $this->header('500 Internal Server Error'); echo 'Broken JSON encoding.'; return; } $payload = $this->attrs->raw; } $this->appInstance->publish('c2s:' . $this->sessId, $payload, function ($redis) { if ($redis->result === 0) { $this->header('404 Not Found'); } else { echo 'ok'; } $this->finish(); }); $this->sleep(30); }
[ "public", "function", "run", "(", ")", "{", "if", "(", "$", "this", "->", "stage", "++", ">", "0", ")", "{", "$", "this", "->", "header", "(", "'500 Too Busy'", ")", ";", "return", ";", "}", "$", "this", "->", "noncache", "(", ")", ";", "if", "...
Called when request iterated @return void
[ "Called", "when", "request", "iterated" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/SockJS/Methods/JsonpSend.php#L18-L59
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.addListener
public function addListener($cb) { if ($this->state === self::STATE_DONE) { $cb($this); return; } $this->listeners[] = CallbackWrapper::wrap($cb); }
php
public function addListener($cb) { if ($this->state === self::STATE_DONE) { $cb($this); return; } $this->listeners[] = CallbackWrapper::wrap($cb); }
[ "public", "function", "addListener", "(", "$", "cb", ")", "{", "if", "(", "$", "this", "->", "state", "===", "self", "::", "STATE_DONE", ")", "{", "$", "cb", "(", "$", "this", ")", ";", "return", ";", "}", "$", "this", "->", "listeners", "[", "]"...
Adds listener @param callable $cb Callback @return void
[ "Adds", "listener" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L82-L89
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.offsetGet
public function offsetGet($j) { return isset($this->results[$j]) ? $this->results[$j] : null; }
php
public function offsetGet($j) { return isset($this->results[$j]) ? $this->results[$j] : null; }
[ "public", "function", "offsetGet", "(", "$", "j", ")", "{", "return", "isset", "(", "$", "this", "->", "results", "[", "$", "j", "]", ")", "?", "$", "this", "->", "results", "[", "$", "j", "]", ":", "null", ";", "}" ]
Handler of $job[$name] @param string $j Job name @return mixed
[ "Handler", "of", "$job", "[", "$name", "]" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L106-L109
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.setResult
public function setResult($jobname, $result = null) { if (isset($this->results[$jobname])) { return false; } $this->results[$jobname] = $result; ++$this->resultsNum; $this->checkIfAllReady(); return true; }
php
public function setResult($jobname, $result = null) { if (isset($this->results[$jobname])) { return false; } $this->results[$jobname] = $result; ++$this->resultsNum; $this->checkIfAllReady(); return true; }
[ "public", "function", "setResult", "(", "$", "jobname", ",", "$", "result", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "results", "[", "$", "jobname", "]", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "re...
Set result @param string $jobname Job name @param mixed $result Result @return boolean
[ "Set", "result" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L128-L137
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.checkIfAllReady
protected function checkIfAllReady() { $this->checkQueue(); if ($this->resultsNum >= $this->jobsNum) { $this->jobs = []; $this->state = self::STATE_DONE; foreach ($this->listeners as $cb) { $cb($this); } if (!$this->keep && $this->resultsNum >= $this->jobsNum) { $this->cleanup(); } } }
php
protected function checkIfAllReady() { $this->checkQueue(); if ($this->resultsNum >= $this->jobsNum) { $this->jobs = []; $this->state = self::STATE_DONE; foreach ($this->listeners as $cb) { $cb($this); } if (!$this->keep && $this->resultsNum >= $this->jobsNum) { $this->cleanup(); } } }
[ "protected", "function", "checkIfAllReady", "(", ")", "{", "$", "this", "->", "checkQueue", "(", ")", ";", "if", "(", "$", "this", "->", "resultsNum", ">=", "$", "this", "->", "jobsNum", ")", "{", "$", "this", "->", "jobs", "=", "[", "]", ";", "$",...
Checks if all jobs are ready @return void
[ "Checks", "if", "all", "jobs", "are", "ready" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L143-L156
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.checkQueue
public function checkQueue() { if ($this->backlog !== null) { while (!$this->backlog->isEmpty()) { if ($this->maxConcurrency !== -1 && ($this->jobsNum - $this->resultsNum > $this->maxConcurrency)) { return; } list($name, $cb) = $this->backlog->shift(); $this->addJob($name, $cb); } } if ($this->more !== null) { $this->more(); } }
php
public function checkQueue() { if ($this->backlog !== null) { while (!$this->backlog->isEmpty()) { if ($this->maxConcurrency !== -1 && ($this->jobsNum - $this->resultsNum > $this->maxConcurrency)) { return; } list($name, $cb) = $this->backlog->shift(); $this->addJob($name, $cb); } } if ($this->more !== null) { $this->more(); } }
[ "public", "function", "checkQueue", "(", ")", "{", "if", "(", "$", "this", "->", "backlog", "!==", "null", ")", "{", "while", "(", "!", "$", "this", "->", "backlog", "->", "isEmpty", "(", ")", ")", "{", "if", "(", "$", "this", "->", "maxConcurrency...
Called automatically. Checks whether if the queue is full. If not, tries to pull more jobs from backlog and 'more' @return void
[ "Called", "automatically", ".", "Checks", "whether", "if", "the", "queue", "is", "full", ".", "If", "not", "tries", "to", "pull", "more", "jobs", "from", "backlog", "and", "more" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L162-L176
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.addJob
public function addJob($name, $cb) { if (isset($this->jobs[$name])) { return false; } $cb = CallbackWrapper::wrap($cb); if ($this->maxConcurrency !== -1 && ($this->jobsNum - $this->resultsNum > $this->maxConcurrency)) { if ($this->backlog === null) { $this->backlog = new \SplStack; } $this->backlog->push([$name, $cb]); return true; } $this->jobs[$name] = $cb; ++$this->jobsNum; if (($this->state === self::STATE_RUNNING) || ($this->state === self::STATE_DONE)) { $this->state = self::STATE_RUNNING; $cb($name, $this); } return true; }
php
public function addJob($name, $cb) { if (isset($this->jobs[$name])) { return false; } $cb = CallbackWrapper::wrap($cb); if ($this->maxConcurrency !== -1 && ($this->jobsNum - $this->resultsNum > $this->maxConcurrency)) { if ($this->backlog === null) { $this->backlog = new \SplStack; } $this->backlog->push([$name, $cb]); return true; } $this->jobs[$name] = $cb; ++$this->jobsNum; if (($this->state === self::STATE_RUNNING) || ($this->state === self::STATE_DONE)) { $this->state = self::STATE_RUNNING; $cb($name, $this); } return true; }
[ "public", "function", "addJob", "(", "$", "name", ",", "$", "cb", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "jobs", "[", "$", "name", "]", ")", ")", "{", "return", "false", ";", "}", "$", "cb", "=", "CallbackWrapper", "::", "wrap", ...
Adds job @param string $name Job name @param callable $cb Callback @return boolean Success
[ "Adds", "job" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L184-L204
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.more
public function more($cb = null) { if ($cb !== null) { $this->more = $cb; $this->moreFirstFlag = true; return $this; } if ($this->more !== null) { if ($this->more instanceof \Iterator) { iterator: $it = $this->more; while (!$this->isQueueFull() && $it->valid()) { if ($this->moreFirstFlag) { $this->moreFirstFlag = false; } else { $it->next(); if (!$it->valid()) { break; } } $this->addJob($it->key(), $it->current()); } } else { $func = $this->more; if (($r = $func($this)) instanceof \Iterator) { $this->more = $r; goto iterator; } } } return $this; }
php
public function more($cb = null) { if ($cb !== null) { $this->more = $cb; $this->moreFirstFlag = true; return $this; } if ($this->more !== null) { if ($this->more instanceof \Iterator) { iterator: $it = $this->more; while (!$this->isQueueFull() && $it->valid()) { if ($this->moreFirstFlag) { $this->moreFirstFlag = false; } else { $it->next(); if (!$it->valid()) { break; } } $this->addJob($it->key(), $it->current()); } } else { $func = $this->more; if (($r = $func($this)) instanceof \Iterator) { $this->more = $r; goto iterator; } } } return $this; }
[ "public", "function", "more", "(", "$", "cb", "=", "null", ")", "{", "if", "(", "$", "cb", "!==", "null", ")", "{", "$", "this", "->", "more", "=", "$", "cb", ";", "$", "this", "->", "moreFirstFlag", "=", "true", ";", "return", "$", "this", ";"...
Sets a callback which is going to be fired always when we have a room for more jobs @param callable $cb Callback @return this
[ "Sets", "a", "callback", "which", "is", "going", "to", "be", "fired", "always", "when", "we", "have", "a", "room", "for", "more", "jobs" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L211-L242
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.cleanup
public function cleanup() { $this->listeners = []; $this->results = []; $this->jobs = []; $this->more = null; }
php
public function cleanup() { $this->listeners = []; $this->results = []; $this->jobs = []; $this->more = null; }
[ "public", "function", "cleanup", "(", ")", "{", "$", "this", "->", "listeners", "=", "[", "]", ";", "$", "this", "->", "results", "=", "[", "]", ";", "$", "this", "->", "jobs", "=", "[", "]", ";", "$", "this", "->", "more", "=", "null", ";", ...
Clean up @return void
[ "Clean", "up" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L257-L263
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.getResult
public function getResult($jobname) { return isset($this->results[$jobname]) ? $this->results[$jobname] : null; }
php
public function getResult($jobname) { return isset($this->results[$jobname]) ? $this->results[$jobname] : null; }
[ "public", "function", "getResult", "(", "$", "jobname", ")", "{", "return", "isset", "(", "$", "this", "->", "results", "[", "$", "jobname", "]", ")", "?", "$", "this", "->", "results", "[", "$", "jobname", "]", ":", "null", ";", "}" ]
Get result @param string $jobname Job name @return mixed Result or null
[ "Get", "result" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L319-L322
kakserpom/phpdaemon
PHPDaemon/Core/ComplexJob.php
ComplexJob.execute
public function execute() { if ($this->state === self::STATE_WAITING) { $this->state = self::STATE_RUNNING; foreach ($this->jobs as $name => $cb) { $cb($name, $this); $this->jobs[$name] = null; } $this->checkIfAllReady(); } }
php
public function execute() { if ($this->state === self::STATE_WAITING) { $this->state = self::STATE_RUNNING; foreach ($this->jobs as $name => $cb) { $cb($name, $this); $this->jobs[$name] = null; } $this->checkIfAllReady(); } }
[ "public", "function", "execute", "(", ")", "{", "if", "(", "$", "this", "->", "state", "===", "self", "::", "STATE_WAITING", ")", "{", "$", "this", "->", "state", "=", "self", "::", "STATE_RUNNING", ";", "foreach", "(", "$", "this", "->", "jobs", "as...
Runs the job @return void
[ "Runs", "the", "job" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/ComplexJob.php#L343-L353
kakserpom/phpdaemon
PHPDaemon/Clients/DNS/Connection.php
Connection.onRead
public function onRead() { start: if ($this->type === 'udp') { $this->onUdpPacket($this->read($this->getInputLength())); return; } if ($this->state === self::STATE_ROOT) { if (false === ($hdr = $this->readExact(2))) { return; // not enough data } $this->pctSize = Binary::bytes2int($hdr); $this->setWatermark($this->pctSize); $this->state = self::STATE_PACKET; } if ($this->state === self::STATE_PACKET) { if (false === ($pct = $this->readExact($this->pctSize))) { return; // not enough data } $this->state = self::STATE_ROOT; $this->setWatermark(2); $this->onUdpPacket($pct); } goto start; }
php
public function onRead() { start: if ($this->type === 'udp') { $this->onUdpPacket($this->read($this->getInputLength())); return; } if ($this->state === self::STATE_ROOT) { if (false === ($hdr = $this->readExact(2))) { return; // not enough data } $this->pctSize = Binary::bytes2int($hdr); $this->setWatermark($this->pctSize); $this->state = self::STATE_PACKET; } if ($this->state === self::STATE_PACKET) { if (false === ($pct = $this->readExact($this->pctSize))) { return; // not enough data } $this->state = self::STATE_ROOT; $this->setWatermark(2); $this->onUdpPacket($pct); } goto start; }
[ "public", "function", "onRead", "(", ")", "{", "start", ":", "if", "(", "$", "this", "->", "type", "===", "'udp'", ")", "{", "$", "this", "->", "onUdpPacket", "(", "$", "this", "->", "read", "(", "$", "this", "->", "getInputLength", "(", ")", ")", ...
Called when new data received @return void
[ "Called", "when", "new", "data", "received" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/DNS/Connection.php#L67-L91
kakserpom/phpdaemon
PHPDaemon/Clients/DNS/Connection.php
Connection.onUdpPacket
public function onUdpPacket($pct) { if (mb_orig_strlen($pct) < 10) { return; } $orig = $pct; $this->response = []; Binary::getWord($pct); // ID $bitmap = Binary::getBitmap(Binary::getByte($pct)) . Binary::getBitmap(Binary::getByte($pct)); //$qr = (int) $bitmap[0]; $opcode = bindec(substr($bitmap, 1, 4)); //$aa = (int) $bitmap[5]; //$tc = (int) $bitmap[6]; //$rd = (int) $bitmap[7]; //$ra = (int) $bitmap[8]; //$z = bindec(substr($bitmap, 9, 3)); $rcode = bindec(mb_orig_substr($bitmap, 12)); $this->response['status'] = [ 'rcode' => $rcode, 'msg' => $this->getMessageByRcode($rcode) ]; $qdcount = Binary::getWord($pct); $ancount = Binary::getWord($pct); $nscount = Binary::getWord($pct); $arcount = Binary::getWord($pct); for ($i = 0; $i < $qdcount; ++$i) { $name = Binary::parseLabels($pct, $orig); $typeInt = Binary::getWord($pct); $type = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')'; $classInt = Binary::getWord($pct); $class = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')'; if (!isset($this->response[$type])) { $this->response[$type] = []; } $record = [ 'name' => $name, 'type' => $type, 'class' => $class, ]; $this->response['query'][] = $record; } $getResRecord = function (&$pct) use ($orig) { $name = Binary::parseLabels($pct, $orig); $typeInt = Binary::getWord($pct); $type = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')'; $classInt = Binary::getWord($pct); $class = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')'; $ttl = Binary::getDWord($pct); $length = Binary::getWord($pct); $data = mb_orig_substr($pct, 0, $length); $pct = mb_orig_substr($pct, $length); $record = [ 'name' => $name, 'type' => $type, 'class' => $class, 'ttl' => $ttl, ]; if (($type === 'A') || ($type === 'AAAA')) { if ($data === "\x00") { $record['ip'] = false; $record['ttl'] = 5; } else { $record['ip'] = inet_ntop($data); } } elseif ($type === 'NS') { $record['ns'] = Binary::parseLabels($data, $orig); } elseif ($type === 'CNAME') { $record['cname'] = Binary::parseLabels($data, $orig); } elseif ($type === 'SOA') { $record['mname'] = Binary::parseLabels($data, $orig); $record['rname'] = Binary::parseLabels($data, $orig); $record['serial'] = Binary::getDWord($data); $record['refresh'] = Binary::getDWord($data); $record['retry'] = Binary::getDWord($data); $record['expire'] = Binary::getDWord($data); $record['nx'] = Binary::getDWord($data); } elseif ($type === 'MX') { $record['preference'] = Binary::getWord($data); $record['exchange'] = Binary::parseLabels($data, $orig); } elseif ($type === 'TXT') { $record['text'] = ''; $lastLength = -1; while (($length = mb_orig_strlen($data)) > 0 && ($length !== $lastLength)) { $record['text'] .= Binary::parseLabels($data, $orig); $lastLength = $length; } } elseif ($type === 'SRV') { $record['priority'] = Binary::getWord($data); $record['weight'] = Binary::getWord($data); $record['port'] = Binary::getWord($data); $record['target'] = Binary::parseLabels($data, $orig); } return $record; }; for ($i = 0; $i < $ancount; ++$i) { $record = $getResRecord($pct); if (!isset($this->response[$record['type']])) { $this->response[$record['type']] = []; } $this->response[$record['type']][] = $record; } for ($i = 0; $i < $nscount; ++$i) { $record = $getResRecord($pct); if (!isset($this->response[$record['type']])) { $this->response[$record['type']] = []; } $this->response[$record['type']][] = $record; } for ($i = 0; $i < $arcount; ++$i) { $record = $getResRecord($pct); if (!isset($this->response[$record['type']])) { $this->response[$record['type']] = []; } $this->response[$record['type']][] = $record; } $this->onResponse->executeOne($this->response); if (!$this->keepalive) { $this->finish(); return; } else { $this->checkFree(); } }
php
public function onUdpPacket($pct) { if (mb_orig_strlen($pct) < 10) { return; } $orig = $pct; $this->response = []; Binary::getWord($pct); // ID $bitmap = Binary::getBitmap(Binary::getByte($pct)) . Binary::getBitmap(Binary::getByte($pct)); //$qr = (int) $bitmap[0]; $opcode = bindec(substr($bitmap, 1, 4)); //$aa = (int) $bitmap[5]; //$tc = (int) $bitmap[6]; //$rd = (int) $bitmap[7]; //$ra = (int) $bitmap[8]; //$z = bindec(substr($bitmap, 9, 3)); $rcode = bindec(mb_orig_substr($bitmap, 12)); $this->response['status'] = [ 'rcode' => $rcode, 'msg' => $this->getMessageByRcode($rcode) ]; $qdcount = Binary::getWord($pct); $ancount = Binary::getWord($pct); $nscount = Binary::getWord($pct); $arcount = Binary::getWord($pct); for ($i = 0; $i < $qdcount; ++$i) { $name = Binary::parseLabels($pct, $orig); $typeInt = Binary::getWord($pct); $type = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')'; $classInt = Binary::getWord($pct); $class = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')'; if (!isset($this->response[$type])) { $this->response[$type] = []; } $record = [ 'name' => $name, 'type' => $type, 'class' => $class, ]; $this->response['query'][] = $record; } $getResRecord = function (&$pct) use ($orig) { $name = Binary::parseLabels($pct, $orig); $typeInt = Binary::getWord($pct); $type = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')'; $classInt = Binary::getWord($pct); $class = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')'; $ttl = Binary::getDWord($pct); $length = Binary::getWord($pct); $data = mb_orig_substr($pct, 0, $length); $pct = mb_orig_substr($pct, $length); $record = [ 'name' => $name, 'type' => $type, 'class' => $class, 'ttl' => $ttl, ]; if (($type === 'A') || ($type === 'AAAA')) { if ($data === "\x00") { $record['ip'] = false; $record['ttl'] = 5; } else { $record['ip'] = inet_ntop($data); } } elseif ($type === 'NS') { $record['ns'] = Binary::parseLabels($data, $orig); } elseif ($type === 'CNAME') { $record['cname'] = Binary::parseLabels($data, $orig); } elseif ($type === 'SOA') { $record['mname'] = Binary::parseLabels($data, $orig); $record['rname'] = Binary::parseLabels($data, $orig); $record['serial'] = Binary::getDWord($data); $record['refresh'] = Binary::getDWord($data); $record['retry'] = Binary::getDWord($data); $record['expire'] = Binary::getDWord($data); $record['nx'] = Binary::getDWord($data); } elseif ($type === 'MX') { $record['preference'] = Binary::getWord($data); $record['exchange'] = Binary::parseLabels($data, $orig); } elseif ($type === 'TXT') { $record['text'] = ''; $lastLength = -1; while (($length = mb_orig_strlen($data)) > 0 && ($length !== $lastLength)) { $record['text'] .= Binary::parseLabels($data, $orig); $lastLength = $length; } } elseif ($type === 'SRV') { $record['priority'] = Binary::getWord($data); $record['weight'] = Binary::getWord($data); $record['port'] = Binary::getWord($data); $record['target'] = Binary::parseLabels($data, $orig); } return $record; }; for ($i = 0; $i < $ancount; ++$i) { $record = $getResRecord($pct); if (!isset($this->response[$record['type']])) { $this->response[$record['type']] = []; } $this->response[$record['type']][] = $record; } for ($i = 0; $i < $nscount; ++$i) { $record = $getResRecord($pct); if (!isset($this->response[$record['type']])) { $this->response[$record['type']] = []; } $this->response[$record['type']][] = $record; } for ($i = 0; $i < $arcount; ++$i) { $record = $getResRecord($pct); if (!isset($this->response[$record['type']])) { $this->response[$record['type']] = []; } $this->response[$record['type']][] = $record; } $this->onResponse->executeOne($this->response); if (!$this->keepalive) { $this->finish(); return; } else { $this->checkFree(); } }
[ "public", "function", "onUdpPacket", "(", "$", "pct", ")", "{", "if", "(", "mb_orig_strlen", "(", "$", "pct", ")", "<", "10", ")", "{", "return", ";", "}", "$", "orig", "=", "$", "pct", ";", "$", "this", "->", "response", "=", "[", "]", ";", "B...
Called when new UDP packet received. @param string $pct @return void
[ "Called", "when", "new", "UDP", "packet", "received", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/DNS/Connection.php#L98-L223
kakserpom/phpdaemon
PHPDaemon/Clients/DNS/Connection.php
Connection.get
public function get($hostname, $cb) { $this->onResponse->push($cb); $this->setFree(false); $e = explode(':', $hostname, 3); $hostname = $e[0]; $qtype = isset($e[1]) ? $e[1] : 'A'; $qclass = isset($e[2]) ? $e[2] : 'IN'; $QD = []; $qtypeInt = array_search($qtype, Pool::$type, true); $qclassInt = array_search($qclass, Pool::$class, true); if (($qtypeInt === false) || ($qclassInt === false)) { $cb(false); return; } $q = Binary::labels($hostname) . // domain Binary::word($qtypeInt) . Binary::word($qclassInt); $QD[] = $q; $packet = Binary::word(++$this->seq) . // Query ID Binary::bitmap2bytes( '0' . // QR = 0 '0000' . // OPCODE = 0000 (standard query) '0' . // AA = 0 '0' . // TC = 0 '1' . // RD = 1 '0' . // RA = 0, '000' . // reserved '0000', // RCODE 2 ) . Binary::word(sizeof($QD)) . // QDCOUNT Binary::word(0) . // ANCOUNT Binary::word(0) . // NSCOUNT Binary::word(0) . // ARCOUNT implode('', $QD); if ($this->type === 'udp') { $this->write($packet); } else { $this->write(Binary::word(mb_orig_strlen($packet)) . $packet); } }
php
public function get($hostname, $cb) { $this->onResponse->push($cb); $this->setFree(false); $e = explode(':', $hostname, 3); $hostname = $e[0]; $qtype = isset($e[1]) ? $e[1] : 'A'; $qclass = isset($e[2]) ? $e[2] : 'IN'; $QD = []; $qtypeInt = array_search($qtype, Pool::$type, true); $qclassInt = array_search($qclass, Pool::$class, true); if (($qtypeInt === false) || ($qclassInt === false)) { $cb(false); return; } $q = Binary::labels($hostname) . // domain Binary::word($qtypeInt) . Binary::word($qclassInt); $QD[] = $q; $packet = Binary::word(++$this->seq) . // Query ID Binary::bitmap2bytes( '0' . // QR = 0 '0000' . // OPCODE = 0000 (standard query) '0' . // AA = 0 '0' . // TC = 0 '1' . // RD = 1 '0' . // RA = 0, '000' . // reserved '0000', // RCODE 2 ) . Binary::word(sizeof($QD)) . // QDCOUNT Binary::word(0) . // ANCOUNT Binary::word(0) . // NSCOUNT Binary::word(0) . // ARCOUNT implode('', $QD); if ($this->type === 'udp') { $this->write($packet); } else { $this->write(Binary::word(mb_orig_strlen($packet)) . $packet); } }
[ "public", "function", "get", "(", "$", "hostname", ",", "$", "cb", ")", "{", "$", "this", "->", "onResponse", "->", "push", "(", "$", "cb", ")", ";", "$", "this", "->", "setFree", "(", "false", ")", ";", "$", "e", "=", "explode", "(", "':'", ",...
Gets the host information @param string $hostname Hostname @param callable $cb Callback @callback $cb ( ) @return void
[ "Gets", "the", "host", "information" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/DNS/Connection.php#L245-L291
kakserpom/phpdaemon
PHPDaemon/Examples/ExampleSandbox.php
ExampleSandboxRequest.run
public function run() { $stime = microtime(true); $this->header('Content-Type: text/html'); $sandbox = new \Runkit_Sandbox([ 'safe_mode' => true, 'open_basedir' => '/var/www/users/jdoe/', 'allow_url_fopen' => 'false', 'disable_functions' => 'exec,shell_exec,passthru,system', 'disable_classes' => '', 'output_handler' => [$this, 'out'] ]); $sandbox->ini_set('html_errors', true); $sandbox->call_user_func(function () { echo "Hello World!"; }); }
php
public function run() { $stime = microtime(true); $this->header('Content-Type: text/html'); $sandbox = new \Runkit_Sandbox([ 'safe_mode' => true, 'open_basedir' => '/var/www/users/jdoe/', 'allow_url_fopen' => 'false', 'disable_functions' => 'exec,shell_exec,passthru,system', 'disable_classes' => '', 'output_handler' => [$this, 'out'] ]); $sandbox->ini_set('html_errors', true); $sandbox->call_user_func(function () { echo "Hello World!"; }); }
[ "public", "function", "run", "(", ")", "{", "$", "stime", "=", "microtime", "(", "true", ")", ";", "$", "this", "->", "header", "(", "'Content-Type: text/html'", ")", ";", "$", "sandbox", "=", "new", "\\", "Runkit_Sandbox", "(", "[", "'safe_mode'", "=>",...
Called when request iterated. @return integer Status.
[ "Called", "when", "request", "iterated", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleSandbox.php#L64-L82
kakserpom/phpdaemon
PHPDaemon/Cache/Item.php
Item.setValue
public function setValue($value) { $this->value = $value; $this->listeners->executeAll($this->value); }
php
public function setValue($value) { $this->value = $value; $this->listeners->executeAll($this->value); }
[ "public", "function", "setValue", "(", "$", "value", ")", "{", "$", "this", "->", "value", "=", "$", "value", ";", "$", "this", "->", "listeners", "->", "executeAll", "(", "$", "this", "->", "value", ")", ";", "}" ]
Sets the value @param mixed $value
[ "Sets", "the", "value" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Cache/Item.php#L65-L69
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseShortString
private function parseShortString() { $length = \ord($this->buffer); try { return mb_orig_substr($this->buffer, 1, $length); } finally { $this->buffer = mb_orig_substr($this->buffer, $length + 1); } }
php
private function parseShortString() { $length = \ord($this->buffer); try { return mb_orig_substr($this->buffer, 1, $length); } finally { $this->buffer = mb_orig_substr($this->buffer, $length + 1); } }
[ "private", "function", "parseShortString", "(", ")", "{", "$", "length", "=", "\\", "ord", "(", "$", "this", "->", "buffer", ")", ";", "try", "{", "return", "mb_orig_substr", "(", "$", "this", "->", "buffer", ",", "1", ",", "$", "length", ")", ";", ...
Parse an AMQP "short string" from the head of the buffer. The maximum length of a short string is 255 bytes. @todo UTF-8 validation, maybe.
[ "Parse", "an", "AMQP", "short", "string", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L29-L38
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseLongString
private function parseLongString() { list(, $length) = \unpack('N', $this->buffer); try { return mb_orig_substr($this->buffer, 4, $length); } finally { $this->buffer = mb_orig_substr($this->buffer, $length + 4); } }
php
private function parseLongString() { list(, $length) = \unpack('N', $this->buffer); try { return mb_orig_substr($this->buffer, 4, $length); } finally { $this->buffer = mb_orig_substr($this->buffer, $length + 4); } }
[ "private", "function", "parseLongString", "(", ")", "{", "list", "(", ",", "$", "length", ")", "=", "\\", "unpack", "(", "'N'", ",", "$", "this", "->", "buffer", ")", ";", "try", "{", "return", "mb_orig_substr", "(", "$", "this", "->", "buffer", ",",...
Parse an AMQP "long string" from the head of the buffer. @todo UTF-8 validation, maybe. @return string
[ "Parse", "an", "AMQP", "long", "string", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L46-L55
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseSignedInt8
private function parseSignedInt8() { try { $result = \ord($this->buffer); if ($result & 0x80) { return $result - 0x100; } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 1); } }
php
private function parseSignedInt8() { try { $result = \ord($this->buffer); if ($result & 0x80) { return $result - 0x100; } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 1); } }
[ "private", "function", "parseSignedInt8", "(", ")", "{", "try", "{", "$", "result", "=", "\\", "ord", "(", "$", "this", "->", "buffer", ")", ";", "if", "(", "$", "result", "&", "0x80", ")", "{", "return", "$", "result", "-", "0x100", ";", "}", "r...
Parse a 8-bit signed integer from the head of the buffer. @return int
[ "Parse", "a", "8", "-", "bit", "signed", "integer", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L61-L74
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseSignedInt16
private function parseSignedInt16() { try { $result = \unpack('n', $this->buffer)[1]; if ($result & 0x8000) { return $result - 0x10000; } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 2); } }
php
private function parseSignedInt16() { try { $result = \unpack('n', $this->buffer)[1]; if ($result & 0x8000) { return $result - 0x10000; } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 2); } }
[ "private", "function", "parseSignedInt16", "(", ")", "{", "try", "{", "$", "result", "=", "\\", "unpack", "(", "'n'", ",", "$", "this", "->", "buffer", ")", "[", "1", "]", ";", "if", "(", "$", "result", "&", "0x8000", ")", "{", "return", "$", "re...
Parse a 16-bit signed integer from the head of the buffer. @return int
[ "Parse", "a", "16", "-", "bit", "signed", "integer", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L93-L106
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseSignedInt32
private function parseSignedInt32() { try { $result = \unpack('N', $this->buffer)[1]; if ($result & 0x80000000) { return $result - 0x100000000; } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 4); } }
php
private function parseSignedInt32() { try { $result = \unpack('N', $this->buffer)[1]; if ($result & 0x80000000) { return $result - 0x100000000; } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 4); } }
[ "private", "function", "parseSignedInt32", "(", ")", "{", "try", "{", "$", "result", "=", "\\", "unpack", "(", "'N'", ",", "$", "this", "->", "buffer", ")", "[", "1", "]", ";", "if", "(", "$", "result", "&", "0x80000000", ")", "{", "return", "$", ...
Parse a 32-bit signed integer from the head of the buffer. @return int
[ "Parse", "a", "32", "-", "bit", "signed", "integer", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L112-L125
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseUnsignedInt64
private function parseUnsignedInt64() { try { $result = \unpack('J', $this->buffer)[1]; if ($result < 0) { return sprintf('%u', $result); } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 8); } }
php
private function parseUnsignedInt64() { try { $result = \unpack('J', $this->buffer)[1]; if ($result < 0) { return sprintf('%u', $result); } return $result; } finally { $this->buffer = mb_orig_substr($this->buffer, 8); } }
[ "private", "function", "parseUnsignedInt64", "(", ")", "{", "try", "{", "$", "result", "=", "\\", "unpack", "(", "'J'", ",", "$", "this", "->", "buffer", ")", "[", "1", "]", ";", "if", "(", "$", "result", "<", "0", ")", "{", "return", "sprintf", ...
Parse a 64-bit unsigned integer from the head of the buffer. @return integer|string A string is returned when the value is is outside the range of PHP's signed integer type.
[ "Parse", "a", "64", "-", "bit", "unsigned", "integer", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L161-L172
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseFloat
public function parseFloat() { try { if (Endianness::LITTLE()) { return \unpack('f', \strrev(mb_orig_substr($this->buffer, 0, 4)))[1]; } return \unpack('f', $this->buffer)[1]; // @codeCoverageIgnore } finally { $this->buffer = mb_orig_substr($this->buffer, 4); } }
php
public function parseFloat() { try { if (Endianness::LITTLE()) { return \unpack('f', \strrev(mb_orig_substr($this->buffer, 0, 4)))[1]; } return \unpack('f', $this->buffer)[1]; // @codeCoverageIgnore } finally { $this->buffer = mb_orig_substr($this->buffer, 4); } }
[ "public", "function", "parseFloat", "(", ")", "{", "try", "{", "if", "(", "Endianness", "::", "LITTLE", "(", ")", ")", "{", "return", "\\", "unpack", "(", "'f'", ",", "\\", "strrev", "(", "mb_orig_substr", "(", "$", "this", "->", "buffer", ",", "0", ...
Parse a float (4-byte) from the head of the buffer. @return float
[ "Parse", "a", "float", "(", "4", "-", "byte", ")", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L178-L188
kakserpom/phpdaemon
PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php
ScalarParserTrait.parseDouble
public function parseDouble() { try { if (Endianness::LITTLE()) { return \unpack('d', \strrev(mb_orig_substr($this->buffer, 0, 8)))[1]; } return \unpack('d', $this->buffer)[1]; // @codeCoverageIgnore } finally { $this->buffer = mb_orig_substr($this->buffer, 8); } }
php
public function parseDouble() { try { if (Endianness::LITTLE()) { return \unpack('d', \strrev(mb_orig_substr($this->buffer, 0, 8)))[1]; } return \unpack('d', $this->buffer)[1]; // @codeCoverageIgnore } finally { $this->buffer = mb_orig_substr($this->buffer, 8); } }
[ "public", "function", "parseDouble", "(", ")", "{", "try", "{", "if", "(", "Endianness", "::", "LITTLE", "(", ")", ")", "{", "return", "\\", "unpack", "(", "'d'", ",", "\\", "strrev", "(", "mb_orig_substr", "(", "$", "this", "->", "buffer", ",", "0",...
Parse a double (8-byte) from the head of the buffer. @return float
[ "Parse", "a", "double", "(", "8", "-", "byte", ")", "from", "the", "head", "of", "the", "buffer", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Parser/ScalarParserTrait.php#L194-L204
kakserpom/phpdaemon
PHPDaemon/Applications/ServerStatusRequest.php
ServerStatusRequest.run
public function run() { $stime = microtime(true); $this->header('Content-Type: text/html; charset=utf-8'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Server status.</title> </head> <body> <br/>Uptime: <b><?php echo DateTime::diffAsText(Daemon::$startTime, time()); ?></b> <br/><br/><b>State of workers:</b><?php $stat = Daemon::getStateOfWorkers(); ?> <br/>Idle: <?php echo $stat['idle']; ?> <br/>Busy: <?php echo $stat['busy']; ?> <br/>Total alive: <?php echo $stat['alive']; ?> <br/>Shutdown: <?php echo $stat['shutdown']; ?> <br/>Pre-init: <?php echo $stat['preinit']; ?> <br/>Wait-init: <?php echo $stat['waitinit']; ?> <br/>Init: <?php echo $stat['init']; ?> <br/> <br/>Request took: <?php printf('%f', round(microtime(true) - $stime, 6)); ?> </body> </html> <?php }
php
public function run() { $stime = microtime(true); $this->header('Content-Type: text/html; charset=utf-8'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Server status.</title> </head> <body> <br/>Uptime: <b><?php echo DateTime::diffAsText(Daemon::$startTime, time()); ?></b> <br/><br/><b>State of workers:</b><?php $stat = Daemon::getStateOfWorkers(); ?> <br/>Idle: <?php echo $stat['idle']; ?> <br/>Busy: <?php echo $stat['busy']; ?> <br/>Total alive: <?php echo $stat['alive']; ?> <br/>Shutdown: <?php echo $stat['shutdown']; ?> <br/>Pre-init: <?php echo $stat['preinit']; ?> <br/>Wait-init: <?php echo $stat['waitinit']; ?> <br/>Init: <?php echo $stat['init']; ?> <br/> <br/>Request took: <?php printf('%f', round(microtime(true) - $stime, 6)); ?> </body> </html> <?php }
[ "public", "function", "run", "(", ")", "{", "$", "stime", "=", "microtime", "(", "true", ")", ";", "$", "this", "->", "header", "(", "'Content-Type: text/html; charset=utf-8'", ")", ";", "?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n ...
Called when request iterated. @return integer Status.
[ "Called", "when", "request", "iterated", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Applications/ServerStatusRequest.php#L21-L58
kakserpom/phpdaemon
PHPDaemon/SockJS/Methods/Info.php
Info.init
public function init() { parent::init(); Crypt::randomInts32(1, function ($ints) { $this->opts['entropy'] = $ints[0]; echo json_encode($this->opts); $this->finish(); }, 9); $this->sleep(5, true); }
php
public function init() { parent::init(); Crypt::randomInts32(1, function ($ints) { $this->opts['entropy'] = $ints[0]; echo json_encode($this->opts); $this->finish(); }, 9); $this->sleep(5, true); }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "Crypt", "::", "randomInts32", "(", "1", ",", "function", "(", "$", "ints", ")", "{", "$", "this", "->", "opts", "[", "'entropy'", "]", "=", "$", "ints", "[", "0"...
Constructor @return void
[ "Constructor" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/SockJS/Methods/Info.php#L19-L28
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.onConnected
public function onConnected($cb) { if ($this->phase === self::PHASE_AUTH_ERR) { $cb($this, false); } elseif ($this->phase === self::PHASE_HANDSHAKED) { $cb($this, true); } else { if (!$this->onConnected) { $this->onConnected = new StackCallbacks(); } $this->onConnected->push($cb); } }
php
public function onConnected($cb) { if ($this->phase === self::PHASE_AUTH_ERR) { $cb($this, false); } elseif ($this->phase === self::PHASE_HANDSHAKED) { $cb($this, true); } else { if (!$this->onConnected) { $this->onConnected = new StackCallbacks(); } $this->onConnected->push($cb); } }
[ "public", "function", "onConnected", "(", "$", "cb", ")", "{", "if", "(", "$", "this", "->", "phase", "===", "self", "::", "PHASE_AUTH_ERR", ")", "{", "$", "cb", "(", "$", "this", ",", "false", ")", ";", "}", "elseif", "(", "$", "this", "->", "ph...
Executes the given callback when/if the connection is handshaked @param callable $cb Callback @callback $cb ( Connection $conn, boolean $success ) @return void
[ "Executes", "the", "given", "callback", "when", "/", "if", "the", "connection", "is", "handshaked" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L198-L210
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.onReady
public function onReady() { if (mb_orig_strlen($this->path) && !mb_orig_strlen($this->dbname)) { $this->dbname = $this->path; } }
php
public function onReady() { if (mb_orig_strlen($this->path) && !mb_orig_strlen($this->dbname)) { $this->dbname = $this->path; } }
[ "public", "function", "onReady", "(", ")", "{", "if", "(", "mb_orig_strlen", "(", "$", "this", "->", "path", ")", "&&", "!", "mb_orig_strlen", "(", "$", "this", "->", "dbname", ")", ")", "{", "$", "this", "->", "dbname", "=", "$", "this", "->", "pa...
Called when the connection is handshaked (at low-level), and peer is ready to recv. data @return void
[ "Called", "when", "the", "connection", "is", "handshaked", "(", "at", "low", "-", "level", ")", "and", "peer", "is", "ready", "to", "recv", ".", "data" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L216-L221
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.sendPacket
public function sendPacket($packet) { //Daemon::log('Client --> Server: ' . Debug::exportBytes($packet) . "\n\n"); return $this->write(Binary::int2bytes(3, mb_orig_strlen($packet), true) . chr($this->seq++) . $packet); }
php
public function sendPacket($packet) { //Daemon::log('Client --> Server: ' . Debug::exportBytes($packet) . "\n\n"); return $this->write(Binary::int2bytes(3, mb_orig_strlen($packet), true) . chr($this->seq++) . $packet); }
[ "public", "function", "sendPacket", "(", "$", "packet", ")", "{", "//Daemon::log('Client --> Server: ' . Debug::exportBytes($packet) . \"\\n\\n\");", "return", "$", "this", "->", "write", "(", "Binary", "::", "int2bytes", "(", "3", ",", "mb_orig_strlen", "(", "$", "pa...
Sends a packet @param string $packet Data @return boolean Success
[ "Sends", "a", "packet" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L228-L232
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.buildLenEncodedBinary
public function buildLenEncodedBinary($s) { if ($s === null) { return "\251"; } $l = mb_orig_strlen($s); if ($l <= 250) { return chr($l) . $s; } if ($l <= 0xFFFF) { return "\252" . Binary::int2bytes(2, true) . $s; } if ($l <= 0xFFFFFF) { return "\254" . Binary::int2bytes(3, true) . $s; } return Binary::int2bytes(8, $l, true) . $s; }
php
public function buildLenEncodedBinary($s) { if ($s === null) { return "\251"; } $l = mb_orig_strlen($s); if ($l <= 250) { return chr($l) . $s; } if ($l <= 0xFFFF) { return "\252" . Binary::int2bytes(2, true) . $s; } if ($l <= 0xFFFFFF) { return "\254" . Binary::int2bytes(3, true) . $s; } return Binary::int2bytes(8, $l, true) . $s; }
[ "public", "function", "buildLenEncodedBinary", "(", "$", "s", ")", "{", "if", "(", "$", "s", "===", "null", ")", "{", "return", "\"\\251\"", ";", "}", "$", "l", "=", "mb_orig_strlen", "(", "$", "s", ")", ";", "if", "(", "$", "l", "<=", "250", ")"...
Builds length-encoded binary string @param string $s String @return string Resulting binary string
[ "Builds", "length", "-", "encoded", "binary", "string" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L239-L260
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.parseEncodedBinary
public function parseEncodedBinary() { $f = ord($this->read(1)); if ($f <= 250) { return $f; } if ($f === 251) { return null; } if ($f === 255) { return false; } if ($f === 252) { return Binary::bytes2int($this->read(2), true); } if ($f === 253) { return Binary::bytes2int($this->read(3), true); } return Binary::bytes2int($this->read(8), true); }
php
public function parseEncodedBinary() { $f = ord($this->read(1)); if ($f <= 250) { return $f; } if ($f === 251) { return null; } if ($f === 255) { return false; } if ($f === 252) { return Binary::bytes2int($this->read(2), true); } if ($f === 253) { return Binary::bytes2int($this->read(3), true); } return Binary::bytes2int($this->read(8), true); }
[ "public", "function", "parseEncodedBinary", "(", ")", "{", "$", "f", "=", "ord", "(", "$", "this", "->", "read", "(", "1", ")", ")", ";", "if", "(", "$", "f", "<=", "250", ")", "{", "return", "$", "f", ";", "}", "if", "(", "$", "f", "===", ...
Parses length-encoded binary integer @return integer Result
[ "Parses", "length", "-", "encoded", "binary", "integer" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L266-L285
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.parseEncodedString
public function parseEncodedString() { $l = $this->parseEncodedBinary(); if (($l === null) || ($l === false)) { return $l; } return $this->read($l); }
php
public function parseEncodedString() { $l = $this->parseEncodedBinary(); if (($l === null) || ($l === false)) { return $l; } return $this->read($l); }
[ "public", "function", "parseEncodedString", "(", ")", "{", "$", "l", "=", "$", "this", "->", "parseEncodedBinary", "(", ")", ";", "if", "(", "(", "$", "l", "===", "null", ")", "||", "(", "$", "l", "===", "false", ")", ")", "{", "return", "$", "l"...
Parse length-encoded string @return integer Result
[ "Parse", "length", "-", "encoded", "string" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L291-L298
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.getAuthToken
public function getAuthToken($scramble, $password) { return sha1($scramble . sha1($hash1 = sha1($password, true), true), true) ^ $hash1; }
php
public function getAuthToken($scramble, $password) { return sha1($scramble . sha1($hash1 = sha1($password, true), true), true) ^ $hash1; }
[ "public", "function", "getAuthToken", "(", "$", "scramble", ",", "$", "password", ")", "{", "return", "sha1", "(", "$", "scramble", ".", "sha1", "(", "$", "hash1", "=", "sha1", "(", "$", "password", ",", "true", ")", ",", "true", ")", ",", "true", ...
Generates auth. token @param string $scramble Scramble string @param string $password Password @return string Result
[ "Generates", "auth", ".", "token" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L306-L309
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.auth
public function auth() { if ($this->phase !== self::PHASE_GOT_INIT) { return; } $this->phase = self::PHASE_AUTH_SENT; $this->onResponse->push(function ($conn, $result) { if ($conn->onConnected) { $conn->connected = true; $conn->onConnected->executeAll($conn, $result); $conn->onConnected = null; } }); $this->clientFlags = Pool::CLIENT_LONG_PASSWORD | Pool::CLIENT_LONG_FLAG | Pool::CLIENT_LOCAL_FILES | Pool::CLIENT_PROTOCOL_41 | Pool::CLIENT_INTERACTIVE | Pool::CLIENT_TRANSACTIONS | Pool::CLIENT_SECURE_CONNECTION | Pool::CLIENT_MULTI_STATEMENTS | Pool::CLIENT_MULTI_RESULTS; $this->sendPacket( $packet = pack('VVc', $this->clientFlags, $this->pool->maxAllowedPacket, $this->charsetNumber) . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" . $this->user . "\x00" . ($this->password === '' ? "\x00" : $this->buildLenEncodedBinary( $this->getAuthToken($this->scramble, $this->password) )) . ($this->path !== '' ? $this->path . "\x00" : '') ); }
php
public function auth() { if ($this->phase !== self::PHASE_GOT_INIT) { return; } $this->phase = self::PHASE_AUTH_SENT; $this->onResponse->push(function ($conn, $result) { if ($conn->onConnected) { $conn->connected = true; $conn->onConnected->executeAll($conn, $result); $conn->onConnected = null; } }); $this->clientFlags = Pool::CLIENT_LONG_PASSWORD | Pool::CLIENT_LONG_FLAG | Pool::CLIENT_LOCAL_FILES | Pool::CLIENT_PROTOCOL_41 | Pool::CLIENT_INTERACTIVE | Pool::CLIENT_TRANSACTIONS | Pool::CLIENT_SECURE_CONNECTION | Pool::CLIENT_MULTI_STATEMENTS | Pool::CLIENT_MULTI_RESULTS; $this->sendPacket( $packet = pack('VVc', $this->clientFlags, $this->pool->maxAllowedPacket, $this->charsetNumber) . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" . $this->user . "\x00" . ($this->password === '' ? "\x00" : $this->buildLenEncodedBinary( $this->getAuthToken($this->scramble, $this->password) )) . ($this->path !== '' ? $this->path . "\x00" : '') ); }
[ "public", "function", "auth", "(", ")", "{", "if", "(", "$", "this", "->", "phase", "!==", "self", "::", "PHASE_GOT_INIT", ")", "{", "return", ";", "}", "$", "this", "->", "phase", "=", "self", "::", "PHASE_AUTH_SENT", ";", "$", "this", "->", "onResp...
Sends auth. packet @return void
[ "Sends", "auth", ".", "packet" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L315-L348
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.query
public function query($q, $cb = null) { if ($this->finished) { throw new ConnectionFinished; } return $this->command(Pool::COM_QUERY, $q, $cb); }
php
public function query($q, $cb = null) { if ($this->finished) { throw new ConnectionFinished; } return $this->command(Pool::COM_QUERY, $q, $cb); }
[ "public", "function", "query", "(", "$", "q", ",", "$", "cb", "=", "null", ")", "{", "if", "(", "$", "this", "->", "finished", ")", "{", "throw", "new", "ConnectionFinished", ";", "}", "return", "$", "this", "->", "command", "(", "Pool", "::", "COM...
Sends SQL-query @param string $q Query @param callable $cb Optional. Callback called when response received @callback $cb ( Connection $conn, boolean $success ) @return boolean Success
[ "Sends", "SQL", "-", "query" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L357-L363
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.command
public function command($cmd, $q = '', $cb = null) { if ($this->phase !== self::PHASE_HANDSHAKED) { return false; } $this->onResponse->push($cb); $this->seq = 0; $this->sendPacket(chr($cmd) . $q); return true; }
php
public function command($cmd, $q = '', $cb = null) { if ($this->phase !== self::PHASE_HANDSHAKED) { return false; } $this->onResponse->push($cb); $this->seq = 0; $this->sendPacket(chr($cmd) . $q); return true; }
[ "public", "function", "command", "(", "$", "cmd", ",", "$", "q", "=", "''", ",", "$", "cb", "=", "null", ")", "{", "if", "(", "$", "this", "->", "phase", "!==", "self", "::", "PHASE_HANDSHAKED", ")", "{", "return", "false", ";", "}", "$", "this",...
Sends arbitrary command @param string $cmd Command @param string $q Data @param callable $cb Optional @throws ConnectionFinished @callback $cb ( Connection $conn, boolean $success ) @return boolean Success
[ "Sends", "arbitrary", "command" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L417-L428
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.selectDB
public function selectDB($name) { $this->dbname = $name; if ($this->phase !== self::PHASE_GOT_INIT) { return $this->query('USE `' . $name . '`'); } return true; }
php
public function selectDB($name) { $this->dbname = $name; if ($this->phase !== self::PHASE_GOT_INIT) { return $this->query('USE `' . $name . '`'); } return true; }
[ "public", "function", "selectDB", "(", "$", "name", ")", "{", "$", "this", "->", "dbname", "=", "$", "name", ";", "if", "(", "$", "this", "->", "phase", "!==", "self", "::", "PHASE_GOT_INIT", ")", "{", "return", "$", "this", "->", "query", "(", "'U...
Sets default database name @param string $name Database name @return boolean Success
[ "Sets", "default", "database", "name" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L435-L444
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.onRead
public function onRead() { packet: if ($this->state === self::STATE_STANDBY) { if ($this->bev->input->length < 4) { return; } $this->pctSize = Binary::bytes2int($this->read(3), true); $this->setWatermark($this->pctSize, $this->pctSize); $this->state = self::STATE_BODY; $this->seq = ord($this->read(1)) + 1; } /* STATE_BODY */ $l = $this->bev->input->length; if ($l < $this->pctSize) { return; } $this->state = self::STATE_STANDBY; $this->setWatermark(4); if ($this->phase === 0) { $this->phase = self::PHASE_GOT_INIT; $this->protover = ord($this->read(1)); if ($this->protover === 0xFF) { // error $fieldCount = $this->protover; $this->protover = 0; $this->onResponse->push(function ($conn, $result) { if ($conn->onConnected) { $conn->connected = true; $conn->onConnected->executeAll($conn, $result); $conn->onConnected = null; } }); goto field; } if (($p = $this->search("\x00")) === false) { $this->log('nul-terminator of \'serverver\' is not found'); $this->finish(); return; } $this->serverver = $this->read($p); $this->drain(1); // drain nul-byte $this->threadId = Binary::bytes2int($this->read(4), true); $this->scramble = $this->read(8); $this->drain(1); // ???? $this->serverCaps = Binary::bytes2int($this->read(2), true); $this->serverLang = ord($this->read(1)); $this->serverStatus = Binary::bytes2int($this->read(2), true); $this->drain(13); $restScramble = $this->read(12); $this->scramble .= $restScramble; $this->drain(1); $this->auth(); } else { $fieldCount = ord($this->read(1)); field: if ($fieldCount === 0xFF) { // Error packet $u = unpack('v', $this->read(2)); $this->errno = $u[1]; $state = $this->read(6); $this->errmsg = $this->read($this->pctSize - $l + $this->bev->input->length); $this->onError(); $this->errno = 0; $this->errmsg = ''; } elseif ($fieldCount === 0x00) { // OK Packet Empty if ($this->phase === self::PHASE_AUTH_SENT) { $this->phase = self::PHASE_HANDSHAKED; if ($this->dbname !== '') { $this->query('USE `' . $this->dbname . '`'); } } $this->affectedRows = $this->parseEncodedBinary(); $this->insertId = $this->parseEncodedBinary(); $u = unpack('v', $this->read(2)); $this->serverStatus = $u[1]; $u = unpack('v', $this->read(2)); $this->warnCount = $u[1]; $this->message = $this->read($this->pctSize - $l + $this->bev->input->length); $this->onResultDone(); } elseif ($fieldCount === 0xFE) { // EOF Packet if ($this->rsState === self::RS_STATE_ROW) { $this->onResultDone(); } else { ++$this->rsState; } } else { // Data packet $this->prependInput(chr($fieldCount)); if ($this->rsState === self::RS_STATE_HEADER) { // Result Set Header Packet $extra = $this->parseEncodedBinary(); $this->rsState = self::RS_STATE_FIELD; } elseif ($this->rsState === self::RS_STATE_FIELD) { // Field Packet $field = [ 'catalog' => $this->parseEncodedString(), 'db' => $this->parseEncodedString(), 'table' => $this->parseEncodedString(), 'org_table' => $this->parseEncodedString(), 'name' => $this->parseEncodedString(), 'org_name' => $this->parseEncodedString() ]; $this->drain(1); // filler $u = unpack('v', $this->read(2)); $field['charset'] = $u[1]; $u = unpack('V', $this->read(4)); $field['length'] = $u[1]; $field['type'] = ord($this->read(1)); $u = unpack('v', $this->read(2)); $field['flags'] = $u[1]; $field['decimals'] = ord($this->read(1)); $this->resultFields[] = $field; } elseif ($this->rsState === self::RS_STATE_ROW) { // Row Packet $row = []; for ($i = 0, $nf = sizeof($this->resultFields); $i < $nf; ++$i) { $row[$this->resultFields[$i]['name']] = $this->parseEncodedString(); } $this->resultRows[] = $row; } } } if ($this->finished) { return; } $this->drain($this->pctSize - $l + $this->bev->input->length); // drain the rest of packet goto packet; }
php
public function onRead() { packet: if ($this->state === self::STATE_STANDBY) { if ($this->bev->input->length < 4) { return; } $this->pctSize = Binary::bytes2int($this->read(3), true); $this->setWatermark($this->pctSize, $this->pctSize); $this->state = self::STATE_BODY; $this->seq = ord($this->read(1)) + 1; } /* STATE_BODY */ $l = $this->bev->input->length; if ($l < $this->pctSize) { return; } $this->state = self::STATE_STANDBY; $this->setWatermark(4); if ($this->phase === 0) { $this->phase = self::PHASE_GOT_INIT; $this->protover = ord($this->read(1)); if ($this->protover === 0xFF) { // error $fieldCount = $this->protover; $this->protover = 0; $this->onResponse->push(function ($conn, $result) { if ($conn->onConnected) { $conn->connected = true; $conn->onConnected->executeAll($conn, $result); $conn->onConnected = null; } }); goto field; } if (($p = $this->search("\x00")) === false) { $this->log('nul-terminator of \'serverver\' is not found'); $this->finish(); return; } $this->serverver = $this->read($p); $this->drain(1); // drain nul-byte $this->threadId = Binary::bytes2int($this->read(4), true); $this->scramble = $this->read(8); $this->drain(1); // ???? $this->serverCaps = Binary::bytes2int($this->read(2), true); $this->serverLang = ord($this->read(1)); $this->serverStatus = Binary::bytes2int($this->read(2), true); $this->drain(13); $restScramble = $this->read(12); $this->scramble .= $restScramble; $this->drain(1); $this->auth(); } else { $fieldCount = ord($this->read(1)); field: if ($fieldCount === 0xFF) { // Error packet $u = unpack('v', $this->read(2)); $this->errno = $u[1]; $state = $this->read(6); $this->errmsg = $this->read($this->pctSize - $l + $this->bev->input->length); $this->onError(); $this->errno = 0; $this->errmsg = ''; } elseif ($fieldCount === 0x00) { // OK Packet Empty if ($this->phase === self::PHASE_AUTH_SENT) { $this->phase = self::PHASE_HANDSHAKED; if ($this->dbname !== '') { $this->query('USE `' . $this->dbname . '`'); } } $this->affectedRows = $this->parseEncodedBinary(); $this->insertId = $this->parseEncodedBinary(); $u = unpack('v', $this->read(2)); $this->serverStatus = $u[1]; $u = unpack('v', $this->read(2)); $this->warnCount = $u[1]; $this->message = $this->read($this->pctSize - $l + $this->bev->input->length); $this->onResultDone(); } elseif ($fieldCount === 0xFE) { // EOF Packet if ($this->rsState === self::RS_STATE_ROW) { $this->onResultDone(); } else { ++$this->rsState; } } else { // Data packet $this->prependInput(chr($fieldCount)); if ($this->rsState === self::RS_STATE_HEADER) { // Result Set Header Packet $extra = $this->parseEncodedBinary(); $this->rsState = self::RS_STATE_FIELD; } elseif ($this->rsState === self::RS_STATE_FIELD) { // Field Packet $field = [ 'catalog' => $this->parseEncodedString(), 'db' => $this->parseEncodedString(), 'table' => $this->parseEncodedString(), 'org_table' => $this->parseEncodedString(), 'name' => $this->parseEncodedString(), 'org_name' => $this->parseEncodedString() ]; $this->drain(1); // filler $u = unpack('v', $this->read(2)); $field['charset'] = $u[1]; $u = unpack('V', $this->read(4)); $field['length'] = $u[1]; $field['type'] = ord($this->read(1)); $u = unpack('v', $this->read(2)); $field['flags'] = $u[1]; $field['decimals'] = ord($this->read(1)); $this->resultFields[] = $field; } elseif ($this->rsState === self::RS_STATE_ROW) { // Row Packet $row = []; for ($i = 0, $nf = sizeof($this->resultFields); $i < $nf; ++$i) { $row[$this->resultFields[$i]['name']] = $this->parseEncodedString(); } $this->resultRows[] = $row; } } } if ($this->finished) { return; } $this->drain($this->pctSize - $l + $this->bev->input->length); // drain the rest of packet goto packet; }
[ "public", "function", "onRead", "(", ")", "{", "packet", ":", "if", "(", "$", "this", "->", "state", "===", "self", "::", "STATE_STANDBY", ")", "{", "if", "(", "$", "this", "->", "bev", "->", "input", "->", "length", "<", "4", ")", "{", "return", ...
Called when new data received @return void
[ "Called", "when", "new", "data", "received" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L450-L597
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.onResultDone
public function onResultDone() { $this->rsState = self::RS_STATE_HEADER; $this->onResponse->executeOne($this, true); $this->checkFree(); $this->resultRows = []; $this->resultFields = []; }
php
public function onResultDone() { $this->rsState = self::RS_STATE_HEADER; $this->onResponse->executeOne($this, true); $this->checkFree(); $this->resultRows = []; $this->resultFields = []; }
[ "public", "function", "onResultDone", "(", ")", "{", "$", "this", "->", "rsState", "=", "self", "::", "RS_STATE_HEADER", ";", "$", "this", "->", "onResponse", "->", "executeOne", "(", "$", "this", ",", "true", ")", ";", "$", "this", "->", "checkFree", ...
Called when the whole result received @return void
[ "Called", "when", "the", "whole", "result", "received" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L613-L620
kakserpom/phpdaemon
PHPDaemon/Clients/MySQL/Connection.php
Connection.onError
public function onError() { $this->rsState = self::RS_STATE_HEADER; $this->onResponse->executeOne($this, false); $this->checkFree(); $this->resultRows = []; $this->resultFields = []; if (($this->phase === self::PHASE_AUTH_SENT) || ($this->phase === self::PHASE_GOT_INIT)) { // in case of auth error $this->phase = self::PHASE_AUTH_ERR; $this->finish(); } Daemon::log(__METHOD__ . ' #' . $this->errno . ': ' . $this->errmsg); }
php
public function onError() { $this->rsState = self::RS_STATE_HEADER; $this->onResponse->executeOne($this, false); $this->checkFree(); $this->resultRows = []; $this->resultFields = []; if (($this->phase === self::PHASE_AUTH_SENT) || ($this->phase === self::PHASE_GOT_INIT)) { // in case of auth error $this->phase = self::PHASE_AUTH_ERR; $this->finish(); } Daemon::log(__METHOD__ . ' #' . $this->errno . ': ' . $this->errmsg); }
[ "public", "function", "onError", "(", ")", "{", "$", "this", "->", "rsState", "=", "self", "::", "RS_STATE_HEADER", ";", "$", "this", "->", "onResponse", "->", "executeOne", "(", "$", "this", ",", "false", ")", ";", "$", "this", "->", "checkFree", "(",...
Called when error occured @return void
[ "Called", "when", "error", "occured" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/MySQL/Connection.php#L626-L641
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.run
protected function run() { $this->lambdaCache = new CappedStorageHits; $this->lambdaCache->setMaxCacheSize(Daemon::$config->lambdacachemaxsize->value); $this->lambdaCache->setCapWindow(Daemon::$config->lambdacachecapwindow->value); if (Daemon::$process instanceof Master) { Daemon::$process->unregisterSignals(); } EventLoop::init(); Daemon::$process = $this; if (Daemon::$logpointerAsync) { Daemon::$logpointerAsync->fd = null; Daemon::$logpointerAsync = null; } class_exists('Timer'); $this->autoReloadLast = time(); $this->reloadDelay = Daemon::$config->mpmdelay->value + 2; $this->setState(Daemon::WSTATE_PREINIT); if (Daemon::$config->autogc->value > 0) { gc_enable(); gc_collect_cycles(); } else { gc_disable(); } if (Daemon::$runworkerMode) { if (!Daemon::$config->verbosetty->value) { fclose(STDIN); fclose(STDOUT); fclose(STDERR); } Daemon::$appResolver->preload(true); } $this->prepareSystemEnv(); $this->overrideNativeFuncs(); $this->setState(Daemon::WSTATE_INIT); $this->registerEventSignals(); FileSystem::init(); FileSystem::initEvent(); Daemon::openLogs(); $this->IPCManager = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager'); if (!$this->IPCManager) { $this->log('cannot instantiate IPCManager'); } Daemon::$appResolver->preload(); foreach (Daemon::$appInstances as $app) { foreach ($app as $appInstance) { if (!$appInstance->ready) { $appInstance->ready = true; $appInstance->onReady(); } } } $this->setState(Daemon::WSTATE_IDLE); Timer::add(function ($event) { if (!Daemon::$runworkerMode) { if ($this->IPCManager) { $this->IPCManager->ensureConnection(); } } $this->breakMainLoopCheck(); if (Daemon::checkAutoGC()) { EventLoop::$instance->interrupt(function () { gc_collect_cycles(); }); } $event->timeout(); }, 1e6 * 1, 'breakMainLoopCheck'); if (Daemon::$config->autoreload->value > 0) { Timer::add(function ($event) { static $n = 0; $list = get_included_files(); $s = sizeof($list); if ($s > $n) { $slice = array_map('realpath', array_slice($list, $n)); Daemon::$process->IPCManager->sendPacket(['op' => 'addIncludedFiles', 'files' => $slice]); $n = $s; } $event->timeout(); }, 1e6 * Daemon::$config->autoreload->value, 'watchIncludedFiles'); } EventLoop::$instance->run(); $this->shutdown(); }
php
protected function run() { $this->lambdaCache = new CappedStorageHits; $this->lambdaCache->setMaxCacheSize(Daemon::$config->lambdacachemaxsize->value); $this->lambdaCache->setCapWindow(Daemon::$config->lambdacachecapwindow->value); if (Daemon::$process instanceof Master) { Daemon::$process->unregisterSignals(); } EventLoop::init(); Daemon::$process = $this; if (Daemon::$logpointerAsync) { Daemon::$logpointerAsync->fd = null; Daemon::$logpointerAsync = null; } class_exists('Timer'); $this->autoReloadLast = time(); $this->reloadDelay = Daemon::$config->mpmdelay->value + 2; $this->setState(Daemon::WSTATE_PREINIT); if (Daemon::$config->autogc->value > 0) { gc_enable(); gc_collect_cycles(); } else { gc_disable(); } if (Daemon::$runworkerMode) { if (!Daemon::$config->verbosetty->value) { fclose(STDIN); fclose(STDOUT); fclose(STDERR); } Daemon::$appResolver->preload(true); } $this->prepareSystemEnv(); $this->overrideNativeFuncs(); $this->setState(Daemon::WSTATE_INIT); $this->registerEventSignals(); FileSystem::init(); FileSystem::initEvent(); Daemon::openLogs(); $this->IPCManager = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager'); if (!$this->IPCManager) { $this->log('cannot instantiate IPCManager'); } Daemon::$appResolver->preload(); foreach (Daemon::$appInstances as $app) { foreach ($app as $appInstance) { if (!$appInstance->ready) { $appInstance->ready = true; $appInstance->onReady(); } } } $this->setState(Daemon::WSTATE_IDLE); Timer::add(function ($event) { if (!Daemon::$runworkerMode) { if ($this->IPCManager) { $this->IPCManager->ensureConnection(); } } $this->breakMainLoopCheck(); if (Daemon::checkAutoGC()) { EventLoop::$instance->interrupt(function () { gc_collect_cycles(); }); } $event->timeout(); }, 1e6 * 1, 'breakMainLoopCheck'); if (Daemon::$config->autoreload->value > 0) { Timer::add(function ($event) { static $n = 0; $list = get_included_files(); $s = sizeof($list); if ($s > $n) { $slice = array_map('realpath', array_slice($list, $n)); Daemon::$process->IPCManager->sendPacket(['op' => 'addIncludedFiles', 'files' => $slice]); $n = $s; } $event->timeout(); }, 1e6 * Daemon::$config->autoreload->value, 'watchIncludedFiles'); } EventLoop::$instance->run(); $this->shutdown(); }
[ "protected", "function", "run", "(", ")", "{", "$", "this", "->", "lambdaCache", "=", "new", "CappedStorageHits", ";", "$", "this", "->", "lambdaCache", "->", "setMaxCacheSize", "(", "Daemon", "::", "$", "config", "->", "lambdacachemaxsize", "->", "value", "...
Runtime of Worker process. @return void
[ "Runtime", "of", "Worker", "process", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L118-L217
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.overrideNativeFuncs
protected function overrideNativeFuncs() { if (Daemon::supported(Daemon::SUPPORT_RUNKIT_INTERNAL_MODIFY)) { function define($k, $v) { if (defined($k)) { runkit_constant_redefine($k, $v); } else { runkit_constant_add($k, $v); } } $this->override('define', 'define'); function header(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->header(...$args); } $this->override('header', 'header'); function isUploadedFile(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->isUploadedFile(...$args); } $this->override('isUploadedFile', 'is_uploaded_file'); function moveUploadedFile(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->moveUploadedFile(...$args); } $this->override('moveUploadedFile', 'move_uploaded_file'); function headersSent(&$file = null, &$line = null) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->headers_sent($file, $line); } //$this->override('headersSent', 'headers_sent); // Commented out due to a runkit bug function headersList() { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->headers_list(); } $this->override('headersList', 'headers_list'); function setcookie(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->setcookie(...$args); } $this->override('setcookie', 'setcookie'); /** * @param callable $cb */ function registerShutdownFunction($cb) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->registerShutdownFunction($cb); } $this->override('registerShutdownFunction', 'register_shutdown_function'); runkit_function_copy('create_function', 'create_function_native'); runkit_function_redefine('create_function', '$arg,$body', 'return \PHPDaemon\Core\Daemon::$process->createFunction($arg,$body);'); } }
php
protected function overrideNativeFuncs() { if (Daemon::supported(Daemon::SUPPORT_RUNKIT_INTERNAL_MODIFY)) { function define($k, $v) { if (defined($k)) { runkit_constant_redefine($k, $v); } else { runkit_constant_add($k, $v); } } $this->override('define', 'define'); function header(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->header(...$args); } $this->override('header', 'header'); function isUploadedFile(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->isUploadedFile(...$args); } $this->override('isUploadedFile', 'is_uploaded_file'); function moveUploadedFile(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->moveUploadedFile(...$args); } $this->override('moveUploadedFile', 'move_uploaded_file'); function headersSent(&$file = null, &$line = null) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->headers_sent($file, $line); } //$this->override('headersSent', 'headers_sent); // Commented out due to a runkit bug function headersList() { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->headers_list(); } $this->override('headersList', 'headers_list'); function setcookie(...$args) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->setcookie(...$args); } $this->override('setcookie', 'setcookie'); /** * @param callable $cb */ function registerShutdownFunction($cb) { if (!Daemon::$context instanceof \PHPDaemon\Request\Generic) { return false; } return Daemon::$context->registerShutdownFunction($cb); } $this->override('registerShutdownFunction', 'register_shutdown_function'); runkit_function_copy('create_function', 'create_function_native'); runkit_function_redefine('create_function', '$arg,$body', 'return \PHPDaemon\Core\Daemon::$process->createFunction($arg,$body);'); } }
[ "protected", "function", "overrideNativeFuncs", "(", ")", "{", "if", "(", "Daemon", "::", "supported", "(", "Daemon", "::", "SUPPORT_RUNKIT_INTERNAL_MODIFY", ")", ")", "{", "function", "define", "(", "$", "k", ",", "$", "v", ")", "{", "if", "(", "defined",...
Overrides native PHP functions. @return void
[ "Overrides", "native", "PHP", "functions", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L234-L325
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.createFunction
public function createFunction($args, $body, $ttl = null) { $key = $args . "\x00" . $body; if (($f = $this->lambdaCache->getValue($key)) !== null) { return $f; } $f = eval('return function(' . $args . '){' . $body . '};'); if ($ttl === null && Daemon::$config->lambdacachettl->value) { $ttl = Daemon::$config->lambdacachettl->value; } $this->lambdaCache->put($key, $f, $ttl); return $f; }
php
public function createFunction($args, $body, $ttl = null) { $key = $args . "\x00" . $body; if (($f = $this->lambdaCache->getValue($key)) !== null) { return $f; } $f = eval('return function(' . $args . '){' . $body . '};'); if ($ttl === null && Daemon::$config->lambdacachettl->value) { $ttl = Daemon::$config->lambdacachettl->value; } $this->lambdaCache->put($key, $f, $ttl); return $f; }
[ "public", "function", "createFunction", "(", "$", "args", ",", "$", "body", ",", "$", "ttl", "=", "null", ")", "{", "$", "key", "=", "$", "args", ".", "\"\\x00\"", ".", "$", "body", ";", "if", "(", "(", "$", "f", "=", "$", "this", "->", "lambda...
Creates anonymous function (old-fashioned) like create_function() @return void
[ "Creates", "anonymous", "function", "(", "old", "-", "fashioned", ")", "like", "create_function", "()" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L331-L343
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.prepareSystemEnv
protected function prepareSystemEnv() { proc_nice(Daemon::$config->workerpriority->value); register_shutdown_function(function () { $this->shutdown(true); }); $this->setTitle( Daemon::$runName . ': worker process' . (Daemon::$config->pidfile->value !== Daemon::$config->defaultpidfile->value ? ' (' . Daemon::$config->pidfile->value . ')' : '') ); if (isset(Daemon::$config->group->value)) { $sg = posix_getgrnam(Daemon::$config->group->value); } if (isset(Daemon::$config->user->value)) { $su = posix_getpwnam(Daemon::$config->user->value); } $flushCache = false; if (Daemon::$config->chroot->value !== '/') { if (posix_getuid() != 0) { Daemon::log('You must have the root privileges to change root.'); exit(0); } elseif (!chroot(Daemon::$config->chroot->value)) { Daemon::log('Couldn\'t change root to \'' . Daemon::$config->chroot->value . '\'.'); exit(0); } $flushCache = true; } if (isset(Daemon::$config->group->value)) { if ($sg === false) { Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . '\'. You must replace config-variable \'group\' with existing group.'); exit(0); } elseif (($sg['gid'] != posix_getgid()) && (!posix_setgid($sg['gid']))) { Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } $flushCache = true; } if (isset(Daemon::$config->user->value)) { if ($su === false) { Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . '\', user not found. You must replace config-variable \'user\' with existing username.'); exit(0); } elseif ($su['uid'] != posix_getuid() & !posix_setuid($su['uid'])) { Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } $flushCache = true; } if ($flushCache) { clearstatcache(true); } if (Daemon::$config->cwd->value !== '.') { if (!@chdir(Daemon::$config->cwd->value)) { Daemon::log('Couldn\'t change directory to \'' . Daemon::$config->cwd->value . '.'); } clearstatcache(true); } }
php
protected function prepareSystemEnv() { proc_nice(Daemon::$config->workerpriority->value); register_shutdown_function(function () { $this->shutdown(true); }); $this->setTitle( Daemon::$runName . ': worker process' . (Daemon::$config->pidfile->value !== Daemon::$config->defaultpidfile->value ? ' (' . Daemon::$config->pidfile->value . ')' : '') ); if (isset(Daemon::$config->group->value)) { $sg = posix_getgrnam(Daemon::$config->group->value); } if (isset(Daemon::$config->user->value)) { $su = posix_getpwnam(Daemon::$config->user->value); } $flushCache = false; if (Daemon::$config->chroot->value !== '/') { if (posix_getuid() != 0) { Daemon::log('You must have the root privileges to change root.'); exit(0); } elseif (!chroot(Daemon::$config->chroot->value)) { Daemon::log('Couldn\'t change root to \'' . Daemon::$config->chroot->value . '\'.'); exit(0); } $flushCache = true; } if (isset(Daemon::$config->group->value)) { if ($sg === false) { Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . '\'. You must replace config-variable \'group\' with existing group.'); exit(0); } elseif (($sg['gid'] != posix_getgid()) && (!posix_setgid($sg['gid']))) { Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } $flushCache = true; } if (isset(Daemon::$config->user->value)) { if ($su === false) { Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . '\', user not found. You must replace config-variable \'user\' with existing username.'); exit(0); } elseif ($su['uid'] != posix_getuid() & !posix_setuid($su['uid'])) { Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } $flushCache = true; } if ($flushCache) { clearstatcache(true); } if (Daemon::$config->cwd->value !== '.') { if (!@chdir(Daemon::$config->cwd->value)) { Daemon::log('Couldn\'t change directory to \'' . Daemon::$config->cwd->value . '.'); } clearstatcache(true); } }
[ "protected", "function", "prepareSystemEnv", "(", ")", "{", "proc_nice", "(", "Daemon", "::", "$", "config", "->", "workerpriority", "->", "value", ")", ";", "register_shutdown_function", "(", "function", "(", ")", "{", "$", "this", "->", "shutdown", "(", "t...
Setup settings on start. @return void
[ "Setup", "settings", "on", "start", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L349-L414
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.breakMainLoopCheck
protected function breakMainLoopCheck() { $time = microtime(true); if ($this->terminated || $this->breakMainLoop) { EventLoop::$instance->stop(); return; } if ($this->shutdown) { EventLoop::$instance->stop(); return; } if ($this->reload) { return; } if (Daemon::$config->maxmemoryusage->value > 0 && (memory_get_usage(true) > Daemon::$config->maxmemoryusage->value) ) { $this->log('\'maxmemory\' exceed. Graceful shutdown.'); $this->gracefulRestart(); } if (Daemon::$config->maxrequests->value > 0 && ($this->reqCounter >= Daemon::$config->maxrequests->value) ) { $this->log('\'max-requests\' exceed. Graceful shutdown.'); $this->gracefulRestart(); } if (Daemon::$config->maxidle->value && $this->timeLastActivity && ($time - $this->timeLastActivity > Daemon::$config->maxidle->value) ) { $this->log('\'maxworkeridle\' exceed. Graceful shutdown.'); $this->gracefulRestart(); } if ($this->update === true) { $this->update = false; $this->update(); } }
php
protected function breakMainLoopCheck() { $time = microtime(true); if ($this->terminated || $this->breakMainLoop) { EventLoop::$instance->stop(); return; } if ($this->shutdown) { EventLoop::$instance->stop(); return; } if ($this->reload) { return; } if (Daemon::$config->maxmemoryusage->value > 0 && (memory_get_usage(true) > Daemon::$config->maxmemoryusage->value) ) { $this->log('\'maxmemory\' exceed. Graceful shutdown.'); $this->gracefulRestart(); } if (Daemon::$config->maxrequests->value > 0 && ($this->reqCounter >= Daemon::$config->maxrequests->value) ) { $this->log('\'max-requests\' exceed. Graceful shutdown.'); $this->gracefulRestart(); } if (Daemon::$config->maxidle->value && $this->timeLastActivity && ($time - $this->timeLastActivity > Daemon::$config->maxidle->value) ) { $this->log('\'maxworkeridle\' exceed. Graceful shutdown.'); $this->gracefulRestart(); } if ($this->update === true) { $this->update = false; $this->update(); } }
[ "protected", "function", "breakMainLoopCheck", "(", ")", "{", "$", "time", "=", "microtime", "(", "true", ")", ";", "if", "(", "$", "this", "->", "terminated", "||", "$", "this", "->", "breakMainLoop", ")", "{", "EventLoop", "::", "$", "instance", "->", ...
Check if we should break main loop @return void
[ "Check", "if", "we", "should", "break", "main", "loop" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L445-L491
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.gracefulRestart
public function gracefulRestart() { $this->graceful = true; $this->reload = true; Timer::add(function () { EventLoop::$instance->stop(); }, $this->reloadDelay * 1e6); $this->setState($this->state); }
php
public function gracefulRestart() { $this->graceful = true; $this->reload = true; Timer::add(function () { EventLoop::$instance->stop(); }, $this->reloadDelay * 1e6); $this->setState($this->state); }
[ "public", "function", "gracefulRestart", "(", ")", "{", "$", "this", "->", "graceful", "=", "true", ";", "$", "this", "->", "reload", "=", "true", ";", "Timer", "::", "add", "(", "function", "(", ")", "{", "EventLoop", "::", "$", "instance", "->", "s...
Graceful restart @return void
[ "Graceful", "restart" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L497-L505
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.gracefulStop
public function gracefulStop() { $this->graceful = true; Timer::add(function () { EventLoop::$instance->stop(); }, $this->reloadDelay * 1e6); $this->setState($this->state); }
php
public function gracefulStop() { $this->graceful = true; Timer::add(function () { EventLoop::$instance->stop(); }, $this->reloadDelay * 1e6); $this->setState($this->state); }
[ "public", "function", "gracefulStop", "(", ")", "{", "$", "this", "->", "graceful", "=", "true", ";", "Timer", "::", "add", "(", "function", "(", ")", "{", "EventLoop", "::", "$", "instance", "->", "stop", "(", ")", ";", "}", ",", "$", "this", "->"...
Graceful stop @return void
[ "Graceful", "stop" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L511-L518
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.appInstancesReloadReady
protected function appInstancesReloadReady() { $ready = true; foreach (Daemon::$appInstances as $k => $app) { foreach ($app as $name => $appInstance) { if (!$appInstance->handleStatus($this->graceful ? AppInstance::EVENT_GRACEFUL_SHUTDOWN : AppInstance::EVENT_SHUTDOWN)) { $this->log(__METHOD__ . ': waiting for ' . $k . ':' . $name); $ready = false; } } } return $ready; }
php
protected function appInstancesReloadReady() { $ready = true; foreach (Daemon::$appInstances as $k => $app) { foreach ($app as $name => $appInstance) { if (!$appInstance->handleStatus($this->graceful ? AppInstance::EVENT_GRACEFUL_SHUTDOWN : AppInstance::EVENT_SHUTDOWN)) { $this->log(__METHOD__ . ': waiting for ' . $k . ':' . $name); $ready = false; } } } return $ready; }
[ "protected", "function", "appInstancesReloadReady", "(", ")", "{", "$", "ready", "=", "true", ";", "foreach", "(", "Daemon", "::", "$", "appInstances", "as", "$", "k", "=>", "$", "app", ")", "{", "foreach", "(", "$", "app", "as", "$", "name", "=>", "...
Asks the running applications the whether we can go to shutdown current (old) worker. @return boolean - Ready?
[ "Asks", "the", "running", "applications", "the", "whether", "we", "can", "go", "to", "shutdown", "current", "(", "old", ")", "worker", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L524-L537
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.shutdown
protected function shutdown($hard = false) { $error = error_get_last(); if ($error) { if ($error['type'] === E_ERROR) { Daemon::log('W#' . $this->pid . ' crashed by error \'' . $error['message'] . '\' at ' . $error['file'] . ':' . $error['line']); } } if (Daemon::$config->throwexceptiononshutdown->value) { throw new \Exception('event shutdown'); } @ob_flush(); if ($this->terminated === true) { if ($hard) { exit(0); } return; } $this->terminated = true; if ($hard) { $this->setState(Daemon::WSTATE_SHUTDOWN); exit(0); } $this->reloadReady = $this->appInstancesReloadReady(); Timer::remove('breakMainLoopCheck'); Timer::add(function ($event) { $self = Daemon::$process; $self->reloadReady = $self->appInstancesReloadReady(); if ($self->reload === true) { $self->reloadReady = $self->reloadReady && (microtime(true) > $self->reloadTime); } if (!$self->reloadReady) { $event->timeout(); } else { EventLoop::$instance->stop(); } }, 1e6, 'checkReloadReady'); while (!$this->reloadReady) { EventLoop::$instance->run(); } FileSystem::waitAllEvents(); // ensure that all I/O events completed before suicide posix_kill(getmypid(), SIGKILL); exit(0); // R.I.P. }
php
protected function shutdown($hard = false) { $error = error_get_last(); if ($error) { if ($error['type'] === E_ERROR) { Daemon::log('W#' . $this->pid . ' crashed by error \'' . $error['message'] . '\' at ' . $error['file'] . ':' . $error['line']); } } if (Daemon::$config->throwexceptiononshutdown->value) { throw new \Exception('event shutdown'); } @ob_flush(); if ($this->terminated === true) { if ($hard) { exit(0); } return; } $this->terminated = true; if ($hard) { $this->setState(Daemon::WSTATE_SHUTDOWN); exit(0); } $this->reloadReady = $this->appInstancesReloadReady(); Timer::remove('breakMainLoopCheck'); Timer::add(function ($event) { $self = Daemon::$process; $self->reloadReady = $self->appInstancesReloadReady(); if ($self->reload === true) { $self->reloadReady = $self->reloadReady && (microtime(true) > $self->reloadTime); } if (!$self->reloadReady) { $event->timeout(); } else { EventLoop::$instance->stop(); } }, 1e6, 'checkReloadReady'); while (!$this->reloadReady) { EventLoop::$instance->run(); } FileSystem::waitAllEvents(); // ensure that all I/O events completed before suicide posix_kill(getmypid(), SIGKILL); exit(0); // R.I.P. }
[ "protected", "function", "shutdown", "(", "$", "hard", "=", "false", ")", "{", "$", "error", "=", "error_get_last", "(", ")", ";", "if", "(", "$", "error", ")", "{", "if", "(", "$", "error", "[", "'type'", "]", "===", "E_ERROR", ")", "{", "Daemon",...
Shutdown this worker @param boolean Hard? If hard, we shouldn't wait for graceful shutdown of the running applications. @return boolean|null Ready?
[ "Shutdown", "this", "worker" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L544-L597
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.setState
public function setState($int) { if (Daemon::$compatMode) { return true; } if (!$this->id) { return false; } if (Daemon::$config->logworkersetstate->value) { $this->log('state is ' . Daemon::$wstateRev[$int]); } $this->state = $int; if ($this->reload) { $int += 100; } Daemon::$shm_wstate->write(chr($int), $this->id - 1); return true; }
php
public function setState($int) { if (Daemon::$compatMode) { return true; } if (!$this->id) { return false; } if (Daemon::$config->logworkersetstate->value) { $this->log('state is ' . Daemon::$wstateRev[$int]); } $this->state = $int; if ($this->reload) { $int += 100; } Daemon::$shm_wstate->write(chr($int), $this->id - 1); return true; }
[ "public", "function", "setState", "(", "$", "int", ")", "{", "if", "(", "Daemon", "::", "$", "compatMode", ")", "{", "return", "true", ";", "}", "if", "(", "!", "$", "this", "->", "id", ")", "{", "return", "false", ";", "}", "if", "(", "Daemon", ...
Set current status of worker @param int Constant @return boolean Success.
[ "Set", "current", "status", "of", "worker" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L604-L624
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.sigterm
protected function sigterm() { if (Daemon::$config->logsignals->value) { $this->log('caught SIGTERM.'); } $this->graceful = false; EventLoop::$instance->stop(); }
php
protected function sigterm() { if (Daemon::$config->logsignals->value) { $this->log('caught SIGTERM.'); } $this->graceful = false; EventLoop::$instance->stop(); }
[ "protected", "function", "sigterm", "(", ")", "{", "if", "(", "Daemon", "::", "$", "config", "->", "logsignals", "->", "value", ")", "{", "$", "this", "->", "log", "(", "'caught SIGTERM.'", ")", ";", "}", "$", "this", "->", "graceful", "=", "false", ...
Handler of the SIGTERM (graceful shutdown) signal in worker process. @return void
[ "Handler", "of", "the", "SIGTERM", "(", "graceful", "shutdown", ")", "signal", "in", "worker", "process", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L643-L651
kakserpom/phpdaemon
PHPDaemon/Thread/Worker.php
Worker.sighup
protected function sighup() { if (Daemon::$config->logsignals->value) { $this->log('caught SIGHUP (reload config).'); } if (isset(Daemon::$config->configfile->value)) { Daemon::loadConfig(Daemon::$config->configfile->value); } $this->update = true; }
php
protected function sighup() { if (Daemon::$config->logsignals->value) { $this->log('caught SIGHUP (reload config).'); } if (isset(Daemon::$config->configfile->value)) { Daemon::loadConfig(Daemon::$config->configfile->value); } $this->update = true; }
[ "protected", "function", "sighup", "(", ")", "{", "if", "(", "Daemon", "::", "$", "config", "->", "logsignals", "->", "value", ")", "{", "$", "this", "->", "log", "(", "'caught SIGHUP (reload config).'", ")", ";", "}", "if", "(", "isset", "(", "Daemon", ...
Handler of the SIGHUP (reload config) signal in worker process. @return void
[ "Handler", "of", "the", "SIGHUP", "(", "reload", "config", ")", "signal", "in", "worker", "process", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Worker.php#L670-L681
kakserpom/phpdaemon
PHPDaemon/Servers/Ident/Connection.php
Connection.onRead
protected function onRead() { while (($line = $this->readline()) !== null) { $e = explode(' , ', $line); if ((sizeof($e) !== 2) || !ctype_digit($e[0]) || !ctype_digit($e[1])) { $this->writeln($line . ' : ERROR : INVALID-PORT'); $this->finish(); return; } $local = (int)$e[0]; $foreign = (int)$e[1]; if ($user = $this->pool->findPair($local, $foreign)) { $this->writeln($line . ' : USERID : ' . $user); } else { $this->writeln($line . ' : ERROR : NO-USER'); } } }
php
protected function onRead() { while (($line = $this->readline()) !== null) { $e = explode(' , ', $line); if ((sizeof($e) !== 2) || !ctype_digit($e[0]) || !ctype_digit($e[1])) { $this->writeln($line . ' : ERROR : INVALID-PORT'); $this->finish(); return; } $local = (int)$e[0]; $foreign = (int)$e[1]; if ($user = $this->pool->findPair($local, $foreign)) { $this->writeln($line . ' : USERID : ' . $user); } else { $this->writeln($line . ' : ERROR : NO-USER'); } } }
[ "protected", "function", "onRead", "(", ")", "{", "while", "(", "(", "$", "line", "=", "$", "this", "->", "readline", "(", ")", ")", "!==", "null", ")", "{", "$", "e", "=", "explode", "(", "' , '", ",", "$", "line", ")", ";", "if", "(", "(", ...
Called when new data received. @return void
[ "Called", "when", "new", "data", "received", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/Ident/Connection.php#L26-L43
kakserpom/phpdaemon
PHPDaemon/Thread/Master.php
Master.run
protected function run() { Daemon::$process = $this; $this->prepareSystemEnv(); class_exists('Timer'); // ensure loading this class gc_enable(); $this->callbacks = new StackCallbacks; /* * @todo This line must be commented according to current libevent binding implementation. * May be uncommented in future. */ //EventLoop::init() if (EventLoop::$instance) { $this->registerEventSignals(); } else { $this->registerSignals(); } $this->workers = new Collection(); $this->collections['workers'] = $this->workers; $this->ipcthreads = new Collection; $this->collections['ipcthreads'] = $this->ipcthreads; Daemon::$appResolver->preload(true); $this->spawnIPCThread(); $this->spawnWorkers( min( Daemon::$config->startworkers->value, Daemon::$config->maxworkers->value ) ); $this->timerCb = function ($event) use (&$cbs) { static $c = 0; ++$c; if ($c > 0xFFFFF) { $c = 1; } if (($c % 10 == 0)) { gc_collect_cycles(); } if (!$this->lastMpmActionTs || ((microtime(true) - $this->lastMpmActionTs) > $this->minMpmActionInterval)) { $this->callMPM(); } if ($event) { $event->timeout(); } }; if (EventLoop::$instance) { // we are using libevent in Master Timer::add($this->timerCb, 1e6 * Daemon::$config->mpmdelay->value, 'MPM'); EventLoop::$instance->run(); } else { // we are NOT using libevent in Master $lastTimerCall = microtime(true); $func = $this->timerCb; while (!$this->breakMainLoop) { $this->callbacks->executeAll($this); if (microtime(true) > $lastTimerCall + Daemon::$config->mpmdelay->value) { $func(null); $lastTimerCall = microtime(true); } $this->sigwait(); } } }
php
protected function run() { Daemon::$process = $this; $this->prepareSystemEnv(); class_exists('Timer'); // ensure loading this class gc_enable(); $this->callbacks = new StackCallbacks; /* * @todo This line must be commented according to current libevent binding implementation. * May be uncommented in future. */ //EventLoop::init() if (EventLoop::$instance) { $this->registerEventSignals(); } else { $this->registerSignals(); } $this->workers = new Collection(); $this->collections['workers'] = $this->workers; $this->ipcthreads = new Collection; $this->collections['ipcthreads'] = $this->ipcthreads; Daemon::$appResolver->preload(true); $this->spawnIPCThread(); $this->spawnWorkers( min( Daemon::$config->startworkers->value, Daemon::$config->maxworkers->value ) ); $this->timerCb = function ($event) use (&$cbs) { static $c = 0; ++$c; if ($c > 0xFFFFF) { $c = 1; } if (($c % 10 == 0)) { gc_collect_cycles(); } if (!$this->lastMpmActionTs || ((microtime(true) - $this->lastMpmActionTs) > $this->minMpmActionInterval)) { $this->callMPM(); } if ($event) { $event->timeout(); } }; if (EventLoop::$instance) { // we are using libevent in Master Timer::add($this->timerCb, 1e6 * Daemon::$config->mpmdelay->value, 'MPM'); EventLoop::$instance->run(); } else { // we are NOT using libevent in Master $lastTimerCall = microtime(true); $func = $this->timerCb; while (!$this->breakMainLoop) { $this->callbacks->executeAll($this); if (microtime(true) > $lastTimerCall + Daemon::$config->mpmdelay->value) { $func(null); $lastTimerCall = microtime(true); } $this->sigwait(); } } }
[ "protected", "function", "run", "(", ")", "{", "Daemon", "::", "$", "process", "=", "$", "this", ";", "$", "this", "->", "prepareSystemEnv", "(", ")", ";", "class_exists", "(", "'Timer'", ")", ";", "// ensure loading this class", "gc_enable", "(", ")", ";"...
Runtime of Master process @return void
[ "Runtime", "of", "Master", "process" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Master.php#L48-L120
kakserpom/phpdaemon
PHPDaemon/Thread/Master.php
Master.prepareSystemEnv
protected function prepareSystemEnv() { register_shutdown_function(function () { if ($this->pid != posix_getpid()) { return; } if ($this->shutdown === true) { return; } $this->log('Unexcepted shutdown.'); $this->shutdown(SIGTERM); }); posix_setsid(); proc_nice(Daemon::$config->masterpriority->value); if (!Daemon::$config->verbosetty->value) { fclose(STDIN); fclose(STDOUT); fclose(STDERR); } $this->setTitle( Daemon::$runName . ': master process' . (Daemon::$config->pidfile->value !== Daemon::$config->pidfile->defaultValue ? ' (' . Daemon::$config->pidfile->value . ')' : '') ); }
php
protected function prepareSystemEnv() { register_shutdown_function(function () { if ($this->pid != posix_getpid()) { return; } if ($this->shutdown === true) { return; } $this->log('Unexcepted shutdown.'); $this->shutdown(SIGTERM); }); posix_setsid(); proc_nice(Daemon::$config->masterpriority->value); if (!Daemon::$config->verbosetty->value) { fclose(STDIN); fclose(STDOUT); fclose(STDERR); } $this->setTitle( Daemon::$runName . ': master process' . (Daemon::$config->pidfile->value !== Daemon::$config->pidfile->defaultValue ? ' (' . Daemon::$config->pidfile->value . ')' : '') ); }
[ "protected", "function", "prepareSystemEnv", "(", ")", "{", "register_shutdown_function", "(", "function", "(", ")", "{", "if", "(", "$", "this", "->", "pid", "!=", "posix_getpid", "(", ")", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "...
Setup settings on start. @return void
[ "Setup", "settings", "on", "start", "." ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Master.php#L185-L210
kakserpom/phpdaemon
PHPDaemon/Thread/Master.php
Master.reloadWorker
public function reloadWorker($id) { if (isset($this->workers->threads[$id])) { if (!$this->workers->threads[$id]->reloaded) { Daemon::$process->log('Spawning worker-replacer for reloaded worker #' . $id); $this->spawnWorkers(1); $this->workers->threads[$id]->reloaded = true; } } }
php
public function reloadWorker($id) { if (isset($this->workers->threads[$id])) { if (!$this->workers->threads[$id]->reloaded) { Daemon::$process->log('Spawning worker-replacer for reloaded worker #' . $id); $this->spawnWorkers(1); $this->workers->threads[$id]->reloaded = true; } } }
[ "public", "function", "reloadWorker", "(", "$", "id", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "workers", "->", "threads", "[", "$", "id", "]", ")", ")", "{", "if", "(", "!", "$", "this", "->", "workers", "->", "threads", "[", "$", ...
Reload worker by internal id @param integer - Id of worker @param integer $id @return void
[ "Reload", "worker", "by", "internal", "id" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Master.php#L218-L227
kakserpom/phpdaemon
PHPDaemon/Thread/Master.php
Master.spawnWorkers
protected function spawnWorkers($n) { if (FileSystem::$supported) { eio_event_loop(); } $n = (int)$n; for ($i = 0; $i < $n; ++$i) { $thread = new Worker; $this->workers->push($thread); $this->callbacks->push(function ($self) use ($thread) { // @check - is it possible to run iterate of main event loop without child termination? $thread->start(); $pid = $thread->getPid(); if ($pid < 0) { Daemon::$process->log('could not fork worker'); } elseif ($pid === 0) { // worker Daemon::log('Unexcepted execution return to outside of Thread->start()'); exit; } }); } if ($n > 0) { $this->lastMpmActionTs = microtime(true); if (EventLoop::$instance) { EventLoop::$instance->interrupt(); } } return true; }
php
protected function spawnWorkers($n) { if (FileSystem::$supported) { eio_event_loop(); } $n = (int)$n; for ($i = 0; $i < $n; ++$i) { $thread = new Worker; $this->workers->push($thread); $this->callbacks->push(function ($self) use ($thread) { // @check - is it possible to run iterate of main event loop without child termination? $thread->start(); $pid = $thread->getPid(); if ($pid < 0) { Daemon::$process->log('could not fork worker'); } elseif ($pid === 0) { // worker Daemon::log('Unexcepted execution return to outside of Thread->start()'); exit; } }); } if ($n > 0) { $this->lastMpmActionTs = microtime(true); if (EventLoop::$instance) { EventLoop::$instance->interrupt(); } } return true; }
[ "protected", "function", "spawnWorkers", "(", "$", "n", ")", "{", "if", "(", "FileSystem", "::", "$", "supported", ")", "{", "eio_event_loop", "(", ")", ";", "}", "$", "n", "=", "(", "int", ")", "$", "n", ";", "for", "(", "$", "i", "=", "0", ";...
Spawn new worker processes @param $n - integer - number of workers to spawn @return boolean - success
[ "Spawn", "new", "worker", "processes" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Master.php#L234-L263
kakserpom/phpdaemon
PHPDaemon/Thread/Master.php
Master.spawnIPCThread
protected function spawnIPCThread() { if (FileSystem::$supported) { eio_event_loop(); } $thread = new IPC; $this->ipcthreads->push($thread); $this->callbacks->push(function ($self) use ($thread) { $thread->start(); $pid = $thread->getPid(); if ($pid < 0) { Daemon::$process->log('could not fork IPCThread'); } elseif ($pid === 0) { // worker $this->log('Unexcepted execution return to outside of Thread->start()'); exit; } }); if (EventLoop::$instance) { EventLoop::$instance->interrupt(); } return true; }
php
protected function spawnIPCThread() { if (FileSystem::$supported) { eio_event_loop(); } $thread = new IPC; $this->ipcthreads->push($thread); $this->callbacks->push(function ($self) use ($thread) { $thread->start(); $pid = $thread->getPid(); if ($pid < 0) { Daemon::$process->log('could not fork IPCThread'); } elseif ($pid === 0) { // worker $this->log('Unexcepted execution return to outside of Thread->start()'); exit; } }); if (EventLoop::$instance) { EventLoop::$instance->interrupt(); } return true; }
[ "protected", "function", "spawnIPCThread", "(", ")", "{", "if", "(", "FileSystem", "::", "$", "supported", ")", "{", "eio_event_loop", "(", ")", ";", "}", "$", "thread", "=", "new", "IPC", ";", "$", "this", "->", "ipcthreads", "->", "push", "(", "$", ...
Spawn IPC process @param $n - integer - number of workers to spawn @return boolean - success
[ "Spawn", "IPC", "process" ]
train
https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/Master.php#L270-L292