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/Clients/Mongo/Pool.php | Pool.insert | public function insert($col, $doc = [], $cb = null, $params = [])
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
if (!isset($doc['_id'])) {
$doc['_id'] = new \MongoId;
}
if ($this->safeMode) {
static::safeModeEnc($doc);
}
try {
$this->request(
self::OP_INSERT,
"\x00\x00\x00\x00" . $col . "\x00" . bson_encode($doc),
false,
null,
function ($conn, $reqId = null) use ($cb, $col, $params) {
if ($cb !== null) {
$this->lastError($col, $cb, $params, $conn);
}
}
);
return $doc['_id'];
} catch (\MongoException $e) {
Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
if ($cb !== null) {
if ($cb !== null) {
$cb(['$err' => $e->getMessage(), '$doc' => $doc]);
}
}
}
} | php | public function insert($col, $doc = [], $cb = null, $params = [])
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
if (!isset($doc['_id'])) {
$doc['_id'] = new \MongoId;
}
if ($this->safeMode) {
static::safeModeEnc($doc);
}
try {
$this->request(
self::OP_INSERT,
"\x00\x00\x00\x00" . $col . "\x00" . bson_encode($doc),
false,
null,
function ($conn, $reqId = null) use ($cb, $col, $params) {
if ($cb !== null) {
$this->lastError($col, $cb, $params, $conn);
}
}
);
return $doc['_id'];
} catch (\MongoException $e) {
Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
if ($cb !== null) {
if ($cb !== null) {
$cb(['$err' => $e->getMessage(), '$doc' => $doc]);
}
}
}
} | [
"public",
"function",
"insert",
"(",
"$",
"col",
",",
"$",
"doc",
"=",
"[",
"]",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"mb_orig_strpos",
"(",
"$",
"col",
",",
"'.'",
")",
"===",
"false",
")",
"{"... | Inserts an object
@param string $col Collection's name
@param array $doc Document
@param callable $cb Optional. Callback
@param array $params Optional. Parameters
@callback $cb ( )
@return MongoId | [
"Inserts",
"an",
"object"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Pool.php#L1274-L1308 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Pool.php | Pool.killCursors | public function killCursors($cursors, $conn)
{
if (!$cursors) {
$cursors = [];
}
$this->request(
self::OP_KILL_CURSORS,
"\x00\x00\x00\x00" . pack('V', sizeof($cursors)) . implode('', $cursors),
false,
$conn
);
} | php | public function killCursors($cursors, $conn)
{
if (!$cursors) {
$cursors = [];
}
$this->request(
self::OP_KILL_CURSORS,
"\x00\x00\x00\x00" . pack('V', sizeof($cursors)) . implode('', $cursors),
false,
$conn
);
} | [
"public",
"function",
"killCursors",
"(",
"$",
"cursors",
",",
"$",
"conn",
")",
"{",
"if",
"(",
"!",
"$",
"cursors",
")",
"{",
"$",
"cursors",
"=",
"[",
"]",
";",
"}",
"$",
"this",
"->",
"request",
"(",
"self",
"::",
"OP_KILL_CURSORS",
",",
"\"\\x... | Sends a request to kill certain cursors on the server side
@param array $cursors Array of cursors
@param Connection $conn Connection
@return void | [
"Sends",
"a",
"request",
"to",
"kill",
"certain",
"cursors",
"on",
"the",
"server",
"side"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Pool.php#L1316-L1328 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Pool.php | Pool.insertMulti | public function insertMulti($col, $docs = [], $cb = null, $params = [])
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
$ids = [];
$bson = '';
foreach ($docs as &$doc) {
if (!isset($doc['_id'])) {
$doc['_id'] = new MongoId();
}
try {
$bson .= bson_encode($doc);
} catch (\MongoException $e) {
Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
if ($cb !== null) {
$cb(['$err' => $e->getMessage(), '$doc' => $doc]);
}
}
$ids[] = $doc['_id'];
}
$this->request(
self::OP_INSERT,
"\x00\x00\x00\x00" . $col . "\x00" . $bson,
false,
null,
function ($conn, $reqId = null) use ($cb, $col, $params) {
if ($cb !== null) {
$this->lastError($col, $cb, $params, $conn);
}
}
);
return $ids;
} | php | public function insertMulti($col, $docs = [], $cb = null, $params = [])
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
$ids = [];
$bson = '';
foreach ($docs as &$doc) {
if (!isset($doc['_id'])) {
$doc['_id'] = new MongoId();
}
try {
$bson .= bson_encode($doc);
} catch (\MongoException $e) {
Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
if ($cb !== null) {
$cb(['$err' => $e->getMessage(), '$doc' => $doc]);
}
}
$ids[] = $doc['_id'];
}
$this->request(
self::OP_INSERT,
"\x00\x00\x00\x00" . $col . "\x00" . $bson,
false,
null,
function ($conn, $reqId = null) use ($cb, $col, $params) {
if ($cb !== null) {
$this->lastError($col, $cb, $params, $conn);
}
}
);
return $ids;
} | [
"public",
"function",
"insertMulti",
"(",
"$",
"col",
",",
"$",
"docs",
"=",
"[",
"]",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"mb_orig_strpos",
"(",
"$",
"col",
",",
"'.'",
")",
"===",
"false",
")",... | Inserts several documents
@param string $col Collection's name
@param array $docs Array of docs
@param callable $cb Optional. Callback
@param array $params Optional. Parameters
@callback $cb ( )
@return array IDs | [
"Inserts",
"several",
"documents"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Pool.php#L1339-L1377 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Pool.php | Pool.remove | public function remove($col, $cond = [], $cb = null, $params = [])
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
if (is_string($cond)) {
$cond = new \MongoCode($cond);
}
if ($this->safeMode && is_array($cond)) {
static::safeModeEnc($cond);
}
try {
$this->request(
self::OP_DELETE,
"\x00\x00\x00\x00" . $col . "\x00" . "\x00\x00\x00\x00" . bson_encode($cond),
false,
null,
function ($conn, $reqId = null) use ($col, $cb, $params) {
if (!$conn) {
!$cb || $cb(['$err' => 'Connection error.']);
return;
}
if ($cb !== null) {
$this->lastError($col, $cb, $params, $conn);
}
}
);
} catch (\MongoException $e) {
Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
if ($cb !== null) {
$cb(['$err' => $e->getMessage(), '$query' => $cond]);
}
}
} | php | public function remove($col, $cond = [], $cb = null, $params = [])
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
if (is_string($cond)) {
$cond = new \MongoCode($cond);
}
if ($this->safeMode && is_array($cond)) {
static::safeModeEnc($cond);
}
try {
$this->request(
self::OP_DELETE,
"\x00\x00\x00\x00" . $col . "\x00" . "\x00\x00\x00\x00" . bson_encode($cond),
false,
null,
function ($conn, $reqId = null) use ($col, $cb, $params) {
if (!$conn) {
!$cb || $cb(['$err' => 'Connection error.']);
return;
}
if ($cb !== null) {
$this->lastError($col, $cb, $params, $conn);
}
}
);
} catch (\MongoException $e) {
Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
if ($cb !== null) {
$cb(['$err' => $e->getMessage(), '$query' => $cond]);
}
}
} | [
"public",
"function",
"remove",
"(",
"$",
"col",
",",
"$",
"cond",
"=",
"[",
"]",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"mb_orig_strpos",
"(",
"$",
"col",
",",
"'.'",
")",
"===",
"false",
")",
"{... | Remove objects from collection
@param string $col Collection's name
@param array $cond Conditions
@param callable $cb Optional. Callback called when response received
@param array $params Optional. Parameters
@callback $cb ( )
@return void | [
"Remove",
"objects",
"from",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Pool.php#L1388-L1423 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Pool.php | Pool.getMore | public function getMore($col, $id, $number, $conn)
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
$this->request(
self::OP_GETMORE,
"\x00\x00\x00\x00" . $col . "\x00" . pack('V', $number) . $id,
false,
$conn,
function ($conn, $reqId = null) use ($id) {
if (!$conn) {
!$cb || $cb(['$err' => 'Connection error.']);
return;
}
$conn->requests[$reqId] = [$id];
}
);
} | php | public function getMore($col, $id, $number, $conn)
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
}
$this->request(
self::OP_GETMORE,
"\x00\x00\x00\x00" . $col . "\x00" . pack('V', $number) . $id,
false,
$conn,
function ($conn, $reqId = null) use ($id) {
if (!$conn) {
!$cb || $cb(['$err' => 'Connection error.']);
return;
}
$conn->requests[$reqId] = [$id];
}
);
} | [
"public",
"function",
"getMore",
"(",
"$",
"col",
",",
"$",
"id",
",",
"$",
"number",
",",
"$",
"conn",
")",
"{",
"if",
"(",
"mb_orig_strpos",
"(",
"$",
"col",
",",
"'.'",
")",
"===",
"false",
")",
"{",
"$",
"col",
"=",
"$",
"this",
"->",
"dbna... | Asks for more objects
@param string $col Collection's name
@param string $id Cursor's ID
@param integer $number Number of objects
@param Connection $conn Connection
@return void | [
"Asks",
"for",
"more",
"objects"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Pool.php#L1433-L1452 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Pool.php | Pool.getCollection | public function getCollection($col)
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
} else {
$collName = explode('.', $col, 2);
}
if (isset($this->collections[$col])) {
return $this->collections[$col];
}
return $this->collections[$col] = new Collection($col, $this);
} | php | public function getCollection($col)
{
if (mb_orig_strpos($col, '.') === false) {
$col = $this->dbname . '.' . $col;
} else {
$collName = explode('.', $col, 2);
}
if (isset($this->collections[$col])) {
return $this->collections[$col];
}
return $this->collections[$col] = new Collection($col, $this);
} | [
"public",
"function",
"getCollection",
"(",
"$",
"col",
")",
"{",
"if",
"(",
"mb_orig_strpos",
"(",
"$",
"col",
",",
"'.'",
")",
"===",
"false",
")",
"{",
"$",
"col",
"=",
"$",
"this",
"->",
"dbname",
".",
"'.'",
".",
"$",
"col",
";",
"}",
"else"... | Returns an object of collection
@param string $col Collection's name
@return Collection | [
"Returns",
"an",
"object",
"of",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Pool.php#L1459-L1472 |
kakserpom/phpdaemon | PHPDaemon/Clients/HTTP/Pool.php | Pool.parseUrl | public static function parseUrl($mixed)
{
$url = static::buildUrl($mixed);
if (false === $url) {
return false;
}
$u = parse_url($url);
$uri = '';
if (!isset($u['path']) && isset($u['query'])) {
$u['path'] = '/';
}
if (isset($u['path'])) {
$uri .= $u['path'];
if (isset($u['query'])) {
$uri .= '?' . $u['query'];
}
}
return [$u['scheme'], $u['host'], $uri, isset($u['port']) ? $u['port'] : null];
} | php | public static function parseUrl($mixed)
{
$url = static::buildUrl($mixed);
if (false === $url) {
return false;
}
$u = parse_url($url);
$uri = '';
if (!isset($u['path']) && isset($u['query'])) {
$u['path'] = '/';
}
if (isset($u['path'])) {
$uri .= $u['path'];
if (isset($u['query'])) {
$uri .= '?' . $u['query'];
}
}
return [$u['scheme'], $u['host'], $uri, isset($u['port']) ? $u['port'] : null];
} | [
"public",
"static",
"function",
"parseUrl",
"(",
"$",
"mixed",
")",
"{",
"$",
"url",
"=",
"static",
"::",
"buildUrl",
"(",
"$",
"mixed",
")",
";",
"if",
"(",
"false",
"===",
"$",
"url",
")",
"{",
"return",
"false",
";",
"}",
"$",
"u",
"=",
"parse... | Parse URL
@param string $mixed Look Pool::buildUrl()
@call ( string $str )
@call ( array $mixed )
@return array|bool | [
"Parse",
"URL"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/HTTP/Pool.php#L55-L73 |
kakserpom/phpdaemon | PHPDaemon/Clients/HTTP/Pool.php | Pool.buildUrl | public static function buildUrl($mixed)
{
if (is_string($mixed)) {
return $mixed;
}
if (!is_array($mixed)) {
return false;
}
$url = '';
$buf = [];
$queryDelimiter = '?';
$mixed[] = '';
foreach ($mixed as $k => $v) {
if (is_int($k) || ctype_digit($k)) {
if (sizeof($buf) > 0) {
if (mb_orig_strpos($url, '?') !== false) {
$queryDelimiter = '&';
}
$url .= $queryDelimiter . http_build_query($buf);
$queryDelimiter = '';
}
$url .= $v;
} else {
$buf[$k] = $v;
}
}
return $url;
} | php | public static function buildUrl($mixed)
{
if (is_string($mixed)) {
return $mixed;
}
if (!is_array($mixed)) {
return false;
}
$url = '';
$buf = [];
$queryDelimiter = '?';
$mixed[] = '';
foreach ($mixed as $k => $v) {
if (is_int($k) || ctype_digit($k)) {
if (sizeof($buf) > 0) {
if (mb_orig_strpos($url, '?') !== false) {
$queryDelimiter = '&';
}
$url .= $queryDelimiter . http_build_query($buf);
$queryDelimiter = '';
}
$url .= $v;
} else {
$buf[$k] = $v;
}
}
return $url;
} | [
"public",
"static",
"function",
"buildUrl",
"(",
"$",
"mixed",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"mixed",
")",
")",
"{",
"return",
"$",
"mixed",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"mixed",
")",
")",
"{",
"return",
"false",
... | Builds URL from array
@param string $mixed
@call ( string $str )
@call ( array $mixed )
@return string|false | [
"Builds",
"URL",
"from",
"array"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/HTTP/Pool.php#L82-L109 |
kakserpom/phpdaemon | PHPDaemon/Clients/HTTP/Pool.php | Pool.get | public function get($url, $params)
{
if (is_callable($params)) {
$params = ['resultcb' => $params];
}
if (!isset($params['uri']) || !isset($params['host'])) {
list($params['scheme'], $params['host'], $params['uri'], $params['port']) = static::parseUrl($url);
}
if (isset($params['connect'])) {
$dest = $params['connect'];
} elseif (isset($params['proxy']) && $params['proxy']) {
if ($params['proxy']['type'] === 'http') {
$dest = 'tcp://' . $params['proxy']['addr'];
}
} else {
$dest = 'tcp://' . $params['host'] . (isset($params['port']) ? ':' . $params['port'] : null) . ($params['scheme'] === 'https' ? '#ssl' : '');
}
$this->getConnection($dest, function ($conn) use ($url, $params) {
if (!$conn->isConnected()) {
$params['resultcb'](false);
return;
}
$conn->get($url, $params);
});
} | php | public function get($url, $params)
{
if (is_callable($params)) {
$params = ['resultcb' => $params];
}
if (!isset($params['uri']) || !isset($params['host'])) {
list($params['scheme'], $params['host'], $params['uri'], $params['port']) = static::parseUrl($url);
}
if (isset($params['connect'])) {
$dest = $params['connect'];
} elseif (isset($params['proxy']) && $params['proxy']) {
if ($params['proxy']['type'] === 'http') {
$dest = 'tcp://' . $params['proxy']['addr'];
}
} else {
$dest = 'tcp://' . $params['host'] . (isset($params['port']) ? ':' . $params['port'] : null) . ($params['scheme'] === 'https' ? '#ssl' : '');
}
$this->getConnection($dest, function ($conn) use ($url, $params) {
if (!$conn->isConnected()) {
$params['resultcb'](false);
return;
}
$conn->get($url, $params);
});
} | [
"public",
"function",
"get",
"(",
"$",
"url",
",",
"$",
"params",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"params",
")",
")",
"{",
"$",
"params",
"=",
"[",
"'resultcb'",
"=>",
"$",
"params",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$... | Perform a GET request
@param string $url
@param array $params
@param callable $resultcb
@call ( url $url, array $params )
@call ( url $url, callable $resultcb )
@callback $resultcb ( Connection $conn, boolean $success ) | [
"Perform",
"a",
"GET",
"request"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/HTTP/Pool.php#L120-L144 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Cursor.php | Cursor.current | public function current()
{
return isset($this->items[$this->pos]) ? $this->items[$this->pos] : null;
} | php | public function current()
{
return isset($this->items[$this->pos]) ? $this->items[$this->pos] : null;
} | [
"public",
"function",
"current",
"(",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"items",
"[",
"$",
"this",
"->",
"pos",
"]",
")",
"?",
"$",
"this",
"->",
"items",
"[",
"$",
"this",
"->",
"pos",
"]",
":",
"null",
";",
"}"
] | Current
@return mixed | [
"Current"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Cursor.php#L116-L119 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Cursor.php | Cursor.valid | public function valid()
{
$key = isset($this->items[$this->pos]) ? $this->items[$this->pos] : null;
return ($key !== null && $key !== false);
} | php | public function valid()
{
$key = isset($this->items[$this->pos]) ? $this->items[$this->pos] : null;
return ($key !== null && $key !== false);
} | [
"public",
"function",
"valid",
"(",
")",
"{",
"$",
"key",
"=",
"isset",
"(",
"$",
"this",
"->",
"items",
"[",
"$",
"this",
"->",
"pos",
"]",
")",
"?",
"$",
"this",
"->",
"items",
"[",
"$",
"this",
"->",
"pos",
"]",
":",
"null",
";",
"return",
... | Valid
@return boolean | [
"Valid"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Cursor.php#L169-L173 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Cursor.php | Cursor.getMore | public function getMore($number = 0)
{
if ($this->finished || $this->destroyed) {
return;
}
if (mb_orig_substr($this->id, 0, 1) === 'c') {
$this->conn->pool->getMore($this->col, mb_orig_substr($this->id, 1), $number, $this->conn);
}
} | php | public function getMore($number = 0)
{
if ($this->finished || $this->destroyed) {
return;
}
if (mb_orig_substr($this->id, 0, 1) === 'c') {
$this->conn->pool->getMore($this->col, mb_orig_substr($this->id, 1), $number, $this->conn);
}
} | [
"public",
"function",
"getMore",
"(",
"$",
"number",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"finished",
"||",
"$",
"this",
"->",
"destroyed",
")",
"{",
"return",
";",
"}",
"if",
"(",
"mb_orig_substr",
"(",
"$",
"this",
"->",
"id",
",",
... | Asks for more objects
@param integer $number Number of objects
@return void | [
"Asks",
"for",
"more",
"objects"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Cursor.php#L210-L218 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Cursor.php | Cursor.destroy | public function destroy($notify = false)
{
if ($this->destroyed) {
return false;
}
$this->destroyed = true;
if ($notify) {
if ($this->callback) {
$func = $this->callback;
$func($this);
}
}
unset($this->conn->cursors[$this->id]);
return true;
} | php | public function destroy($notify = false)
{
if ($this->destroyed) {
return false;
}
$this->destroyed = true;
if ($notify) {
if ($this->callback) {
$func = $this->callback;
$func($this);
}
}
unset($this->conn->cursors[$this->id]);
return true;
} | [
"public",
"function",
"destroy",
"(",
"$",
"notify",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"destroyed",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"destroyed",
"=",
"true",
";",
"if",
"(",
"$",
"notify",
")",
"{",
"... | Destroys the cursors
@param boolean $notify
@return boolean Success | [
"Destroys",
"the",
"cursors"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Cursor.php#L244-L258 |
kakserpom/phpdaemon | PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Queue/QueueDeclareFrame.php | QueueDeclareFrame.create | public static function create(
$queue = null, $passive = null, $durable = null, $exclusive = null, $autoDelete = null, $nowait = null, $arguments = null
)
{
$frame = new self();
if (null !== $queue) {
$frame->queue = $queue;
}
if (null !== $passive) {
$frame->passive = $passive;
}
if (null !== $durable) {
$frame->durable = $durable;
}
if (null !== $exclusive) {
$frame->exclusive = $exclusive;
}
if (null !== $autoDelete) {
$frame->autoDelete = $autoDelete;
}
if (null !== $nowait) {
$frame->nowait = $nowait;
}
if (null !== $arguments) {
$frame->arguments = $arguments;
}
return $frame;
} | php | public static function create(
$queue = null, $passive = null, $durable = null, $exclusive = null, $autoDelete = null, $nowait = null, $arguments = null
)
{
$frame = new self();
if (null !== $queue) {
$frame->queue = $queue;
}
if (null !== $passive) {
$frame->passive = $passive;
}
if (null !== $durable) {
$frame->durable = $durable;
}
if (null !== $exclusive) {
$frame->exclusive = $exclusive;
}
if (null !== $autoDelete) {
$frame->autoDelete = $autoDelete;
}
if (null !== $nowait) {
$frame->nowait = $nowait;
}
if (null !== $arguments) {
$frame->arguments = $arguments;
}
return $frame;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"queue",
"=",
"null",
",",
"$",
"passive",
"=",
"null",
",",
"$",
"durable",
"=",
"null",
",",
"$",
"exclusive",
"=",
"null",
",",
"$",
"autoDelete",
"=",
"null",
",",
"$",
"nowait",
"=",
"null",
... | table | [
"table"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Queue/QueueDeclareFrame.php#L27-L56 |
kakserpom/phpdaemon | PHPDaemon/Examples/ExamplePubSub.php | ExamplePubSub.onReady | public function onReady()
{
$appInstance = $this; // a reference to this application instance for ExampleWebSocketRoute
\PHPDaemon\Servers\WebSocket\Pool::getInstance()->addRoute('ExamplePubSub',
function ($client) use ($appInstance) {
return new ExamplePubSubWebSocketRoute($client, $appInstance);
});
$this->sql = \PHPDaemon\Clients\MySQL\Pool::getInstance();
$this->pubsub = new \PHPDaemon\PubSub\PubSub();
$this->pubsub->addEvent('usersNum', \PHPDaemon\PubSub\PubSubEvent::init()
->onActivation(function ($pubsub) use ($appInstance) {
\PHPDaemon\Core\Daemon::log('onActivation');
if (isset($pubsub->event)) {
\PHPDaemon\Core\Timer::setTimeout($pubsub->event, 0);
return;
}
$pubsub->event = setTimeout(function ($timer) use ($pubsub, $appInstance) {
$appInstance->sql->getConnection(function ($sql) use ($pubsub) {
if (!$sql->connected) {
return;
}
$sql->query('SELECT COUNT(*) `num` FROM `dle_users`', function ($sql, $success) use ($pubsub) {
$pubsub->pub(sizeof($sql->resultRows) ? $sql->resultRows[0]['num'] : 'null');
});
});
$timer->timeout(5e6); // 5 seconds
}, 0);
})
->onDeactivation(function ($pubsub) {
if (isset($pubsub->event)) {
\PHPDaemon\Core\Timer::cancelTimeout($pubsub->event);
}
})
);
} | php | public function onReady()
{
$appInstance = $this; // a reference to this application instance for ExampleWebSocketRoute
\PHPDaemon\Servers\WebSocket\Pool::getInstance()->addRoute('ExamplePubSub',
function ($client) use ($appInstance) {
return new ExamplePubSubWebSocketRoute($client, $appInstance);
});
$this->sql = \PHPDaemon\Clients\MySQL\Pool::getInstance();
$this->pubsub = new \PHPDaemon\PubSub\PubSub();
$this->pubsub->addEvent('usersNum', \PHPDaemon\PubSub\PubSubEvent::init()
->onActivation(function ($pubsub) use ($appInstance) {
\PHPDaemon\Core\Daemon::log('onActivation');
if (isset($pubsub->event)) {
\PHPDaemon\Core\Timer::setTimeout($pubsub->event, 0);
return;
}
$pubsub->event = setTimeout(function ($timer) use ($pubsub, $appInstance) {
$appInstance->sql->getConnection(function ($sql) use ($pubsub) {
if (!$sql->connected) {
return;
}
$sql->query('SELECT COUNT(*) `num` FROM `dle_users`', function ($sql, $success) use ($pubsub) {
$pubsub->pub(sizeof($sql->resultRows) ? $sql->resultRows[0]['num'] : 'null');
});
});
$timer->timeout(5e6); // 5 seconds
}, 0);
})
->onDeactivation(function ($pubsub) {
if (isset($pubsub->event)) {
\PHPDaemon\Core\Timer::cancelTimeout($pubsub->event);
}
})
);
} | [
"public",
"function",
"onReady",
"(",
")",
"{",
"$",
"appInstance",
"=",
"$",
"this",
";",
"// a reference to this application instance for ExampleWebSocketRoute",
"\\",
"PHPDaemon",
"\\",
"Servers",
"\\",
"WebSocket",
"\\",
"Pool",
"::",
"getInstance",
"(",
")",
"-... | 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/ExamplePubSub.php#L13-L47 |
kakserpom/phpdaemon | PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Basic/BasicNackFrame.php | BasicNackFrame.create | public static function create(
$deliveryTag = null, $multiple = null, $requeue = null
)
{
$frame = new self();
if (null !== $deliveryTag) {
$frame->deliveryTag = $deliveryTag;
}
if (null !== $multiple) {
$frame->multiple = $multiple;
}
if (null !== $requeue) {
$frame->requeue = $requeue;
}
return $frame;
} | php | public static function create(
$deliveryTag = null, $multiple = null, $requeue = null
)
{
$frame = new self();
if (null !== $deliveryTag) {
$frame->deliveryTag = $deliveryTag;
}
if (null !== $multiple) {
$frame->multiple = $multiple;
}
if (null !== $requeue) {
$frame->requeue = $requeue;
}
return $frame;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"deliveryTag",
"=",
"null",
",",
"$",
"multiple",
"=",
"null",
",",
"$",
"requeue",
"=",
"null",
")",
"{",
"$",
"frame",
"=",
"new",
"self",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"delivery... | bit | [
"bit"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Basic/BasicNackFrame.php#L23-L40 |
kakserpom/phpdaemon | PHPDaemon/Traits/DeferredEventHandlers.php | DeferredEventHandlers.cleanupDeferredEventHandlers | public function cleanupDeferredEventHandlers()
{
foreach ($this as $key => $property) {
if ($property instanceof DeferredEvent) {
$property->cleanup();
$this->{$key} = null;
}
}
} | php | public function cleanupDeferredEventHandlers()
{
foreach ($this as $key => $property) {
if ($property instanceof DeferredEvent) {
$property->cleanup();
$this->{$key} = null;
}
}
} | [
"public",
"function",
"cleanupDeferredEventHandlers",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"key",
"=>",
"$",
"property",
")",
"{",
"if",
"(",
"$",
"property",
"instanceof",
"DeferredEvent",
")",
"{",
"$",
"property",
"->",
"cleanup",
"(",... | Cleans up events
@return void | [
"Cleans",
"up",
"events"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/DeferredEventHandlers.php#L53-L61 |
kakserpom/phpdaemon | PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Basic/BasicCancelFrame.php | BasicCancelFrame.create | public static function create(
$consumerTag = null, $nowait = null
)
{
$frame = new self();
if (null !== $consumerTag) {
$frame->consumerTag = $consumerTag;
}
if (null !== $nowait) {
$frame->nowait = $nowait;
}
return $frame;
} | php | public static function create(
$consumerTag = null, $nowait = null
)
{
$frame = new self();
if (null !== $consumerTag) {
$frame->consumerTag = $consumerTag;
}
if (null !== $nowait) {
$frame->nowait = $nowait;
}
return $frame;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"consumerTag",
"=",
"null",
",",
"$",
"nowait",
"=",
"null",
")",
"{",
"$",
"frame",
"=",
"new",
"self",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"consumerTag",
")",
"{",
"$",
"frame",
"->",
... | bit | [
"bit"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Basic/BasicCancelFrame.php#L21-L35 |
kakserpom/phpdaemon | PHPDaemon/Clients/Gearman/Connection.php | Connection.onRead | public function onRead()
{
if (($head = $this->lookExact(static::HEADER_LENGTH)) === false) {
return;
}
list($magic, $typeInt, $size) = unpack(static::HEADER_READ_FORMAT, $head);
if ($this->getInputLength() < static::HEADER_LENGTH + $size) {
return;
}
$this->drain(static::HEADER_LENGTH);
$pct = $this->read($size);
if ($magic === static::MAGIC_RESPONSE) {
$this->responseType = static::$responseCommandListFlipped[$typeInt];
$this->response = explode(static::ARGS_DELIMITER, $pct);
$this->onResponse->executeOne($this);
$this->responseType = null;
$this->responseCommand = null;
$this->responseType = null;
$this->checkFree();
return;
} else {
$type = static::$requestCommandListFlipped[$typeInt];
// @TODO
}
} | php | public function onRead()
{
if (($head = $this->lookExact(static::HEADER_LENGTH)) === false) {
return;
}
list($magic, $typeInt, $size) = unpack(static::HEADER_READ_FORMAT, $head);
if ($this->getInputLength() < static::HEADER_LENGTH + $size) {
return;
}
$this->drain(static::HEADER_LENGTH);
$pct = $this->read($size);
if ($magic === static::MAGIC_RESPONSE) {
$this->responseType = static::$responseCommandListFlipped[$typeInt];
$this->response = explode(static::ARGS_DELIMITER, $pct);
$this->onResponse->executeOne($this);
$this->responseType = null;
$this->responseCommand = null;
$this->responseType = null;
$this->checkFree();
return;
} else {
$type = static::$requestCommandListFlipped[$typeInt];
// @TODO
}
} | [
"public",
"function",
"onRead",
"(",
")",
"{",
"if",
"(",
"(",
"$",
"head",
"=",
"$",
"this",
"->",
"lookExact",
"(",
"static",
"::",
"HEADER_LENGTH",
")",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"list",
"(",
"$",
"magic",
",",
"$",
"t... | Called when new data received
@return void | [
"Called",
"when",
"new",
"data",
"received"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Gearman/Connection.php#L124-L152 |
kakserpom/phpdaemon | PHPDaemon/Clients/Gearman/Connection.php | Connection.onReady | public function onReady()
{
if (static::$requestCommandListFlipped === null) {
static::$requestCommandListFlipped = array_flip(static::$requestCommandList);
}
if (static::$responseCommandListFlipped === null) {
static::$responseCommandListFlipped = array_flip(static::$responseCommandList);
}
parent::onReady();
} | php | public function onReady()
{
if (static::$requestCommandListFlipped === null) {
static::$requestCommandListFlipped = array_flip(static::$requestCommandList);
}
if (static::$responseCommandListFlipped === null) {
static::$responseCommandListFlipped = array_flip(static::$responseCommandList);
}
parent::onReady();
} | [
"public",
"function",
"onReady",
"(",
")",
"{",
"if",
"(",
"static",
"::",
"$",
"requestCommandListFlipped",
"===",
"null",
")",
"{",
"static",
"::",
"$",
"requestCommandListFlipped",
"=",
"array_flip",
"(",
"static",
"::",
"$",
"requestCommandList",
")",
";",... | 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/Gearman/Connection.php#L158-L167 |
kakserpom/phpdaemon | PHPDaemon/Clients/Gearman/Connection.php | Connection.sendCommand | public function sendCommand($commandName, $payload, $cb = null)
{
$pct = implode(
static::ARGS_DELIMITER,
array_map(function ($item) {
return !is_scalar($item) ? serialize($item) : $item;
}, (array)$payload)
);
$this->onResponse->push($cb);
$this->write(
pack(
static::HEADER_WRITE_FORMAT,
static::MAGIC_REQUEST,
$this->requestCommandList[$commandName],
mb_orig_strlen($pct)
)
);
$this->write($pct);
} | php | public function sendCommand($commandName, $payload, $cb = null)
{
$pct = implode(
static::ARGS_DELIMITER,
array_map(function ($item) {
return !is_scalar($item) ? serialize($item) : $item;
}, (array)$payload)
);
$this->onResponse->push($cb);
$this->write(
pack(
static::HEADER_WRITE_FORMAT,
static::MAGIC_REQUEST,
$this->requestCommandList[$commandName],
mb_orig_strlen($pct)
)
);
$this->write($pct);
} | [
"public",
"function",
"sendCommand",
"(",
"$",
"commandName",
",",
"$",
"payload",
",",
"$",
"cb",
"=",
"null",
")",
"{",
"$",
"pct",
"=",
"implode",
"(",
"static",
"::",
"ARGS_DELIMITER",
",",
"array_map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
... | Send a command
@param $commandName
@param $payload
@param callable $cb = null | [
"Send",
"a",
"command"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Gearman/Connection.php#L188-L207 |
kakserpom/phpdaemon | PHPDaemon/Clients/Gearman/Connection.php | Connection.submitJob | public function submitJob($params, $cb = null)
{
$closure = function () use (&$params, $cb) {
$this->sendCommand(
'SUBMIT_JOB'
. (isset($params['pri']) ? '_ ' . strtoupper($params['pri']) : '')
. (isset($params['bg']) && $params['bg'] ? '_BG' : ''),
[$params['function'], $params['unique'], $params['payload']],
$cb
);
};
if (isset($params['unique'])) {
$closure();
} else {
Crypt::randomString(
10,
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
function ($random) use ($closure) {
$params['unique'] = $random;
$closure();
}
);
}
} | php | public function submitJob($params, $cb = null)
{
$closure = function () use (&$params, $cb) {
$this->sendCommand(
'SUBMIT_JOB'
. (isset($params['pri']) ? '_ ' . strtoupper($params['pri']) : '')
. (isset($params['bg']) && $params['bg'] ? '_BG' : ''),
[$params['function'], $params['unique'], $params['payload']],
$cb
);
};
if (isset($params['unique'])) {
$closure();
} else {
Crypt::randomString(
10,
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
function ($random) use ($closure) {
$params['unique'] = $random;
$closure();
}
);
}
} | [
"public",
"function",
"submitJob",
"(",
"$",
"params",
",",
"$",
"cb",
"=",
"null",
")",
"{",
"$",
"closure",
"=",
"function",
"(",
")",
"use",
"(",
"&",
"$",
"params",
",",
"$",
"cb",
")",
"{",
"$",
"this",
"->",
"sendCommand",
"(",
"'SUBMIT_JOB'"... | Function run task and wait result in callback
@param $params
@param callable $cb = null
@param boolean $unique | [
"Function",
"run",
"task",
"and",
"wait",
"result",
"in",
"callback"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Gearman/Connection.php#L216-L239 |
kakserpom/phpdaemon | PHPDaemon/Utils/MIME.php | MIME.get | public static function get($path)
{
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (!isset(self::$fileTypes[$ext])) {
return false;
}
return self::$fileTypes[$ext];
} | php | public static function get($path)
{
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (!isset(self::$fileTypes[$ext])) {
return false;
}
return self::$fileTypes[$ext];
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"path",
")",
"{",
"$",
"ext",
"=",
"strtolower",
"(",
"pathinfo",
"(",
"$",
"path",
",",
"PATHINFO_EXTENSION",
")",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"fileTypes",
"[",
"$",
"... | Returns MIME type of the given file
@param string $path Path
@return string MIME type | [
"Returns",
"MIME",
"type",
"of",
"the",
"given",
"file"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/MIME.php#L77-L84 |
kakserpom/phpdaemon | PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Basic/BasicPublishFrame.php | BasicPublishFrame.create | public static function create(
$exchange = null, $routingKey = null, $mandatory = null, $immediate = null
)
{
$frame = new self();
if (null !== $exchange) {
$frame->exchange = $exchange;
}
if (null !== $routingKey) {
$frame->routingKey = $routingKey;
}
if (null !== $mandatory) {
$frame->mandatory = $mandatory;
}
if (null !== $immediate) {
$frame->immediate = $immediate;
}
return $frame;
} | php | public static function create(
$exchange = null, $routingKey = null, $mandatory = null, $immediate = null
)
{
$frame = new self();
if (null !== $exchange) {
$frame->exchange = $exchange;
}
if (null !== $routingKey) {
$frame->routingKey = $routingKey;
}
if (null !== $mandatory) {
$frame->mandatory = $mandatory;
}
if (null !== $immediate) {
$frame->immediate = $immediate;
}
return $frame;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"exchange",
"=",
"null",
",",
"$",
"routingKey",
"=",
"null",
",",
"$",
"mandatory",
"=",
"null",
",",
"$",
"immediate",
"=",
"null",
")",
"{",
"$",
"frame",
"=",
"new",
"self",
"(",
")",
";",
"if... | bit | [
"bit"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Basic/BasicPublishFrame.php#L25-L45 |
kakserpom/phpdaemon | PHPDaemon/Servers/WebSocket/Pool.php | Pool.setRouteOptions | public function setRouteOptions($path, $opts)
{
$routeName = ltrim($path, '/');
if (!isset($this->routes[$routeName])) {
Daemon::log(__METHOD__ . ': Route \'' . $path . '\' is not found.');
return false;
}
$this->routeOptions[$routeName] = $opts;
return true;
} | php | public function setRouteOptions($path, $opts)
{
$routeName = ltrim($path, '/');
if (!isset($this->routes[$routeName])) {
Daemon::log(__METHOD__ . ': Route \'' . $path . '\' is not found.');
return false;
}
$this->routeOptions[$routeName] = $opts;
return true;
} | [
"public",
"function",
"setRouteOptions",
"(",
"$",
"path",
",",
"$",
"opts",
")",
"{",
"$",
"routeName",
"=",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"routeName",
"]",
... | Sets an array of options associated to the route
@param string $path Route name.
@param array $opts Options
@return boolean Success. | [
"Sets",
"an",
"array",
"of",
"options",
"associated",
"to",
"the",
"route"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Pool.php#L58-L67 |
kakserpom/phpdaemon | PHPDaemon/Servers/WebSocket/Pool.php | Pool.getRouteOptions | public function getRouteOptions($path)
{
$routeName = ltrim($path, '/');
if (!isset($this->routeOptions[$routeName])) {
return [];
}
return $this->routeOptions[$routeName];
} | php | public function getRouteOptions($path)
{
$routeName = ltrim($path, '/');
if (!isset($this->routeOptions[$routeName])) {
return [];
}
return $this->routeOptions[$routeName];
} | [
"public",
"function",
"getRouteOptions",
"(",
"$",
"path",
")",
"{",
"$",
"routeName",
"=",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"routeOptions",
"[",
"$",
"routeName",
"]",
")",
")",
"{",... | Return options by route
@param string $path Route name
@return array Options | [
"Return",
"options",
"by",
"route"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Pool.php#L75-L82 |
kakserpom/phpdaemon | PHPDaemon/Servers/WebSocket/Pool.php | Pool.addRoute | public function addRoute($path, $cb)
{
$routeName = ltrim($path, '/');
if (isset($this->routes[$routeName])) {
Daemon::log(__METHOD__ . ': Route \'' . $path . '\' is already defined.');
return false;
}
$this->routes[$routeName] = $cb;
return true;
} | php | public function addRoute($path, $cb)
{
$routeName = ltrim($path, '/');
if (isset($this->routes[$routeName])) {
Daemon::log(__METHOD__ . ': Route \'' . $path . '\' is already defined.');
return false;
}
$this->routes[$routeName] = $cb;
return true;
} | [
"public",
"function",
"addRoute",
"(",
"$",
"path",
",",
"$",
"cb",
")",
"{",
"$",
"routeName",
"=",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"routeName",
"]",
")",
")",
"{... | Adds a route if it doesn't exist already.
@param string $path Route name.
@param callable $cb Route's callback.
@callback $cb ( )
@return boolean Success. | [
"Adds",
"a",
"route",
"if",
"it",
"doesn",
"t",
"exist",
"already",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Pool.php#L91-L100 |
kakserpom/phpdaemon | PHPDaemon/Servers/WebSocket/Pool.php | Pool.setRoute | public function setRoute($path, $cb)
{
$routeName = ltrim($path, '/');
$this->routes[$routeName] = $cb;
return true;
} | php | public function setRoute($path, $cb)
{
$routeName = ltrim($path, '/');
$this->routes[$routeName] = $cb;
return true;
} | [
"public",
"function",
"setRoute",
"(",
"$",
"path",
",",
"$",
"cb",
")",
"{",
"$",
"routeName",
"=",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"$",
"this",
"->",
"routes",
"[",
"$",
"routeName",
"]",
"=",
"$",
"cb",
";",
"return",
"true",
... | Force add/replace a route.
@param string $path Path
@param callable $cb Callback
@callback $cb ( )
@return boolean Success | [
"Force",
"add",
"/",
"replace",
"a",
"route",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Pool.php#L157-L162 |
kakserpom/phpdaemon | PHPDaemon/Servers/WebSocket/Pool.php | Pool.removeRoute | public function removeRoute($path)
{
$routeName = ltrim($path, '/');
if (!isset($this->routes[$routeName])) {
return false;
}
unset($this->routes[$routeName]);
return true;
} | php | public function removeRoute($path)
{
$routeName = ltrim($path, '/');
if (!isset($this->routes[$routeName])) {
return false;
}
unset($this->routes[$routeName]);
return true;
} | [
"public",
"function",
"removeRoute",
"(",
"$",
"path",
")",
"{",
"$",
"routeName",
"=",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"routeName",
"]",
")",
")",
"{",
"return... | Removes a route.
@param string $path Route name
@return boolean Success | [
"Removes",
"a",
"route",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Servers/WebSocket/Pool.php#L169-L177 |
kakserpom/phpdaemon | PHPDaemon/Clients/WebSocket/Example.php | Example.init | public function init()
{
if ($this->isEnabled()) {
$this->wsclient = Pool::getInstance($this->config->wsclientname->value);
}
} | php | public function init()
{
if ($this->isEnabled()) {
$this->wsclient = Pool::getInstance($this->config->wsclientname->value);
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"$",
"this",
"->",
"wsclient",
"=",
"Pool",
"::",
"getInstance",
"(",
"$",
"this",
"->",
"config",
"->",
"wsclientname",
"->",
"value",
")",
... | Constructor.
@return void | [
"Constructor",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/WebSocket/Example.php#L23-L28 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.find | public function find($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->find($p, $cb);
} | php | public function find($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->find($p, $cb);
} | [
"public",
"function",
"find",
"(",
"$",
"cb",
",",
"$",
"p",
"=",
"[",
"]",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"find",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
"}"
... | Finds objects in collection
@param callable $cb Callback called when response received
@param array $p Hash of properties (offset, limit, opts, tailable, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)
@callback $cb ( )
@return void | [
"Finds",
"objects",
"in",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L43-L47 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.findAll | public function findAll($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->findAll($p, $cb);
} | php | public function findAll($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->findAll($p, $cb);
} | [
"public",
"function",
"findAll",
"(",
"$",
"cb",
",",
"$",
"p",
"=",
"[",
"]",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"findAll",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
... | Finds objects in collection and fires callback when got all objects
@param callable $cb Callback called when response received
@param array $p Hash of properties (offset, limit, opts, tailable, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)
@callback $cb ( )
@return void | [
"Finds",
"objects",
"in",
"collection",
"and",
"fires",
"callback",
"when",
"got",
"all",
"objects"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L56-L60 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.findOne | public function findOne($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->findOne($p, $cb);
} | php | public function findOne($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->findOne($p, $cb);
} | [
"public",
"function",
"findOne",
"(",
"$",
"cb",
",",
"$",
"p",
"=",
"[",
"]",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"findOne",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
... | Finds one object in collection
@param callable $cb Callback called when response received
@param array $p Hash of properties (offset, opts, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)
@callback $cb ( )
@return void | [
"Finds",
"one",
"object",
"in",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L69-L73 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.count | public function count($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->findCount($p, $cb);
} | php | public function count($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->findCount($p, $cb);
} | [
"public",
"function",
"count",
"(",
"$",
"cb",
",",
"$",
"p",
"=",
"[",
"]",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"findCount",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
... | Counts objects in collection
@param callable $cb Callback called when response received
@param array $p Hash of properties (offset, limit, opts, where, col)
@callback $cb ( )
@return void | [
"Counts",
"objects",
"in",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L82-L86 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.ensureIndex | public function ensureIndex($keys, $options = [], $cb = null)
{
$this->pool->ensureIndex($this->name, $keys, $options, $cb);
} | php | public function ensureIndex($keys, $options = [], $cb = null)
{
$this->pool->ensureIndex($this->name, $keys, $options, $cb);
} | [
"public",
"function",
"ensureIndex",
"(",
"$",
"keys",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"cb",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"pool",
"->",
"ensureIndex",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"keys",
",",
"$",
"options... | Ensure index
@param array $keys Keys
@param array $options Optional. Options
@param callable $cb Optional. Callback called when response received
@callback $cb ( )
@return void | [
"Ensure",
"index"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L96-L99 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.group | public function group($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->group($p, $cb);
} | php | public function group($cb, $p = [])
{
$p['col'] = $this->name;
$this->pool->group($p, $cb);
} | [
"public",
"function",
"group",
"(",
"$",
"cb",
",",
"$",
"p",
"=",
"[",
"]",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"group",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
"}... | Groupping function
@param callable $cb Callback called when response received
@param array $p Hash of properties (offset, limit, opts, key, col, reduce, initial)
@callback $cb ( )
@return void | [
"Groupping",
"function"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L108-L112 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.insert | public function insert($doc, $cb = null, $params = null)
{
return $this->pool->insert($this->name, $doc, $cb, $params);
} | php | public function insert($doc, $cb = null, $params = null)
{
return $this->pool->insert($this->name, $doc, $cb, $params);
} | [
"public",
"function",
"insert",
"(",
"$",
"doc",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"pool",
"->",
"insert",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"doc",
",",
"$",
"cb",
",",
... | Inserts an object
@param array $doc Data
@param callable $cb Optional. Callback called when response received
@param array $params Optional. Params
@callback $cb ( )
@return MongoId | [
"Inserts",
"an",
"object"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L122-L125 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.insertMulti | public function insertMulti($docs, $cb = null, $params = null)
{
return $this->pool->insertMulti($this->name, $docs, $cb, $params);
} | php | public function insertMulti($docs, $cb = null, $params = null)
{
return $this->pool->insertMulti($this->name, $docs, $cb, $params);
} | [
"public",
"function",
"insertMulti",
"(",
"$",
"docs",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"pool",
"->",
"insertMulti",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"docs",
",",
"$",
"... | Inserts several documents
@param array $docs Array of docs
@param callable $cb Optional. Callback called when response received.
@param array $params Optional. Params
@callback $cb ( )
@return array IDs | [
"Inserts",
"several",
"documents"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L148-L151 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.update | public function update($cond, $data, $flags = 0, $cb = null, $params = null)
{
$this->pool->update($this->name, $cond, $data, $flags, $cb, $params);
} | php | public function update($cond, $data, $flags = 0, $cb = null, $params = null)
{
$this->pool->update($this->name, $cond, $data, $flags, $cb, $params);
} | [
"public",
"function",
"update",
"(",
"$",
"cond",
",",
"$",
"data",
",",
"$",
"flags",
"=",
"0",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"pool",
"->",
"update",
"(",
"$",
"this",
"->",
"name",
... | Updates one object in collection
@param array $cond Conditions
@param array $data Data
@param integer $flags Optional. Flags
@param callable $cb Optional. Callback called when response received
@param array $params Optional. Params
@callback $cb ( )
@return void | [
"Updates",
"one",
"object",
"in",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L163-L166 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.updateOne | public function updateOne($cond, $data, $cb = null, $params = null)
{
$this->pool->updateOne($this->name, $cond, $data, $cb, $params);
} | php | public function updateOne($cond, $data, $cb = null, $params = null)
{
$this->pool->updateOne($this->name, $cond, $data, $cb, $params);
} | [
"public",
"function",
"updateOne",
"(",
"$",
"cond",
",",
"$",
"data",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"pool",
"->",
"updateOne",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"cond",
",",
... | Updates one object in collection
@param array $cond Conditions
@param array $data Data
@param callable $cb Optional. Callback called when response received
@param array $params Optional. Params
@callback $cb ( )
@return void | [
"Updates",
"one",
"object",
"in",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L178-L181 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.upsert | public function upsert($cond, $data, $multi = false, $cb = null, $params = null)
{
$this->pool->upsert($this->name, $cond, $data, $multi, $cb, $params);
} | php | public function upsert($cond, $data, $multi = false, $cb = null, $params = null)
{
$this->pool->upsert($this->name, $cond, $data, $multi, $cb, $params);
} | [
"public",
"function",
"upsert",
"(",
"$",
"cond",
",",
"$",
"data",
",",
"$",
"multi",
"=",
"false",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"pool",
"->",
"upsert",
"(",
"$",
"this",
"->",
"nam... | Upserts an object (updates if exists, insert if not exists)
@param array $cond Conditions
@param array $data Data
@param boolean $multi Optional. Multi-flag
@param callable $cb Optional. Callback called when response received
@param array $params Optional. Params
@callback $cb ( )
@return void | [
"Upserts",
"an",
"object",
"(",
"updates",
"if",
"exists",
"insert",
"if",
"not",
"exists",
")"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L207-L210 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.remove | public function remove($cond = [], $cb = null, $params = null)
{
$this->pool->remove($this->name, $cond, $cb);
} | php | public function remove($cond = [], $cb = null, $params = null)
{
$this->pool->remove($this->name, $cond, $cb);
} | [
"public",
"function",
"remove",
"(",
"$",
"cond",
"=",
"[",
"]",
",",
"$",
"cb",
"=",
"null",
",",
"$",
"params",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"pool",
"->",
"remove",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"cond",
",",
"$",
"c... | Removes objects from collection
@param array $cond Conditions
@param callable $cb Optional. Callback called when response received
@param array $params Optional. Params
@callback $cb ( )
@return void | [
"Removes",
"objects",
"from",
"collection"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L248-L251 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.aggregate | public function aggregate($p, $cb)
{
$p['col'] = $this->name;
$this->pool->aggregate($p, $cb);
} | php | public function aggregate($p, $cb)
{
$p['col'] = $this->name;
$this->pool->aggregate($p, $cb);
} | [
"public",
"function",
"aggregate",
"(",
"$",
"p",
",",
"$",
"cb",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"aggregate",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
"}"
] | Aggregate
@param array $p Params
@param callable $cb Callback called when response received
@callback $cb ( )
@return void | [
"Aggregate"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L273-L277 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.autoincrement | public function autoincrement($cb, $plain = false)
{
$e = explode('.', $this->name);
$col = (isset($e[1]) ? $e[0] . '.' : '') . 'autoincrement';
$this->pool->{$col}->findAndModify([
'query' => ['_id' => isset($e[1]) ? $e[1] : $e[0]],
'update' => ['$inc' => ['seq' => 1]],
'new' => true,
'upsert' => true,
], $plain ? function ($lastError) use ($cb) {
$cb(isset($lastError['value']['seq']) ? $lastError['value']['seq'] : false);
} : $cb);
} | php | public function autoincrement($cb, $plain = false)
{
$e = explode('.', $this->name);
$col = (isset($e[1]) ? $e[0] . '.' : '') . 'autoincrement';
$this->pool->{$col}->findAndModify([
'query' => ['_id' => isset($e[1]) ? $e[1] : $e[0]],
'update' => ['$inc' => ['seq' => 1]],
'new' => true,
'upsert' => true,
], $plain ? function ($lastError) use ($cb) {
$cb(isset($lastError['value']['seq']) ? $lastError['value']['seq'] : false);
} : $cb);
} | [
"public",
"function",
"autoincrement",
"(",
"$",
"cb",
",",
"$",
"plain",
"=",
"false",
")",
"{",
"$",
"e",
"=",
"explode",
"(",
"'.'",
",",
"$",
"this",
"->",
"name",
")",
";",
"$",
"col",
"=",
"(",
"isset",
"(",
"$",
"e",
"[",
"1",
"]",
")"... | Generation autoincrement
@param callable $cb Called when response received
@param boolean $plain Plain?
@callback $cb ( )
@return void | [
"Generation",
"autoincrement"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L286-L298 |
kakserpom/phpdaemon | PHPDaemon/Clients/Mongo/Collection.php | Collection.findAndModify | public function findAndModify($p, $cb)
{
$p['col'] = $this->name;
$this->pool->findAndModify($p, $cb);
} | php | public function findAndModify($p, $cb)
{
$p['col'] = $this->name;
$this->pool->findAndModify($p, $cb);
} | [
"public",
"function",
"findAndModify",
"(",
"$",
"p",
",",
"$",
"cb",
")",
"{",
"$",
"p",
"[",
"'col'",
"]",
"=",
"$",
"this",
"->",
"name",
";",
"$",
"this",
"->",
"pool",
"->",
"findAndModify",
"(",
"$",
"p",
",",
"$",
"cb",
")",
";",
"}"
] | Generation autoincrement
@param array $p Params
@param callable $cb Callback called when response received
@callback $cb ( )
@return void | [
"Generation",
"autoincrement"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Mongo/Collection.php#L307-L311 |
kakserpom/phpdaemon | PHPDaemon/Structures/PriorityQueueCallbacks.php | PriorityQueueCallbacks.executeOne | public function executeOne(...$args)
{
if ($this->isEmpty()) {
return false;
}
$cb = $this->extract();
if ($cb) {
$cb(...$args);
}
return true;
} | php | public function executeOne(...$args)
{
if ($this->isEmpty()) {
return false;
}
$cb = $this->extract();
if ($cb) {
$cb(...$args);
}
return true;
} | [
"public",
"function",
"executeOne",
"(",
"...",
"$",
"args",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEmpty",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"cb",
"=",
"$",
"this",
"->",
"extract",
"(",
")",
";",
"if",
"(",
"$",
"cb",
... | Executes one callback from the top of queue with arbitrary arguments
@param mixed ...$args Arguments
@return boolean | [
"Executes",
"one",
"callback",
"from",
"the",
"top",
"of",
"queue",
"with",
"arbitrary",
"arguments"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Structures/PriorityQueueCallbacks.php#L66-L76 |
kakserpom/phpdaemon | PHPDaemon/Structures/PriorityQueueCallbacks.php | PriorityQueueCallbacks.executeAll | public function executeAll(...$args)
{
if ($this->isEmpty()) {
return 0;
}
$n = 0;
do {
$cb = $this->extract();
if ($cb) {
$cb(...$args);
++$n;
}
} while (!$this->isEmpty());
return $n;
} | php | public function executeAll(...$args)
{
if ($this->isEmpty()) {
return 0;
}
$n = 0;
do {
$cb = $this->extract();
if ($cb) {
$cb(...$args);
++$n;
}
} while (!$this->isEmpty());
return $n;
} | [
"public",
"function",
"executeAll",
"(",
"...",
"$",
"args",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEmpty",
"(",
")",
")",
"{",
"return",
"0",
";",
"}",
"$",
"n",
"=",
"0",
";",
"do",
"{",
"$",
"cb",
"=",
"$",
"this",
"->",
"extract",
"("... | Executes all callbacks from the top of queue to bottom with arbitrary arguments
@param mixed ...$args Arguments
@return integer | [
"Executes",
"all",
"callbacks",
"from",
"the",
"top",
"of",
"queue",
"to",
"bottom",
"with",
"arbitrary",
"arguments"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Structures/PriorityQueueCallbacks.php#L83-L97 |
kakserpom/phpdaemon | PHPDaemon/Clients/WebSocket/Connection.php | Connection.onReady | public function onReady()
{
$this->setWatermark(2, $this->pool->maxAllowedPacket);
Crypt::randomString(16, null, function ($string) {
$this->key = base64_encode($string);
$this->write('GET /' . $this->path . " HTTP/1.1\r\nHost: " . $this->host . ($this->port != 80 ? ':' . $this->port : '') . "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " . $this->key . "\r\nSec-WebSocket-Version: 13\r\n\r\n");
});
} | php | public function onReady()
{
$this->setWatermark(2, $this->pool->maxAllowedPacket);
Crypt::randomString(16, null, function ($string) {
$this->key = base64_encode($string);
$this->write('GET /' . $this->path . " HTTP/1.1\r\nHost: " . $this->host . ($this->port != 80 ? ':' . $this->port : '') . "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " . $this->key . "\r\nSec-WebSocket-Version: 13\r\n\r\n");
});
} | [
"public",
"function",
"onReady",
"(",
")",
"{",
"$",
"this",
"->",
"setWatermark",
"(",
"2",
",",
"$",
"this",
"->",
"pool",
"->",
"maxAllowedPacket",
")",
";",
"Crypt",
"::",
"randomString",
"(",
"16",
",",
"null",
",",
"function",
"(",
"$",
"string",... | 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/WebSocket/Connection.php#L73-L80 |
kakserpom/phpdaemon | PHPDaemon/Clients/WebSocket/Connection.php | Connection.onRead | public function onRead()
{
start:
if ($this->state === static::STATE_HEADER) {
$l = $this->getInputLength();
if ($l < 2) {
return;
}
$hdr = $this->look(2);
$fb = Binary::getbitmap(ord($hdr));
$fin = (bool)$fb{0};
$opCode = bindec(substr($fb, 4, 4));
if (isset($this->opCodes[$opCode])) {
$this->type = $this->opCodes[$opCode];
} else {
$this->log('opCode: ' . $opCode . ': unknown frame type');
$this->finish();
return;
}
$sb = ord(mb_orig_substr($hdr, 1));
$sbm = Binary::getbitmap($sb);
$this->isMasked = (bool)$sbm{0};
$payloadLength = $sb & 127;
if ($payloadLength <= 125) {
$this->drain(2);
$this->pctLength = $payloadLength;
} elseif ($payloadLength === 126) {
if ($l < 4) {
return;
}
$this->drain(2);
$this->pctLength = Binary::b2i($this->read(2));
} elseif ($payloadLength === 127) {
if ($l < 10) {
return;
}
$this->drain(2);
$this->pctLength = Binary::b2i($this->read(8));
}
if ($this->pool->maxAllowedPacket < $this->pctLength) {
Daemon::$process->log('max-allowed-packet (' . $this->pool->config->maxallowedpacket->getHumanValue() . ') exceed, aborting connection');
$this->finish();
return;
}
$this->setWatermark($this->pctLength + ($this->isMasked ? 4 : 0));
$this->state = static::STATE_DATA;
}
if ($this->state === static::STATE_DATA) {
if ($this->getInputLength() < $this->pctLength + ($this->isMasked ? 4 : 0)) {
return;
}
$this->state = static::STATE_HEADER;
$this->setWatermark(2);
if ($this->isMasked) {
$this->trigger('frame', static::mask($this->read(4), $this->read($this->pctLength)));
} else {
$this->trigger('frame', $this->read($this->pctLength));
}
}
if ($this->state === static::STATE_STANDBY) {
while (($line = $this->readLine()) !== null) {
$line = trim($line);
if ($line === '') {
$expectedKey = base64_encode(pack('H*', sha1($this->key . static::GUID)));
if (isset($this->headers['HTTP_SEC_WEBSOCKET_ACCEPT']) && $expectedKey === $this->headers['HTTP_SEC_WEBSOCKET_ACCEPT']) {
$this->state = static::STATE_HEADER;
if ($this->onConnected) {
$this->connected = true;
$this->onConnected->executeAll($this);
$this->onConnected = null;
}
$this->trigger('connected');
goto start;
} else {
Daemon::$process->log(__METHOD__ . ': Handshake failed. Connection to ' . $this->url . ' failed.');
$this->finish();
}
} else {
$e = explode(': ', $line);
if (isset($e[1])) {
$this->headers['HTTP_' . strtoupper(strtr($e[0], ['-' => '_']))] = $e[1];
}
}
}
return;
}
goto start;
} | php | public function onRead()
{
start:
if ($this->state === static::STATE_HEADER) {
$l = $this->getInputLength();
if ($l < 2) {
return;
}
$hdr = $this->look(2);
$fb = Binary::getbitmap(ord($hdr));
$fin = (bool)$fb{0};
$opCode = bindec(substr($fb, 4, 4));
if (isset($this->opCodes[$opCode])) {
$this->type = $this->opCodes[$opCode];
} else {
$this->log('opCode: ' . $opCode . ': unknown frame type');
$this->finish();
return;
}
$sb = ord(mb_orig_substr($hdr, 1));
$sbm = Binary::getbitmap($sb);
$this->isMasked = (bool)$sbm{0};
$payloadLength = $sb & 127;
if ($payloadLength <= 125) {
$this->drain(2);
$this->pctLength = $payloadLength;
} elseif ($payloadLength === 126) {
if ($l < 4) {
return;
}
$this->drain(2);
$this->pctLength = Binary::b2i($this->read(2));
} elseif ($payloadLength === 127) {
if ($l < 10) {
return;
}
$this->drain(2);
$this->pctLength = Binary::b2i($this->read(8));
}
if ($this->pool->maxAllowedPacket < $this->pctLength) {
Daemon::$process->log('max-allowed-packet (' . $this->pool->config->maxallowedpacket->getHumanValue() . ') exceed, aborting connection');
$this->finish();
return;
}
$this->setWatermark($this->pctLength + ($this->isMasked ? 4 : 0));
$this->state = static::STATE_DATA;
}
if ($this->state === static::STATE_DATA) {
if ($this->getInputLength() < $this->pctLength + ($this->isMasked ? 4 : 0)) {
return;
}
$this->state = static::STATE_HEADER;
$this->setWatermark(2);
if ($this->isMasked) {
$this->trigger('frame', static::mask($this->read(4), $this->read($this->pctLength)));
} else {
$this->trigger('frame', $this->read($this->pctLength));
}
}
if ($this->state === static::STATE_STANDBY) {
while (($line = $this->readLine()) !== null) {
$line = trim($line);
if ($line === '') {
$expectedKey = base64_encode(pack('H*', sha1($this->key . static::GUID)));
if (isset($this->headers['HTTP_SEC_WEBSOCKET_ACCEPT']) && $expectedKey === $this->headers['HTTP_SEC_WEBSOCKET_ACCEPT']) {
$this->state = static::STATE_HEADER;
if ($this->onConnected) {
$this->connected = true;
$this->onConnected->executeAll($this);
$this->onConnected = null;
}
$this->trigger('connected');
goto start;
} else {
Daemon::$process->log(__METHOD__ . ': Handshake failed. Connection to ' . $this->url . ' failed.');
$this->finish();
}
} else {
$e = explode(': ', $line);
if (isset($e[1])) {
$this->headers['HTTP_' . strtoupper(strtr($e[0], ['-' => '_']))] = $e[1];
}
}
}
return;
}
goto start;
} | [
"public",
"function",
"onRead",
"(",
")",
"{",
"start",
":",
"if",
"(",
"$",
"this",
"->",
"state",
"===",
"static",
"::",
"STATE_HEADER",
")",
"{",
"$",
"l",
"=",
"$",
"this",
"->",
"getInputLength",
"(",
")",
";",
"if",
"(",
"$",
"l",
"<",
"2",... | Called when new data received
@return void | [
"Called",
"when",
"new",
"data",
"received"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/WebSocket/Connection.php#L86-L177 |
kakserpom/phpdaemon | PHPDaemon/Clients/WebSocket/Connection.php | Connection.sendFrame | public function sendFrame($payload, $type = Pool::TYPE_TEXT, $isMasked = true)
{
$payloadLength = mb_orig_strlen($payload);
if ($payloadLength > $this->pool->maxAllowedPacket) {
Daemon::$process->log('max-allowed-packet (' . $this->pool->config->maxallowedpacket->getHumanValue() . ') exceed, aborting connection');
return;
}
$firstByte = '';
switch ($type) {
case Pool::TYPE_TEXT:
$firstByte = 129;
break;
case Pool::TYPE_CLOSE:
$firstByte = 136;
break;
case Pool::TYPE_PING:
$firstByte = 137;
break;
case Pool::TYPE_PONG:
$firstByte = 138;
break;
}
$hdrPacket = chr($firstByte);
$isMaskedInt = $isMasked ? 128 : 0;
if ($payloadLength <= 125) {
$hdrPacket .= chr($payloadLength + $isMaskedInt);
} elseif ($payloadLength <= 65535) {
$hdrPacket .= chr(126 + $isMaskedInt) . // 126 + 128
chr($payloadLength >> 8) .
chr($payloadLength & 0xFF);
} else {
$hdrPacket .= chr(127 + $isMaskedInt) . // 127 + 128
chr($payloadLength >> 56) .
chr($payloadLength >> 48) .
chr($payloadLength >> 40) .
chr($payloadLength >> 32) .
chr($payloadLength >> 24) .
chr($payloadLength >> 16) .
chr($payloadLength >> 8) .
chr($payloadLength & 0xFF);
}
$this->write($hdrPacket);
if ($isMasked) {
$this->write($mask = chr(mt_rand(0, 0xFF)) .
chr(mt_rand(0, 0xFF)) .
chr(mt_rand(0, 0xFF)) .
chr(mt_rand(0, 0xFF)));
$this->write(static::mask($mask, $payload));
} else {
$this->write($payload);
}
} | php | public function sendFrame($payload, $type = Pool::TYPE_TEXT, $isMasked = true)
{
$payloadLength = mb_orig_strlen($payload);
if ($payloadLength > $this->pool->maxAllowedPacket) {
Daemon::$process->log('max-allowed-packet (' . $this->pool->config->maxallowedpacket->getHumanValue() . ') exceed, aborting connection');
return;
}
$firstByte = '';
switch ($type) {
case Pool::TYPE_TEXT:
$firstByte = 129;
break;
case Pool::TYPE_CLOSE:
$firstByte = 136;
break;
case Pool::TYPE_PING:
$firstByte = 137;
break;
case Pool::TYPE_PONG:
$firstByte = 138;
break;
}
$hdrPacket = chr($firstByte);
$isMaskedInt = $isMasked ? 128 : 0;
if ($payloadLength <= 125) {
$hdrPacket .= chr($payloadLength + $isMaskedInt);
} elseif ($payloadLength <= 65535) {
$hdrPacket .= chr(126 + $isMaskedInt) . // 126 + 128
chr($payloadLength >> 8) .
chr($payloadLength & 0xFF);
} else {
$hdrPacket .= chr(127 + $isMaskedInt) . // 127 + 128
chr($payloadLength >> 56) .
chr($payloadLength >> 48) .
chr($payloadLength >> 40) .
chr($payloadLength >> 32) .
chr($payloadLength >> 24) .
chr($payloadLength >> 16) .
chr($payloadLength >> 8) .
chr($payloadLength & 0xFF);
}
$this->write($hdrPacket);
if ($isMasked) {
$this->write($mask = chr(mt_rand(0, 0xFF)) .
chr(mt_rand(0, 0xFF)) .
chr(mt_rand(0, 0xFF)) .
chr(mt_rand(0, 0xFF)));
$this->write(static::mask($mask, $payload));
} else {
$this->write($payload);
}
} | [
"public",
"function",
"sendFrame",
"(",
"$",
"payload",
",",
"$",
"type",
"=",
"Pool",
"::",
"TYPE_TEXT",
",",
"$",
"isMasked",
"=",
"true",
")",
"{",
"$",
"payloadLength",
"=",
"mb_orig_strlen",
"(",
"$",
"payload",
")",
";",
"if",
"(",
"$",
"payloadL... | Send frame to WebSocket server
@param string $payload
@param string $type
@param boolean $isMasked | [
"Send",
"frame",
"to",
"WebSocket",
"server"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/WebSocket/Connection.php#L185-L239 |
kakserpom/phpdaemon | PHPDaemon/Clients/XMPP/XMPPRoster.php | XMPPRoster._addContact | public function _addContact($jid, $subscription, $name = '', $groups = [])
{
$contact = ['jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups];
if ($this->isContact($jid)) {
$this->roster_array[$jid]['contact'] = $contact;
} else {
$this->roster_array[$jid] = ['contact' => $contact];
}
} | php | public function _addContact($jid, $subscription, $name = '', $groups = [])
{
$contact = ['jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups];
if ($this->isContact($jid)) {
$this->roster_array[$jid]['contact'] = $contact;
} else {
$this->roster_array[$jid] = ['contact' => $contact];
}
} | [
"public",
"function",
"_addContact",
"(",
"$",
"jid",
",",
"$",
"subscription",
",",
"$",
"name",
"=",
"''",
",",
"$",
"groups",
"=",
"[",
"]",
")",
"{",
"$",
"contact",
"=",
"[",
"'jid'",
"=>",
"$",
"jid",
",",
"'subscription'",
"=>",
"$",
"subscr... | Add given contact to roster
@param string $jid
@param string $subscription
@param string $name
@param array $groups | [
"Add",
"given",
"contact",
"to",
"roster"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/XMPP/XMPPRoster.php#L116-L124 |
kakserpom/phpdaemon | PHPDaemon/SockJS/Methods/Iframe.php | Iframe.init | public function init()
{
parent::init();
if (isset($this->attrs->version)) {
$this->version = $this->attrs->version;
}
$this->header('Cache-Control: max-age=31536000, public, pre-check=0, post-check=0');
$this->header('Expires: ' . date('r', strtotime('+1 year')));
$html = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
document.domain = document.domain;
_sockjs_onload = function(){SockJS.bootstrap_iframe();};
</script>
<script src="https://cdn.jsdelivr.net/sockjs/' . htmlentities($this->version, ENT_QUOTES, 'UTF-8') . '/sockjs.min.js"></script>
</head>
<body>
<h2>Don\'t panic!</h2>
<p>This is a SockJS hidden iframe. It\'s used for cross domain magic.</p>
</body>
</html>';
$etag = 'W/"' . sha1($html) . '"';
$this->header('ETag: ' . $etag);
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
if ($_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
$this->status(304);
$this->removeHeader('Content-Type');
$this->finish();
return;
}
}
$this->header('Content-Length: ' . mb_orig_strlen($html));
echo $html;
$this->finish();
} | php | public function init()
{
parent::init();
if (isset($this->attrs->version)) {
$this->version = $this->attrs->version;
}
$this->header('Cache-Control: max-age=31536000, public, pre-check=0, post-check=0');
$this->header('Expires: ' . date('r', strtotime('+1 year')));
$html = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
document.domain = document.domain;
_sockjs_onload = function(){SockJS.bootstrap_iframe();};
</script>
<script src="https://cdn.jsdelivr.net/sockjs/' . htmlentities($this->version, ENT_QUOTES, 'UTF-8') . '/sockjs.min.js"></script>
</head>
<body>
<h2>Don\'t panic!</h2>
<p>This is a SockJS hidden iframe. It\'s used for cross domain magic.</p>
</body>
</html>';
$etag = 'W/"' . sha1($html) . '"';
$this->header('ETag: ' . $etag);
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
if ($_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
$this->status(304);
$this->removeHeader('Content-Type');
$this->finish();
return;
}
}
$this->header('Content-Length: ' . mb_orig_strlen($html));
echo $html;
$this->finish();
} | [
"public",
"function",
"init",
"(",
")",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attrs",
"->",
"version",
")",
")",
"{",
"$",
"this",
"->",
"version",
"=",
"$",
"this",
"->",
"attrs",
"->",
"version... | Constructor
@return void | [
"Constructor"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/SockJS/Methods/Iframe.php#L19-L56 |
kakserpom/phpdaemon | PHPDaemon/Core/Bootstrap.php | Bootstrap.init | public static function init($configFile = null)
{
if (!version_compare(PHP_VERSION, '5.6.0', '>=')) {
Daemon::log('PHP >= 5.6.0 required.');
return;
}
//run without composer
if (!function_exists('setTimeout')) {
require 'PHPDaemon/Utils/func.php';
}
Daemon::initSettings();
FileSystem::init();
Daemon::$runName = basename($_SERVER['argv'][0]);
$error = false;
$argv = $_SERVER['argv'];
$runmode = isset($argv[1]) ? str_replace('-', '', $argv[1]) : '';
$args = Bootstrap::getArgs($argv);
if (!isset(self::$params[$runmode]) && !in_array($runmode, self::$commands)) {
if ('' !== $runmode) {
echo('Unrecognized command: ' . $runmode . "\n");
}
self::printUsage();
exit;
} elseif ('help' === $runmode) {
self::printHelp();
exit;
}
$n = null;
if ('log' === $runmode) {
if (isset($args['n'])) {
$n = $args['n'];
unset($args['n']);
} else {
$n = 20;
}
}
if (isset($configFile)) {
Daemon::$config->configfile->setHumanValue($configFile);
}
if (isset($args['configfile'])) {
Daemon::$config->configfile->setHumanValue($args['configfile']);
}
if (!Daemon::$config->loadCmdLineArgs($args)) {
$error = true;
}
if (!Daemon::loadConfig(Daemon::$config->configfile->value)) {
$error = true;
}
if ('log' === $runmode) {
passthru('tail -n ' . $n . ' -f ' . escapeshellarg(Daemon::$config->logstorage->value));
exit;
}
if (extension_loaded('apc') && ini_get('apc.enabled')) {
Daemon::log('Detected pecl-apc extension enabled. Usage of bytecode caching (APC/eAccelerator/xcache/...) makes no sense at all in case of using phpDaemon \'cause phpDaemon includes files just in time itself.');
}
if (isset(Daemon::$config->locale->value) && Daemon::$config->locale->value !== '') {
setlocale(LC_ALL, array_map('trim', explode(',', Daemon::$config->locale->value)));
}
if (Daemon::$config->autoreimport->value && !is_callable('runkit_import')) {
Daemon::log('[WARN] runkit extension not found. You should install it or disable --auto-reimport. Non-critical error.');
}
if (!is_callable('posix_kill')) {
Daemon::log('[EMERG] Posix not found. You should compile PHP without \'--disable-posix\'.');
$error = true;
}
if (!is_callable('pcntl_signal')) {
Daemon::log('[EMERG] PCNTL not found. You should compile PHP with \'--enable-pcntl\'.');
$error = true;
}
if (extension_loaded('libevent')) {
Daemon::log('[EMERG] libevent extension found. You have to remove libevent.so extension.');
$error = true;
}
$eventVer = '1.6.1';
$eventVerType = 'stable';
if (!Daemon::loadModuleIfAbsent('event', $eventVer . '-' . $eventVerType)) {
Daemon::log('[EMERG] event extension >= ' . $eventVer . ' not found (or OUTDATED). You have to install it. `pecl install http://pecl.php.net/get/event`');
$error = true;
}
if (!is_callable('socket_create')) {
Daemon::log('[EMERG] Sockets extension not found. You should compile PHP with \'--enable-sockets\'.');
$error = true;
}
if (!is_callable('shmop_open')) {
Daemon::log('[EMERG] Shmop extension not found. You should compile PHP with \'--enable-shmop\'.');
$error = true;
}
if (!isset(Daemon::$config->user)) {
Daemon::log('[EMERG] You must set \'user\' parameter.');
$error = true;
}
if (!isset(Daemon::$config->path)) {
Daemon::log('[EMERG] You must set \'path\' parameter (path to your application resolver).');
$error = true;
}
if (!file_exists(Daemon::$config->pidfile->value)) {
if (!touch(Daemon::$config->pidfile->value)) {
Daemon::log('[EMERG] Couldn\'t create pid-file \'' . Daemon::$config->pidfile->value . '\'.');
$error = true;
}
Bootstrap::$pid = 0;
} elseif (!is_file(Daemon::$config->pidfile->value)) {
Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be a regular file.');
Bootstrap::$pid = false;
$error = true;
} elseif (!is_writable(Daemon::$config->pidfile->value)) {
Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be writable.');
$error = true;
} elseif (!is_readable(Daemon::$config->pidfile->value)) {
Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be readable.');
Bootstrap::$pid = false;
$error = true;
} else {
Bootstrap::$pid = (int)file_get_contents(Daemon::$config->pidfile->value);
}
if (Daemon::$config->chroot->value !== '/') {
if (posix_getuid() != 0) {
Daemon::log('You must have the root privileges to change root.');
$error = true;
}
}
$pathList = preg_split('~\s*;\s*~', Daemon::$config->path->value);
$found = false;
foreach ($pathList as $path) {
if (@is_file($path)) {
Daemon::$appResolverPath = $path;
$found = true;
break;
}
}
if (!$found) {
Daemon::log('Your application resolver \'' . Daemon::$config->path->value . '\' is not available (config directive \'path\').');
$error = true;
}
Daemon::$appResolver = require Daemon::$appResolverPath;
if (isset(Daemon::$config->group->value) && is_callable('posix_getgid')) {
if (($sg = posix_getgrnam(Daemon::$config->group->value)) === false) {
Daemon::log('Unexisting group \'' . Daemon::$config->group->value . '\'. You have to replace config-variable \'group\' with existing group-name.');
$error = true;
} elseif (($sg['gid'] != posix_getgid()) && (posix_getuid() != 0)) {
Daemon::log('You must have the root privileges to change group.');
$error = true;
}
}
if (isset(Daemon::$config->user->value) && is_callable('posix_getuid')) {
if (($su = posix_getpwnam(Daemon::$config->user->value)) === false) {
Daemon::log('Unexisting user \'' . Daemon::$config->user->value . '\', user not found. You have to replace config-variable \'user\' with existing username.');
$error = true;
} elseif (($su['uid'] != posix_getuid()) && (posix_getuid() != 0)) {
Daemon::log('You must have the root privileges to change user.');
$error = true;
}
}
if (isset(Daemon::$config->minspareworkers->value)
&& Daemon::$config->minspareworkers->value > 0
&& isset(Daemon::$config->maxspareworkers->value)
&& Daemon::$config->maxspareworkers->value > 0
) {
if (Daemon::$config->minspareworkers->value > Daemon::$config->maxspareworkers->value) {
Daemon::log('\'minspareworkers\' cannot be greater than \'maxspareworkers\'.');
$error = true;
}
}
if (isset(Daemon::$config->addincludepath->value)) {
ini_set(
'include_path',
ini_get('include_path') . ':' . implode(':', Daemon::$config->addincludepath->value)
);
}
if (isset(Daemon::$config->minworkers->value) && isset(Daemon::$config->maxworkers->value)) {
if (Daemon::$config->minworkers->value > Daemon::$config->maxworkers->value) {
Daemon::$config->minworkers->value = Daemon::$config->maxworkers->value;
}
}
if ($runmode === 'start') {
if ($error === false) {
Bootstrap::start();
} else {
exit(6);
}
} elseif ($runmode === 'runworker') {
if ($error === false) {
Bootstrap::runworker();
} else {
exit(6);
}
} elseif ($runmode === 'status' || $runmode === 'fullstatus') {
$status = Bootstrap::$pid && Thread\Generic::ifExistsByPid(Bootstrap::$pid);
echo '[STATUS] phpDaemon ' . Daemon::$version . ' is ' . ($status ? 'running' : 'NOT running') . ' (' . Daemon::$config->pidfile->value . ").\n";
if ($status && ($runmode === 'fullstatus')) {
echo 'Uptime: ' . DateTime::diffAsText(filemtime(Daemon::$config->pidfile->value), time()) . "\n";
Daemon::$shm_wstate = new ShmEntity(Daemon::$config->pidfile->value, Daemon::SHM_WSTATE_SIZE, 'wstate');
$stat = Daemon::getStateOfWorkers();
echo "State of workers:\n";
echo "\tTotal: " . $stat['alive'] . "\n";
echo "\tIdle: " . $stat['idle'] . "\n";
echo "\tBusy: " . $stat['busy'] . "\n";
echo "\tShutdown: " . $stat['shutdown'] . "\n";
echo "\tPre-init: " . $stat['preinit'] . "\n";
echo "\tInit: " . $stat['init'] . "\n";
}
echo "\n";
} elseif ($runmode === 'update') {
if ((!Bootstrap::$pid) || (!posix_kill(Bootstrap::$pid, SIGHUP))) {
echo '[UPDATE] ERROR. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
} elseif ($runmode === 'reopenlog') {
if ((!Bootstrap::$pid) || (!posix_kill(Bootstrap::$pid, SIGUSR1))) {
echo '[REOPEN-LOG] ERROR. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
} elseif ($runmode === 'reload') {
if ((!Bootstrap::$pid) || (!posix_kill(Bootstrap::$pid, SIGUSR2))) {
echo '[RELOAD] ERROR. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
} elseif ($runmode === 'restart') {
if ($error === false) {
Bootstrap::stop(2);
Bootstrap::start();
}
} elseif ($runmode === 'hardrestart') {
Bootstrap::stop(3);
Bootstrap::start();
} elseif ($runmode === 'ipcpath') {
$i = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager');
echo $i->getSocketUrl() . PHP_EOL;
} elseif ($runmode === 'configtest') {
$term = new Terminal;
$term->enableColor();
echo "\n";
$rows = [];
$rows[] = [
'parameter' => 'PARAMETER',
'value' => 'VALUE',
'_color' => '37',
'_bold' => true,
];
foreach (Daemon::$config as $name => $entry) {
if (!$entry instanceof Generic) {
continue;
}
$row = [
'parameter' => $name,
'value' => var_export($entry->humanValue, true),
];
if ($entry->defaultValue != $entry->humanValue) {
$row['value'] .= ' (' . var_export($entry->defaultValue, true) . ')';
}
$rows[] = $row;
}
$term->drawtable($rows);
echo "\n";
} elseif ($runmode === 'stop') {
Bootstrap::stop();
} elseif ($runmode === 'gracefulstop') {
Bootstrap::stop(4);
} elseif ($runmode === 'hardstop') {
echo '[HARDSTOP] Sending SIGINT to ' . Bootstrap::$pid . '... ';
$ok = Bootstrap::$pid && posix_kill(Bootstrap::$pid, SIGINT);
echo $ok ? 'OK.' : 'ERROR. It seems that phpDaemon is not running.';
if ($ok) {
$i = 0;
while ($r = Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
usleep(500000);
if ($i === 9) {
echo "\nphpDaemon master-process hasn't finished. Sending SIGKILL... ";
posix_kill(Bootstrap::$pid, SIGKILL);
sleep(0.2);
if (!Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
echo " Oh, his blood is on my hands :'(";
} else {
echo "ERROR: Process alive. Permissions?";
}
break;
}
++$i;
}
}
echo "\n";
}
} | php | public static function init($configFile = null)
{
if (!version_compare(PHP_VERSION, '5.6.0', '>=')) {
Daemon::log('PHP >= 5.6.0 required.');
return;
}
//run without composer
if (!function_exists('setTimeout')) {
require 'PHPDaemon/Utils/func.php';
}
Daemon::initSettings();
FileSystem::init();
Daemon::$runName = basename($_SERVER['argv'][0]);
$error = false;
$argv = $_SERVER['argv'];
$runmode = isset($argv[1]) ? str_replace('-', '', $argv[1]) : '';
$args = Bootstrap::getArgs($argv);
if (!isset(self::$params[$runmode]) && !in_array($runmode, self::$commands)) {
if ('' !== $runmode) {
echo('Unrecognized command: ' . $runmode . "\n");
}
self::printUsage();
exit;
} elseif ('help' === $runmode) {
self::printHelp();
exit;
}
$n = null;
if ('log' === $runmode) {
if (isset($args['n'])) {
$n = $args['n'];
unset($args['n']);
} else {
$n = 20;
}
}
if (isset($configFile)) {
Daemon::$config->configfile->setHumanValue($configFile);
}
if (isset($args['configfile'])) {
Daemon::$config->configfile->setHumanValue($args['configfile']);
}
if (!Daemon::$config->loadCmdLineArgs($args)) {
$error = true;
}
if (!Daemon::loadConfig(Daemon::$config->configfile->value)) {
$error = true;
}
if ('log' === $runmode) {
passthru('tail -n ' . $n . ' -f ' . escapeshellarg(Daemon::$config->logstorage->value));
exit;
}
if (extension_loaded('apc') && ini_get('apc.enabled')) {
Daemon::log('Detected pecl-apc extension enabled. Usage of bytecode caching (APC/eAccelerator/xcache/...) makes no sense at all in case of using phpDaemon \'cause phpDaemon includes files just in time itself.');
}
if (isset(Daemon::$config->locale->value) && Daemon::$config->locale->value !== '') {
setlocale(LC_ALL, array_map('trim', explode(',', Daemon::$config->locale->value)));
}
if (Daemon::$config->autoreimport->value && !is_callable('runkit_import')) {
Daemon::log('[WARN] runkit extension not found. You should install it or disable --auto-reimport. Non-critical error.');
}
if (!is_callable('posix_kill')) {
Daemon::log('[EMERG] Posix not found. You should compile PHP without \'--disable-posix\'.');
$error = true;
}
if (!is_callable('pcntl_signal')) {
Daemon::log('[EMERG] PCNTL not found. You should compile PHP with \'--enable-pcntl\'.');
$error = true;
}
if (extension_loaded('libevent')) {
Daemon::log('[EMERG] libevent extension found. You have to remove libevent.so extension.');
$error = true;
}
$eventVer = '1.6.1';
$eventVerType = 'stable';
if (!Daemon::loadModuleIfAbsent('event', $eventVer . '-' . $eventVerType)) {
Daemon::log('[EMERG] event extension >= ' . $eventVer . ' not found (or OUTDATED). You have to install it. `pecl install http://pecl.php.net/get/event`');
$error = true;
}
if (!is_callable('socket_create')) {
Daemon::log('[EMERG] Sockets extension not found. You should compile PHP with \'--enable-sockets\'.');
$error = true;
}
if (!is_callable('shmop_open')) {
Daemon::log('[EMERG] Shmop extension not found. You should compile PHP with \'--enable-shmop\'.');
$error = true;
}
if (!isset(Daemon::$config->user)) {
Daemon::log('[EMERG] You must set \'user\' parameter.');
$error = true;
}
if (!isset(Daemon::$config->path)) {
Daemon::log('[EMERG] You must set \'path\' parameter (path to your application resolver).');
$error = true;
}
if (!file_exists(Daemon::$config->pidfile->value)) {
if (!touch(Daemon::$config->pidfile->value)) {
Daemon::log('[EMERG] Couldn\'t create pid-file \'' . Daemon::$config->pidfile->value . '\'.');
$error = true;
}
Bootstrap::$pid = 0;
} elseif (!is_file(Daemon::$config->pidfile->value)) {
Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be a regular file.');
Bootstrap::$pid = false;
$error = true;
} elseif (!is_writable(Daemon::$config->pidfile->value)) {
Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be writable.');
$error = true;
} elseif (!is_readable(Daemon::$config->pidfile->value)) {
Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be readable.');
Bootstrap::$pid = false;
$error = true;
} else {
Bootstrap::$pid = (int)file_get_contents(Daemon::$config->pidfile->value);
}
if (Daemon::$config->chroot->value !== '/') {
if (posix_getuid() != 0) {
Daemon::log('You must have the root privileges to change root.');
$error = true;
}
}
$pathList = preg_split('~\s*;\s*~', Daemon::$config->path->value);
$found = false;
foreach ($pathList as $path) {
if (@is_file($path)) {
Daemon::$appResolverPath = $path;
$found = true;
break;
}
}
if (!$found) {
Daemon::log('Your application resolver \'' . Daemon::$config->path->value . '\' is not available (config directive \'path\').');
$error = true;
}
Daemon::$appResolver = require Daemon::$appResolverPath;
if (isset(Daemon::$config->group->value) && is_callable('posix_getgid')) {
if (($sg = posix_getgrnam(Daemon::$config->group->value)) === false) {
Daemon::log('Unexisting group \'' . Daemon::$config->group->value . '\'. You have to replace config-variable \'group\' with existing group-name.');
$error = true;
} elseif (($sg['gid'] != posix_getgid()) && (posix_getuid() != 0)) {
Daemon::log('You must have the root privileges to change group.');
$error = true;
}
}
if (isset(Daemon::$config->user->value) && is_callable('posix_getuid')) {
if (($su = posix_getpwnam(Daemon::$config->user->value)) === false) {
Daemon::log('Unexisting user \'' . Daemon::$config->user->value . '\', user not found. You have to replace config-variable \'user\' with existing username.');
$error = true;
} elseif (($su['uid'] != posix_getuid()) && (posix_getuid() != 0)) {
Daemon::log('You must have the root privileges to change user.');
$error = true;
}
}
if (isset(Daemon::$config->minspareworkers->value)
&& Daemon::$config->minspareworkers->value > 0
&& isset(Daemon::$config->maxspareworkers->value)
&& Daemon::$config->maxspareworkers->value > 0
) {
if (Daemon::$config->minspareworkers->value > Daemon::$config->maxspareworkers->value) {
Daemon::log('\'minspareworkers\' cannot be greater than \'maxspareworkers\'.');
$error = true;
}
}
if (isset(Daemon::$config->addincludepath->value)) {
ini_set(
'include_path',
ini_get('include_path') . ':' . implode(':', Daemon::$config->addincludepath->value)
);
}
if (isset(Daemon::$config->minworkers->value) && isset(Daemon::$config->maxworkers->value)) {
if (Daemon::$config->minworkers->value > Daemon::$config->maxworkers->value) {
Daemon::$config->minworkers->value = Daemon::$config->maxworkers->value;
}
}
if ($runmode === 'start') {
if ($error === false) {
Bootstrap::start();
} else {
exit(6);
}
} elseif ($runmode === 'runworker') {
if ($error === false) {
Bootstrap::runworker();
} else {
exit(6);
}
} elseif ($runmode === 'status' || $runmode === 'fullstatus') {
$status = Bootstrap::$pid && Thread\Generic::ifExistsByPid(Bootstrap::$pid);
echo '[STATUS] phpDaemon ' . Daemon::$version . ' is ' . ($status ? 'running' : 'NOT running') . ' (' . Daemon::$config->pidfile->value . ").\n";
if ($status && ($runmode === 'fullstatus')) {
echo 'Uptime: ' . DateTime::diffAsText(filemtime(Daemon::$config->pidfile->value), time()) . "\n";
Daemon::$shm_wstate = new ShmEntity(Daemon::$config->pidfile->value, Daemon::SHM_WSTATE_SIZE, 'wstate');
$stat = Daemon::getStateOfWorkers();
echo "State of workers:\n";
echo "\tTotal: " . $stat['alive'] . "\n";
echo "\tIdle: " . $stat['idle'] . "\n";
echo "\tBusy: " . $stat['busy'] . "\n";
echo "\tShutdown: " . $stat['shutdown'] . "\n";
echo "\tPre-init: " . $stat['preinit'] . "\n";
echo "\tInit: " . $stat['init'] . "\n";
}
echo "\n";
} elseif ($runmode === 'update') {
if ((!Bootstrap::$pid) || (!posix_kill(Bootstrap::$pid, SIGHUP))) {
echo '[UPDATE] ERROR. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
} elseif ($runmode === 'reopenlog') {
if ((!Bootstrap::$pid) || (!posix_kill(Bootstrap::$pid, SIGUSR1))) {
echo '[REOPEN-LOG] ERROR. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
} elseif ($runmode === 'reload') {
if ((!Bootstrap::$pid) || (!posix_kill(Bootstrap::$pid, SIGUSR2))) {
echo '[RELOAD] ERROR. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
} elseif ($runmode === 'restart') {
if ($error === false) {
Bootstrap::stop(2);
Bootstrap::start();
}
} elseif ($runmode === 'hardrestart') {
Bootstrap::stop(3);
Bootstrap::start();
} elseif ($runmode === 'ipcpath') {
$i = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager');
echo $i->getSocketUrl() . PHP_EOL;
} elseif ($runmode === 'configtest') {
$term = new Terminal;
$term->enableColor();
echo "\n";
$rows = [];
$rows[] = [
'parameter' => 'PARAMETER',
'value' => 'VALUE',
'_color' => '37',
'_bold' => true,
];
foreach (Daemon::$config as $name => $entry) {
if (!$entry instanceof Generic) {
continue;
}
$row = [
'parameter' => $name,
'value' => var_export($entry->humanValue, true),
];
if ($entry->defaultValue != $entry->humanValue) {
$row['value'] .= ' (' . var_export($entry->defaultValue, true) . ')';
}
$rows[] = $row;
}
$term->drawtable($rows);
echo "\n";
} elseif ($runmode === 'stop') {
Bootstrap::stop();
} elseif ($runmode === 'gracefulstop') {
Bootstrap::stop(4);
} elseif ($runmode === 'hardstop') {
echo '[HARDSTOP] Sending SIGINT to ' . Bootstrap::$pid . '... ';
$ok = Bootstrap::$pid && posix_kill(Bootstrap::$pid, SIGINT);
echo $ok ? 'OK.' : 'ERROR. It seems that phpDaemon is not running.';
if ($ok) {
$i = 0;
while ($r = Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
usleep(500000);
if ($i === 9) {
echo "\nphpDaemon master-process hasn't finished. Sending SIGKILL... ";
posix_kill(Bootstrap::$pid, SIGKILL);
sleep(0.2);
if (!Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
echo " Oh, his blood is on my hands :'(";
} else {
echo "ERROR: Process alive. Permissions?";
}
break;
}
++$i;
}
}
echo "\n";
}
} | [
"public",
"static",
"function",
"init",
"(",
"$",
"configFile",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"version_compare",
"(",
"PHP_VERSION",
",",
"'5.6.0'",
",",
"'>='",
")",
")",
"{",
"Daemon",
"::",
"log",
"(",
"'PHP >= 5.6.0 required.'",
")",
";",
"r... | Actions on early startup.
@param string Optional. Config file path.
@return void | [
"Actions",
"on",
"early",
"startup",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Bootstrap.php#L101-L434 |
kakserpom/phpdaemon | PHPDaemon/Core/Bootstrap.php | Bootstrap.printHelp | protected static function printHelp()
{
$term = new Terminal();
echo 'phpDaemon ' . Daemon::$version . ". http://phpdaemon.net\n";
self::printUsage();
echo "\nAlso you can use some optional parameters to override the same configuration variables:\n";
foreach (self::$params as $name => $desc) {
if (empty($desc)) {
continue;
} elseif (!is_array($desc)) {
$term->drawParam($name, $desc);
} else {
$term->drawParam(
$name,
isset($desc['desc']) ? $desc['desc'] : '',
isset($desc['val']) ? $desc['val'] : ''
);
}
}
echo "\n";
} | php | protected static function printHelp()
{
$term = new Terminal();
echo 'phpDaemon ' . Daemon::$version . ". http://phpdaemon.net\n";
self::printUsage();
echo "\nAlso you can use some optional parameters to override the same configuration variables:\n";
foreach (self::$params as $name => $desc) {
if (empty($desc)) {
continue;
} elseif (!is_array($desc)) {
$term->drawParam($name, $desc);
} else {
$term->drawParam(
$name,
isset($desc['desc']) ? $desc['desc'] : '',
isset($desc['val']) ? $desc['val'] : ''
);
}
}
echo "\n";
} | [
"protected",
"static",
"function",
"printHelp",
"(",
")",
"{",
"$",
"term",
"=",
"new",
"Terminal",
"(",
")",
";",
"echo",
"'phpDaemon '",
".",
"Daemon",
"::",
"$",
"version",
".",
"\". http://phpdaemon.net\\n\"",
";",
"self",
"::",
"printUsage",
"(",
")",
... | Print help
@return void | [
"Print",
"help"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Bootstrap.php#L449-L474 |
kakserpom/phpdaemon | PHPDaemon/Core/Bootstrap.php | Bootstrap.start | public static function start()
{
if (Bootstrap::$pid && Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
Daemon::log('[START] phpDaemon with pid-file \'' . Daemon::$config->pidfile->value . '\' is running already (PID ' . Bootstrap::$pid . ')');
exit(6);
}
Daemon::init();
$pid = Daemon::spawnMaster();
file_put_contents(Daemon::$config->pidfile->value, $pid);
} | php | public static function start()
{
if (Bootstrap::$pid && Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
Daemon::log('[START] phpDaemon with pid-file \'' . Daemon::$config->pidfile->value . '\' is running already (PID ' . Bootstrap::$pid . ')');
exit(6);
}
Daemon::init();
$pid = Daemon::spawnMaster();
file_put_contents(Daemon::$config->pidfile->value, $pid);
} | [
"public",
"static",
"function",
"start",
"(",
")",
"{",
"if",
"(",
"Bootstrap",
"::",
"$",
"pid",
"&&",
"Thread",
"\\",
"Generic",
"::",
"ifExistsByPid",
"(",
"Bootstrap",
"::",
"$",
"pid",
")",
")",
"{",
"Daemon",
"::",
"log",
"(",
"'[START] phpDaemon w... | Start master.
@return void | [
"Start",
"master",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Bootstrap.php#L480-L490 |
kakserpom/phpdaemon | PHPDaemon/Core/Bootstrap.php | Bootstrap.stop | public static function stop($mode = 1)
{
$ok = Bootstrap::$pid && posix_kill(
Bootstrap::$pid,
$mode === 3 ? SIGINT : (($mode === 4) ? SIGTSTP : SIGTERM)
);
if (!$ok) {
echo '[WARN]. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
if ($ok && ($mode > 1)) {
$i = 0;
while ($r = Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
usleep(10000);
++$i;
}
}
} | php | public static function stop($mode = 1)
{
$ok = Bootstrap::$pid && posix_kill(
Bootstrap::$pid,
$mode === 3 ? SIGINT : (($mode === 4) ? SIGTSTP : SIGTERM)
);
if (!$ok) {
echo '[WARN]. It seems that phpDaemon is not running' . (Bootstrap::$pid ? ' (PID ' . Bootstrap::$pid . ')' : '') . ".\n";
}
if ($ok && ($mode > 1)) {
$i = 0;
while ($r = Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
usleep(10000);
++$i;
}
}
} | [
"public",
"static",
"function",
"stop",
"(",
"$",
"mode",
"=",
"1",
")",
"{",
"$",
"ok",
"=",
"Bootstrap",
"::",
"$",
"pid",
"&&",
"posix_kill",
"(",
"Bootstrap",
"::",
"$",
"pid",
",",
"$",
"mode",
"===",
"3",
"?",
"SIGINT",
":",
"(",
"(",
"$",
... | Stop script.
@param int $mode
@return void | [
"Stop",
"script",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Bootstrap.php#L508-L527 |
kakserpom/phpdaemon | PHPDaemon/Core/Bootstrap.php | Bootstrap.getArgs | public static function getArgs($args)
{
$out = [];
$last_arg = null;
for ($i = 1, $il = sizeof($args); $i < $il; ++$i) {
if (preg_match('~^--(.+)~', $args[$i], $match)) {
$parts = explode('=', $match[1]);
$key = preg_replace('~[^a-z0-9]+~', '', $parts[0]);
if (isset($parts[1])) {
$out[$key] = $parts[1];
} else {
$out[$key] = true;
}
$last_arg = $key;
} elseif (preg_match('~^-([a-zA-Z0-9]+)~', $args[$i], $match)) {
$key = null;
for ($j = 0, $jl = mb_orig_strlen($match[1]); $j < $jl; ++$j) {
$key = $match[1]{$j};
$out[$key] = true;
}
$last_arg = $key;
} elseif ($last_arg !== null) {
$out[$last_arg] = $args[$i];
}
}
return $out;
} | php | public static function getArgs($args)
{
$out = [];
$last_arg = null;
for ($i = 1, $il = sizeof($args); $i < $il; ++$i) {
if (preg_match('~^--(.+)~', $args[$i], $match)) {
$parts = explode('=', $match[1]);
$key = preg_replace('~[^a-z0-9]+~', '', $parts[0]);
if (isset($parts[1])) {
$out[$key] = $parts[1];
} else {
$out[$key] = true;
}
$last_arg = $key;
} elseif (preg_match('~^-([a-zA-Z0-9]+)~', $args[$i], $match)) {
$key = null;
for ($j = 0, $jl = mb_orig_strlen($match[1]); $j < $jl; ++$j) {
$key = $match[1]{$j};
$out[$key] = true;
}
$last_arg = $key;
} elseif ($last_arg !== null) {
$out[$last_arg] = $args[$i];
}
}
return $out;
} | [
"public",
"static",
"function",
"getArgs",
"(",
"$",
"args",
")",
"{",
"$",
"out",
"=",
"[",
"]",
";",
"$",
"last_arg",
"=",
"null",
";",
"for",
"(",
"$",
"i",
"=",
"1",
",",
"$",
"il",
"=",
"sizeof",
"(",
"$",
"args",
")",
";",
"$",
"i",
"... | Parses command-line arguments.
@param array $args $_SERVER ['argv']
@return array Arguments | [
"Parses",
"command",
"-",
"line",
"arguments",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Bootstrap.php#L534-L565 |
kakserpom/phpdaemon | PHPDaemon/SockJS/WebSocketRouteProxy.php | WebSocketRouteProxy.onFrame | public function onFrame($data, $type)
{
foreach (explode("\n", $data) as $pct) {
if ($pct === '') {
continue;
}
$pct = json_decode($pct, true);
if (isset($pct[0])) {
foreach ($pct as $i) {
$this->onPacket(rtrim($i, "\n"), $type);
}
} else {
$this->onPacket($pct, $type);
}
}
} | php | public function onFrame($data, $type)
{
foreach (explode("\n", $data) as $pct) {
if ($pct === '') {
continue;
}
$pct = json_decode($pct, true);
if (isset($pct[0])) {
foreach ($pct as $i) {
$this->onPacket(rtrim($i, "\n"), $type);
}
} else {
$this->onPacket($pct, $type);
}
}
} | [
"public",
"function",
"onFrame",
"(",
"$",
"data",
",",
"$",
"type",
")",
"{",
"foreach",
"(",
"explode",
"(",
"\"\\n\"",
",",
"$",
"data",
")",
"as",
"$",
"pct",
")",
"{",
"if",
"(",
"$",
"pct",
"===",
"''",
")",
"{",
"continue",
";",
"}",
"$"... | Called when new frame received.
@param string $data Frame's contents.
@param integer $type Frame's type.
@return void | [
"Called",
"when",
"new",
"frame",
"received",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/SockJS/WebSocketRouteProxy.php#L60-L75 |
kakserpom/phpdaemon | PHPDaemon/SockJS/WebSocketRouteProxy.php | WebSocketRouteProxy.onBeforeHandshake | public function onBeforeHandshake($cb)
{
if (!method_exists($this->realRoute, 'onBeforeHandshake')) {
return false;
}
$this->realRoute->onBeforeHandshake($cb);
} | php | public function onBeforeHandshake($cb)
{
if (!method_exists($this->realRoute, 'onBeforeHandshake')) {
return false;
}
$this->realRoute->onBeforeHandshake($cb);
} | [
"public",
"function",
"onBeforeHandshake",
"(",
"$",
"cb",
")",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
"->",
"realRoute",
",",
"'onBeforeHandshake'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"realRoute",
"->",
"onBe... | realRoute onBeforeHandshake
@param callable $cb
@return void|false | [
"realRoute",
"onBeforeHandshake"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/SockJS/WebSocketRouteProxy.php#L93-L99 |
kakserpom/phpdaemon | PHPDaemon/Clients/Memcache/Pool.php | Pool.get | public function get($key, $onResponse)
{
$this->requestByKey($key, 'get ' . $this->config->prefix->value . $key . "\r\n", $onResponse);
} | php | public function get($key, $onResponse)
{
$this->requestByKey($key, 'get ' . $this->config->prefix->value . $key . "\r\n", $onResponse);
} | [
"public",
"function",
"get",
"(",
"$",
"key",
",",
"$",
"onResponse",
")",
"{",
"$",
"this",
"->",
"requestByKey",
"(",
"$",
"key",
",",
"'get '",
".",
"$",
"this",
"->",
"config",
"->",
"prefix",
"->",
"value",
".",
"$",
"key",
".",
"\"\\r\\n\"",
... | Gets the key
@param string $key Key
@param callable $onResponse Callback called when response received
@callback $onResponse ( )
@return void | [
"Gets",
"the",
"key"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Memcache/Pool.php#L19-L22 |
kakserpom/phpdaemon | PHPDaemon/Clients/Memcache/Pool.php | Pool.set | public function set($key, $value, $exp = 0, $onResponse = null)
{
$this->getConnectionByKey($key, function ($conn) use ($key, $value, $exp, $onResponse) {
if (!$conn->connected) {
return;
}
if ($onResponse !== null) {
$conn->onResponse->push($onResponse);
$conn->checkFree();
}
$conn->writeln(
'set ' . $this->config->prefix->value . $key . ' 0 ' . $exp . ' '
. mb_orig_strlen($value) . ($onResponse === null ? ' noreply' : '') . "\r\n" . $value
);
});
} | php | public function set($key, $value, $exp = 0, $onResponse = null)
{
$this->getConnectionByKey($key, function ($conn) use ($key, $value, $exp, $onResponse) {
if (!$conn->connected) {
return;
}
if ($onResponse !== null) {
$conn->onResponse->push($onResponse);
$conn->checkFree();
}
$conn->writeln(
'set ' . $this->config->prefix->value . $key . ' 0 ' . $exp . ' '
. mb_orig_strlen($value) . ($onResponse === null ? ' noreply' : '') . "\r\n" . $value
);
});
} | [
"public",
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"exp",
"=",
"0",
",",
"$",
"onResponse",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"getConnectionByKey",
"(",
"$",
"key",
",",
"function",
"(",
"$",
"conn",
")",
"use",
"(... | Sets the key
@param string $key Key
@param string $value Value
@param integer $exp Lifetime in seconds (0 - immortal)
@param callable $onResponse Callback called when the request complete
@callback $onResponse ( )
@return void | [
"Sets",
"the",
"key"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Memcache/Pool.php#L33-L49 |
kakserpom/phpdaemon | PHPDaemon/Clients/Memcache/Pool.php | Pool.delete | public function delete($key, $onResponse = null, $time = 0)
{
$this->getConnectionByKey($key, function ($conn) use ($key, $time, $onResponse) {
if (!$conn->connected) {
return;
}
if ($onResponse !== null) {
$conn->onResponse->push($onResponse);
$conn->checkFree();
}
$conn->writeln('delete ' . $this->config->prefix->value . $key . ' ' . $time);
});
} | php | public function delete($key, $onResponse = null, $time = 0)
{
$this->getConnectionByKey($key, function ($conn) use ($key, $time, $onResponse) {
if (!$conn->connected) {
return;
}
if ($onResponse !== null) {
$conn->onResponse->push($onResponse);
$conn->checkFree();
}
$conn->writeln('delete ' . $this->config->prefix->value . $key . ' ' . $time);
});
} | [
"public",
"function",
"delete",
"(",
"$",
"key",
",",
"$",
"onResponse",
"=",
"null",
",",
"$",
"time",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"getConnectionByKey",
"(",
"$",
"key",
",",
"function",
"(",
"$",
"conn",
")",
"use",
"(",
"$",
"key",
... | Deletes the key
@param string $key Key
@param callable $onResponse Callback called when the request complete
@param integer $time Time to block this key
@callback $onResponse ( )
@return void | [
"Deletes",
"the",
"key"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Memcache/Pool.php#L83-L95 |
kakserpom/phpdaemon | PHPDaemon/Clients/Memcache/Pool.php | Pool.prepend | public function prepend($key, $value, $exp = 0, $onResponse = null)
{
$this->getConnectionByKey($key, function ($conn) use ($key, $value, $exp, $onResponse) {
if (!$conn->connected) {
return;
}
if ($onResponse !== null) {
$conn->onResponse->push($onResponse);
$conn->setFree(false);
}
$conn->writeln('prepend ' . $this->config->prefix->value . $key . ' 0 ' . $exp . ' ' . mb_orig_strlen($value)
. ($onResponse === null ? ' noreply' : '') . "\r\n" . $value);
});
} | php | public function prepend($key, $value, $exp = 0, $onResponse = null)
{
$this->getConnectionByKey($key, function ($conn) use ($key, $value, $exp, $onResponse) {
if (!$conn->connected) {
return;
}
if ($onResponse !== null) {
$conn->onResponse->push($onResponse);
$conn->setFree(false);
}
$conn->writeln('prepend ' . $this->config->prefix->value . $key . ' 0 ' . $exp . ' ' . mb_orig_strlen($value)
. ($onResponse === null ? ' noreply' : '') . "\r\n" . $value);
});
} | [
"public",
"function",
"prepend",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"exp",
"=",
"0",
",",
"$",
"onResponse",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"getConnectionByKey",
"(",
"$",
"key",
",",
"function",
"(",
"$",
"conn",
")",
"use",
... | Prepends a string to the key's value
@param string $key Key
@param string $value Value
@param integer $exp Lifetime in seconds (0 - immortal)
@param callable $onResponse Callback called when the request complete
@callback $onResponse ( )
@return void | [
"Prepends",
"a",
"string",
"to",
"the",
"key",
"s",
"value"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/Memcache/Pool.php#L154-L167 |
kakserpom/phpdaemon | PHPDaemon/Utils/DateTime.php | DateTime.diffAsText | public static function diffAsText($datetime1, $datetime2, $absolute = false)
{
if (!($datetime1 instanceof \DateTimeInterface)) {
$datetime1 = new static($datetime1);
}
if (!($datetime2 instanceof \DateTimeInterface)) {
$datetime2 = new static($datetime2);
}
$interval = $datetime1->diff($datetime2, $absolute);
$str = '';
$str .= $interval->y ? $interval->y . ' year. ' : '';
$str .= $interval->m ? $interval->m . ' mon. ' : '';
$str .= $interval->d ? $interval->d . ' day. ' : '';
$str .= $interval->h ? $interval->h . ' hour. ' : '';
$str .= $interval->i ? $interval->i . ' min. ' : '';
$str .= $interval->s || $str === '' ? $interval->s . ' sec. ' : '';
return rtrim($str);
} | php | public static function diffAsText($datetime1, $datetime2, $absolute = false)
{
if (!($datetime1 instanceof \DateTimeInterface)) {
$datetime1 = new static($datetime1);
}
if (!($datetime2 instanceof \DateTimeInterface)) {
$datetime2 = new static($datetime2);
}
$interval = $datetime1->diff($datetime2, $absolute);
$str = '';
$str .= $interval->y ? $interval->y . ' year. ' : '';
$str .= $interval->m ? $interval->m . ' mon. ' : '';
$str .= $interval->d ? $interval->d . ' day. ' : '';
$str .= $interval->h ? $interval->h . ' hour. ' : '';
$str .= $interval->i ? $interval->i . ' min. ' : '';
$str .= $interval->s || $str === '' ? $interval->s . ' sec. ' : '';
return rtrim($str);
} | [
"public",
"static",
"function",
"diffAsText",
"(",
"$",
"datetime1",
",",
"$",
"datetime2",
",",
"$",
"absolute",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"datetime1",
"instanceof",
"\\",
"DateTimeInterface",
")",
")",
"{",
"$",
"datetime1",
"="... | Calculates a difference between two dates
@see http://www.php.net/manual/en/datetime.diff.php
@param integer|string|\DateTimeInterface $datetime1
@param integer|string|\DateTimeInterface $datetime2
@param boolean $absolute
@return string Something like this: 1 year. 2 mon. 6 day. 4 hours. 21 min. 10 sec. | [
"Calculates",
"a",
"difference",
"between",
"two",
"dates"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/DateTime.php#L34-L53 |
kakserpom/phpdaemon | PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Exchange/ExchangeDeleteFrame.php | ExchangeDeleteFrame.create | public static function create(
$exchange = null, $ifUnused = null, $nowait = null
)
{
$frame = new self();
if (null !== $exchange) {
$frame->exchange = $exchange;
}
if (null !== $ifUnused) {
$frame->ifUnused = $ifUnused;
}
if (null !== $nowait) {
$frame->nowait = $nowait;
}
return $frame;
} | php | public static function create(
$exchange = null, $ifUnused = null, $nowait = null
)
{
$frame = new self();
if (null !== $exchange) {
$frame->exchange = $exchange;
}
if (null !== $ifUnused) {
$frame->ifUnused = $ifUnused;
}
if (null !== $nowait) {
$frame->nowait = $nowait;
}
return $frame;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"exchange",
"=",
"null",
",",
"$",
"ifUnused",
"=",
"null",
",",
"$",
"nowait",
"=",
"null",
")",
"{",
"$",
"frame",
"=",
"new",
"self",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"exchange",
... | bit | [
"bit"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Exchange/ExchangeDeleteFrame.php#L23-L40 |
kakserpom/phpdaemon | PHPDaemon/IPCManager/IPCManager.php | IPCManager.init | public function init()
{
$this->socketurl = sprintf($this->config->mastersocket->value,
crc32(Daemon::$config->pidfile->value . "\x00" . Daemon::$config->user->value . "\x00" . Daemon::$config->group->value));
if (Daemon::$process instanceof Thread\IPC) {
$this->pool = MasterPool::getInstance(['listen' => $this->socketurl]);
$this->pool->appInstance = $this;
$this->pool->onReady();
}
} | php | public function init()
{
$this->socketurl = sprintf($this->config->mastersocket->value,
crc32(Daemon::$config->pidfile->value . "\x00" . Daemon::$config->user->value . "\x00" . Daemon::$config->group->value));
if (Daemon::$process instanceof Thread\IPC) {
$this->pool = MasterPool::getInstance(['listen' => $this->socketurl]);
$this->pool->appInstance = $this;
$this->pool->onReady();
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"$",
"this",
"->",
"socketurl",
"=",
"sprintf",
"(",
"$",
"this",
"->",
"config",
"->",
"mastersocket",
"->",
"value",
",",
"crc32",
"(",
"Daemon",
"::",
"$",
"config",
"->",
"pidfile",
"->",
"value",
".",
... | Constructor.
@return void | [
"Constructor",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/IPCManager/IPCManager.php#L35-L44 |
kakserpom/phpdaemon | PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Connection/ConnectionSecureFrame.php | ConnectionSecureFrame.create | public static function create(
$challenge = null
)
{
$frame = new self();
if (null !== $challenge) {
$frame->challenge = $challenge;
}
return $frame;
} | php | public static function create(
$challenge = null
)
{
$frame = new self();
if (null !== $challenge) {
$frame->challenge = $challenge;
}
return $frame;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"challenge",
"=",
"null",
")",
"{",
"$",
"frame",
"=",
"new",
"self",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"challenge",
")",
"{",
"$",
"frame",
"->",
"challenge",
"=",
"$",
"challenge",
"... | longstr | [
"longstr"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Clients/AMQP/Driver/Protocol/v091/Protocol/Connection/ConnectionSecureFrame.php#L20-L31 |
kakserpom/phpdaemon | PHPDaemon/BoundSocket/TCP.php | TCP.bindSocket | public function bindSocket()
{
if ($this->erroneous) {
return false;
}
$port = $this->getPort();
if (!is_int($port)) {
Daemon::log(get_class($this) . ' (' . get_class($this->pool) . '): no port defined for \'' . $this->uri['uri'] . '\'');
return;
}
if (($port < 1024) && Daemon::$config->user->value !== 'root') {
$this->listenerMode = false;
}
if ($this->listenerMode) {
$this->setFd($this->host . ':' . $port);
return true;
}
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$sock) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t create TCP-socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
if ($this->reuse) {
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEADDR to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
if (defined('SO_REUSEPORT') && !@socket_set_option($sock, SOL_SOCKET, SO_REUSEPORT, 1)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEPORT to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
}
if (!@socket_bind($sock, $this->host, $port)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t bind TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
socket_getsockname($sock, $this->host, $this->port);
socket_set_nonblock($sock);
if (!$this->listenerMode) {
if (!socket_listen($sock, SOMAXCONN)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t listen TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ')');
return false;
}
}
$this->setFd($sock);
return true;
} | php | public function bindSocket()
{
if ($this->erroneous) {
return false;
}
$port = $this->getPort();
if (!is_int($port)) {
Daemon::log(get_class($this) . ' (' . get_class($this->pool) . '): no port defined for \'' . $this->uri['uri'] . '\'');
return;
}
if (($port < 1024) && Daemon::$config->user->value !== 'root') {
$this->listenerMode = false;
}
if ($this->listenerMode) {
$this->setFd($this->host . ':' . $port);
return true;
}
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$sock) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t create TCP-socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
if ($this->reuse) {
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEADDR to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
if (defined('SO_REUSEPORT') && !@socket_set_option($sock, SOL_SOCKET, SO_REUSEPORT, 1)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEPORT to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
}
if (!@socket_bind($sock, $this->host, $port)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t bind TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ').');
return false;
}
socket_getsockname($sock, $this->host, $this->port);
socket_set_nonblock($sock);
if (!$this->listenerMode) {
if (!socket_listen($sock, SOMAXCONN)) {
$errno = socket_last_error();
Daemon::$process->log(get_class($this->pool) . ': Couldn\'t listen TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ')');
return false;
}
}
$this->setFd($sock);
return true;
} | [
"public",
"function",
"bindSocket",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"erroneous",
")",
"{",
"return",
"false",
";",
"}",
"$",
"port",
"=",
"$",
"this",
"->",
"getPort",
"(",
")",
";",
"if",
"(",
"!",
"is_int",
"(",
"$",
"port",
")",
... | Bind the socket
@return null|boolean Success. | [
"Bind",
"the",
"socket"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/BoundSocket/TCP.php#L47-L98 |
kakserpom/phpdaemon | PHPDaemon/BoundSocket/TCP.php | TCP.onBound | protected function onBound()
{
if ($this->ev) {
$this->ev->getSocketName($this->locHost, $this->locPort);
} else {
Daemon::log('Unable to bind TCP-socket ' . $this->host . ':' . $this->getPort());
}
} | php | protected function onBound()
{
if ($this->ev) {
$this->ev->getSocketName($this->locHost, $this->locPort);
} else {
Daemon::log('Unable to bind TCP-socket ' . $this->host . ':' . $this->getPort());
}
} | [
"protected",
"function",
"onBound",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ev",
")",
"{",
"$",
"this",
"->",
"ev",
"->",
"getSocketName",
"(",
"$",
"this",
"->",
"locHost",
",",
"$",
"this",
"->",
"locPort",
")",
";",
"}",
"else",
"{",
"Da... | Called when socket is bound
@return boolean|null Success | [
"Called",
"when",
"socket",
"is",
"bound"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/BoundSocket/TCP.php#L104-L111 |
kakserpom/phpdaemon | PHPDaemon/Thread/IPC.php | IPC.run | protected function run()
{
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');
if (Daemon::$config->autogc->value > 0) {
gc_enable();
} else {
gc_disable();
}
$this->prepareSystemEnv();
$this->registerEventSignals();
FileSystem::init(); // re-init
FileSystem::initEvent();
Daemon::openLogs();
$this->fileWatcher = new FileWatcher();
$this->IPCManager = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager');
if (!$this->IPCManager) {
$this->log('cannot instantiate IPCManager');
}
EventLoop::$instance->run();
} | php | protected function run()
{
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');
if (Daemon::$config->autogc->value > 0) {
gc_enable();
} else {
gc_disable();
}
$this->prepareSystemEnv();
$this->registerEventSignals();
FileSystem::init(); // re-init
FileSystem::initEvent();
Daemon::openLogs();
$this->fileWatcher = new FileWatcher();
$this->IPCManager = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager');
if (!$this->IPCManager) {
$this->log('cannot instantiate IPCManager');
}
EventLoop::$instance->run();
} | [
"protected",
"function",
"run",
"(",
")",
"{",
"if",
"(",
"Daemon",
"::",
"$",
"process",
"instanceof",
"Master",
")",
"{",
"Daemon",
"::",
"$",
"process",
"->",
"unregisterSignals",
"(",
")",
";",
"}",
"EventLoop",
"::",
"init",
"(",
")",
";",
"Daemon... | Runtime of Worker process.
@return void | [
"Runtime",
"of",
"Worker",
"process",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/IPC.php#L76-L107 |
kakserpom/phpdaemon | PHPDaemon/Thread/IPC.php | IPC.update | protected function update()
{
FileSystem::updateConfig();
foreach (Daemon::$appInstances as $app) {
foreach ($app as $appInstance) {
$appInstance->handleStatus(AppInstance::EVENT_CONFIG_UPDATED);
}
}
} | php | protected function update()
{
FileSystem::updateConfig();
foreach (Daemon::$appInstances as $app) {
foreach ($app as $appInstance) {
$appInstance->handleStatus(AppInstance::EVENT_CONFIG_UPDATED);
}
}
} | [
"protected",
"function",
"update",
"(",
")",
"{",
"FileSystem",
"::",
"updateConfig",
"(",
")",
";",
"foreach",
"(",
"Daemon",
"::",
"$",
"appInstances",
"as",
"$",
"app",
")",
"{",
"foreach",
"(",
"$",
"app",
"as",
"$",
"appInstance",
")",
"{",
"$",
... | Reloads additional config-files on-the-fly.
@return void | [
"Reloads",
"additional",
"config",
"-",
"files",
"on",
"-",
"the",
"-",
"fly",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/IPC.php#L187-L195 |
kakserpom/phpdaemon | PHPDaemon/Thread/IPC.php | IPC.shutdown | public function shutdown($hard = false)
{
$error = error_get_last();
if ($error) {
if ($error['type'] === E_ERROR) {
$this->log('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) {
posix_kill(getmypid(), SIGKILL);
exit(0);
}
return;
}
$this->terminated = true;
if ($hard) {
posix_kill(getmypid(), SIGKILL);
exit(0);
}
FileSystem::waitAllEvents(); // ensure that all I/O events completed before suicide
posix_kill(posix_getppid(), SIGCHLD); // praying to Master
posix_kill(getmypid(), SIGKILL);
exit(0); // R.I.P.
} | php | public function shutdown($hard = false)
{
$error = error_get_last();
if ($error) {
if ($error['type'] === E_ERROR) {
$this->log('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) {
posix_kill(getmypid(), SIGKILL);
exit(0);
}
return;
}
$this->terminated = true;
if ($hard) {
posix_kill(getmypid(), SIGKILL);
exit(0);
}
FileSystem::waitAllEvents(); // ensure that all I/O events completed before suicide
posix_kill(posix_getppid(), SIGCHLD); // praying to Master
posix_kill(getmypid(), SIGKILL);
exit(0); // R.I.P.
} | [
"public",
"function",
"shutdown",
"(",
"$",
"hard",
"=",
"false",
")",
"{",
"$",
"error",
"=",
"error_get_last",
"(",
")",
";",
"if",
"(",
"$",
"error",
")",
"{",
"if",
"(",
"$",
"error",
"[",
"'type'",
"]",
"===",
"E_ERROR",
")",
"{",
"$",
"this... | Shutdown thread
@param boolean - Hard? If hard, we shouldn't wait for graceful shutdown of the running applications.
@return boolean|null - Ready? | [
"Shutdown",
"thread"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/IPC.php#L202-L235 |
kakserpom/phpdaemon | PHPDaemon/Thread/IPC.php | IPC.sigint | protected function sigint()
{
if (Daemon::$config->logsignals->value) {
$this->log('caught SIGINT.');
}
$this->shutdown(true);
} | php | protected function sigint()
{
if (Daemon::$config->logsignals->value) {
$this->log('caught SIGINT.');
}
$this->shutdown(true);
} | [
"protected",
"function",
"sigint",
"(",
")",
"{",
"if",
"(",
"Daemon",
"::",
"$",
"config",
"->",
"logsignals",
"->",
"value",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'caught SIGINT.'",
")",
";",
"}",
"$",
"this",
"->",
"shutdown",
"(",
"true",
")"... | Handler of the SIGINT (hard shutdown) signal in worker process.
@return void | [
"Handler",
"of",
"the",
"SIGINT",
"(",
"hard",
"shutdown",
")",
"signal",
"in",
"worker",
"process",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/IPC.php#L241-L248 |
kakserpom/phpdaemon | PHPDaemon/Thread/IPC.php | IPC.sigunknown | public function sigunknown($signo)
{
if (isset(Generic::$signals[$signo])) {
$sig = Generic::$signals[$signo];
} else {
$sig = 'UNKNOWN';
}
$this->log('caught signal #' . $signo . ' (' . $sig . ').');
} | php | public function sigunknown($signo)
{
if (isset(Generic::$signals[$signo])) {
$sig = Generic::$signals[$signo];
} else {
$sig = 'UNKNOWN';
}
$this->log('caught signal #' . $signo . ' (' . $sig . ').');
} | [
"public",
"function",
"sigunknown",
"(",
"$",
"signo",
")",
"{",
"if",
"(",
"isset",
"(",
"Generic",
"::",
"$",
"signals",
"[",
"$",
"signo",
"]",
")",
")",
"{",
"$",
"sig",
"=",
"Generic",
"::",
"$",
"signals",
"[",
"$",
"signo",
"]",
";",
"}",
... | Handler of non-known signals.
@return void | [
"Handler",
"of",
"non",
"-",
"known",
"signals",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Thread/IPC.php#L351-L360 |
kakserpom/phpdaemon | PHPDaemon/Config/Section.php | Section.toArray | public function toArray()
{
$arr = [];
foreach ($this as $k => $entry) {
if (!$entry instanceof Generic) {
continue;
}
$arr[$k] = $entry->value;
}
return $arr;
} | php | public function toArray()
{
$arr = [];
foreach ($this as $k => $entry) {
if (!$entry instanceof Generic) {
continue;
}
$arr[$k] = $entry->value;
}
return $arr;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"arr",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"k",
"=>",
"$",
"entry",
")",
"{",
"if",
"(",
"!",
"$",
"entry",
"instanceof",
"Generic",
")",
"{",
"continue",
";",
"}",
"$... | toArray handler
@return hash | [
"toArray",
"handler"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Config/Section.php#L64-L74 |
kakserpom/phpdaemon | PHPDaemon/Config/Section.php | Section.imposeDefault | public function imposeDefault($settings = [])
{
foreach ($settings as $name => $value) {
$name = strtolower(str_replace('-', '', $name));
if (!isset($this->{$name})) {
if (is_scalar($value)) {
$this->{$name} = new Generic($value);
} else {
$this->{$name} = $value;
}
} elseif ($value instanceof Section) {
$value->imposeDefault($value);
} else {
$current = $this->{$name};
if (!is_object($value)) {
$this->{$name} = new Generic($value);
} else {
$this->{$name} = $value;
}
$this->{$name}->setHumanValue($current->value);
$this->{$name}->source = $current->source;
$this->{$name}->revision = $current->revision;
}
}
} | php | public function imposeDefault($settings = [])
{
foreach ($settings as $name => $value) {
$name = strtolower(str_replace('-', '', $name));
if (!isset($this->{$name})) {
if (is_scalar($value)) {
$this->{$name} = new Generic($value);
} else {
$this->{$name} = $value;
}
} elseif ($value instanceof Section) {
$value->imposeDefault($value);
} else {
$current = $this->{$name};
if (!is_object($value)) {
$this->{$name} = new Generic($value);
} else {
$this->{$name} = $value;
}
$this->{$name}->setHumanValue($current->value);
$this->{$name}->source = $current->source;
$this->{$name}->revision = $current->revision;
}
}
} | [
"public",
"function",
"imposeDefault",
"(",
"$",
"settings",
"=",
"[",
"]",
")",
"{",
"foreach",
"(",
"$",
"settings",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"name",
"=",
"strtolower",
"(",
"str_replace",
"(",
"'-'",
",",
"''",
",",
... | Impose default config
@param array {"setting": "value"}
@return void | [
"Impose",
"default",
"config"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Config/Section.php#L137-L161 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.timeout | public function timeout($timeout = null)
{
if ($timeout !== null) {
$this->lastTimeout = $timeout;
}
$this->ev->add($this->lastTimeout / 1e6);
} | php | public function timeout($timeout = null)
{
if ($timeout !== null) {
$this->lastTimeout = $timeout;
}
$this->ev->add($this->lastTimeout / 1e6);
} | [
"public",
"function",
"timeout",
"(",
"$",
"timeout",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"timeout",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"lastTimeout",
"=",
"$",
"timeout",
";",
"}",
"$",
"this",
"->",
"ev",
"->",
"add",
"(",
"$",
"thi... | Sets timeout
@param integer $timeout Timeout
@return void | [
"Sets",
"timeout"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L95-L101 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.add | public static function add($cb, $timeout = null, $id = null, $priority = null)
{
$obj = new self($cb, $timeout, $id, $priority);
return $obj->id;
} | php | public static function add($cb, $timeout = null, $id = null, $priority = null)
{
$obj = new self($cb, $timeout, $id, $priority);
return $obj->id;
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"cb",
",",
"$",
"timeout",
"=",
"null",
",",
"$",
"id",
"=",
"null",
",",
"$",
"priority",
"=",
"null",
")",
"{",
"$",
"obj",
"=",
"new",
"self",
"(",
"$",
"cb",
",",
"$",
"timeout",
",",
"$",
... | Adds timer
@param callable $cb Callback
@param integer $timeout Timeout
@param integer|string $id Timer ID
@param integer $priority Priority
@return integer|string Timer ID | [
"Adds",
"timer"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L111-L115 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.setTimeout | public static function setTimeout($id, $timeout = null)
{
if (isset(self::$list[$id])) {
self::$list[$id]->timeout($timeout);
return true;
}
return false;
} | php | public static function setTimeout($id, $timeout = null)
{
if (isset(self::$list[$id])) {
self::$list[$id]->timeout($timeout);
return true;
}
return false;
} | [
"public",
"static",
"function",
"setTimeout",
"(",
"$",
"id",
",",
"$",
"timeout",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"list",
"[",
"$",
"id",
"]",
")",
")",
"{",
"self",
"::",
"$",
"list",
"[",
"$",
"id",
"]",
... | Sets timeout
@param integer|string $id Timer ID
@param integer $timeout Timeout
@return boolean | [
"Sets",
"timeout"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L123-L130 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.remove | public static function remove($id)
{
if (isset(self::$list[$id])) {
self::$list[$id]->free();
}
} | php | public static function remove($id)
{
if (isset(self::$list[$id])) {
self::$list[$id]->free();
}
} | [
"public",
"static",
"function",
"remove",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"list",
"[",
"$",
"id",
"]",
")",
")",
"{",
"self",
"::",
"$",
"list",
"[",
"$",
"id",
"]",
"->",
"free",
"(",
")",
";",
"}",
"}... | Removes timer by ID
@param integer|string $id Timer ID
@return void | [
"Removes",
"timer",
"by",
"ID"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L137-L142 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.free | public function free()
{
unset(self::$list[$this->id]);
if ($this->ev !== null) {
$this->ev->free();
$this->ev = null;
}
} | php | public function free()
{
unset(self::$list[$this->id]);
if ($this->ev !== null) {
$this->ev->free();
$this->ev = null;
}
} | [
"public",
"function",
"free",
"(",
")",
"{",
"unset",
"(",
"self",
"::",
"$",
"list",
"[",
"$",
"this",
"->",
"id",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"ev",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"ev",
"->",
"free",
"(",
")",
... | Frees the timer
@return void | [
"Frees",
"the",
"timer"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L148-L155 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.cancelTimeout | public static function cancelTimeout($id)
{
if (isset(self::$list[$id])) {
self::$list[$id]->cancel();
}
} | php | public static function cancelTimeout($id)
{
if (isset(self::$list[$id])) {
self::$list[$id]->cancel();
}
} | [
"public",
"static",
"function",
"cancelTimeout",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"list",
"[",
"$",
"id",
"]",
")",
")",
"{",
"self",
"::",
"$",
"list",
"[",
"$",
"id",
"]",
"->",
"cancel",
"(",
")",
";",
... | Cancels timer by ID
@param integer|string $id Timer ID
@return void | [
"Cancels",
"timer",
"by",
"ID"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L162-L167 |
kakserpom/phpdaemon | PHPDaemon/Core/Timer.php | Timer.eventCall | public function eventCall()
{
try {
//Daemon::log('cb - '.Debug::zdump($this->cb));
$func = $this->cb;
$func($this);
} catch (\Exception $e) {
Daemon::uncaughtExceptionHandler($e);
}
} | php | public function eventCall()
{
try {
//Daemon::log('cb - '.Debug::zdump($this->cb));
$func = $this->cb;
$func($this);
} catch (\Exception $e) {
Daemon::uncaughtExceptionHandler($e);
}
} | [
"public",
"function",
"eventCall",
"(",
")",
"{",
"try",
"{",
"//Daemon::log('cb - '.Debug::zdump($this->cb));",
"$",
"func",
"=",
"$",
"this",
"->",
"cb",
";",
"$",
"func",
"(",
"$",
"this",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",... | Called when timer is triggered
@return void | [
"Called",
"when",
"timer",
"is",
"triggered"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Core/Timer.php#L182-L191 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.onSessionStartEvent | public function onSessionStartEvent()
{
return function ($sessionStartEvent) {
/** @var \PHPDaemon\Core\DeferredEvent $sessionStartEvent */
$name = ini_get('session.name');
$sid = $this->getCookieStr($name);
if ($sid === '') {
$this->sessionStartNew(function ($success) use ($sessionStartEvent) {
$sessionStartEvent->setResult($success);
});
return;
}
$this->onSessionRead(function ($session) use ($sessionStartEvent) {
if ($this->getSessionState() === null) {
$this->sessionStartNew(function ($success) use ($sessionStartEvent) {
$sessionStartEvent->setResult($success);
});
return;
}
$sessionStartEvent->setResult(true);
});
};
} | php | public function onSessionStartEvent()
{
return function ($sessionStartEvent) {
/** @var \PHPDaemon\Core\DeferredEvent $sessionStartEvent */
$name = ini_get('session.name');
$sid = $this->getCookieStr($name);
if ($sid === '') {
$this->sessionStartNew(function ($success) use ($sessionStartEvent) {
$sessionStartEvent->setResult($success);
});
return;
}
$this->onSessionRead(function ($session) use ($sessionStartEvent) {
if ($this->getSessionState() === null) {
$this->sessionStartNew(function ($success) use ($sessionStartEvent) {
$sessionStartEvent->setResult($success);
});
return;
}
$sessionStartEvent->setResult(true);
});
};
} | [
"public",
"function",
"onSessionStartEvent",
"(",
")",
"{",
"return",
"function",
"(",
"$",
"sessionStartEvent",
")",
"{",
"/** @var \\PHPDaemon\\Core\\DeferredEvent $sessionStartEvent */",
"$",
"name",
"=",
"ini_get",
"(",
"'session.name'",
")",
";",
"$",
"sid",
"=",... | Deferred event 'onSessionStart'
@return callable | [
"Deferred",
"event",
"onSessionStart"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L58-L80 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.onSessionReadEvent | public function onSessionReadEvent()
{
return function ($sessionEvent) {
/** @var \PHPDaemon\Core\DeferredEvent $sessionEvent */
$name = ini_get('session.name');
$sid = $this->getCookieStr($name);
if ($sid === '') {
$sessionEvent->setResult(false);
return;
}
if ($this->getSessionState() !== null) {
$sessionEvent->setResult(true);
return;
}
$this->sessionRead($sid, function ($data) use ($sessionEvent, $sid) {
$canDecode = $data !== false && $this->sessionDecode($data);
$sessionEvent->setResult($canDecode);
});
};
} | php | public function onSessionReadEvent()
{
return function ($sessionEvent) {
/** @var \PHPDaemon\Core\DeferredEvent $sessionEvent */
$name = ini_get('session.name');
$sid = $this->getCookieStr($name);
if ($sid === '') {
$sessionEvent->setResult(false);
return;
}
if ($this->getSessionState() !== null) {
$sessionEvent->setResult(true);
return;
}
$this->sessionRead($sid, function ($data) use ($sessionEvent, $sid) {
$canDecode = $data !== false && $this->sessionDecode($data);
$sessionEvent->setResult($canDecode);
});
};
} | [
"public",
"function",
"onSessionReadEvent",
"(",
")",
"{",
"return",
"function",
"(",
"$",
"sessionEvent",
")",
"{",
"/** @var \\PHPDaemon\\Core\\DeferredEvent $sessionEvent */",
"$",
"name",
"=",
"ini_get",
"(",
"'session.name'",
")",
";",
"$",
"sid",
"=",
"$",
"... | Deferred event 'onSessionRead'
@return callable | [
"Deferred",
"event",
"onSessionRead"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L86-L105 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.sessionRead | public function sessionRead($sid, $cb = null)
{
FileSystem::open(FileSystem::genRndTempnamPrefix(session_save_path(), $this->sessionPrefix) . basename($sid),
'r+!', function ($fp) use ($cb) {
if (!$fp) {
$cb(false);
return;
}
$fp->readAll(function ($fp, $data) use ($cb) {
$this->sessionFp = $fp;
$cb($data);
});
});
} | php | public function sessionRead($sid, $cb = null)
{
FileSystem::open(FileSystem::genRndTempnamPrefix(session_save_path(), $this->sessionPrefix) . basename($sid),
'r+!', function ($fp) use ($cb) {
if (!$fp) {
$cb(false);
return;
}
$fp->readAll(function ($fp, $data) use ($cb) {
$this->sessionFp = $fp;
$cb($data);
});
});
} | [
"public",
"function",
"sessionRead",
"(",
"$",
"sid",
",",
"$",
"cb",
"=",
"null",
")",
"{",
"FileSystem",
"::",
"open",
"(",
"FileSystem",
"::",
"genRndTempnamPrefix",
"(",
"session_save_path",
"(",
")",
",",
"$",
"this",
"->",
"sessionPrefix",
")",
".",
... | Reads session data
@param string $sid Session ID
@param callable $cb Callback
@return void | [
"Reads",
"session",
"data"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L113-L126 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.sessionCommit | public function sessionCommit($cb = null)
{
if (!$this->sessionFp || $this->sessionFlushing) {
if ($cb) {
$cb(false);
}
return;
}
$this->sessionFlushing = true;
$data = $this->sessionEncode();
$l = mb_orig_strlen($data);
$cb = CallbackWrapper::wrap($cb);
$this->sessionFp->write($data, function ($file, $result) use ($l, $cb) {
$file->truncate($l, function ($file, $result) use ($cb) {
$this->sessionFlushing = false;
if ($cb) {
$cb(true);
}
});
});
} | php | public function sessionCommit($cb = null)
{
if (!$this->sessionFp || $this->sessionFlushing) {
if ($cb) {
$cb(false);
}
return;
}
$this->sessionFlushing = true;
$data = $this->sessionEncode();
$l = mb_orig_strlen($data);
$cb = CallbackWrapper::wrap($cb);
$this->sessionFp->write($data, function ($file, $result) use ($l, $cb) {
$file->truncate($l, function ($file, $result) use ($cb) {
$this->sessionFlushing = false;
if ($cb) {
$cb(true);
}
});
});
} | [
"public",
"function",
"sessionCommit",
"(",
"$",
"cb",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"sessionFp",
"||",
"$",
"this",
"->",
"sessionFlushing",
")",
"{",
"if",
"(",
"$",
"cb",
")",
"{",
"$",
"cb",
"(",
"false",
")",
";",... | Commmit session data
@param callable $cb Callback
@return void | [
"Commmit",
"session",
"data"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L133-L153 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.sessionStart | protected function sessionStart($force_start = true)
{
if ($this->sessionStarted) {
return;
}
$this->sessionStarted = true;
if (!$this instanceof \PHPDaemon\HTTPRequest\Generic) {
Daemon::log('Called ' . get_class($this) . '(trait \PHPDaemon\Traits\Sessions)->sessionStart() outside of Request. You should use onSessionStart.');
return;
}
$f = true; // hack to avoid a sort of "race condition"
$this->onSessionStart(function ($event) use (&$f) {
$f = false;
$this->wakeup();
});
if ($f) {
$this->sleep($this->sessionStartTimeout);
}
} | php | protected function sessionStart($force_start = true)
{
if ($this->sessionStarted) {
return;
}
$this->sessionStarted = true;
if (!$this instanceof \PHPDaemon\HTTPRequest\Generic) {
Daemon::log('Called ' . get_class($this) . '(trait \PHPDaemon\Traits\Sessions)->sessionStart() outside of Request. You should use onSessionStart.');
return;
}
$f = true; // hack to avoid a sort of "race condition"
$this->onSessionStart(function ($event) use (&$f) {
$f = false;
$this->wakeup();
});
if ($f) {
$this->sleep($this->sessionStartTimeout);
}
} | [
"protected",
"function",
"sessionStart",
"(",
"$",
"force_start",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"sessionStarted",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"sessionStarted",
"=",
"true",
";",
"if",
"(",
"!",
"$",
"this",
... | Session start
@param boolean $force_start
@return void | [
"Session",
"start"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L160-L178 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.sessionStartNew | protected function sessionStartNew($cb = null)
{
FileSystem::tempnam(session_save_path(), $this->sessionPrefix, function ($fp) use ($cb) {
if (!$fp) {
$cb(false);
return;
}
$this->sessionFp = $fp;
$this->sessionId = substr(basename($fp->path), mb_orig_strlen($this->sessionPrefix));
$this->setcookie(
ini_get('session.name'),
$this->sessionId,
ini_get('session.cookie_lifetime'),
ini_get('session.cookie_path'),
ini_get('session.cookie_domain'),
ini_get('session.cookie_secure'),
ini_get('session.cookie_httponly')
);
$cb(true);
});
} | php | protected function sessionStartNew($cb = null)
{
FileSystem::tempnam(session_save_path(), $this->sessionPrefix, function ($fp) use ($cb) {
if (!$fp) {
$cb(false);
return;
}
$this->sessionFp = $fp;
$this->sessionId = substr(basename($fp->path), mb_orig_strlen($this->sessionPrefix));
$this->setcookie(
ini_get('session.name'),
$this->sessionId,
ini_get('session.cookie_lifetime'),
ini_get('session.cookie_path'),
ini_get('session.cookie_domain'),
ini_get('session.cookie_secure'),
ini_get('session.cookie_httponly')
);
$cb(true);
});
} | [
"protected",
"function",
"sessionStartNew",
"(",
"$",
"cb",
"=",
"null",
")",
"{",
"FileSystem",
"::",
"tempnam",
"(",
"session_save_path",
"(",
")",
",",
"$",
"this",
"->",
"sessionPrefix",
",",
"function",
"(",
"$",
"fp",
")",
"use",
"(",
"$",
"cb",
... | Start new session
@param callable $cb Callback
@return void | [
"Start",
"new",
"session"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L185-L207 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.sessionEncode | protected function sessionEncode()
{
$type = ini_get('session.serialize_handler');
if ($type === 'php') {
return $this->serializePHP($this->getSessionState());
}
if ($type === 'php_binary') {
return igbinary_serialize($this->getSessionState());
}
return false;
} | php | protected function sessionEncode()
{
$type = ini_get('session.serialize_handler');
if ($type === 'php') {
return $this->serializePHP($this->getSessionState());
}
if ($type === 'php_binary') {
return igbinary_serialize($this->getSessionState());
}
return false;
} | [
"protected",
"function",
"sessionEncode",
"(",
")",
"{",
"$",
"type",
"=",
"ini_get",
"(",
"'session.serialize_handler'",
")",
";",
"if",
"(",
"$",
"type",
"===",
"'php'",
")",
"{",
"return",
"$",
"this",
"->",
"serializePHP",
"(",
"$",
"this",
"->",
"ge... | Encodes session data
@return string|false | [
"Encodes",
"session",
"data"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L213-L223 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.sessionDecode | protected function sessionDecode($str)
{
$type = ini_get('session.serialize_handler');
if ($type === 'php') {
$this->setSessionState($this->unserializePHP($str));
return true;
}
if ($type === 'php_binary') {
$this->setSessionState(igbinary_unserialize($str));
return true;
}
return false;
} | php | protected function sessionDecode($str)
{
$type = ini_get('session.serialize_handler');
if ($type === 'php') {
$this->setSessionState($this->unserializePHP($str));
return true;
}
if ($type === 'php_binary') {
$this->setSessionState(igbinary_unserialize($str));
return true;
}
return false;
} | [
"protected",
"function",
"sessionDecode",
"(",
"$",
"str",
")",
"{",
"$",
"type",
"=",
"ini_get",
"(",
"'session.serialize_handler'",
")",
";",
"if",
"(",
"$",
"type",
"===",
"'php'",
")",
"{",
"$",
"this",
"->",
"setSessionState",
"(",
"$",
"this",
"->"... | Decodes session data
@param string $str Data
@return boolean | [
"Decodes",
"session",
"data"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L249-L261 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.serializePHP | public function serializePHP($array)
{
$raw = '';
$line = 0;
$keys = array_keys($array);
foreach ($keys as $key) {
$value = $array[$key];
$line++;
$raw .= $key . '|';
if (is_array($value) && isset($value['huge_recursion_blocker_we_hope'])) {
$raw .= 'R:' . $value['huge_recursion_blocker_we_hope'] . ';';
} else {
$raw .= serialize($value);
}
$array[$key] = array('huge_recursion_blocker_we_hope' => $line);
}
return $raw;
} | php | public function serializePHP($array)
{
$raw = '';
$line = 0;
$keys = array_keys($array);
foreach ($keys as $key) {
$value = $array[$key];
$line++;
$raw .= $key . '|';
if (is_array($value) && isset($value['huge_recursion_blocker_we_hope'])) {
$raw .= 'R:' . $value['huge_recursion_blocker_we_hope'] . ';';
} else {
$raw .= serialize($value);
}
$array[$key] = array('huge_recursion_blocker_we_hope' => $line);
}
return $raw;
} | [
"public",
"function",
"serializePHP",
"(",
"$",
"array",
")",
"{",
"$",
"raw",
"=",
"''",
";",
"$",
"line",
"=",
"0",
";",
"$",
"keys",
"=",
"array_keys",
"(",
"$",
"array",
")",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"$"... | session_encode() - clone, which not require session_start()
@see http://www.php.net/manual/en/function.session-encode.php
@param array $array
@return string | [
"session_encode",
"()",
"-",
"clone",
"which",
"not",
"require",
"session_start",
"()"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L269-L288 |
kakserpom/phpdaemon | PHPDaemon/Traits/Sessions.php | Sessions.unserializePHP | protected function unserializePHP($session_data)
{
$return_data = array();
$offset = 0;
while ($offset < mb_orig_strlen($session_data)) {
if (!strstr(substr($session_data, $offset), "|")) {
return $return_data;
//throw new \Exception("invalid session data, remaining: " . substr($session_data, $offset));
}
$pos = mb_orig_strpos($session_data, "|", $offset);
$num = $pos - $offset;
$varname = substr($session_data, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($session_data, $offset));
$return_data[$varname] = $data;
$offset += mb_orig_strlen(serialize($data));
}
return $return_data;
} | php | protected function unserializePHP($session_data)
{
$return_data = array();
$offset = 0;
while ($offset < mb_orig_strlen($session_data)) {
if (!strstr(substr($session_data, $offset), "|")) {
return $return_data;
//throw new \Exception("invalid session data, remaining: " . substr($session_data, $offset));
}
$pos = mb_orig_strpos($session_data, "|", $offset);
$num = $pos - $offset;
$varname = substr($session_data, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($session_data, $offset));
$return_data[$varname] = $data;
$offset += mb_orig_strlen(serialize($data));
}
return $return_data;
} | [
"protected",
"function",
"unserializePHP",
"(",
"$",
"session_data",
")",
"{",
"$",
"return_data",
"=",
"array",
"(",
")",
";",
"$",
"offset",
"=",
"0",
";",
"while",
"(",
"$",
"offset",
"<",
"mb_orig_strlen",
"(",
"$",
"session_data",
")",
")",
"{",
"... | session_decode() - clone, which not require session_start()
@see http://www.php.net/manual/en/function.session-decode.php#108037
@param string $session_data
@return array | [
"session_decode",
"()",
"-",
"clone",
"which",
"not",
"require",
"session_start",
"()"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Traits/Sessions.php#L296-L316 |
kakserpom/phpdaemon | PHPDaemon/Examples/ExampleWithMemcache.php | ExampleWithMemcacheRequest.init | public function init()
{
try {
$this->header('Content-Type: text/html');
} catch (\Exception $e) {
}
$req = $this;
$job = $this->job = new \PHPDaemon\Core\ComplexJob(function () use ($req) { // called when job is done
$req->wakeup(); // wake up the request immediately
});
$memcache = \PHPDaemon\Clients\Memcache\Pool::getInstance();
$job('testquery', function ($name, $job) use ($memcache) { // registering job named 'testquery'
$memcache->stats(function ($memcache) use ($name, $job) { // calling 'stats'
$job->setResult($name, $memcache->result); // setting job result
});
});
$job(); // let the fun begin
$this->sleep(5, true); // setting timeout
} | php | public function init()
{
try {
$this->header('Content-Type: text/html');
} catch (\Exception $e) {
}
$req = $this;
$job = $this->job = new \PHPDaemon\Core\ComplexJob(function () use ($req) { // called when job is done
$req->wakeup(); // wake up the request immediately
});
$memcache = \PHPDaemon\Clients\Memcache\Pool::getInstance();
$job('testquery', function ($name, $job) use ($memcache) { // registering job named 'testquery'
$memcache->stats(function ($memcache) use ($name, $job) { // calling 'stats'
$job->setResult($name, $memcache->result); // setting job result
});
});
$job(); // let the fun begin
$this->sleep(5, true); // setting timeout
} | [
"public",
"function",
"init",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"header",
"(",
"'Content-Type: text/html'",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"$",
"req",
"=",
"$",
"this",
";",
"$",
"job",
"=",
"... | Constructor.
@return void | [
"Constructor",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleWithMemcache.php#L35-L63 |
kakserpom/phpdaemon | PHPDaemon/Examples/ExampleWithMemcache.php | ExampleWithMemcacheRequest.run | public function run()
{
?><!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>Example with Memcache</title>
</head>
<body>
<?php
if ($r = $this->job->getResult('testquery')) {
echo '<h1>It works! Be happy! ;-)</h1>Result of query: <pre>';
var_dump($r);
echo '</pre>';
} else {
echo '<h1>Something went wrong! We have no result.</h1>';
}
echo '<br />Request (http) took: ' . round(microtime(true) - $this->attrs->server['REQUEST_TIME_FLOAT'], 6);
?>
</body>
</html>
<?php
} | php | public function run()
{
?><!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>Example with Memcache</title>
</head>
<body>
<?php
if ($r = $this->job->getResult('testquery')) {
echo '<h1>It works! Be happy! ;-)</h1>Result of query: <pre>';
var_dump($r);
echo '</pre>';
} else {
echo '<h1>Something went wrong! We have no result.</h1>';
}
echo '<br />Request (http) took: ' . round(microtime(true) - $this->attrs->server['REQUEST_TIME_FLOAT'], 6);
?>
</body>
</html>
<?php
} | [
"public",
"function",
"run",
"(",
")",
"{",
"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf... | Called when request iterated.
@return integer Status. | [
"Called",
"when",
"request",
"iterated",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleWithMemcache.php#L69-L93 |
kakserpom/phpdaemon | PHPDaemon/Utils/ShmEntity.php | ShmEntity.open | public function open($segno = 0, $create = false)
{
if (isset($this->segments[$segno])) {
return $this->segments[$segno];
}
$key = $this->key + $segno;
if (!$create) {
$shm = @shmop_open($key, 'w', 0, 0);
} else {
$shm = @shmop_open($key, 'w', 0, 0);
if ($shm) {
shmop_delete($shm);
shmop_close($shm);
}
$shm = shmop_open($key, 'c', 0755, $this->segsize);
}
if (!$shm) {
return false;
}
$this->segments[$segno] = $shm;
return $shm;
} | php | public function open($segno = 0, $create = false)
{
if (isset($this->segments[$segno])) {
return $this->segments[$segno];
}
$key = $this->key + $segno;
if (!$create) {
$shm = @shmop_open($key, 'w', 0, 0);
} else {
$shm = @shmop_open($key, 'w', 0, 0);
if ($shm) {
shmop_delete($shm);
shmop_close($shm);
}
$shm = shmop_open($key, 'c', 0755, $this->segsize);
}
if (!$shm) {
return false;
}
$this->segments[$segno] = $shm;
return $shm;
} | [
"public",
"function",
"open",
"(",
"$",
"segno",
"=",
"0",
",",
"$",
"create",
"=",
"false",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"segments",
"[",
"$",
"segno",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"segments",
"[",
... | Opens segment of shared memory
@param integer $segno Segment number
@param boolean $create Create
@return integer Segment number | [
"Opens",
"segment",
"of",
"shared",
"memory"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/ShmEntity.php#L74-L97 |
kakserpom/phpdaemon | PHPDaemon/Utils/ShmEntity.php | ShmEntity.write | public function write($data, $offset)
{
$segno = floor($offset / $this->segsize);
if (!isset($this->segments[$segno])) {
if (!$this->open($segno, true)) {
return false;
}
}
$sOffset = $offset % $this->segsize;
$d = $this->segsize - ($sOffset + mb_orig_strlen($data));
if ($d < 0) {
$this->write(mb_orig_substr($data, $d), ($segno + 1) * $this->segsize);
$data = mb_orig_substr($data, 0, $d);
}
//Daemon::log('writing to #'.$offset.' (segno '.$segno.')');
shmop_write($this->segments[$segno], $data, $sOffset);
return true;
} | php | public function write($data, $offset)
{
$segno = floor($offset / $this->segsize);
if (!isset($this->segments[$segno])) {
if (!$this->open($segno, true)) {
return false;
}
}
$sOffset = $offset % $this->segsize;
$d = $this->segsize - ($sOffset + mb_orig_strlen($data));
if ($d < 0) {
$this->write(mb_orig_substr($data, $d), ($segno + 1) * $this->segsize);
$data = mb_orig_substr($data, 0, $d);
}
//Daemon::log('writing to #'.$offset.' (segno '.$segno.')');
shmop_write($this->segments[$segno], $data, $sOffset);
return true;
} | [
"public",
"function",
"write",
"(",
"$",
"data",
",",
"$",
"offset",
")",
"{",
"$",
"segno",
"=",
"floor",
"(",
"$",
"offset",
"/",
"$",
"this",
"->",
"segsize",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"segments",
"[",
"$",
"... | Write to shared memory
@param string $data Data
@param integer $offset Offset
@return boolean Success | [
"Write",
"to",
"shared",
"memory"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/ShmEntity.php#L125-L142 |
kakserpom/phpdaemon | PHPDaemon/Utils/ShmEntity.php | ShmEntity.read | public function read($offset, $length = 1)
{
$ret = '';
$segno = floor($offset / $this->segsize);
$sOffset = $offset % $this->segsize;
while (true) {
if (!isset($this->segments[$segno])) {
if (!$this->open($segno)) {
goto ret;
}
}
$ret .= shmop_read($this->segments[$segno], $sOffset, min($length - mb_orig_strlen($ret), $this->segsize));
if (mb_orig_strlen($ret) >= $length) {
goto ret;
}
++$segno;
$sOffset = 0;
}
ret:
return $ret === '' ? false : $ret;
} | php | public function read($offset, $length = 1)
{
$ret = '';
$segno = floor($offset / $this->segsize);
$sOffset = $offset % $this->segsize;
while (true) {
if (!isset($this->segments[$segno])) {
if (!$this->open($segno)) {
goto ret;
}
}
$ret .= shmop_read($this->segments[$segno], $sOffset, min($length - mb_orig_strlen($ret), $this->segsize));
if (mb_orig_strlen($ret) >= $length) {
goto ret;
}
++$segno;
$sOffset = 0;
}
ret:
return $ret === '' ? false : $ret;
} | [
"public",
"function",
"read",
"(",
"$",
"offset",
",",
"$",
"length",
"=",
"1",
")",
"{",
"$",
"ret",
"=",
"''",
";",
"$",
"segno",
"=",
"floor",
"(",
"$",
"offset",
"/",
"$",
"this",
"->",
"segsize",
")",
";",
"$",
"sOffset",
"=",
"$",
"offset... | Read from shared memory
@param integer $offset Offset
@param integer $length Length
@return string Data | [
"Read",
"from",
"shared",
"memory"
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Utils/ShmEntity.php#L150-L175 |
kakserpom/phpdaemon | PHPDaemon/Examples/ExampleJabberbot.php | ExampleJabberbot.init | public function init()
{
if ($this->isEnabled()) {
$this->xmppclient = \PHPDaemon\Clients\XMPP\Pool::getInstance();
}
} | php | public function init()
{
if ($this->isEnabled()) {
$this->xmppclient = \PHPDaemon\Clients\XMPP\Pool::getInstance();
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"$",
"this",
"->",
"xmppclient",
"=",
"\\",
"PHPDaemon",
"\\",
"Clients",
"\\",
"XMPP",
"\\",
"Pool",
"::",
"getInstance",
"(",
")",
";",
"}... | Constructor.
@return void | [
"Constructor",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleJabberbot.php#L20-L25 |
kakserpom/phpdaemon | PHPDaemon/Examples/ExampleJabberbot.php | ExampleJabberbot.onConfigUpdated | public function onConfigUpdated()
{
if ($this->xmppclient) {
$this->xmppclient->config = $this->config;
$this->xmppclient->onConfigUpdated();
}
} | php | public function onConfigUpdated()
{
if ($this->xmppclient) {
$this->xmppclient->config = $this->config;
$this->xmppclient->onConfigUpdated();
}
} | [
"public",
"function",
"onConfigUpdated",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"xmppclient",
")",
"{",
"$",
"this",
"->",
"xmppclient",
"->",
"config",
"=",
"$",
"this",
"->",
"config",
";",
"$",
"this",
"->",
"xmppclient",
"->",
"onConfigUpdated"... | Called when worker is going to update configuration.
@return void | [
"Called",
"when",
"worker",
"is",
"going",
"to",
"update",
"configuration",
"."
] | train | https://github.com/kakserpom/phpdaemon/blob/cfbe02e60e162853747ea9484c12f15341e56833/PHPDaemon/Examples/ExampleJabberbot.php#L64-L70 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.