repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
enygma/expose | src/Expose/Console/Command/ProcessQueueCommand.php | ProcessQueueCommand.buildAdapter | protected function buildAdapter($queueType, $queueConnect, $databaseName)
{
preg_match('/(.+):(.+)@(.+)/', $queueConnect, $connect);
if (count($connect) < 4) {
return false;
}
list($full, $username, $password, $host) = $connect;
unset($full);
switch(strtolower($queueType)) {
case 'mongo':
if (!extension_loaded('mongo')) {
return false;
}
$connectString = 'mongodb://'.$username.':'.$password.'@'.$host.'/'.$databaseName;
$adapter = new \MongoClient($connectString);
break;
case 'mysql':
if (!extension_loaded('mysqli')) {
return false;
}
$adapter = new \mysqli($host, $username, $password, $databaseName);
break;
}
return $adapter;
} | php | protected function buildAdapter($queueType, $queueConnect, $databaseName)
{
preg_match('/(.+):(.+)@(.+)/', $queueConnect, $connect);
if (count($connect) < 4) {
return false;
}
list($full, $username, $password, $host) = $connect;
unset($full);
switch(strtolower($queueType)) {
case 'mongo':
if (!extension_loaded('mongo')) {
return false;
}
$connectString = 'mongodb://'.$username.':'.$password.'@'.$host.'/'.$databaseName;
$adapter = new \MongoClient($connectString);
break;
case 'mysql':
if (!extension_loaded('mysqli')) {
return false;
}
$adapter = new \mysqli($host, $username, $password, $databaseName);
break;
}
return $adapter;
} | [
"protected",
"function",
"buildAdapter",
"(",
"$",
"queueType",
",",
"$",
"queueConnect",
",",
"$",
"databaseName",
")",
"{",
"preg_match",
"(",
"'/(.+):(.+)@(.+)/'",
",",
"$",
"queueConnect",
",",
"$",
"connect",
")",
";",
"if",
"(",
"count",
"(",
"$",
"c... | Build an adapter based on the type+connection string
@param string $queueType Queue type (Ex. "mongo" or "mysql")
@param string $queueConnect Queue connection string (format: user:pass@host)
@param string $databaseName Database name
@return object Connection adapter | [
"Build",
"an",
"adapter",
"based",
"on",
"the",
"type",
"+",
"connection",
"string"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Console/Command/ProcessQueueCommand.php#L201-L227 | train |
enygma/expose | src/Expose/Converter/Converter.php | Converter.runAllConversions | public function runAllConversions($value)
{
$misc = new \Expose\Converter\ConvertMisc;
$value = $misc->convertFromUrlEncode($value);
$value = $misc->convertFromCommented($value);
$value = $misc->convertFromWhiteSpace($value);
$value = $misc->convertEntities($value);
$value = $misc->convertQuotes($value);
$value = $misc->convertFromControlChars($value);
$value = $misc->convertFromNestedBase64($value);
$value = $misc->convertFromOutOfRangeChars($value);
$value = $misc->convertFromXML($value);
$value = $misc->convertFromUTF7($value);
$value = $misc->convertFromConcatenated($value);
$value = $misc->convertFromProprietaryEncodings($value);
$js = new \Expose\Converter\ConvertJS;
$value = $js->convertFromJSCharcode($value);
$value = $js->convertJSRegexModifiers($value);
$value = $js->convertFromJSUnicode($value);
$sql = new \Expose\Converter\ConvertSQL;
$value = $sql->convertFromSQLHex($value);
$value = $sql->convertFromSQLKeywords($value);
$value = $sql->convertFromUrlencodeSqlComment($value);
return $value;
} | php | public function runAllConversions($value)
{
$misc = new \Expose\Converter\ConvertMisc;
$value = $misc->convertFromUrlEncode($value);
$value = $misc->convertFromCommented($value);
$value = $misc->convertFromWhiteSpace($value);
$value = $misc->convertEntities($value);
$value = $misc->convertQuotes($value);
$value = $misc->convertFromControlChars($value);
$value = $misc->convertFromNestedBase64($value);
$value = $misc->convertFromOutOfRangeChars($value);
$value = $misc->convertFromXML($value);
$value = $misc->convertFromUTF7($value);
$value = $misc->convertFromConcatenated($value);
$value = $misc->convertFromProprietaryEncodings($value);
$js = new \Expose\Converter\ConvertJS;
$value = $js->convertFromJSCharcode($value);
$value = $js->convertJSRegexModifiers($value);
$value = $js->convertFromJSUnicode($value);
$sql = new \Expose\Converter\ConvertSQL;
$value = $sql->convertFromSQLHex($value);
$value = $sql->convertFromSQLKeywords($value);
$value = $sql->convertFromUrlencodeSqlComment($value);
return $value;
} | [
"public",
"function",
"runAllConversions",
"(",
"$",
"value",
")",
"{",
"$",
"misc",
"=",
"new",
"\\",
"Expose",
"\\",
"Converter",
"\\",
"ConvertMisc",
";",
"$",
"value",
"=",
"$",
"misc",
"->",
"convertFromUrlEncode",
"(",
"$",
"value",
")",
";",
"$",
... | Run all the existing conversion methods
@param string $value the value to convert
@return string | [
"Run",
"all",
"the",
"existing",
"conversion",
"methods"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/Converter.php#L17-L44 | train |
enygma/expose | src/Expose/Filter.php | Filter.load | public function load($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
foreach ($data as $index => $value) {
if ($index == 'tags' && !is_array($value)) {
if (isset($value->tag)) {
$value = (!is_array($value->tag)) ? array($value->tag) : $value->tag;
}
}
$this->$index = $value;
}
} | php | public function load($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
foreach ($data as $index => $value) {
if ($index == 'tags' && !is_array($value)) {
if (isset($value->tag)) {
$value = (!is_array($value->tag)) ? array($value->tag) : $value->tag;
}
}
$this->$index = $value;
}
} | [
"public",
"function",
"load",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
"$",
"data",
"=",
"get_object_vars",
"(",
"$",
"data",
")",
";",
"}",
"foreach",
"(",
"$",
"data",
"as",
"$",
"index",
"=>",
"$",
... | Load the data into the filter object
@param array $data Filter data | [
"Load",
"the",
"data",
"into",
"the",
"filter",
"object"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Filter.php#L54-L67 | train |
enygma/expose | src/Expose/Filter.php | Filter.toArray | public function toArray()
{
return array(
'id' => $this->getId(),
'rule' => $this->getRule(),
'description' => $this->getDescription(),
'tags' => implode(', ', $this->getTags()),
'impact' => $this->getImpact()
);
} | php | public function toArray()
{
return array(
'id' => $this->getId(),
'rule' => $this->getRule(),
'description' => $this->getDescription(),
'tags' => implode(', ', $this->getTags()),
'impact' => $this->getImpact()
);
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"return",
"array",
"(",
"'id'",
"=>",
"$",
"this",
"->",
"getId",
"(",
")",
",",
"'rule'",
"=>",
"$",
"this",
"->",
"getRule",
"(",
")",
",",
"'description'",
"=>",
"$",
"this",
"->",
"getDescription",
... | Return the current Filter's data as an array
@return array Filter data | [
"Return",
"the",
"current",
"Filter",
"s",
"data",
"as",
"an",
"array"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Filter.php#L191-L200 | train |
enygma/expose | src/Expose/Converter/ConvertJS.php | ConvertJS.convertFromJSCharcode | public function convertFromJSCharcode($value)
{
$matches = array();
// check if value matches typical charCode pattern
if (preg_match_all('/(?:[\d+\-=\/ \*]+(?:\s?,\s?\d+)){4,}/ms', $value, $matches)) {
$converted = '';
$string = implode(',', $matches[0]);
$string = preg_replace('/\s/', '', $string);
$string = preg_replace('/\w+=/', '', $string);
$charcode = explode(',', $string);
foreach ($charcode as $char) {
$char = preg_replace('/\W0/s', '', $char);
if (preg_match_all('/\d*[+-\/\* ]\d+/', $char, $matches)) {
$match = preg_split('/(\W?\d+)/', implode('', $matches[0]), null, PREG_SPLIT_DELIM_CAPTURE);
if (array_sum($match) >= 20 && array_sum($match) <= 127) {
$converted .= chr(array_sum($match));
}
} elseif (!empty($char) && $char >= 20 && $char <= 127) {
$converted .= chr($char);
}
}
$value .= "\n" . $converted;
}
// check for octal charcode pattern
if (preg_match_all('/(?:(?:[\\\]+\d+[ \t]*){8,})/ims', $value, $matches)) {
$converted = '';
$charcode = explode('\\', preg_replace('/\s/', '', implode(',', $matches[0])));
foreach (array_map('octdec', array_filter($charcode)) as $char) {
if (20 <= $char && $char <= 127) {
$converted .= chr($char);
}
}
$value .= "\n" . $converted;
}
// check for hexadecimal charcode pattern
if (preg_match_all('/(?:(?:[\\\]+\w+\s*){8,})/ims', $value, $matches)) {
$converted = '';
$charcode = explode('\\', preg_replace('/[ux]/', '', implode(',', $matches[0])));
foreach (array_map('hexdec', array_filter($charcode)) as $char) {
if (20 <= $char && $char <= 127) {
$converted .= chr($char);
}
}
$value .= "\n" . $converted;
}
return $value;
} | php | public function convertFromJSCharcode($value)
{
$matches = array();
// check if value matches typical charCode pattern
if (preg_match_all('/(?:[\d+\-=\/ \*]+(?:\s?,\s?\d+)){4,}/ms', $value, $matches)) {
$converted = '';
$string = implode(',', $matches[0]);
$string = preg_replace('/\s/', '', $string);
$string = preg_replace('/\w+=/', '', $string);
$charcode = explode(',', $string);
foreach ($charcode as $char) {
$char = preg_replace('/\W0/s', '', $char);
if (preg_match_all('/\d*[+-\/\* ]\d+/', $char, $matches)) {
$match = preg_split('/(\W?\d+)/', implode('', $matches[0]), null, PREG_SPLIT_DELIM_CAPTURE);
if (array_sum($match) >= 20 && array_sum($match) <= 127) {
$converted .= chr(array_sum($match));
}
} elseif (!empty($char) && $char >= 20 && $char <= 127) {
$converted .= chr($char);
}
}
$value .= "\n" . $converted;
}
// check for octal charcode pattern
if (preg_match_all('/(?:(?:[\\\]+\d+[ \t]*){8,})/ims', $value, $matches)) {
$converted = '';
$charcode = explode('\\', preg_replace('/\s/', '', implode(',', $matches[0])));
foreach (array_map('octdec', array_filter($charcode)) as $char) {
if (20 <= $char && $char <= 127) {
$converted .= chr($char);
}
}
$value .= "\n" . $converted;
}
// check for hexadecimal charcode pattern
if (preg_match_all('/(?:(?:[\\\]+\w+\s*){8,})/ims', $value, $matches)) {
$converted = '';
$charcode = explode('\\', preg_replace('/[ux]/', '', implode(',', $matches[0])));
foreach (array_map('hexdec', array_filter($charcode)) as $char) {
if (20 <= $char && $char <= 127) {
$converted .= chr($char);
}
}
$value .= "\n" . $converted;
}
return $value;
} | [
"public",
"function",
"convertFromJSCharcode",
"(",
"$",
"value",
")",
"{",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"// check if value matches typical charCode pattern",
"if",
"(",
"preg_match_all",
"(",
"'/(?:[\\d+\\-=\\/ \\*]+(?:\\s?,\\s?\\d+)){4,}/ms'",
",",
"$",
... | Checks for common charcode pattern and decodes them
@param string $value the value to convert
@return string | [
"Checks",
"for",
"common",
"charcode",
"pattern",
"and",
"decodes",
"them"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertJS.php#L18-L64 | train |
enygma/expose | src/Expose/Converter/ConvertJS.php | ConvertJS.convertFromJSUnicode | public function convertFromJSUnicode($value)
{
$matches = array();
preg_match_all('/\\\u[0-9a-f]{4}/ims', $value, $matches);
if (!empty($matches[0])) {
foreach ($matches[0] as $match) {
$chr = chr(hexdec(substr($match, 2, 4)));
$value = str_replace($match, $chr, $value);
}
$value .= "\n\u0001";
}
return $value;
} | php | public function convertFromJSUnicode($value)
{
$matches = array();
preg_match_all('/\\\u[0-9a-f]{4}/ims', $value, $matches);
if (!empty($matches[0])) {
foreach ($matches[0] as $match) {
$chr = chr(hexdec(substr($match, 2, 4)));
$value = str_replace($match, $chr, $value);
}
$value .= "\n\u0001";
}
return $value;
} | [
"public",
"function",
"convertFromJSUnicode",
"(",
"$",
"value",
")",
"{",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"preg_match_all",
"(",
"'/\\\\\\u[0-9a-f]{4}/ims'",
",",
"$",
"value",
",",
"$",
"matches",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$... | This method converts JS unicode code points to regular characters
@param string $value the value to convert
@return string | [
"This",
"method",
"converts",
"JS",
"unicode",
"code",
"points",
"to",
"regular",
"characters"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertJS.php#L83-L95 | train |
enygma/expose | src/Expose/Notify/Email.php | Email.setToAddress | public function setToAddress($emailAddress)
{
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) {
throw new \InvalidArgumentException('Invalid email address: '.$emailAddress);
}
$this->toAddress = $emailAddress;
} | php | public function setToAddress($emailAddress)
{
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) {
throw new \InvalidArgumentException('Invalid email address: '.$emailAddress);
}
$this->toAddress = $emailAddress;
} | [
"public",
"function",
"setToAddress",
"(",
"$",
"emailAddress",
")",
"{",
"if",
"(",
"filter_var",
"(",
"$",
"emailAddress",
",",
"FILTER_VALIDATE_EMAIL",
")",
"!==",
"$",
"emailAddress",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid... | Set the "To" address for the notification
@param string $emailAddress Email address | [
"Set",
"the",
"To",
"address",
"for",
"the",
"notification"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Notify/Email.php#L40-L46 | train |
enygma/expose | src/Expose/Notify/Email.php | Email.setFromAddress | public function setFromAddress($emailAddress)
{
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) {
throw new \InvalidArgumentException('Invalid email address: '.$emailAddress);
}
$this->fromAddress = $emailAddress;
} | php | public function setFromAddress($emailAddress)
{
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== $emailAddress) {
throw new \InvalidArgumentException('Invalid email address: '.$emailAddress);
}
$this->fromAddress = $emailAddress;
} | [
"public",
"function",
"setFromAddress",
"(",
"$",
"emailAddress",
")",
"{",
"if",
"(",
"filter_var",
"(",
"$",
"emailAddress",
",",
"FILTER_VALIDATE_EMAIL",
")",
"!==",
"$",
"emailAddress",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Inval... | Set the current "From" email address on notifications
@param string $emailAddress Email address | [
"Set",
"the",
"current",
"From",
"email",
"address",
"on",
"notifications"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Notify/Email.php#L63-L69 | train |
enygma/expose | src/Expose/Notify/Email.php | Email.send | public function send($filterMatches)
{
$toAddress = $this->getToAddress();
$fromAddress = $this->getFromAddress();
if ($toAddress === null) {
throw new \InvalidArgumentException('Invalid "to" email address');
}
if ($fromAddress === null) {
throw new \InvalidArgumentException('Invalid "from" email address');
}
$loader = new \Twig_Loader_Filesystem(__DIR__.'/../Template');
$twig = new \Twig_Environment($loader);
$template = $twig->loadTemplate('Notify/Email.twig');
$headers = array(
"From: ".$fromAddress,
"Content-type: text/html; charset=iso-8859-1"
);
$totalImpact = 0;
$impactData = array();
foreach ($filterMatches as $match) {
$impactData[] = array(
'impact' => $match->getImpact(),
'description' => $match->getDescription(),
'id' => $match->getId(),
'tags' => implode(', ', $match->getTags())
);
$totalImpact += $match->getImpact();
}
$subject = 'Expose Notification - Impact Score '.$totalImpact;
$body = $template->render(array(
'impactData' => $impactData,
'runTime' => date('r'),
'totalImpact' => $totalImpact
));
return mail($toAddress, $subject, $body, implode("\r\n", $headers));
} | php | public function send($filterMatches)
{
$toAddress = $this->getToAddress();
$fromAddress = $this->getFromAddress();
if ($toAddress === null) {
throw new \InvalidArgumentException('Invalid "to" email address');
}
if ($fromAddress === null) {
throw new \InvalidArgumentException('Invalid "from" email address');
}
$loader = new \Twig_Loader_Filesystem(__DIR__.'/../Template');
$twig = new \Twig_Environment($loader);
$template = $twig->loadTemplate('Notify/Email.twig');
$headers = array(
"From: ".$fromAddress,
"Content-type: text/html; charset=iso-8859-1"
);
$totalImpact = 0;
$impactData = array();
foreach ($filterMatches as $match) {
$impactData[] = array(
'impact' => $match->getImpact(),
'description' => $match->getDescription(),
'id' => $match->getId(),
'tags' => implode(', ', $match->getTags())
);
$totalImpact += $match->getImpact();
}
$subject = 'Expose Notification - Impact Score '.$totalImpact;
$body = $template->render(array(
'impactData' => $impactData,
'runTime' => date('r'),
'totalImpact' => $totalImpact
));
return mail($toAddress, $subject, $body, implode("\r\n", $headers));
} | [
"public",
"function",
"send",
"(",
"$",
"filterMatches",
")",
"{",
"$",
"toAddress",
"=",
"$",
"this",
"->",
"getToAddress",
"(",
")",
";",
"$",
"fromAddress",
"=",
"$",
"this",
"->",
"getFromAddress",
"(",
")",
";",
"if",
"(",
"$",
"toAddress",
"===",... | Send the notification to the given email address
@param array $filterMatches Set of filter matches from execution
@return boolean Success/fail of sending email | [
"Send",
"the",
"notification",
"to",
"the",
"given",
"email",
"address"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Notify/Email.php#L87-L129 | train |
enygma/expose | src/Expose/Queue/Mongo.php | Mongo.getCollection | public function getCollection()
{
$queueDatabase = $this->database;
$queueResource = $this->collection;
$db = $this->getAdapter();
return $db->$queueDatabase->$queueResource;
} | php | public function getCollection()
{
$queueDatabase = $this->database;
$queueResource = $this->collection;
$db = $this->getAdapter();
return $db->$queueDatabase->$queueResource;
} | [
"public",
"function",
"getCollection",
"(",
")",
"{",
"$",
"queueDatabase",
"=",
"$",
"this",
"->",
"database",
";",
"$",
"queueResource",
"=",
"$",
"this",
"->",
"collection",
";",
"$",
"db",
"=",
"$",
"this",
"->",
"getAdapter",
"(",
")",
";",
"retur... | Get the queue collection
@return \MongoCollection Collection instance | [
"Get",
"the",
"queue",
"collection"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Queue/Mongo.php#L47-L54 | train |
enygma/expose | src/Expose/Queue/Mongo.php | Mongo.add | public function add($requestData)
{
$data = array(
'data' => $requestData,
'remote_ip' => (isset($_SERVER['REMOTE_ADDR']))
? $_SERVER['REMOTE_ADDR'] : 0,
'datetime' => time(),
'processed' => false
);
return $this->getCollection()->insert($data);
} | php | public function add($requestData)
{
$data = array(
'data' => $requestData,
'remote_ip' => (isset($_SERVER['REMOTE_ADDR']))
? $_SERVER['REMOTE_ADDR'] : 0,
'datetime' => time(),
'processed' => false
);
return $this->getCollection()->insert($data);
} | [
"public",
"function",
"add",
"(",
"$",
"requestData",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"'data'",
"=>",
"$",
"requestData",
",",
"'remote_ip'",
"=>",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'REMOTE_ADDR'",
"]",
")",
")",
"?",
"$",
"_SERVER",
... | Add a new record to the queue
@param array $requestData Request data | [
"Add",
"a",
"new",
"record",
"to",
"the",
"queue"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Queue/Mongo.php#L61-L72 | train |
enygma/expose | src/Expose/Queue/Mongo.php | Mongo.getPending | public function getPending($limit = 10)
{
$results = $this->getCollection()
->find(array('processed' => false))
->limit($limit);
return iterator_to_array($results);
} | php | public function getPending($limit = 10)
{
$results = $this->getCollection()
->find(array('processed' => false))
->limit($limit);
return iterator_to_array($results);
} | [
"public",
"function",
"getPending",
"(",
"$",
"limit",
"=",
"10",
")",
"{",
"$",
"results",
"=",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"find",
"(",
"array",
"(",
"'processed'",
"=>",
"false",
")",
")",
"->",
"limit",
"(",
"$",
"limit",
... | Get the current list of pending records
@return array Record results | [
"Get",
"the",
"current",
"list",
"of",
"pending",
"records"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Queue/Mongo.php#L93-L100 | train |
enygma/expose | src/Expose/Config.php | Config.get | public function get($path)
{
$p = explode('.', $path);
$cfg = &$this->config;
$count = 1;
foreach ($p as $part) {
if (array_key_exists($part, $cfg)) {
// see if it's the end
if ($count == count($p)) {
echo 'end';
return $cfg[$part];
}
$cfg = &$cfg[$part];
}
$count++;
}
return null;
} | php | public function get($path)
{
$p = explode('.', $path);
$cfg = &$this->config;
$count = 1;
foreach ($p as $part) {
if (array_key_exists($part, $cfg)) {
// see if it's the end
if ($count == count($p)) {
echo 'end';
return $cfg[$part];
}
$cfg = &$cfg[$part];
}
$count++;
}
return null;
} | [
"public",
"function",
"get",
"(",
"$",
"path",
")",
"{",
"$",
"p",
"=",
"explode",
"(",
"'.'",
",",
"$",
"path",
")",
";",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"config",
";",
"$",
"count",
"=",
"1",
";",
"foreach",
"(",
"$",
"p",
"as",
... | Get the value from the config by "path"
@param string $path Path to config option (Ex. "foo.bar.baz")
@return mixed Either the found value or null if not found | [
"Get",
"the",
"value",
"from",
"the",
"config",
"by",
"path"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Config.php#L43-L61 | train |
enygma/expose | src/Expose/Config.php | Config.set | public function set($path, $value)
{
$p = explode('.', $path);
$cfg = &$this->config;
$count = 1;
foreach ($p as $part) {
if ($count == count($p)) {
$cfg[$part] = $value;
continue;
}
if (array_key_exists($part, $cfg)) {
$cfg = &$cfg[$part];
} else {
// create the path
$cfg[$part] = array();
$cfg = &$cfg[$part];
}
$count++;
}
} | php | public function set($path, $value)
{
$p = explode('.', $path);
$cfg = &$this->config;
$count = 1;
foreach ($p as $part) {
if ($count == count($p)) {
$cfg[$part] = $value;
continue;
}
if (array_key_exists($part, $cfg)) {
$cfg = &$cfg[$part];
} else {
// create the path
$cfg[$part] = array();
$cfg = &$cfg[$part];
}
$count++;
}
} | [
"public",
"function",
"set",
"(",
"$",
"path",
",",
"$",
"value",
")",
"{",
"$",
"p",
"=",
"explode",
"(",
"'.'",
",",
"$",
"path",
")",
";",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"config",
";",
"$",
"count",
"=",
"1",
";",
"foreach",
"(",... | Set the configuration option based on the "path"
@param string $path Config "path" (Ex. "foo.bar.baz")
@param mixed $value Value of config | [
"Set",
"the",
"configuration",
"option",
"based",
"on",
"the",
"path"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Config.php#L69-L89 | train |
enygma/expose | src/Expose/FilterCollection.php | FilterCollection.setFilterImpact | public function setFilterImpact($filterId, $impact) {
$filter = $this->getFilterData($filterId);
if($filter === null) {
return;
}
$filter->setImpact($impact);
} | php | public function setFilterImpact($filterId, $impact) {
$filter = $this->getFilterData($filterId);
if($filter === null) {
return;
}
$filter->setImpact($impact);
} | [
"public",
"function",
"setFilterImpact",
"(",
"$",
"filterId",
",",
"$",
"impact",
")",
"{",
"$",
"filter",
"=",
"$",
"this",
"->",
"getFilterData",
"(",
"$",
"filterId",
")",
";",
"if",
"(",
"$",
"filter",
"===",
"null",
")",
"{",
"return",
";",
"}"... | Alter the impact level of a specific filter id.
@param integer $filterId
@param integer $impact | [
"Alter",
"the",
"impact",
"level",
"of",
"a",
"specific",
"filter",
"id",
"."
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/FilterCollection.php#L100-L107 | train |
enygma/expose | src/Expose/Console/Command/FilterCommand.php | FilterCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$col = new \Expose\FilterCollection();
$col->load();
$filters = $col->getFilterData();
$id = $input->getOption('id');
if ($id !== false) {
$idList = explode(',', $id);
foreach ($idList as $id) {
if (array_key_exists($id, $filters)) {
$detail = "[".$id."] ".$filters[$id]->getDescription()."\n";
$detail .= "\tRule: ".$filters[$id]->getRule()."\n";
$detail .= "\tTags: ".implode(', ', $filters[$id]->getTags())."\n";
$detail .= "\tImpact: ".$filters[$id]->getImpact()."\n";
$output->writeLn($detail);
} else {
$output->writeLn('Filter ID '.$id.' not found!');
}
}
return;
}
foreach ($filters as $filter) {
echo $filter->getId().': '. $filter->getDescription()."\n";
}
return;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$col = new \Expose\FilterCollection();
$col->load();
$filters = $col->getFilterData();
$id = $input->getOption('id');
if ($id !== false) {
$idList = explode(',', $id);
foreach ($idList as $id) {
if (array_key_exists($id, $filters)) {
$detail = "[".$id."] ".$filters[$id]->getDescription()."\n";
$detail .= "\tRule: ".$filters[$id]->getRule()."\n";
$detail .= "\tTags: ".implode(', ', $filters[$id]->getTags())."\n";
$detail .= "\tImpact: ".$filters[$id]->getImpact()."\n";
$output->writeLn($detail);
} else {
$output->writeLn('Filter ID '.$id.' not found!');
}
}
return;
}
foreach ($filters as $filter) {
echo $filter->getId().': '. $filter->getDescription()."\n";
}
return;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"col",
"=",
"new",
"\\",
"Expose",
"\\",
"FilterCollection",
"(",
")",
";",
"$",
"col",
"->",
"load",
"(",
")",
";",
"$",
"fi... | Execute the filter command
@param InputInterface $input Input object
@param OutputInterface $output Output object
@return null | [
"Execute",
"the",
"filter",
"command"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Console/Command/FilterCommand.php#L31-L59 | train |
enygma/expose | src/Expose/Converter/ConvertMisc.php | ConvertMisc.convertFromUTF7 | public function convertFromUTF7($value)
{
if (preg_match('/\+A\w+-?/m', $value)) {
if (function_exists('mb_convert_encoding')) {
if (version_compare(PHP_VERSION, '5.2.8', '<')) {
$tmp_chars = str_split($value);
$value = '';
foreach ($tmp_chars as $char) {
if (ord($char) <= 127) {
$value .= $char;
}
}
}
$value .= "\n" . mb_convert_encoding($value, 'UTF-8', 'UTF-7');
} else {
//list of all critical UTF7 codepoints
$schemes = array(
'+ACI-' => '"',
'+ADw-' => '<',
'+AD4-' => '>',
'+AFs-' => '[',
'+AF0-' => ']',
'+AHs-' => '{',
'+AH0-' => '}',
'+AFw-' => '\\',
'+ADs-' => ';',
'+ACM-' => '#',
'+ACY-' => '&',
'+ACU-' => '%',
'+ACQ-' => '$',
'+AD0-' => '=',
'+AGA-' => '`',
'+ALQ-' => '"',
'+IBg-' => '"',
'+IBk-' => '"',
'+AHw-' => '|',
'+ACo-' => '*',
'+AF4-' => '^',
'+ACIAPg-' => '">',
'+ACIAPgA8-' => '">'
);
$value = str_ireplace(
array_keys($schemes),
array_values($schemes),
$value
);
}
}
return $value;
} | php | public function convertFromUTF7($value)
{
if (preg_match('/\+A\w+-?/m', $value)) {
if (function_exists('mb_convert_encoding')) {
if (version_compare(PHP_VERSION, '5.2.8', '<')) {
$tmp_chars = str_split($value);
$value = '';
foreach ($tmp_chars as $char) {
if (ord($char) <= 127) {
$value .= $char;
}
}
}
$value .= "\n" . mb_convert_encoding($value, 'UTF-8', 'UTF-7');
} else {
//list of all critical UTF7 codepoints
$schemes = array(
'+ACI-' => '"',
'+ADw-' => '<',
'+AD4-' => '>',
'+AFs-' => '[',
'+AF0-' => ']',
'+AHs-' => '{',
'+AH0-' => '}',
'+AFw-' => '\\',
'+ADs-' => ';',
'+ACM-' => '#',
'+ACY-' => '&',
'+ACU-' => '%',
'+ACQ-' => '$',
'+AD0-' => '=',
'+AGA-' => '`',
'+ALQ-' => '"',
'+IBg-' => '"',
'+IBk-' => '"',
'+AHw-' => '|',
'+ACo-' => '*',
'+AF4-' => '^',
'+ACIAPg-' => '">',
'+ACIAPgA8-' => '">'
);
$value = str_ireplace(
array_keys($schemes),
array_values($schemes),
$value
);
}
}
return $value;
} | [
"public",
"function",
"convertFromUTF7",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/\\+A\\w+-?/m'",
",",
"$",
"value",
")",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'mb_convert_encoding'",
")",
")",
"{",
"if",
"(",
"version_compare",
... | Converts relevant UTF-7 tags to UTF-8
@param string $value the value to convert
@return string | [
"Converts",
"relevant",
"UTF",
"-",
"7",
"tags",
"to",
"UTF",
"-",
"8"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertMisc.php#L222-L271 | train |
enygma/expose | src/Expose/Converter/ConvertMisc.php | ConvertMisc.convertFromUrlEncode | public function convertFromUrlEncode($value)
{
$converted = urldecode($value);
if (!$converted || $converted === $value) {
return $value;
} else {
return $value . "\n" . $converted;
}
} | php | public function convertFromUrlEncode($value)
{
$converted = urldecode($value);
if (!$converted || $converted === $value) {
return $value;
} else {
return $value . "\n" . $converted;
}
} | [
"public",
"function",
"convertFromUrlEncode",
"(",
"$",
"value",
")",
"{",
"$",
"converted",
"=",
"urldecode",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"$",
"converted",
"||",
"$",
"converted",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"value",... | Check for basic urlencoded information
@param string $value the value to convert
@return string | [
"Check",
"for",
"basic",
"urlencoded",
"information"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Converter/ConvertMisc.php#L371-L379 | train |
enygma/expose | src/Expose/Manager.php | Manager.processFilters | protected function processFilters($value, $index, $path)
{
$filterMatches = array();
$filters = $this->getFilters();
$filters->rewind();
while($filters->valid() && !$this->impactLimitReached()) {
$filter = $filters->current();
$filters->next();
if ($filter->execute($value) === true) {
$filterMatches[] = $filter;
$this->getLogger()->info(
'Match found on Filter ID '.$filter->getId(),
array($filter->toArray())
);
$report = new \Expose\Report($index, $value, $path);
$report->addFilterMatch($filter);
$this->reports[] = $report;
$this->impact += $filter->getImpact();
}
}
return $filterMatches;
} | php | protected function processFilters($value, $index, $path)
{
$filterMatches = array();
$filters = $this->getFilters();
$filters->rewind();
while($filters->valid() && !$this->impactLimitReached()) {
$filter = $filters->current();
$filters->next();
if ($filter->execute($value) === true) {
$filterMatches[] = $filter;
$this->getLogger()->info(
'Match found on Filter ID '.$filter->getId(),
array($filter->toArray())
);
$report = new \Expose\Report($index, $value, $path);
$report->addFilterMatch($filter);
$this->reports[] = $report;
$this->impact += $filter->getImpact();
}
}
return $filterMatches;
} | [
"protected",
"function",
"processFilters",
"(",
"$",
"value",
",",
"$",
"index",
",",
"$",
"path",
")",
"{",
"$",
"filterMatches",
"=",
"array",
"(",
")",
";",
"$",
"filters",
"=",
"$",
"this",
"->",
"getFilters",
"(",
")",
";",
"$",
"filters",
"->",... | Runs value through all filters
@param $value
@param $index
@param $path | [
"Runs",
"value",
"through",
"all",
"filters"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L239-L262 | train |
enygma/expose | src/Expose/Manager.php | Manager.impactLimitReached | protected function impactLimitReached()
{
if ($this->impactLimit < 1) {
return false;
}
$reached = $this->impact >= $this->impactLimit;
if ($reached) {
$this->getLogger()->info(
'Reached Impact limit'
);
}
return $reached;
} | php | protected function impactLimitReached()
{
if ($this->impactLimit < 1) {
return false;
}
$reached = $this->impact >= $this->impactLimit;
if ($reached) {
$this->getLogger()->info(
'Reached Impact limit'
);
}
return $reached;
} | [
"protected",
"function",
"impactLimitReached",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"impactLimit",
"<",
"1",
")",
"{",
"return",
"false",
";",
"}",
"$",
"reached",
"=",
"$",
"this",
"->",
"impact",
">=",
"$",
"this",
"->",
"impactLimit",
";",
... | Tests if the impact limit has been reached
@return bool | [
"Tests",
"if",
"the",
"impact",
"limit",
"has",
"been",
"reached"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L269-L282 | train |
enygma/expose | src/Expose/Manager.php | Manager.notify | public function notify(array $filterMatches)
{
$notify = $this->getNotify();
if ($notify === null) {
throw new \InvalidArgumentException(
'Invalid notification method'
);
}
$notify->send($filterMatches);
} | php | public function notify(array $filterMatches)
{
$notify = $this->getNotify();
if ($notify === null) {
throw new \InvalidArgumentException(
'Invalid notification method'
);
}
$notify->send($filterMatches);
} | [
"public",
"function",
"notify",
"(",
"array",
"$",
"filterMatches",
")",
"{",
"$",
"notify",
"=",
"$",
"this",
"->",
"getNotify",
"(",
")",
";",
"if",
"(",
"$",
"notify",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"... | If enabled, send the notification of the test run
@param array $filterMatches Set of matches against filters
@throws \InvalidArgumentException If notify type is inavlid | [
"If",
"enabled",
"send",
"the",
"notification",
"of",
"the",
"test",
"run"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L300-L309 | train |
enygma/expose | src/Expose/Manager.php | Manager.isException | public function isException($path)
{
$isException = false;
foreach ($this->exceptions as $exception) {
if ($isException === false) {
if ($path === $exception || preg_match('/^'.$exception.'$/', $path) !== 0) {
$isException = true;
}
}
}
return $isException;
} | php | public function isException($path)
{
$isException = false;
foreach ($this->exceptions as $exception) {
if ($isException === false) {
if ($path === $exception || preg_match('/^'.$exception.'$/', $path) !== 0) {
$isException = true;
}
}
}
return $isException;
} | [
"public",
"function",
"isException",
"(",
"$",
"path",
")",
"{",
"$",
"isException",
"=",
"false",
";",
"foreach",
"(",
"$",
"this",
"->",
"exceptions",
"as",
"$",
"exception",
")",
"{",
"if",
"(",
"$",
"isException",
"===",
"false",
")",
"{",
"if",
... | Test to see if a variable is an exception
Checks can be exceptions, so we preg_match it
@param string $path Variable "path" (Ex. "POST.foo.bar")
@return boolean Found/not found | [
"Test",
"to",
"see",
"if",
"a",
"variable",
"is",
"an",
"exception",
"Checks",
"can",
"be",
"exceptions",
"so",
"we",
"preg_match",
"it"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L522-L534 | train |
enygma/expose | src/Expose/Manager.php | Manager.setConfig | public function setConfig($config)
{
if (is_array($config)) {
$this->config = new Config($config);
} else {
// see if it's a file path
if (is_file($config)) {
$cfg = parse_ini_file($config, true);
$this->config = new Config($cfg);
} else {
throw new \InvalidArgumentException(
'Could not load configuration file '.$config
);
}
}
} | php | public function setConfig($config)
{
if (is_array($config)) {
$this->config = new Config($config);
} else {
// see if it's a file path
if (is_file($config)) {
$cfg = parse_ini_file($config, true);
$this->config = new Config($cfg);
} else {
throw new \InvalidArgumentException(
'Could not load configuration file '.$config
);
}
}
} | [
"public",
"function",
"setConfig",
"(",
"$",
"config",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"new",
"Config",
"(",
"$",
"config",
")",
";",
"}",
"else",
"{",
"// see if it's a file path",
... | Set the configuration for the object
@param array|string $config Either an array of config settings
or the path to the config file
@throws \InvalidArgumentException If config file doesn't exist | [
"Set",
"the",
"configuration",
"for",
"the",
"object"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L567-L582 | train |
enygma/expose | src/Expose/Manager.php | Manager.export | public function export($format = 'text')
{
$className = '\\Expose\\Export\\'.ucwords(strtolower($format));
if (class_exists($className)) {
$export = new $className($this->getReports());
return $export->render();
}
return null;
} | php | public function export($format = 'text')
{
$className = '\\Expose\\Export\\'.ucwords(strtolower($format));
if (class_exists($className)) {
$export = new $className($this->getReports());
return $export->render();
}
return null;
} | [
"public",
"function",
"export",
"(",
"$",
"format",
"=",
"'text'",
")",
"{",
"$",
"className",
"=",
"'\\\\Expose\\\\Export\\\\'",
".",
"ucwords",
"(",
"strtolower",
"(",
"$",
"format",
")",
")",
";",
"if",
"(",
"class_exists",
"(",
"$",
"className",
")",
... | Expose the current set of reports in the given format
@param string $format Fromat for the export
@return mixed Report output (or null if the export type isn't found) | [
"Expose",
"the",
"current",
"set",
"of",
"reports",
"in",
"the",
"given",
"format"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Manager.php#L640-L648 | train |
enygma/expose | src/Expose/Cache/File.php | File.save | public function save($key, $data)
{
$hash = md5($key);
$cacheFile = $this->getPath().'/'.$hash.'.cache';
return file_put_contents($cacheFile, serialize($data));
} | php | public function save($key, $data)
{
$hash = md5($key);
$cacheFile = $this->getPath().'/'.$hash.'.cache';
return file_put_contents($cacheFile, serialize($data));
} | [
"public",
"function",
"save",
"(",
"$",
"key",
",",
"$",
"data",
")",
"{",
"$",
"hash",
"=",
"md5",
"(",
"$",
"key",
")",
";",
"$",
"cacheFile",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
".",
"'/'",
".",
"$",
"hash",
".",
"'.cache'",
";",
... | Save the cache data to a file
@param string $key Identifier key (used in filename)
@param mixed $data Data to cache
@return boolean Success/fail of save | [
"Save",
"the",
"cache",
"data",
"to",
"a",
"file"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Cache/File.php#L20-L26 | train |
enygma/expose | src/Expose/Cache/File.php | File.get | public function get($key)
{
$hash = md5($key);
$cacheFile = $this->getPath().'/'.$hash.'.cache';
if (!is_file($cacheFile)) {
return null;
}
return unserialize(file_get_contents($cacheFile));
} | php | public function get($key)
{
$hash = md5($key);
$cacheFile = $this->getPath().'/'.$hash.'.cache';
if (!is_file($cacheFile)) {
return null;
}
return unserialize(file_get_contents($cacheFile));
} | [
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"$",
"hash",
"=",
"md5",
"(",
"$",
"key",
")",
";",
"$",
"cacheFile",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
".",
"'/'",
".",
"$",
"hash",
".",
"'.cache'",
";",
"if",
"(",
"!",
"is... | Get the record identified by the given key
@param string $key Cache identifier key
@return mixed Returns either data or null if not found | [
"Get",
"the",
"record",
"identified",
"by",
"the",
"given",
"key"
] | 07ee1ebe5af6a23029d4d30147463141df724fc5 | https://github.com/enygma/expose/blob/07ee1ebe5af6a23029d4d30147463141df724fc5/src/Expose/Cache/File.php#L34-L43 | train |
Brain-WP/Cortex | src/Cortex/Router/Router.php | Router.ensurePreviewVars | private function ensurePreviewVars(array $vars, array $uriVars)
{
if (! is_user_logged_in()) {
return $vars;
}
foreach (['preview', 'preview_id', 'preview_nonce'] as $var) {
if (! isset($vars[$var]) && isset($uriVars[$var])) {
$vars[$var] = $uriVars[$var];
}
}
return $vars;
} | php | private function ensurePreviewVars(array $vars, array $uriVars)
{
if (! is_user_logged_in()) {
return $vars;
}
foreach (['preview', 'preview_id', 'preview_nonce'] as $var) {
if (! isset($vars[$var]) && isset($uriVars[$var])) {
$vars[$var] = $uriVars[$var];
}
}
return $vars;
} | [
"private",
"function",
"ensurePreviewVars",
"(",
"array",
"$",
"vars",
",",
"array",
"$",
"uriVars",
")",
"{",
"if",
"(",
"!",
"is_user_logged_in",
"(",
")",
")",
"{",
"return",
"$",
"vars",
";",
"}",
"foreach",
"(",
"[",
"'preview'",
",",
"'preview_id'"... | To ensure preview works, we need to merge preview-related query string
to query arguments.
@param array $vars
@param array $uriVars
@return array | [
"To",
"ensure",
"preview",
"works",
"we",
"need",
"to",
"merge",
"preview",
"-",
"related",
"query",
"string",
"to",
"query",
"arguments",
"."
] | 4c9cf21d3f25775cbd6faf6a75638b1c11ac0368 | https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Router/Router.php#L278-L291 | train |
Brain-WP/Cortex | src/Cortex/Uri/PsrUri.php | PsrUri.marshallFromServer | private function marshallFromServer()
{
$scheme = is_ssl() ? 'https' : 'http';
$host = $this->marshallHostFromServer() ? : parse_url(home_url(), PHP_URL_HOST);
$host = trim($host, '/');
$pathArray = explode('?', $this->marshallPathFromServer(), 2);
$path = trim($pathArray[0], '/');
empty($path) and $path = '/';
$query_string = '';
if (isset($this->server['QUERY_STRING'])) {
$query_string = ltrim($this->server['QUERY_STRING'], '?');
}
$this->storage = compact('scheme', 'host', 'path', 'query_string');
$this->parsed = true;
} | php | private function marshallFromServer()
{
$scheme = is_ssl() ? 'https' : 'http';
$host = $this->marshallHostFromServer() ? : parse_url(home_url(), PHP_URL_HOST);
$host = trim($host, '/');
$pathArray = explode('?', $this->marshallPathFromServer(), 2);
$path = trim($pathArray[0], '/');
empty($path) and $path = '/';
$query_string = '';
if (isset($this->server['QUERY_STRING'])) {
$query_string = ltrim($this->server['QUERY_STRING'], '?');
}
$this->storage = compact('scheme', 'host', 'path', 'query_string');
$this->parsed = true;
} | [
"private",
"function",
"marshallFromServer",
"(",
")",
"{",
"$",
"scheme",
"=",
"is_ssl",
"(",
")",
"?",
"'https'",
":",
"'http'",
";",
"$",
"host",
"=",
"$",
"this",
"->",
"marshallHostFromServer",
"(",
")",
"?",
":",
"parse_url",
"(",
"home_url",
"(",
... | Parse server array to find url components. | [
"Parse",
"server",
"array",
"to",
"find",
"url",
"components",
"."
] | 4c9cf21d3f25775cbd6faf6a75638b1c11ac0368 | https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Uri/PsrUri.php#L222-L241 | train |
Brain-WP/Cortex | src/Cortex/Uri/PsrUri.php | PsrUri.marshallHostFromServer | private function marshallHostFromServer()
{
$host = isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : '';
if (empty($host)) {
return isset($this->server['SERVER_NAME']) ? $this->server['SERVER_NAME'] : '';
}
if (is_string($host) && preg_match('|\:(\d+)$|', $host, $matches)) {
$host = substr($host, 0, -1 * (strlen($matches[1]) + 1));
}
return $host;
} | php | private function marshallHostFromServer()
{
$host = isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : '';
if (empty($host)) {
return isset($this->server['SERVER_NAME']) ? $this->server['SERVER_NAME'] : '';
}
if (is_string($host) && preg_match('|\:(\d+)$|', $host, $matches)) {
$host = substr($host, 0, -1 * (strlen($matches[1]) + 1));
}
return $host;
} | [
"private",
"function",
"marshallHostFromServer",
"(",
")",
"{",
"$",
"host",
"=",
"isset",
"(",
"$",
"this",
"->",
"server",
"[",
"'HTTP_HOST'",
"]",
")",
"?",
"$",
"this",
"->",
"server",
"[",
"'HTTP_HOST'",
"]",
":",
"''",
";",
"if",
"(",
"empty",
... | Parse server array to find url host.
Contains code from Zend\Diactoros\ServerRequestFactory
@copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com)
@license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD
License
@return string | [
"Parse",
"server",
"array",
"to",
"find",
"url",
"host",
"."
] | 4c9cf21d3f25775cbd6faf6a75638b1c11ac0368 | https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Uri/PsrUri.php#L254-L266 | train |
Brain-WP/Cortex | src/Cortex/Uri/PsrUri.php | PsrUri.marshallPathFromServer | private function marshallPathFromServer()
{
$get = function ($key, array $values, $default = null) {
return array_key_exists($key, $values) ? $values[$key] : $default;
};
// IIS7 with URL Rewrite: make sure we get the unencoded url
// (double slash problem).
$iisUrlRewritten = $get('IIS_WasUrlRewritten', $this->server);
$unencodedUrl = $get('UNENCODED_URL', $this->server, '');
if ('1' == $iisUrlRewritten && ! empty($unencodedUrl)) {
return $unencodedUrl;
}
$requestUri = $get('REQUEST_URI', $this->server);
// Check this first so IIS will catch.
$httpXRewriteUrl = $get('HTTP_X_REWRITE_URL', $this->server);
if ($httpXRewriteUrl !== null) {
$requestUri = $httpXRewriteUrl;
}
// Check for IIS 7.0 or later with ISAPI_Rewrite
$httpXOriginalUrl = $get('HTTP_X_ORIGINAL_URL', $this->server);
if ($httpXOriginalUrl !== null) {
$requestUri = $httpXOriginalUrl;
}
if ($requestUri !== null) {
return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri);
}
$origPathInfo = $get('ORIG_PATH_INFO', $this->server);
return empty($origPathInfo) ? '/' : $origPathInfo;
} | php | private function marshallPathFromServer()
{
$get = function ($key, array $values, $default = null) {
return array_key_exists($key, $values) ? $values[$key] : $default;
};
// IIS7 with URL Rewrite: make sure we get the unencoded url
// (double slash problem).
$iisUrlRewritten = $get('IIS_WasUrlRewritten', $this->server);
$unencodedUrl = $get('UNENCODED_URL', $this->server, '');
if ('1' == $iisUrlRewritten && ! empty($unencodedUrl)) {
return $unencodedUrl;
}
$requestUri = $get('REQUEST_URI', $this->server);
// Check this first so IIS will catch.
$httpXRewriteUrl = $get('HTTP_X_REWRITE_URL', $this->server);
if ($httpXRewriteUrl !== null) {
$requestUri = $httpXRewriteUrl;
}
// Check for IIS 7.0 or later with ISAPI_Rewrite
$httpXOriginalUrl = $get('HTTP_X_ORIGINAL_URL', $this->server);
if ($httpXOriginalUrl !== null) {
$requestUri = $httpXOriginalUrl;
}
if ($requestUri !== null) {
return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri);
}
$origPathInfo = $get('ORIG_PATH_INFO', $this->server);
return empty($origPathInfo) ? '/' : $origPathInfo;
} | [
"private",
"function",
"marshallPathFromServer",
"(",
")",
"{",
"$",
"get",
"=",
"function",
"(",
"$",
"key",
",",
"array",
"$",
"values",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"values",
")... | Parse server array to find url path.
Contains code from Zend\Diactoros\ServerRequestFactory
@copyright Copyright (c) 2015 Zend Technologies USA Inc. (http://www.zend.com)
@license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD
License
@return string | [
"Parse",
"server",
"array",
"to",
"find",
"url",
"path",
"."
] | 4c9cf21d3f25775cbd6faf6a75638b1c11ac0368 | https://github.com/Brain-WP/Cortex/blob/4c9cf21d3f25775cbd6faf6a75638b1c11ac0368/src/Cortex/Uri/PsrUri.php#L279-L314 | train |
huyanping/simple-fork-php | src/Queue/SystemVMessageQueue.php | SystemVMessageQueue.setStatus | public function setStatus($key, $value)
{
$this->checkSetPrivilege($key);
if ($key == 'msg_qbytes')
return $this->setMaxQueueSize($value);
$queue_status[$key] = $value;
return \msg_set_queue($this->queue, $queue_status);
} | php | public function setStatus($key, $value)
{
$this->checkSetPrivilege($key);
if ($key == 'msg_qbytes')
return $this->setMaxQueueSize($value);
$queue_status[$key] = $value;
return \msg_set_queue($this->queue, $queue_status);
} | [
"public",
"function",
"setStatus",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"checkSetPrivilege",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"key",
"==",
"'msg_qbytes'",
")",
"return",
"$",
"this",
"->",
"setMaxQueueSize",
"(",
... | allows you to change the values of the msg_perm.uid,
msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure
@param string $key status key
@param int $value status value
@return bool | [
"allows",
"you",
"to",
"change",
"the",
"values",
"of",
"the",
"msg_perm",
".",
"uid",
"msg_perm",
".",
"gid",
"msg_perm",
".",
"mode",
"and",
"msg_qbytes",
"fields",
"of",
"the",
"underlying",
"message",
"queue",
"data",
"structure"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/SystemVMessageQueue.php#L213-L221 | train |
huyanping/simple-fork-php | src/Queue/Pipe.php | Pipe.read | public function read($size = 1024)
{
if (!is_resource($this->read)) {
$this->read = fopen($this->filename, 'r+');
if (!is_resource($this->read)) {
throw new \RuntimeException('open file failed');
}
if (!$this->block) {
$set = stream_set_blocking($this->read, false);
if (!$set) {
throw new \RuntimeException('stream_set_blocking failed');
}
}
}
return fread($this->read, $size);
} | php | public function read($size = 1024)
{
if (!is_resource($this->read)) {
$this->read = fopen($this->filename, 'r+');
if (!is_resource($this->read)) {
throw new \RuntimeException('open file failed');
}
if (!$this->block) {
$set = stream_set_blocking($this->read, false);
if (!$set) {
throw new \RuntimeException('stream_set_blocking failed');
}
}
}
return fread($this->read, $size);
} | [
"public",
"function",
"read",
"(",
"$",
"size",
"=",
"1024",
")",
"{",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"this",
"->",
"read",
")",
")",
"{",
"$",
"this",
"->",
"read",
"=",
"fopen",
"(",
"$",
"this",
"->",
"filename",
",",
"'r+'",
")",
... | if the stream is blocking, you would better set the value of size,
it will not return until the data size is equal to the value of param size
@param int $size
@return string | [
"if",
"the",
"stream",
"is",
"blocking",
"you",
"would",
"better",
"set",
"the",
"value",
"of",
"size",
"it",
"will",
"not",
"return",
"until",
"the",
"data",
"size",
"is",
"equal",
"to",
"the",
"value",
"of",
"param",
"size"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/Pipe.php#L78-L94 | train |
huyanping/simple-fork-php | src/FixedPool.php | FixedPool.wait | public function wait($block = false, $interval = 100)
{
do {
if ($this->isFinished()) {
return;
}
parent::wait(false);
if ($this->aliveCount() < $this->max) {
foreach ($this->processes as $process) {
if ($process->isStarted()) continue;
$process->start();
if ($this->aliveCount() >= $this->max) break;
}
}
$block ? usleep($interval) : null;
} while ($block);
} | php | public function wait($block = false, $interval = 100)
{
do {
if ($this->isFinished()) {
return;
}
parent::wait(false);
if ($this->aliveCount() < $this->max) {
foreach ($this->processes as $process) {
if ($process->isStarted()) continue;
$process->start();
if ($this->aliveCount() >= $this->max) break;
}
}
$block ? usleep($interval) : null;
} while ($block);
} | [
"public",
"function",
"wait",
"(",
"$",
"block",
"=",
"false",
",",
"$",
"interval",
"=",
"100",
")",
"{",
"do",
"{",
"if",
"(",
"$",
"this",
"->",
"isFinished",
"(",
")",
")",
"{",
"return",
";",
"}",
"parent",
"::",
"wait",
"(",
"false",
")",
... | wait for all process done
@param bool $block block the master process
to keep the sub process count all the time
@param int $interval check time interval | [
"wait",
"for",
"all",
"process",
"done"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/FixedPool.php#L49-L65 | train |
huyanping/simple-fork-php | src/Utils.php | Utils.checkOverwriteRunMethod | public static function checkOverwriteRunMethod($child_class)
{
$parent_class = '\\Jenner\\SimpleFork\\Process';
if ($child_class == $parent_class) {
$message = "you should extend the `{$parent_class}`" .
' and overwrite the run method';
throw new \RuntimeException($message);
}
$child = new \ReflectionClass($child_class);
if ($child->getParentClass() === false) {
$message = "you should extend the `{$parent_class}`" .
' and overwrite the run method';
throw new \RuntimeException($message);
}
$parent_methods = $child->getParentClass()->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($parent_methods as $parent_method) {
if ($parent_method->getName() !== 'run') continue;
$declaring_class = $child->getMethod($parent_method->getName())
->getDeclaringClass()
->getName();
if ($declaring_class === $parent_class) {
throw new \RuntimeException('you must overwrite the run method');
}
}
} | php | public static function checkOverwriteRunMethod($child_class)
{
$parent_class = '\\Jenner\\SimpleFork\\Process';
if ($child_class == $parent_class) {
$message = "you should extend the `{$parent_class}`" .
' and overwrite the run method';
throw new \RuntimeException($message);
}
$child = new \ReflectionClass($child_class);
if ($child->getParentClass() === false) {
$message = "you should extend the `{$parent_class}`" .
' and overwrite the run method';
throw new \RuntimeException($message);
}
$parent_methods = $child->getParentClass()->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($parent_methods as $parent_method) {
if ($parent_method->getName() !== 'run') continue;
$declaring_class = $child->getMethod($parent_method->getName())
->getDeclaringClass()
->getName();
if ($declaring_class === $parent_class) {
throw new \RuntimeException('you must overwrite the run method');
}
}
} | [
"public",
"static",
"function",
"checkOverwriteRunMethod",
"(",
"$",
"child_class",
")",
"{",
"$",
"parent_class",
"=",
"'\\\\Jenner\\\\SimpleFork\\\\Process'",
";",
"if",
"(",
"$",
"child_class",
"==",
"$",
"parent_class",
")",
"{",
"$",
"message",
"=",
"\"you sh... | check if the sub class of Process has overwrite the run method
@param $child_class | [
"check",
"if",
"the",
"sub",
"class",
"of",
"Process",
"has",
"overwrite",
"the",
"run",
"method"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Utils.php#L18-L47 | train |
huyanping/simple-fork-php | src/Process.php | Process.initStatus | protected function initStatus()
{
$this->pid = null;
$this->running = null;
$this->term_signal = null;
$this->stop_signal = null;
$this->errno = null;
$this->errmsg = null;
} | php | protected function initStatus()
{
$this->pid = null;
$this->running = null;
$this->term_signal = null;
$this->stop_signal = null;
$this->errno = null;
$this->errmsg = null;
} | [
"protected",
"function",
"initStatus",
"(",
")",
"{",
"$",
"this",
"->",
"pid",
"=",
"null",
";",
"$",
"this",
"->",
"running",
"=",
"null",
";",
"$",
"this",
"->",
"term_signal",
"=",
"null",
";",
"$",
"this",
"->",
"stop_signal",
"=",
"null",
";",
... | init process status | [
"init",
"process",
"status"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L99-L107 | train |
huyanping/simple-fork-php | src/Process.php | Process.start | public function start()
{
if (!empty($this->pid) && $this->isRunning()) {
throw new \LogicException("the process is already running");
}
$callback = $this->getCallable();
$pid = pcntl_fork();
if ($pid < 0) {
throw new \RuntimeException("fork error");
} elseif ($pid > 0) {
$this->pid = $pid;
$this->running = true;
$this->started = true;
} else {
$this->pid = getmypid();
$this->signal();
foreach ($this->signal_handlers as $signal => $handler) {
pcntl_signal($signal, $handler);
}
call_user_func($callback);
exit(0);
}
} | php | public function start()
{
if (!empty($this->pid) && $this->isRunning()) {
throw new \LogicException("the process is already running");
}
$callback = $this->getCallable();
$pid = pcntl_fork();
if ($pid < 0) {
throw new \RuntimeException("fork error");
} elseif ($pid > 0) {
$this->pid = $pid;
$this->running = true;
$this->started = true;
} else {
$this->pid = getmypid();
$this->signal();
foreach ($this->signal_handlers as $signal => $handler) {
pcntl_signal($signal, $handler);
}
call_user_func($callback);
exit(0);
}
} | [
"public",
"function",
"start",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"pid",
")",
"&&",
"$",
"this",
"->",
"isRunning",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"\"the process is already running\"",
")",
... | start the sub process
and run the callback
@return string pid | [
"start",
"the",
"sub",
"process",
"and",
"run",
"the",
"callback"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L189-L213 | train |
huyanping/simple-fork-php | src/Process.php | Process.updateStatus | protected function updateStatus($block = false)
{
if ($this->running !== true) {
return;
}
if ($block) {
$res = pcntl_waitpid($this->pid, $status);
} else {
$res = pcntl_waitpid($this->pid, $status, WNOHANG | WUNTRACED);
}
if ($res === -1) {
throw new \RuntimeException('pcntl_waitpid failed. the process maybe available');
} elseif ($res === 0) {
$this->running = true;
} else {
if (pcntl_wifsignaled($status)) {
$this->term_signal = pcntl_wtermsig($status);
}
if (pcntl_wifstopped($status)) {
$this->stop_signal = pcntl_wstopsig($status);
}
if (pcntl_wifexited($status)) {
$this->errno = pcntl_wexitstatus($status);
$this->errmsg = pcntl_strerror($this->errno);
} else {
$this->errno = pcntl_get_last_error();
$this->errmsg = pcntl_strerror($this->errno);
}
if (pcntl_wifsignaled($status)) {
$this->if_signal = true;
} else {
$this->if_signal = false;
}
$this->running = false;
}
} | php | protected function updateStatus($block = false)
{
if ($this->running !== true) {
return;
}
if ($block) {
$res = pcntl_waitpid($this->pid, $status);
} else {
$res = pcntl_waitpid($this->pid, $status, WNOHANG | WUNTRACED);
}
if ($res === -1) {
throw new \RuntimeException('pcntl_waitpid failed. the process maybe available');
} elseif ($res === 0) {
$this->running = true;
} else {
if (pcntl_wifsignaled($status)) {
$this->term_signal = pcntl_wtermsig($status);
}
if (pcntl_wifstopped($status)) {
$this->stop_signal = pcntl_wstopsig($status);
}
if (pcntl_wifexited($status)) {
$this->errno = pcntl_wexitstatus($status);
$this->errmsg = pcntl_strerror($this->errno);
} else {
$this->errno = pcntl_get_last_error();
$this->errmsg = pcntl_strerror($this->errno);
}
if (pcntl_wifsignaled($status)) {
$this->if_signal = true;
} else {
$this->if_signal = false;
}
$this->running = false;
}
} | [
"protected",
"function",
"updateStatus",
"(",
"$",
"block",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"running",
"!==",
"true",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"block",
")",
"{",
"$",
"res",
"=",
"pcntl_waitpid",
"(",
"$",... | update the process status
@param bool $block | [
"update",
"the",
"process",
"status"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L231-L269 | train |
huyanping/simple-fork-php | src/Process.php | Process.getCallable | protected function getCallable()
{
$callback = null;
if (is_object($this->runnable) && $this->runnable instanceof Runnable) {
$callback = array($this->runnable, 'run');
} elseif (is_callable($this->runnable)) {
$callback = $this->runnable;
} else {
$callback = array($this, 'run');
}
return $callback;
} | php | protected function getCallable()
{
$callback = null;
if (is_object($this->runnable) && $this->runnable instanceof Runnable) {
$callback = array($this->runnable, 'run');
} elseif (is_callable($this->runnable)) {
$callback = $this->runnable;
} else {
$callback = array($this, 'run');
}
return $callback;
} | [
"protected",
"function",
"getCallable",
"(",
")",
"{",
"$",
"callback",
"=",
"null",
";",
"if",
"(",
"is_object",
"(",
"$",
"this",
"->",
"runnable",
")",
"&&",
"$",
"this",
"->",
"runnable",
"instanceof",
"Runnable",
")",
"{",
"$",
"callback",
"=",
"a... | get sub process callback
@return array|callable|null | [
"get",
"sub",
"process",
"callback"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L276-L288 | train |
huyanping/simple-fork-php | src/Process.php | Process.wait | public function wait($block = true, $sleep = 100000)
{
while (true) {
if ($this->isRunning() === false) {
return;
}
if (!$block) {
break;
}
usleep($sleep);
}
} | php | public function wait($block = true, $sleep = 100000)
{
while (true) {
if ($this->isRunning() === false) {
return;
}
if (!$block) {
break;
}
usleep($sleep);
}
} | [
"public",
"function",
"wait",
"(",
"$",
"block",
"=",
"true",
",",
"$",
"sleep",
"=",
"100000",
")",
"{",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isRunning",
"(",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"if",
"... | waiting for the sub process exit
@param bool|true $block if block the process
@param int $sleep default 0.1s check sub process status
every $sleep milliseconds. | [
"waiting",
"for",
"the",
"sub",
"process",
"exit"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Process.php#L330-L341 | train |
huyanping/simple-fork-php | src/Lock/Semaphore.php | Semaphore._stringToSemKey | protected function _stringToSemKey($identifier)
{
$md5 = md5($identifier);
$key = 0;
for ($i = 0; $i < 32; $i++) {
$key += ord($md5{$i}) * $i;
}
return $key;
} | php | protected function _stringToSemKey($identifier)
{
$md5 = md5($identifier);
$key = 0;
for ($i = 0; $i < 32; $i++) {
$key += ord($md5{$i}) * $i;
}
return $key;
} | [
"protected",
"function",
"_stringToSemKey",
"(",
"$",
"identifier",
")",
"{",
"$",
"md5",
"=",
"md5",
"(",
"$",
"identifier",
")",
";",
"$",
"key",
"=",
"0",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"32",
";",
"$",
"i",
"++",
... | Semaphore requires a numeric value as the key
@param $identifier
@return int | [
"Semaphore",
"requires",
"a",
"numeric",
"value",
"as",
"the",
"key"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Lock/Semaphore.php#L48-L56 | train |
huyanping/simple-fork-php | src/Lock/Semaphore.php | Semaphore.remove | public function remove()
{
if ($this->locked) {
throw new \RuntimeException('can not remove a locked semaphore resource');
}
if (!is_resource($this->lock_id)) {
throw new \RuntimeException('can not remove a empty semaphore resource');
}
if (!sem_release($this->lock_id)) {
return false;
}
return true;
} | php | public function remove()
{
if ($this->locked) {
throw new \RuntimeException('can not remove a locked semaphore resource');
}
if (!is_resource($this->lock_id)) {
throw new \RuntimeException('can not remove a empty semaphore resource');
}
if (!sem_release($this->lock_id)) {
return false;
}
return true;
} | [
"public",
"function",
"remove",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"locked",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'can not remove a locked semaphore resource'",
")",
";",
"}",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"this",
... | remove the semaphore resource
@return bool | [
"remove",
"the",
"semaphore",
"resource"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Lock/Semaphore.php#L148-L162 | train |
huyanping/simple-fork-php | src/Cache/SharedMemory.php | SharedMemory.attach | public function attach($file = __FILE__)
{
if (!file_exists($file)) {
$touch = touch($file);
if (!$touch) {
throw new \RuntimeException("file is not exists and it can not be created. file: {$file}");
}
}
$key = ftok($file, 'a');
$this->shm = shm_attach($key, $this->size); //allocate shared memory
} | php | public function attach($file = __FILE__)
{
if (!file_exists($file)) {
$touch = touch($file);
if (!$touch) {
throw new \RuntimeException("file is not exists and it can not be created. file: {$file}");
}
}
$key = ftok($file, 'a');
$this->shm = shm_attach($key, $this->size); //allocate shared memory
} | [
"public",
"function",
"attach",
"(",
"$",
"file",
"=",
"__FILE__",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"$",
"touch",
"=",
"touch",
"(",
"$",
"file",
")",
";",
"if",
"(",
"!",
"$",
"touch",
")",
"{",
"throw"... | connect shared memory
@param string $file | [
"connect",
"shared",
"memory"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Cache/SharedMemory.php#L60-L70 | train |
huyanping/simple-fork-php | src/Cache/SharedMemory.php | SharedMemory.remove | public function remove()
{
//dallocate shared memory
if (!shm_remove($this->shm)) {
return false;
}
$this->dettach();
// shm_remove maybe not working. it likes a php bug.
unset($this->shm);
return true;
} | php | public function remove()
{
//dallocate shared memory
if (!shm_remove($this->shm)) {
return false;
}
$this->dettach();
// shm_remove maybe not working. it likes a php bug.
unset($this->shm);
return true;
} | [
"public",
"function",
"remove",
"(",
")",
"{",
"//dallocate shared memory",
"if",
"(",
"!",
"shm_remove",
"(",
"$",
"this",
"->",
"shm",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"dettach",
"(",
")",
";",
"// shm_remove maybe not worki... | remove shared memory.
you should know that it maybe does not work.
@return bool | [
"remove",
"shared",
"memory",
".",
"you",
"should",
"know",
"that",
"it",
"maybe",
"does",
"not",
"work",
"."
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Cache/SharedMemory.php#L78-L89 | train |
huyanping/simple-fork-php | src/Cache/SharedMemory.php | SharedMemory.has | public function has($key)
{
if (shm_has_var($this->shm, $this->shm_key($key))) { // check is isset
return true;
} else {
return false;
}
} | php | public function has($key)
{
if (shm_has_var($this->shm, $this->shm_key($key))) { // check is isset
return true;
} else {
return false;
}
} | [
"public",
"function",
"has",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"shm_has_var",
"(",
"$",
"this",
"->",
"shm",
",",
"$",
"this",
"->",
"shm_key",
"(",
"$",
"key",
")",
")",
")",
"{",
"// check is isset",
"return",
"true",
";",
"}",
"else",
"{",
... | has var ?
@param $key
@return bool | [
"has",
"var",
"?"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Cache/SharedMemory.php#L145-L152 | train |
huyanping/simple-fork-php | src/Pool.php | Pool.execute | public function execute(Process $process, $name = null)
{
if (!is_null($name)) {
$process->name($name);
}
if (!$process->isStarted()) {
$process->start();
}
return array_push($this->processes, $process);
} | php | public function execute(Process $process, $name = null)
{
if (!is_null($name)) {
$process->name($name);
}
if (!$process->isStarted()) {
$process->start();
}
return array_push($this->processes, $process);
} | [
"public",
"function",
"execute",
"(",
"Process",
"$",
"process",
",",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"name",
")",
")",
"{",
"$",
"process",
"->",
"name",
"(",
"$",
"name",
")",
";",
"}",
"if",
"(",
"!",... | add a process
@param Process $process
@param null|string $name process name
@return int | [
"add",
"a",
"process"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Pool.php#L27-L37 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.getProcessByPid | public function getProcessByPid($pid)
{
foreach ($this->processes as $process) {
if ($process->getPid() == $pid) {
return $process;
}
}
return null;
} | php | public function getProcessByPid($pid)
{
foreach ($this->processes as $process) {
if ($process->getPid() == $pid) {
return $process;
}
}
return null;
} | [
"public",
"function",
"getProcessByPid",
"(",
"$",
"pid",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"process",
"->",
"getPid",
"(",
")",
"==",
"$",
"pid",
")",
"{",
"return",
"$",
"pro... | get process by pid
@param $pid
@return null|Process | [
"get",
"process",
"by",
"pid"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L32-L41 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.shutdown | public function shutdown($signal = SIGTERM)
{
foreach ($this->processes as $process) {
if ($process->isRunning()) {
$process->shutdown(true, $signal);
}
}
} | php | public function shutdown($signal = SIGTERM)
{
foreach ($this->processes as $process) {
if ($process->isRunning()) {
$process->shutdown(true, $signal);
}
}
} | [
"public",
"function",
"shutdown",
"(",
"$",
"signal",
"=",
"SIGTERM",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"process",
"->",
"isRunning",
"(",
")",
")",
"{",
"$",
"process",
"->",
... | shutdown all process
@param int $signal | [
"shutdown",
"all",
"process"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L57-L64 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.wait | public function wait($block = true, $sleep = 100)
{
do {
foreach ($this->processes as $process) {
if (!$process->isRunning()) {
continue;
}
}
usleep($sleep);
} while ($block && $this->aliveCount() > 0);
} | php | public function wait($block = true, $sleep = 100)
{
do {
foreach ($this->processes as $process) {
if (!$process->isRunning()) {
continue;
}
}
usleep($sleep);
} while ($block && $this->aliveCount() > 0);
} | [
"public",
"function",
"wait",
"(",
"$",
"block",
"=",
"true",
",",
"$",
"sleep",
"=",
"100",
")",
"{",
"do",
"{",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"process",
")",
"{",
"if",
"(",
"!",
"$",
"process",
"->",
"isRunning",
"... | waiting for the sub processes to exit
@param bool|true $block if true the parent process will be blocked until all
sub processes exit. else it will check if there are processes that had been exited once and return.
@param int $sleep when $block is true, it will check sub processes every $sleep minute | [
"waiting",
"for",
"the",
"sub",
"processes",
"to",
"exit"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L88-L98 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.aliveCount | public function aliveCount()
{
$count = 0;
foreach ($this->processes as $process) {
if ($process->isRunning()) {
$count++;
}
}
return $count;
} | php | public function aliveCount()
{
$count = 0;
foreach ($this->processes as $process) {
if ($process->isRunning()) {
$count++;
}
}
return $count;
} | [
"public",
"function",
"aliveCount",
"(",
")",
"{",
"$",
"count",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"process",
"->",
"isRunning",
"(",
")",
")",
"{",
"$",
"count",
"++",
... | get the count of running processes
@return int | [
"get",
"the",
"count",
"of",
"running",
"processes"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L105-L115 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.getProcessByName | public function getProcessByName($name)
{
foreach ($this->processes as $process) {
if ($process->name() == $name) {
return $process;
}
}
return null;
} | php | public function getProcessByName($name)
{
foreach ($this->processes as $process) {
if ($process->name() == $name) {
return $process;
}
}
return null;
} | [
"public",
"function",
"getProcessByName",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"process",
"->",
"name",
"(",
")",
"==",
"$",
"name",
")",
"{",
"return",
"$",
"pr... | get process by name
@param string $name process name
@return Process|null | [
"get",
"process",
"by",
"name"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L123-L132 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.removeProcessByName | public function removeProcessByName($name)
{
foreach ($this->processes as $key => $process) {
if ($process->name() == $name) {
if ($process->isRunning()) {
throw new \RuntimeException("can not remove a running process");
}
unset($this->processes[$key]);
}
}
} | php | public function removeProcessByName($name)
{
foreach ($this->processes as $key => $process) {
if ($process->name() == $name) {
if ($process->isRunning()) {
throw new \RuntimeException("can not remove a running process");
}
unset($this->processes[$key]);
}
}
} | [
"public",
"function",
"removeProcessByName",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"key",
"=>",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"process",
"->",
"name",
"(",
")",
"==",
"$",
"name",
")",
"{... | remove process by name
@param string $name process name
@throws \RuntimeException | [
"remove",
"process",
"by",
"name"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L140-L150 | train |
huyanping/simple-fork-php | src/AbstractPool.php | AbstractPool.removeExitedProcess | public function removeExitedProcess()
{
foreach ($this->processes as $key => $process) {
if ($process->isStopped()) {
unset($this->processes[$key]);
}
}
} | php | public function removeExitedProcess()
{
foreach ($this->processes as $key => $process) {
if ($process->isStopped()) {
unset($this->processes[$key]);
}
}
} | [
"public",
"function",
"removeExitedProcess",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"processes",
"as",
"$",
"key",
"=>",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"process",
"->",
"isStopped",
"(",
")",
")",
"{",
"unset",
"(",
"$",
"this",... | remove exited process | [
"remove",
"exited",
"process"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/AbstractPool.php#L155-L162 | train |
huyanping/simple-fork-php | src/ParallelPool.php | ParallelPool.reload | public function reload($block = true)
{
$old_processes = $this->processes;
for ($i = 0; $i < $this->max; $i++) {
$process = new Process($this->runnable);
$process->start();
$this->processes[$process->getPid()] = $process;
}
foreach ($old_processes as $process) {
$process->shutdown();
$process->wait($block);
unset($this->processes[$process->getPid()]);
}
} | php | public function reload($block = true)
{
$old_processes = $this->processes;
for ($i = 0; $i < $this->max; $i++) {
$process = new Process($this->runnable);
$process->start();
$this->processes[$process->getPid()] = $process;
}
foreach ($old_processes as $process) {
$process->shutdown();
$process->wait($block);
unset($this->processes[$process->getPid()]);
}
} | [
"public",
"function",
"reload",
"(",
"$",
"block",
"=",
"true",
")",
"{",
"$",
"old_processes",
"=",
"$",
"this",
"->",
"processes",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"max",
";",
"$",
"i",
"++",
")",
... | start the same number processes and kill the old sub process
just like nginx -s reload
this method will block until all the old process exit;
@param bool $block | [
"start",
"the",
"same",
"number",
"processes",
"and",
"kill",
"the",
"old",
"sub",
"process",
"just",
"like",
"nginx",
"-",
"s",
"reload",
"this",
"method",
"will",
"block",
"until",
"all",
"the",
"old",
"process",
"exit",
";"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/ParallelPool.php#L50-L64 | train |
huyanping/simple-fork-php | src/ParallelPool.php | ParallelPool.keep | public function keep($block = false, $interval = 100)
{
do {
$this->start();
// recycle sub process and delete the processes
// which are not running from process list
foreach ($this->processes as $process) {
if (!$process->isRunning()) {
unset($this->processes[$process->getPid()]);
}
}
$block ? usleep($interval) : null;
} while ($block);
} | php | public function keep($block = false, $interval = 100)
{
do {
$this->start();
// recycle sub process and delete the processes
// which are not running from process list
foreach ($this->processes as $process) {
if (!$process->isRunning()) {
unset($this->processes[$process->getPid()]);
}
}
$block ? usleep($interval) : null;
} while ($block);
} | [
"public",
"function",
"keep",
"(",
"$",
"block",
"=",
"false",
",",
"$",
"interval",
"=",
"100",
")",
"{",
"do",
"{",
"$",
"this",
"->",
"start",
"(",
")",
";",
"// recycle sub process and delete the processes",
"// which are not running from process list",
"forea... | keep sub process count
@param bool $block block the master process
to keep the sub process count all the time
@param int $interval check time interval | [
"keep",
"sub",
"process",
"count"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/ParallelPool.php#L73-L88 | train |
huyanping/simple-fork-php | src/ParallelPool.php | ParallelPool.start | public function start()
{
$alive_count = $this->aliveCount();
// create sub process and run
if ($alive_count < $this->max) {
$need = $this->max - $alive_count;
for ($i = 0; $i < $need; $i++) {
$process = new Process($this->runnable);
$process->start();
$this->processes[$process->getPid()] = $process;
}
}
} | php | public function start()
{
$alive_count = $this->aliveCount();
// create sub process and run
if ($alive_count < $this->max) {
$need = $this->max - $alive_count;
for ($i = 0; $i < $need; $i++) {
$process = new Process($this->runnable);
$process->start();
$this->processes[$process->getPid()] = $process;
}
}
} | [
"public",
"function",
"start",
"(",
")",
"{",
"$",
"alive_count",
"=",
"$",
"this",
"->",
"aliveCount",
"(",
")",
";",
"// create sub process and run",
"if",
"(",
"$",
"alive_count",
"<",
"$",
"this",
"->",
"max",
")",
"{",
"$",
"need",
"=",
"$",
"this... | start the pool | [
"start",
"the",
"pool"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/ParallelPool.php#L93-L105 | train |
huyanping/simple-fork-php | src/Queue/PipeQueue.php | PipeQueue.put | public function put($value)
{
$len = strlen($value);
if ($len > 2147483647) {
throw new \RuntimeException('value is too long');
}
$raw = pack('N', $len) . $value;
$write_len = $this->pipe->write($raw);
return $write_len == strlen($raw);
} | php | public function put($value)
{
$len = strlen($value);
if ($len > 2147483647) {
throw new \RuntimeException('value is too long');
}
$raw = pack('N', $len) . $value;
$write_len = $this->pipe->write($raw);
return $write_len == strlen($raw);
} | [
"public",
"function",
"put",
"(",
"$",
"value",
")",
"{",
"$",
"len",
"=",
"strlen",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"len",
">",
"2147483647",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'value is too long'",
")",
";",
"}",... | put value into the queue of channel
@param $value
@return bool | [
"put",
"value",
"into",
"the",
"queue",
"of",
"channel"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/PipeQueue.php#L42-L52 | train |
huyanping/simple-fork-php | src/Queue/PipeQueue.php | PipeQueue.get | public function get($block = false)
{
if ($this->block != $block) {
$this->pipe->setBlock($block);
$this->block = $block;
}
$len = $this->pipe->read(4);
if ($len === false) {
throw new \RuntimeException('read pipe failed');
}
if (strlen($len) === 0) {
return null;
}
$len = unpack('N', $len);
if (empty($len) || !array_key_exists(1, $len) || empty($len[1])) {
throw new \RuntimeException('data protocol error');
}
$len = intval($len[1]);
$value = '';
while (true) {
$temp = $this->pipe->read($len);
if (strlen($temp) == $len) {
return $temp;
}
$value .= $temp;
$len -= strlen($temp);
if ($len == 0) {
return $value;
}
}
} | php | public function get($block = false)
{
if ($this->block != $block) {
$this->pipe->setBlock($block);
$this->block = $block;
}
$len = $this->pipe->read(4);
if ($len === false) {
throw new \RuntimeException('read pipe failed');
}
if (strlen($len) === 0) {
return null;
}
$len = unpack('N', $len);
if (empty($len) || !array_key_exists(1, $len) || empty($len[1])) {
throw new \RuntimeException('data protocol error');
}
$len = intval($len[1]);
$value = '';
while (true) {
$temp = $this->pipe->read($len);
if (strlen($temp) == $len) {
return $temp;
}
$value .= $temp;
$len -= strlen($temp);
if ($len == 0) {
return $value;
}
}
} | [
"public",
"function",
"get",
"(",
"$",
"block",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"block",
"!=",
"$",
"block",
")",
"{",
"$",
"this",
"->",
"pipe",
"->",
"setBlock",
"(",
"$",
"block",
")",
";",
"$",
"this",
"->",
"block",
"... | get value from the queue of channel
@param bool $block if block when the queue is empty
@return bool|string | [
"get",
"value",
"from",
"the",
"queue",
"of",
"channel"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/PipeQueue.php#L60-L92 | train |
huyanping/simple-fork-php | src/Queue/RedisQueue.php | RedisQueue.put | public function put($value)
{
if ($this->redis->lPush($this->channel, $value) !== false) {
return true;
}
return false;
} | php | public function put($value)
{
if ($this->redis->lPush($this->channel, $value) !== false) {
return true;
}
return false;
} | [
"public",
"function",
"put",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"redis",
"->",
"lPush",
"(",
"$",
"this",
"->",
"channel",
",",
"$",
"value",
")",
"!==",
"false",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";... | put value into the queue
@param $value
@return bool | [
"put",
"value",
"into",
"the",
"queue"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/RedisQueue.php#L76-L84 | train |
huyanping/simple-fork-php | src/Queue/RedisQueue.php | RedisQueue.get | public function get($block = false)
{
if (!$block) {
return $this->redis->rPop($this->channel);
} else {
while (true) {
$record = $this->redis->rPop($this->channel);
if ($record === false) {
usleep(1000);
continue;
}
return $record;
}
}
} | php | public function get($block = false)
{
if (!$block) {
return $this->redis->rPop($this->channel);
} else {
while (true) {
$record = $this->redis->rPop($this->channel);
if ($record === false) {
usleep(1000);
continue;
}
return $record;
}
}
} | [
"public",
"function",
"get",
"(",
"$",
"block",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"block",
")",
"{",
"return",
"$",
"this",
"->",
"redis",
"->",
"rPop",
"(",
"$",
"this",
"->",
"channel",
")",
";",
"}",
"else",
"{",
"while",
"(",
"tr... | get value from the queue
@param bool $block if block when the queue is empty
@return bool|string | [
"get",
"value",
"from",
"the",
"queue"
] | 4af8f61b283a612492ca9ab790472309ce681156 | https://github.com/huyanping/simple-fork-php/blob/4af8f61b283a612492ca9ab790472309ce681156/src/Queue/RedisQueue.php#L92-L107 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/Item.php | Item.getPropertyIndex | protected function getPropertyIndex(array $propertyValues, $index)
{
// If the property value index is out of bounds
if (!isset($propertyValues[$index])) {
throw new OutOfBoundsException(
sprintf(OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX_STR, $index),
OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX
);
}
return $this->getPropertyValue($propertyValues[$index]);
} | php | protected function getPropertyIndex(array $propertyValues, $index)
{
// If the property value index is out of bounds
if (!isset($propertyValues[$index])) {
throw new OutOfBoundsException(
sprintf(OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX_STR, $index),
OutOfBoundsException::INVALID_PROPERTY_VALUE_INDEX
);
}
return $this->getPropertyValue($propertyValues[$index]);
} | [
"protected",
"function",
"getPropertyIndex",
"(",
"array",
"$",
"propertyValues",
",",
"$",
"index",
")",
"{",
"// If the property value index is out of bounds",
"if",
"(",
"!",
"isset",
"(",
"$",
"propertyValues",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",... | Return a particular property index
@param ValueInterface[] $propertyValues Property values
@param int $index Property value index
@return ValueInterface|ItemInterface | [
"Return",
"a",
"particular",
"property",
"index"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/Item.php#L124-L135 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/Item.php | Item.isOfProfiledTypes | protected function isOfProfiledTypes($profile, array $names, ProfiledNamesList $types)
{
// Run through all query types
/** @var \stdClass $queryType */
foreach ($types as $queryType) {
if ($this->isTypeInNames($queryType, $profile, $names)) {
return true;
}
}
return false;
} | php | protected function isOfProfiledTypes($profile, array $names, ProfiledNamesList $types)
{
// Run through all query types
/** @var \stdClass $queryType */
foreach ($types as $queryType) {
if ($this->isTypeInNames($queryType, $profile, $names)) {
return true;
}
}
return false;
} | [
"protected",
"function",
"isOfProfiledTypes",
"(",
"$",
"profile",
",",
"array",
"$",
"names",
",",
"ProfiledNamesList",
"$",
"types",
")",
"{",
"// Run through all query types",
"/** @var \\stdClass $queryType */",
"foreach",
"(",
"$",
"types",
"as",
"$",
"queryType"... | Return whether an aliased item type is contained in a set of query types
@param string $profile Type profile
@param array $names Aliased type names
@param ProfiledNamesList $types Query types
@return bool Item type is contained in the set of query types | [
"Return",
"whether",
"an",
"aliased",
"item",
"type",
"is",
"contained",
"in",
"a",
"set",
"of",
"query",
"types"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/Item.php#L187-L198 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/Item.php | Item.isTypeInNames | protected function isTypeInNames($type, $profile, array $names)
{
return in_array($type->name, $names) &&
(($type->profile === null) ? true : ($type->profile == $profile));
} | php | protected function isTypeInNames($type, $profile, array $names)
{
return in_array($type->name, $names) &&
(($type->profile === null) ? true : ($type->profile == $profile));
} | [
"protected",
"function",
"isTypeInNames",
"(",
"$",
"type",
",",
"$",
"profile",
",",
"array",
"$",
"names",
")",
"{",
"return",
"in_array",
"(",
"$",
"type",
"->",
"name",
",",
"$",
"names",
")",
"&&",
"(",
"(",
"$",
"type",
"->",
"profile",
"===",
... | Test whether a type is contained in a list of names
@param \stdClass $type Type
@param string $profile Type profile
@param array $names Aliased type names
@return bool Type is contained in names list | [
"Test",
"whether",
"a",
"type",
"is",
"contained",
"in",
"a",
"list",
"of",
"names"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/Item.php#L209-L213 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/Item.php | Item.getFirstProperty | public function getFirstProperty(...$properties)
{
/** @var ProfiledNamesList $properties */
$properties = ProfiledNamesFactory::createFromArguments(func_get_args());
// Prepare a default exception
$exception = new OutOfBoundsException(
OutOfBoundsException::NO_MATCHING_PROPERTIES_STR,
OutOfBoundsException::NO_MATCHING_PROPERTIES
);
// Run through all properties
foreach ($properties as $property) {
try {
return (array)$this->getProperty($property->name, $property->profile);
} catch (OutOfBoundsException $exception) {
continue;
}
}
throw $exception;
} | php | public function getFirstProperty(...$properties)
{
/** @var ProfiledNamesList $properties */
$properties = ProfiledNamesFactory::createFromArguments(func_get_args());
// Prepare a default exception
$exception = new OutOfBoundsException(
OutOfBoundsException::NO_MATCHING_PROPERTIES_STR,
OutOfBoundsException::NO_MATCHING_PROPERTIES
);
// Run through all properties
foreach ($properties as $property) {
try {
return (array)$this->getProperty($property->name, $property->profile);
} catch (OutOfBoundsException $exception) {
continue;
}
}
throw $exception;
} | [
"public",
"function",
"getFirstProperty",
"(",
"...",
"$",
"properties",
")",
"{",
"/** @var ProfiledNamesList $properties */",
"$",
"properties",
"=",
"ProfiledNamesFactory",
"::",
"createFromArguments",
"(",
"func_get_args",
"(",
")",
")",
";",
"// Prepare a default exc... | Get all values of the first available property in a stack
The property stack can be specified in a variety of ways, @see ProfiledNamesFactory::createFromArguments()
@param array $properties Properties
@return ValueInterface[]|array Property values
@throws InvalidArgumentException If no property name was given
@throws OutOfBoundsException If none of the requested properties is known
@api | [
"Get",
"all",
"values",
"of",
"the",
"first",
"available",
"property",
"in",
"a",
"stack"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/Item.php#L227-L248 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/Item.php | Item.getProperties | public function getProperties()
{
$propertyList = (new PropertyListFactory())->create();
foreach ($this->item->getProperties() as $propertyName => $propertyValues) {
$propertyList[$propertyName] = array_map([$this, 'getPropertyValue'], $propertyValues);
}
return $propertyList;
} | php | public function getProperties()
{
$propertyList = (new PropertyListFactory())->create();
foreach ($this->item->getProperties() as $propertyName => $propertyValues) {
$propertyList[$propertyName] = array_map([$this, 'getPropertyValue'], $propertyValues);
}
return $propertyList;
} | [
"public",
"function",
"getProperties",
"(",
")",
"{",
"$",
"propertyList",
"=",
"(",
"new",
"PropertyListFactory",
"(",
")",
")",
"->",
"create",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"item",
"->",
"getProperties",
"(",
")",
"as",
"$",
"pro... | Return all properties
@return PropertyListInterface Properties
@api | [
"Return",
"all",
"properties"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/Item.php#L256-L264 | train |
jkphl/micrometa | src/Micrometa/Ports/Parser.php | Parser.createDom | protected function createDom($uri, $source = null, array $httpOptions = [])
{
return (($source !== null) && strlen(trim($source))) ?
Dom::createFromString($source) : Dom::createFromUri($uri, $httpOptions);
} | php | protected function createDom($uri, $source = null, array $httpOptions = [])
{
return (($source !== null) && strlen(trim($source))) ?
Dom::createFromString($source) : Dom::createFromUri($uri, $httpOptions);
} | [
"protected",
"function",
"createDom",
"(",
"$",
"uri",
",",
"$",
"source",
"=",
"null",
",",
"array",
"$",
"httpOptions",
"=",
"[",
"]",
")",
"{",
"return",
"(",
"(",
"$",
"source",
"!==",
"null",
")",
"&&",
"strlen",
"(",
"trim",
"(",
"$",
"source... | Create the DOM document to parse
@param string $uri URI
@param string|null $source Source code
@param array $httpOptions HTTP request options
@return \DOMDocument DOM document | [
"Create",
"the",
"DOM",
"document",
"to",
"parse"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Parser.php#L127-L131 | train |
jkphl/micrometa | src/Micrometa/Ports/Parser.php | Parser.extractItems | protected function extractItems(\DOMDocument $dom, \Generator $parsers)
{
$items = [];
$extractor = new ExtractorService();
foreach ($parsers as $parser) {
$results = $extractor->extract($dom, $parser);
$items = array_merge($items, ItemFactory::createFromApplicationItems($results->getItems()));
}
return $items;
} | php | protected function extractItems(\DOMDocument $dom, \Generator $parsers)
{
$items = [];
$extractor = new ExtractorService();
foreach ($parsers as $parser) {
$results = $extractor->extract($dom, $parser);
$items = array_merge($items, ItemFactory::createFromApplicationItems($results->getItems()));
}
return $items;
} | [
"protected",
"function",
"extractItems",
"(",
"\\",
"DOMDocument",
"$",
"dom",
",",
"\\",
"Generator",
"$",
"parsers",
")",
"{",
"$",
"items",
"=",
"[",
"]",
";",
"$",
"extractor",
"=",
"new",
"ExtractorService",
"(",
")",
";",
"foreach",
"(",
"$",
"pa... | Extract all items from a DOM using particular parsers
@param \DOMDocument $dom DOM document
@param \Generator $parsers Parsers
@return ItemInterface[] Items | [
"Extract",
"all",
"items",
"from",
"a",
"DOM",
"using",
"particular",
"parsers"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Parser.php#L141-L151 | train |
jkphl/micrometa | src/Micrometa/Application/Factory/AliasFactory.php | AliasFactory.createAliases | public function createAliases($name)
{
$aliases = [$name];
// Sanitize the name if it isn't usable as PHP function name
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name)) {
$name = preg_replace('/^[^a-zA-Z_\x7f-\xff]+(.*)?/', '$1', $name);
$aliases[] = lcfirst(
implode(
'',
array_map('ucfirst', preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $name))
)
);
}
return $aliases;
} | php | public function createAliases($name)
{
$aliases = [$name];
// Sanitize the name if it isn't usable as PHP function name
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $name)) {
$name = preg_replace('/^[^a-zA-Z_\x7f-\xff]+(.*)?/', '$1', $name);
$aliases[] = lcfirst(
implode(
'',
array_map('ucfirst', preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $name))
)
);
}
return $aliases;
} | [
"public",
"function",
"createAliases",
"(",
"$",
"name",
")",
"{",
"$",
"aliases",
"=",
"[",
"$",
"name",
"]",
";",
"// Sanitize the name if it isn't usable as PHP function name",
"if",
"(",
"!",
"preg_match",
"(",
"'/^[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*$/'",
"... | Create aliases for a particular name
@param string $name Name
@return string[] Name aliases (including the name itself as first item) | [
"Create",
"aliases",
"for",
"a",
"particular",
"name"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Application/Factory/AliasFactory.php#L54-L70 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.parseDocument | protected function parseDocument($jsonLDDocSource)
{
// Unserialize the JSON-LD document
$jsonLDDoc = @json_decode($jsonLDDocSource);
// If this is not a valid JSON document: Return
if (!is_object($jsonLDDoc) && !is_array($jsonLDDoc)) {
$this->logger->error('Skipping invalid JSON-LD document');
return [];
}
// Parse the document
return array_filter(
is_array($jsonLDDoc) ?
array_map([$this, 'parseRootNode'], $jsonLDDoc) : [$this->parseRootNode($jsonLDDoc)]
);
} | php | protected function parseDocument($jsonLDDocSource)
{
// Unserialize the JSON-LD document
$jsonLDDoc = @json_decode($jsonLDDocSource);
// If this is not a valid JSON document: Return
if (!is_object($jsonLDDoc) && !is_array($jsonLDDoc)) {
$this->logger->error('Skipping invalid JSON-LD document');
return [];
}
// Parse the document
return array_filter(
is_array($jsonLDDoc) ?
array_map([$this, 'parseRootNode'], $jsonLDDoc) : [$this->parseRootNode($jsonLDDoc)]
);
} | [
"protected",
"function",
"parseDocument",
"(",
"$",
"jsonLDDocSource",
")",
"{",
"// Unserialize the JSON-LD document",
"$",
"jsonLDDoc",
"=",
"@",
"json_decode",
"(",
"$",
"jsonLDDocSource",
")",
";",
"// If this is not a valid JSON document: Return",
"if",
"(",
"!",
"... | Parse a JSON-LD document
@param string $jsonLDDocSource JSON-LD document
@return array Items | [
"Parse",
"a",
"JSON",
"-",
"LD",
"document"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L135-L152 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.parseRootNode | protected function parseRootNode($jsonLDRoot)
{
$item = null;
try {
$jsonDLDocument = JsonLDParser::getDocument($jsonLDRoot, ['documentLoader' => $this->contextLoader]);
// Run through all nodes to parse the first one
/** @var Node $node */
foreach ($jsonDLDocument->getGraph()->getNodes() as $node) {
$item = $this->parseNode($node);
break;
}
} catch (JsonLdException $exception) {
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
}
return $item;
} | php | protected function parseRootNode($jsonLDRoot)
{
$item = null;
try {
$jsonDLDocument = JsonLDParser::getDocument($jsonLDRoot, ['documentLoader' => $this->contextLoader]);
// Run through all nodes to parse the first one
/** @var Node $node */
foreach ($jsonDLDocument->getGraph()->getNodes() as $node) {
$item = $this->parseNode($node);
break;
}
} catch (JsonLdException $exception) {
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
}
return $item;
} | [
"protected",
"function",
"parseRootNode",
"(",
"$",
"jsonLDRoot",
")",
"{",
"$",
"item",
"=",
"null",
";",
"try",
"{",
"$",
"jsonDLDocument",
"=",
"JsonLDParser",
"::",
"getDocument",
"(",
"$",
"jsonLDRoot",
",",
"[",
"'documentLoader'",
"=>",
"$",
"this",
... | Parse a JSON-LD root node
@param \stdClass $jsonLDRoot JSON-LD root node | [
"Parse",
"a",
"JSON",
"-",
"LD",
"root",
"node"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L159-L177 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.parseNode | protected function parseNode(NodeInterface $node)
{
return (object)[
'type' => $this->parseNodeType($node),
'id' => $node->getId() ?: null,
'properties' => $this->parseNodeProperties($node),
];
} | php | protected function parseNode(NodeInterface $node)
{
return (object)[
'type' => $this->parseNodeType($node),
'id' => $node->getId() ?: null,
'properties' => $this->parseNodeProperties($node),
];
} | [
"protected",
"function",
"parseNode",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"return",
"(",
"object",
")",
"[",
"'type'",
"=>",
"$",
"this",
"->",
"parseNodeType",
"(",
"$",
"node",
")",
",",
"'id'",
"=>",
"$",
"node",
"->",
"getId",
"(",
")",
... | Parse a JSON-LD node
@param NodeInterface $node Node
@return \stdClass Item | [
"Parse",
"a",
"JSON",
"-",
"LD",
"node"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L186-L193 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.parseNodeType | protected function parseNodeType(NodeInterface $node)
{
/** @var Node $itemType */
return ($itemType = $node->getType()) ? [$this->vocabularyCache->expandIRI($itemType->getId())] : [];
} | php | protected function parseNodeType(NodeInterface $node)
{
/** @var Node $itemType */
return ($itemType = $node->getType()) ? [$this->vocabularyCache->expandIRI($itemType->getId())] : [];
} | [
"protected",
"function",
"parseNodeType",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"/** @var Node $itemType */",
"return",
"(",
"$",
"itemType",
"=",
"$",
"node",
"->",
"getType",
"(",
")",
")",
"?",
"[",
"$",
"this",
"->",
"vocabularyCache",
"->",
"expa... | Parse the type of a JSON-LD node
@param NodeInterface $node Node
@return array Item type | [
"Parse",
"the",
"type",
"of",
"a",
"JSON",
"-",
"LD",
"node"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L202-L206 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.parseNodeProperties | protected function parseNodeProperties(NodeInterface $node)
{
$properties = [];
// Run through all node properties
foreach ($node->getProperties() as $name => $property) {
// Skip the node type
if ($name === Node::TYPE) {
continue;
}
// Initialize the property (if necessary)
$this->initializeNodeProperty($name, $properties);
// Parse and process the property value
$this->processNodeProperty($name, $this->parse($property), $properties);
}
return $properties;
} | php | protected function parseNodeProperties(NodeInterface $node)
{
$properties = [];
// Run through all node properties
foreach ($node->getProperties() as $name => $property) {
// Skip the node type
if ($name === Node::TYPE) {
continue;
}
// Initialize the property (if necessary)
$this->initializeNodeProperty($name, $properties);
// Parse and process the property value
$this->processNodeProperty($name, $this->parse($property), $properties);
}
return $properties;
} | [
"protected",
"function",
"parseNodeProperties",
"(",
"NodeInterface",
"$",
"node",
")",
"{",
"$",
"properties",
"=",
"[",
"]",
";",
"// Run through all node properties",
"foreach",
"(",
"$",
"node",
"->",
"getProperties",
"(",
")",
"as",
"$",
"name",
"=>",
"$"... | Parse the properties of a JSON-LD node
@param NodeInterface $node Node
@return array Item properties | [
"Parse",
"the",
"properties",
"of",
"a",
"JSON",
"-",
"LD",
"node"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L215-L234 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.processNodeProperty | protected function processNodeProperty($name, $value, array &$properties)
{
// If this is a nested item
if (is_object($value)) {
$this->processNodePropertyObject($name, $value, $properties);
// Else: If this is a value list
} elseif (is_array($value)) {
foreach ($value as $listValue) {
$this->processNodeProperty($name, $listValue, $properties);
}
// Else: If the value is not empty
} elseif ($value) {
$properties[$name]->values[] = $value;
}
} | php | protected function processNodeProperty($name, $value, array &$properties)
{
// If this is a nested item
if (is_object($value)) {
$this->processNodePropertyObject($name, $value, $properties);
// Else: If this is a value list
} elseif (is_array($value)) {
foreach ($value as $listValue) {
$this->processNodeProperty($name, $listValue, $properties);
}
// Else: If the value is not empty
} elseif ($value) {
$properties[$name]->values[] = $value;
}
} | [
"protected",
"function",
"processNodeProperty",
"(",
"$",
"name",
",",
"$",
"value",
",",
"array",
"&",
"$",
"properties",
")",
"{",
"// If this is a nested item",
"if",
"(",
"is_object",
"(",
"$",
"value",
")",
")",
"{",
"$",
"this",
"->",
"processNodePrope... | Process a property value
@param string $name Property name
@param \stdClass|array|string $value Property value
@param array $properties Item properties | [
"Process",
"a",
"property",
"value"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L257-L273 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.processNodePropertyObject | protected function processNodePropertyObject($name, $value, array &$properties)
{
if (!empty($value->type) || !empty($value->lang)) {
$properties[$name]->values[] = $value;
// @type = @id
} elseif (!empty($value->id)) {
$properties[$name]->values[] = $value->id;
}
} | php | protected function processNodePropertyObject($name, $value, array &$properties)
{
if (!empty($value->type) || !empty($value->lang)) {
$properties[$name]->values[] = $value;
// @type = @id
} elseif (!empty($value->id)) {
$properties[$name]->values[] = $value->id;
}
} | [
"protected",
"function",
"processNodePropertyObject",
"(",
"$",
"name",
",",
"$",
"value",
",",
"array",
"&",
"$",
"properties",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
"->",
"type",
")",
"||",
"!",
"empty",
"(",
"$",
"value",
"->",
"la... | Process a property value object
@param string $name Property name
@param \stdClass $value Property value
@param array $properties Properties | [
"Process",
"a",
"property",
"value",
"object"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L282-L291 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD.php | JsonLD.parse | protected function parse($jsonLD)
{
// If it's a node object
if ($jsonLD instanceof NodeInterface) {
return $this->parseNode($jsonLD);
// Else if it's a language tagged string
} elseif ($jsonLD instanceof LanguageTaggedString) {
return $this->parseLanguageTaggedString($jsonLD);
// Else if it's a typed value
} elseif ($jsonLD instanceof TypedValue) {
return $this->parseTypedValue($jsonLD);
}
// Else if it's a list of items
return array_map([$this, 'parse'], $jsonLD);
} | php | protected function parse($jsonLD)
{
// If it's a node object
if ($jsonLD instanceof NodeInterface) {
return $this->parseNode($jsonLD);
// Else if it's a language tagged string
} elseif ($jsonLD instanceof LanguageTaggedString) {
return $this->parseLanguageTaggedString($jsonLD);
// Else if it's a typed value
} elseif ($jsonLD instanceof TypedValue) {
return $this->parseTypedValue($jsonLD);
}
// Else if it's a list of items
return array_map([$this, 'parse'], $jsonLD);
} | [
"protected",
"function",
"parse",
"(",
"$",
"jsonLD",
")",
"{",
"// If it's a node object",
"if",
"(",
"$",
"jsonLD",
"instanceof",
"NodeInterface",
")",
"{",
"return",
"$",
"this",
"->",
"parseNode",
"(",
"$",
"jsonLD",
")",
";",
"// Else if it's a language tag... | Parse a JSON-LD fragment
@param NodeInterface|LanguageTaggedString|TypedValue|array $jsonLD JSON-LD fragment
@return \stdClass|string|array Parsed fragment | [
"Parse",
"a",
"JSON",
"-",
"LD",
"fragment"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD.php#L300-L317 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php | ProfiledNamesFactory.createFromArguments | public static function createFromArguments(array $args)
{
$profiledNames = [];
$profile = false;
// Consume and register all given names and profiles
while (count($args)) {
$profiledNames[] = self::consumeProfiledName($args, $profile);
}
return new ProfiledNamesList($profiledNames);
} | php | public static function createFromArguments(array $args)
{
$profiledNames = [];
$profile = false;
// Consume and register all given names and profiles
while (count($args)) {
$profiledNames[] = self::consumeProfiledName($args, $profile);
}
return new ProfiledNamesList($profiledNames);
} | [
"public",
"static",
"function",
"createFromArguments",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"profiledNames",
"=",
"[",
"]",
";",
"$",
"profile",
"=",
"false",
";",
"// Consume and register all given names and profiles",
"while",
"(",
"count",
"(",
"$",
"arg... | Create a list of profiled names from method arguments
The method takes an arbitrary number of arguments and tries to parse them as profiled names. Arguments
may be strings, arrays or objects.
String values are interpreted as names — with one exception: If the first two arguments are both strings,
the second one is taken as profile IRI. Optionally following string arguments are taken as names again,
assuming to share the same profile:
createFromArguments($name1 [, $profile])
createFromArguments($name1, $profile1, $name2, $profile2 ...)
Arrays arguments are expected to have at least one argument which is taken as name. If present, the
second argument is used as profile (otherwise an empty profile is assumed):
createFromArguments(array($name [, $profile]))
Object values are expected to have a "name" and an optional "profile" property:
createFromArguments((object)array('name' => $name [, 'profile' => $profile]))
When an array or object argument is consumed, the profile value will be used for any following string
argument. You can "reset" the profile to another value by specifying another array or object value in
this case.
createFromArguments(array($name1, $profile1), $name2, $name3 ...)
@param array $args Arguments
@return ProfiledNamesList Profiled names
@see Item::isOfType()
@see Item::getFirstProperty()
@see ItemList::getFirstItem()
@see ItemList::getItems() | [
"Create",
"a",
"list",
"of",
"profiled",
"names",
"from",
"method",
"arguments"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php#L88-L99 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php | ProfiledNamesFactory.consumeProfiledName | protected static function consumeProfiledName(&$args, &$profile)
{
$profiledName = new \stdClass();
$profiledName->profile = $profile;
// Get the first argument
$arg = array_shift($args);
// If it's not a scalar argument
if (!is_scalar($arg)) {
return self::consumeNonScalarProfiledName($arg, $profile);
}
if (($profile === false) && is_string(current($args))) {
$profile = array_shift($args);
}
return self::createProfiledNameFromString(strval($arg), $profile);
} | php | protected static function consumeProfiledName(&$args, &$profile)
{
$profiledName = new \stdClass();
$profiledName->profile = $profile;
// Get the first argument
$arg = array_shift($args);
// If it's not a scalar argument
if (!is_scalar($arg)) {
return self::consumeNonScalarProfiledName($arg, $profile);
}
if (($profile === false) && is_string(current($args))) {
$profile = array_shift($args);
}
return self::createProfiledNameFromString(strval($arg), $profile);
} | [
"protected",
"static",
"function",
"consumeProfiledName",
"(",
"&",
"$",
"args",
",",
"&",
"$",
"profile",
")",
"{",
"$",
"profiledName",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"$",
"profiledName",
"->",
"profile",
"=",
"$",
"profile",
";",
"// Get... | Create a single profiled name by argument consumption
@param array $args Arguments
@param string|boolean|null $profile Profile
@return \stdClass Profiled name | [
"Create",
"a",
"single",
"profiled",
"name",
"by",
"argument",
"consumption"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php#L109-L127 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php | ProfiledNamesFactory.consumeNonScalarProfiledName | protected static function consumeNonScalarProfiledName($arg, &$profile)
{
// If it's an object argument
if (is_object($arg)) {
return self::createProfiledNameFromObject($arg, $profile);
}
// Else: It must be an array
return self::createProfiledNameFromArray($arg, $profile);
} | php | protected static function consumeNonScalarProfiledName($arg, &$profile)
{
// If it's an object argument
if (is_object($arg)) {
return self::createProfiledNameFromObject($arg, $profile);
}
// Else: It must be an array
return self::createProfiledNameFromArray($arg, $profile);
} | [
"protected",
"static",
"function",
"consumeNonScalarProfiledName",
"(",
"$",
"arg",
",",
"&",
"$",
"profile",
")",
"{",
"// If it's an object argument",
"if",
"(",
"is_object",
"(",
"$",
"arg",
")",
")",
"{",
"return",
"self",
"::",
"createProfiledNameFromObject",... | Create a profiled name by consuming a non-scalar argument
@param \stdClass|array $arg Argument
@param string|boolean|null $profile Profile
@return \stdClass Profiled name | [
"Create",
"a",
"profiled",
"name",
"by",
"consuming",
"a",
"non",
"-",
"scalar",
"argument"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php#L137-L146 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php | ProfiledNamesFactory.createProfiledNameFromObject | protected static function createProfiledNameFromObject($arg, &$profile)
{
// If the name is invalid
if (!isset($arg->name)) {
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME_STR,
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME
);
}
if (isset($arg->profile)) {
$profile = trim($arg->profile) ?: null;
}
return self::createProfiledNameFromString($arg->name, $profile);
} | php | protected static function createProfiledNameFromObject($arg, &$profile)
{
// If the name is invalid
if (!isset($arg->name)) {
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME_STR,
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME
);
}
if (isset($arg->profile)) {
$profile = trim($arg->profile) ?: null;
}
return self::createProfiledNameFromString($arg->name, $profile);
} | [
"protected",
"static",
"function",
"createProfiledNameFromObject",
"(",
"$",
"arg",
",",
"&",
"$",
"profile",
")",
"{",
"// If the name is invalid",
"if",
"(",
"!",
"isset",
"(",
"$",
"arg",
"->",
"name",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentExceptio... | Create a profiled name from an object argument
@param \stdClass $arg Object argument
@param string|boolean|null $profile Profile
@return \stdClass Profiled name
@throws InvalidArgumentException If the name is missing | [
"Create",
"a",
"profiled",
"name",
"from",
"an",
"object",
"argument"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php#L157-L172 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php | ProfiledNamesFactory.createProfiledNameFromString | protected static function createProfiledNameFromString($name, $profile)
{
// If the name is invalid
if (!strlen(trim($name))) {
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME_STR,
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME
);
}
return (object)[
'name' => trim($name),
'profile' => trim($profile) ?: null,
];
} | php | protected static function createProfiledNameFromString($name, $profile)
{
// If the name is invalid
if (!strlen(trim($name))) {
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME_STR,
InvalidArgumentException::INVALID_TYPE_PROPERTY_NAME
);
}
return (object)[
'name' => trim($name),
'profile' => trim($profile) ?: null,
];
} | [
"protected",
"static",
"function",
"createProfiledNameFromString",
"(",
"$",
"name",
",",
"$",
"profile",
")",
"{",
"// If the name is invalid",
"if",
"(",
"!",
"strlen",
"(",
"trim",
"(",
"$",
"name",
")",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentExcept... | Create a profiled name from string arguments
@param string $name Name
@param string|boolean|null $profile Profile
@return \stdClass Profiled name
@throws InvalidArgumentException If the name is invalid | [
"Create",
"a",
"profiled",
"name",
"from",
"string",
"arguments"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php#L183-L197 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php | ProfiledNamesFactory.createProfiledNameFromArray | protected static function createProfiledNameFromArray(array $arg, &$profile)
{
// If it's an associative array containing a "name" key
if (array_key_exists('name', $arg)) {
return self::createProfiledNameFromObject((object)$arg, $profile);
}
// If the argument has two items at least
if (count($arg) > 1) {
$name = array_shift($arg);
$profile = trim(array_shift($arg)) ?: null;
return self::createProfiledNameFromString($name, $profile);
}
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_TYPE_PROPERTY_ARRAY_STR,
InvalidArgumentException::INVALID_TYPE_PROPERTY_ARRAY
);
} | php | protected static function createProfiledNameFromArray(array $arg, &$profile)
{
// If it's an associative array containing a "name" key
if (array_key_exists('name', $arg)) {
return self::createProfiledNameFromObject((object)$arg, $profile);
}
// If the argument has two items at least
if (count($arg) > 1) {
$name = array_shift($arg);
$profile = trim(array_shift($arg)) ?: null;
return self::createProfiledNameFromString($name, $profile);
}
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_TYPE_PROPERTY_ARRAY_STR,
InvalidArgumentException::INVALID_TYPE_PROPERTY_ARRAY
);
} | [
"protected",
"static",
"function",
"createProfiledNameFromArray",
"(",
"array",
"$",
"arg",
",",
"&",
"$",
"profile",
")",
"{",
"// If it's an associative array containing a \"name\" key",
"if",
"(",
"array_key_exists",
"(",
"'name'",
",",
"$",
"arg",
")",
")",
"{",... | Create a profiled name from an array argument
@param array $arg Array argument
@param string|boolean|null $profile Profile
@return \stdClass Profiled name
@throws InvalidArgumentException If the array definition is invalid | [
"Create",
"a",
"profiled",
"name",
"from",
"an",
"array",
"argument"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ProfiledNamesFactory.php#L208-L227 | train |
jkphl/micrometa | src/Micrometa/Domain/Factory/IriFactory.php | IriFactory.create | public static function create($iri)
{
// Cast as item type object if only a string is given
if (is_string($iri)) {
$iri = (object)['profile' => '', 'name' => $iri];
}
// If the IRI is invalid
if (!self::validateIriStructure($iri)) {
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_IRI_STR,
InvalidArgumentException::INVALID_IRI
);
}
return new Iri($iri->profile, $iri->name);
} | php | public static function create($iri)
{
// Cast as item type object if only a string is given
if (is_string($iri)) {
$iri = (object)['profile' => '', 'name' => $iri];
}
// If the IRI is invalid
if (!self::validateIriStructure($iri)) {
throw new InvalidArgumentException(
InvalidArgumentException::INVALID_IRI_STR,
InvalidArgumentException::INVALID_IRI
);
}
return new Iri($iri->profile, $iri->name);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"iri",
")",
"{",
"// Cast as item type object if only a string is given",
"if",
"(",
"is_string",
"(",
"$",
"iri",
")",
")",
"{",
"$",
"iri",
"=",
"(",
"object",
")",
"[",
"'profile'",
"=>",
"''",
",",
"'... | Validate and sanitize an IRI
@param Iri|\stdClass|string $iri IRI
@return Iri Sanitized IRI
@throws InvalidArgumentException If the IRI is invalid | [
"Validate",
"and",
"sanitize",
"an",
"IRI"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Domain/Factory/IriFactory.php#L58-L74 | train |
jkphl/micrometa | src/Micrometa/Domain/Factory/IriFactory.php | IriFactory.validateIriStructure | protected static function validateIriStructure($iri)
{
return is_object($iri) && isset($iri->profile) && isset($iri->name);
} | php | protected static function validateIriStructure($iri)
{
return is_object($iri) && isset($iri->profile) && isset($iri->name);
} | [
"protected",
"static",
"function",
"validateIriStructure",
"(",
"$",
"iri",
")",
"{",
"return",
"is_object",
"(",
"$",
"iri",
")",
"&&",
"isset",
"(",
"$",
"iri",
"->",
"profile",
")",
"&&",
"isset",
"(",
"$",
"iri",
"->",
"name",
")",
";",
"}"
] | Test if an object has a valid IRI structure
@param \stdClass $iri IRI
@return bool Is a valid IRI | [
"Test",
"if",
"an",
"object",
"has",
"a",
"valid",
"IRI",
"structure"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Domain/Factory/IriFactory.php#L83-L86 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Factory/ParserFactory.php | ParserFactory.createParsersFromFormats | public static function createParsersFromFormats($formats, UriInterface $uri, LoggerInterface $logger)
{
$formatBits = intval($formats);
// Run through all registered parsers and yield the requested instances
foreach (self::$parsers as $parserFormat => $parserClass) {
if ($parserFormat & $formatBits) {
yield $parserFormat => new $parserClass($uri, $logger);
}
}
} | php | public static function createParsersFromFormats($formats, UriInterface $uri, LoggerInterface $logger)
{
$formatBits = intval($formats);
// Run through all registered parsers and yield the requested instances
foreach (self::$parsers as $parserFormat => $parserClass) {
if ($parserFormat & $formatBits) {
yield $parserFormat => new $parserClass($uri, $logger);
}
}
} | [
"public",
"static",
"function",
"createParsersFromFormats",
"(",
"$",
"formats",
",",
"UriInterface",
"$",
"uri",
",",
"LoggerInterface",
"$",
"logger",
")",
"{",
"$",
"formatBits",
"=",
"intval",
"(",
"$",
"formats",
")",
";",
"// Run through all registered parse... | Create a list of parsers from a formats bitmask
@param int $formats Parser format bitmask
@param UriInterface $uri Base Uri
@param LoggerInterface $logger Logger
@return \Generator Parser generator | [
"Create",
"a",
"list",
"of",
"parsers",
"from",
"a",
"formats",
"bitmask"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Factory/ParserFactory.php#L77-L87 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/LinkType.php | LinkType.parseLinkType | protected function parseLinkType($relAttr)
{
$type = [];
foreach (preg_split('/\040+/', $relAttr) as $rel) {
$type[] = (object)['name' => $rel, 'profile' => self::HTML_PROFILE_URI];
}
return $type;
} | php | protected function parseLinkType($relAttr)
{
$type = [];
foreach (preg_split('/\040+/', $relAttr) as $rel) {
$type[] = (object)['name' => $rel, 'profile' => self::HTML_PROFILE_URI];
}
return $type;
} | [
"protected",
"function",
"parseLinkType",
"(",
"$",
"relAttr",
")",
"{",
"$",
"type",
"=",
"[",
"]",
";",
"foreach",
"(",
"preg_split",
"(",
"'/\\040+/'",
",",
"$",
"relAttr",
")",
"as",
"$",
"rel",
")",
"{",
"$",
"type",
"[",
"]",
"=",
"(",
"objec... | Process the item types
@param string $relAttr rel attribute value
@return array Item types | [
"Process",
"the",
"item",
"types"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/LinkType.php#L93-L101 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/LinkType.php | LinkType.parseProperties | protected function parseProperties(\DOMElement $linkType)
{
$properties = [];
/**
* @var string $attributeName Attribute name
* @var \DOMAttr $attribute Attribute
*/
foreach ($linkType->attributes as $attributeName => $attribute) {
if (!in_array($attributeName, ['rel', 'id'])) {
$profile = $attribute->lookupNamespaceUri($attribute->prefix ?: null);
$property = (object)[
'name' => $attributeName,
'profile' => $profile,
'values' => $this->parseAttributeValue($profile, $attributeName, $attribute->value),
];
$properties[] = $property;
}
}
return $properties;
} | php | protected function parseProperties(\DOMElement $linkType)
{
$properties = [];
/**
* @var string $attributeName Attribute name
* @var \DOMAttr $attribute Attribute
*/
foreach ($linkType->attributes as $attributeName => $attribute) {
if (!in_array($attributeName, ['rel', 'id'])) {
$profile = $attribute->lookupNamespaceUri($attribute->prefix ?: null);
$property = (object)[
'name' => $attributeName,
'profile' => $profile,
'values' => $this->parseAttributeValue($profile, $attributeName, $attribute->value),
];
$properties[] = $property;
}
}
return $properties;
} | [
"protected",
"function",
"parseProperties",
"(",
"\\",
"DOMElement",
"$",
"linkType",
")",
"{",
"$",
"properties",
"=",
"[",
"]",
";",
"/**\n * @var string $attributeName Attribute name\n * @var \\DOMAttr $attribute Attribute\n */",
"foreach",
"(",
"$"... | Parse the LinkType attributes
@param \DOMElement $linkType LinkType element
@return array Properties | [
"Parse",
"the",
"LinkType",
"attributes"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/LinkType.php#L110-L130 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/LinkType.php | LinkType.parseAttributeValue | protected function parseAttributeValue($profile, $attribute, $value)
{
// If it's a HTML attribute
if ($profile == LinkType::HTML_PROFILE_URI) {
switch ($attribute) {
// Space delimited lists
case 'sizes':
return array_filter(preg_split('/\040+/', $value));
// Space or comma delimited lists
case 'charset':
return array_filter(preg_split('/[,\040]+/', $value));
}
}
return [$value];
} | php | protected function parseAttributeValue($profile, $attribute, $value)
{
// If it's a HTML attribute
if ($profile == LinkType::HTML_PROFILE_URI) {
switch ($attribute) {
// Space delimited lists
case 'sizes':
return array_filter(preg_split('/\040+/', $value));
// Space or comma delimited lists
case 'charset':
return array_filter(preg_split('/[,\040]+/', $value));
}
}
return [$value];
} | [
"protected",
"function",
"parseAttributeValue",
"(",
"$",
"profile",
",",
"$",
"attribute",
",",
"$",
"value",
")",
"{",
"// If it's a HTML attribute",
"if",
"(",
"$",
"profile",
"==",
"LinkType",
"::",
"HTML_PROFILE_URI",
")",
"{",
"switch",
"(",
"$",
"attrib... | Parse an attribute value
@param string $profile Profile
@param string $attribute Attribute name
@param string $value Attribute value
@return array Attribute values | [
"Parse",
"an",
"attribute",
"value"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/LinkType.php#L141-L156 | train |
jkphl/micrometa | src/Micrometa/Domain/Item/PropertyList.php | PropertyList.offsetUnset | public function offsetUnset($iri)
{
throw new ErrorException(
sprintf(ErrorException::CANNOT_UNSET_PROPERTY_STR, $iri),
ErrorException::CANNOT_UNSET_PROPERTY,
E_WARNING
);
} | php | public function offsetUnset($iri)
{
throw new ErrorException(
sprintf(ErrorException::CANNOT_UNSET_PROPERTY_STR, $iri),
ErrorException::CANNOT_UNSET_PROPERTY,
E_WARNING
);
} | [
"public",
"function",
"offsetUnset",
"(",
"$",
"iri",
")",
"{",
"throw",
"new",
"ErrorException",
"(",
"sprintf",
"(",
"ErrorException",
"::",
"CANNOT_UNSET_PROPERTY_STR",
",",
"$",
"iri",
")",
",",
"ErrorException",
"::",
"CANNOT_UNSET_PROPERTY",
",",
"E_WARNING"... | Unset a property
@param \stdClass|string $iri IRI
@throws ErrorException | [
"Unset",
"a",
"property"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Domain/Item/PropertyList.php#L83-L90 | train |
jkphl/micrometa | src/Micrometa/Domain/Item/PropertyList.php | PropertyList.offsetExists | public function offsetExists($iri)
{
$iri = IriFactory::create($iri);
try {
($iri->profile !== '') ?
$this->getProfiledPropertyCursor($iri) : $this->getPropertyCursor($iri->name);
return true;
} catch (OutOfBoundsException $exception) {
return false;
}
} | php | public function offsetExists($iri)
{
$iri = IriFactory::create($iri);
try {
($iri->profile !== '') ?
$this->getProfiledPropertyCursor($iri) : $this->getPropertyCursor($iri->name);
return true;
} catch (OutOfBoundsException $exception) {
return false;
}
} | [
"public",
"function",
"offsetExists",
"(",
"$",
"iri",
")",
"{",
"$",
"iri",
"=",
"IriFactory",
"::",
"create",
"(",
"$",
"iri",
")",
";",
"try",
"{",
"(",
"$",
"iri",
"->",
"profile",
"!==",
"''",
")",
"?",
"$",
"this",
"->",
"getProfiledPropertyCur... | Return whether a property exists
@param \stdClass|Iri|string $iri IRI
@return boolean Property exists | [
"Return",
"whether",
"a",
"property",
"exists"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Domain/Item/PropertyList.php#L176-L187 | train |
jkphl/micrometa | src/Micrometa/Domain/Item/PropertyList.php | PropertyList.getProfiledPropertyCursor | protected function getProfiledPropertyCursor($iri)
{
$iriStr = strval($iri);
// If the property name is unknown
if (!isset($this->nameToCursor[$iriStr])) {
$this->handleUnknownName($iriStr);
}
return $this->nameToCursor[$iriStr];
} | php | protected function getProfiledPropertyCursor($iri)
{
$iriStr = strval($iri);
// If the property name is unknown
if (!isset($this->nameToCursor[$iriStr])) {
$this->handleUnknownName($iriStr);
}
return $this->nameToCursor[$iriStr];
} | [
"protected",
"function",
"getProfiledPropertyCursor",
"(",
"$",
"iri",
")",
"{",
"$",
"iriStr",
"=",
"strval",
"(",
"$",
"iri",
")",
";",
"// If the property name is unknown",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"nameToCursor",
"[",
"$",
"iriStr... | Get a particular property cursor by its profiled name
@param Iri $iri IRI
@return int Property cursor
@throws OutOfBoundsException If the property name is unknown | [
"Get",
"a",
"particular",
"property",
"cursor",
"by",
"its",
"profiled",
"name"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Domain/Item/PropertyList.php#L197-L207 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/ItemList.php | ItemList.getFirstItem | public function getFirstItem(...$types)
{
$items = $this->getItems(...$types);
// If there are no matching items
if (!count($items)) {
throw new OutOfBoundsException(
OutOfBoundsException::NO_MATCHING_ITEMS_STR,
OutOfBoundsException::NO_MATCHING_ITEMS
);
}
return $items[0];
} | php | public function getFirstItem(...$types)
{
$items = $this->getItems(...$types);
// If there are no matching items
if (!count($items)) {
throw new OutOfBoundsException(
OutOfBoundsException::NO_MATCHING_ITEMS_STR,
OutOfBoundsException::NO_MATCHING_ITEMS
);
}
return $items[0];
} | [
"public",
"function",
"getFirstItem",
"(",
"...",
"$",
"types",
")",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"getItems",
"(",
"...",
"$",
"types",
")",
";",
"// If there are no matching items",
"if",
"(",
"!",
"count",
"(",
"$",
"items",
")",
")",
"... | Return the first item, optionally of particular types
@param array ...$types Item types
@return ItemInterface Item
@throws OutOfBoundsException If there are no matching items
@api | [
"Return",
"the",
"first",
"item",
"optionally",
"of",
"particular",
"types"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/ItemList.php#L210-L223 | train |
jkphl/micrometa | src/Micrometa/Ports/Item/ItemList.php | ItemList.getItemByTypeAndIndex | protected function getItemByTypeAndIndex($type, $index)
{
$typeItems = $this->getItems($type);
// If the item index is out of bounds
if (count($typeItems) <= $index) {
throw new OutOfBoundsException(
sprintf(OutOfBoundsException::INVALID_ITEM_INDEX_STR, $index),
OutOfBoundsException::INVALID_ITEM_INDEX
);
}
return $typeItems[$index];
} | php | protected function getItemByTypeAndIndex($type, $index)
{
$typeItems = $this->getItems($type);
// If the item index is out of bounds
if (count($typeItems) <= $index) {
throw new OutOfBoundsException(
sprintf(OutOfBoundsException::INVALID_ITEM_INDEX_STR, $index),
OutOfBoundsException::INVALID_ITEM_INDEX
);
}
return $typeItems[$index];
} | [
"protected",
"function",
"getItemByTypeAndIndex",
"(",
"$",
"type",
",",
"$",
"index",
")",
"{",
"$",
"typeItems",
"=",
"$",
"this",
"->",
"getItems",
"(",
"$",
"type",
")",
";",
"// If the item index is out of bounds",
"if",
"(",
"count",
"(",
"$",
"typeIte... | Return an item by type and index
@param string $type Item type
@param int $index Item index
@return ItemInterface Item
@throws OutOfBoundsException If the item index is out of bounds | [
"Return",
"an",
"item",
"by",
"type",
"and",
"index"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Ports/Item/ItemList.php#L297-L310 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.getDocument | public function getDocument($url)
{
$urlHash = $this->getCacheHash($url, self::SLOT_DOC);
// Try to retrieve the document from the cache
if (Cache::getAdapter()->hasItem($urlHash)) {
return Cache::getAdapter()->getItem($urlHash)->get();
}
return null;
} | php | public function getDocument($url)
{
$urlHash = $this->getCacheHash($url, self::SLOT_DOC);
// Try to retrieve the document from the cache
if (Cache::getAdapter()->hasItem($urlHash)) {
return Cache::getAdapter()->getItem($urlHash)->get();
}
return null;
} | [
"public",
"function",
"getDocument",
"(",
"$",
"url",
")",
"{",
"$",
"urlHash",
"=",
"$",
"this",
"->",
"getCacheHash",
"(",
"$",
"url",
",",
"self",
"::",
"SLOT_DOC",
")",
";",
"// Try to retrieve the document from the cache",
"if",
"(",
"Cache",
"::",
"get... | Return a cached document
@param string $url URL
@return RemoteDocument|null Cached document | [
"Return",
"a",
"cached",
"document"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L88-L98 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.setDocument | public function setDocument($url, RemoteDocument $document)
{
// Process the context
if (isset($document->document->{'@context'}) && is_object($document->document->{'@context'})) {
$this->processContext((array)$document->document->{'@context'});
}
// Save the document to the cache
$docUrlHash = $this->getCacheHash($url, self::SLOT_DOC);
$cachedDocument = Cache::getAdapter()->getItem($docUrlHash);
$cachedDocument->set($document);
Cache::getAdapter()->save($cachedDocument);
// Return the document
return $document;
} | php | public function setDocument($url, RemoteDocument $document)
{
// Process the context
if (isset($document->document->{'@context'}) && is_object($document->document->{'@context'})) {
$this->processContext((array)$document->document->{'@context'});
}
// Save the document to the cache
$docUrlHash = $this->getCacheHash($url, self::SLOT_DOC);
$cachedDocument = Cache::getAdapter()->getItem($docUrlHash);
$cachedDocument->set($document);
Cache::getAdapter()->save($cachedDocument);
// Return the document
return $document;
} | [
"public",
"function",
"setDocument",
"(",
"$",
"url",
",",
"RemoteDocument",
"$",
"document",
")",
"{",
"// Process the context",
"if",
"(",
"isset",
"(",
"$",
"document",
"->",
"document",
"->",
"{",
"'@context'",
"}",
")",
"&&",
"is_object",
"(",
"$",
"d... | Cache a document
@param string $url URL
@param RemoteDocument $document Document
@return RemoteDocument Document | [
"Cache",
"a",
"document"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L121-L136 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.processContext | protected function processContext(array $context)
{
$prefices = [];
$vocabularyCache = Cache::getAdapter()->getItem(self::SLOT_VOCABS);
$vocabularies = $vocabularyCache->isHit() ? $vocabularyCache->get() : [];
// Run through all vocabulary terms
foreach ($context as $name => $definition) {
// Skip JSON-LD reserved terms
if ($this->isReservedTokens($name, $definition)) {
continue;
}
// Process this prefix / vocabulary term
$this->processPrefixVocabularyTerm($name, $definition, $prefices, $vocabularies);
}
$vocabularyCache->set($vocabularies);
Cache::getAdapter()->save($vocabularyCache);
} | php | protected function processContext(array $context)
{
$prefices = [];
$vocabularyCache = Cache::getAdapter()->getItem(self::SLOT_VOCABS);
$vocabularies = $vocabularyCache->isHit() ? $vocabularyCache->get() : [];
// Run through all vocabulary terms
foreach ($context as $name => $definition) {
// Skip JSON-LD reserved terms
if ($this->isReservedTokens($name, $definition)) {
continue;
}
// Process this prefix / vocabulary term
$this->processPrefixVocabularyTerm($name, $definition, $prefices, $vocabularies);
}
$vocabularyCache->set($vocabularies);
Cache::getAdapter()->save($vocabularyCache);
} | [
"protected",
"function",
"processContext",
"(",
"array",
"$",
"context",
")",
"{",
"$",
"prefices",
"=",
"[",
"]",
";",
"$",
"vocabularyCache",
"=",
"Cache",
"::",
"getAdapter",
"(",
")",
"->",
"getItem",
"(",
"self",
"::",
"SLOT_VOCABS",
")",
";",
"$",
... | Process a context vocabulary
@param array $context Context | [
"Process",
"a",
"context",
"vocabulary"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L143-L162 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.processPrefix | protected function processPrefix($name, $definition, array &$prefices, array &$vocabularies)
{
$prefices[$name] = $definition;
// Register the vocabulary
if (!isset($vocabularies[$definition])) {
$vocabularies[$definition] = [];
}
} | php | protected function processPrefix($name, $definition, array &$prefices, array &$vocabularies)
{
$prefices[$name] = $definition;
// Register the vocabulary
if (!isset($vocabularies[$definition])) {
$vocabularies[$definition] = [];
}
} | [
"protected",
"function",
"processPrefix",
"(",
"$",
"name",
",",
"$",
"definition",
",",
"array",
"&",
"$",
"prefices",
",",
"array",
"&",
"$",
"vocabularies",
")",
"{",
"$",
"prefices",
"[",
"$",
"name",
"]",
"=",
"$",
"definition",
";",
"// Register th... | Process a vocabulary prefix
@param string $name Prefix name
@param string $definition Prefix definition
@param array $prefices Prefix register
@param array $vocabularies Vocabulary register | [
"Process",
"a",
"vocabulary",
"prefix"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L219-L227 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.processVocabularyTerm | protected function processVocabularyTerm($definition, array &$prefices, array &$vocabularies)
{
$prefixName = explode(':', $definition->{'@id'}, 2);
if (count($prefixName) == 2) {
if (isset($prefices[$prefixName[0]])) {
$vocabularies[$prefices[$prefixName[0]]][$prefixName[1]] = true;
}
}
} | php | protected function processVocabularyTerm($definition, array &$prefices, array &$vocabularies)
{
$prefixName = explode(':', $definition->{'@id'}, 2);
if (count($prefixName) == 2) {
if (isset($prefices[$prefixName[0]])) {
$vocabularies[$prefices[$prefixName[0]]][$prefixName[1]] = true;
}
}
} | [
"protected",
"function",
"processVocabularyTerm",
"(",
"$",
"definition",
",",
"array",
"&",
"$",
"prefices",
",",
"array",
"&",
"$",
"vocabularies",
")",
"{",
"$",
"prefixName",
"=",
"explode",
"(",
"':'",
",",
"$",
"definition",
"->",
"{",
"'@id'",
"}",
... | Process a vocabulary term
@param \stdClass $definition Term definition
@param array $prefices Prefix register
@param array $vocabularies Vocabulary register | [
"Process",
"a",
"vocabulary",
"term"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L248-L256 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.expandIRI | public function expandIRI($name)
{
$iri = (object)['name' => $name, 'profile' => ''];
$vocabularies = Cache::getAdapter()->getItem(self::SLOT_VOCABS);
// Run through all vocabularies
if ($vocabularies->isHit()) {
$this->matchVocabularies($name, $vocabularies->get(), $iri);
}
return $iri;
} | php | public function expandIRI($name)
{
$iri = (object)['name' => $name, 'profile' => ''];
$vocabularies = Cache::getAdapter()->getItem(self::SLOT_VOCABS);
// Run through all vocabularies
if ($vocabularies->isHit()) {
$this->matchVocabularies($name, $vocabularies->get(), $iri);
}
return $iri;
} | [
"public",
"function",
"expandIRI",
"(",
"$",
"name",
")",
"{",
"$",
"iri",
"=",
"(",
"object",
")",
"[",
"'name'",
"=>",
"$",
"name",
",",
"'profile'",
"=>",
"''",
"]",
";",
"$",
"vocabularies",
"=",
"Cache",
"::",
"getAdapter",
"(",
")",
"->",
"ge... | Create an IRI from a name considering the known vocabularies
@param string $name Name
@return \stdClass IRI | [
"Create",
"an",
"IRI",
"from",
"a",
"name",
"considering",
"the",
"known",
"vocabularies"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L265-L276 | train |
jkphl/micrometa | src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php | VocabularyCache.matchVocabularies | protected function matchVocabularies($name, array $vocabularies, &$iri)
{
// Run through all vocabularies
foreach ($vocabularies as $profile => $terms) {
$profileLength = strlen($profile);
// If the name matches the profile and the remaining string is a registered term
if (!strncasecmp($profile, $name, $profileLength) && !empty($terms[substr($name, $profileLength)])) {
$iri->profile = $profile;
$iri->name = substr($name, $profileLength);
return;
}
}
} | php | protected function matchVocabularies($name, array $vocabularies, &$iri)
{
// Run through all vocabularies
foreach ($vocabularies as $profile => $terms) {
$profileLength = strlen($profile);
// If the name matches the profile and the remaining string is a registered term
if (!strncasecmp($profile, $name, $profileLength) && !empty($terms[substr($name, $profileLength)])) {
$iri->profile = $profile;
$iri->name = substr($name, $profileLength);
return;
}
}
} | [
"protected",
"function",
"matchVocabularies",
"(",
"$",
"name",
",",
"array",
"$",
"vocabularies",
",",
"&",
"$",
"iri",
")",
"{",
"// Run through all vocabularies",
"foreach",
"(",
"$",
"vocabularies",
"as",
"$",
"profile",
"=>",
"$",
"terms",
")",
"{",
"$"... | Match a name with the known vocabularies
@param string $name Name
@param array $vocabularies Vocabularies
@param \stdClass $iri IRI | [
"Match",
"a",
"name",
"with",
"the",
"known",
"vocabularies"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Infrastructure/Parser/JsonLD/VocabularyCache.php#L285-L299 | train |
jkphl/micrometa | src/Micrometa/Domain/Item/ItemSetupTrait.php | ItemSetupTrait.setup | protected function setup(
PropertyListFactoryInterface $propertyListFactory,
array $type,
array $properties,
$itemId,
$itemLanguage
) {
$this->propertyListFactory = $propertyListFactory;
$this->type = $this->valTypes($type);
$this->properties = $this->valProperties($properties);
$this->itemId = $itemId ?: null;
$this->itemLanguage = $itemLanguage ?: null;
} | php | protected function setup(
PropertyListFactoryInterface $propertyListFactory,
array $type,
array $properties,
$itemId,
$itemLanguage
) {
$this->propertyListFactory = $propertyListFactory;
$this->type = $this->valTypes($type);
$this->properties = $this->valProperties($properties);
$this->itemId = $itemId ?: null;
$this->itemLanguage = $itemLanguage ?: null;
} | [
"protected",
"function",
"setup",
"(",
"PropertyListFactoryInterface",
"$",
"propertyListFactory",
",",
"array",
"$",
"type",
",",
"array",
"$",
"properties",
",",
"$",
"itemId",
",",
"$",
"itemLanguage",
")",
"{",
"$",
"this",
"->",
"propertyListFactory",
"=",
... | Setup the item
@param PropertyListFactoryInterface $propertyListFactory Property list factory
@param string[]|\stdClass[] $type Item type(s)
@param \stdClass[] $properties Item properties
@param string $itemId Item ID
@param string $itemLanguage Item language | [
"Setup",
"the",
"item"
] | eb7d5159a7f43b352d13b370a4269c17e1a23d3e | https://github.com/jkphl/micrometa/blob/eb7d5159a7f43b352d13b370a4269c17e1a23d3e/src/Micrometa/Domain/Item/ItemSetupTrait.php#L96-L108 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.