repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assertMultipleSuccessMessage | public function assertMultipleSuccessMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'success messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['success messages']);
$this->assertSuccessMessage($message);
}
} | php | public function assertMultipleSuccessMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'success messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['success messages']);
$this->assertSuccessMessage($message);
}
} | [
"public",
"function",
"assertMultipleSuccessMessage",
"(",
"TableNode",
"$",
"messages",
")",
"{",
"$",
"this",
"->",
"assertValidMessageTable",
"(",
"$",
"messages",
",",
"'success messages'",
")",
";",
"foreach",
"(",
"$",
"messages",
"->",
"getHash",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"array_change_key_case",
"(",
"$",
"value",
")",
";",
"$",
"message",
"=",
"trim",
"(",
"$",
"value",
"[",
"'success messages'",
"]",
")",
";",
"$",
"this",
"->",
"assertSuccessMessage",
"(",
"$",
"message",
")",
";",
"}",
"}"
] | Checks if the current page contains the given set of success messages
@param array $message
An array of texts to be checked. The first row should consist of the
string "Success messages".
@Then I should see the following success messages: | [
"Checks",
"if",
"the",
"current",
"page",
"contains",
"the",
"given",
"set",
"of",
"success",
"messages"
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L123-L131 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assertNotMultipleSuccessMessage | public function assertNotMultipleSuccessMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'success messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['success messages']);
$this->assertNotSuccessMessage($message);
}
} | php | public function assertNotMultipleSuccessMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'success messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['success messages']);
$this->assertNotSuccessMessage($message);
}
} | [
"public",
"function",
"assertNotMultipleSuccessMessage",
"(",
"TableNode",
"$",
"messages",
")",
"{",
"$",
"this",
"->",
"assertValidMessageTable",
"(",
"$",
"messages",
",",
"'success messages'",
")",
";",
"foreach",
"(",
"$",
"messages",
"->",
"getHash",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"array_change_key_case",
"(",
"$",
"value",
")",
";",
"$",
"message",
"=",
"trim",
"(",
"$",
"value",
"[",
"'success messages'",
"]",
")",
";",
"$",
"this",
"->",
"assertNotSuccessMessage",
"(",
"$",
"message",
")",
";",
"}",
"}"
] | Checks if the current page does not contain the given set of success messages
@param array $message
An array of texts to be checked. The first row should consist of the
string "Success messages".
@Then I should not see the following success messages: | [
"Checks",
"if",
"the",
"current",
"page",
"does",
"not",
"contain",
"the",
"given",
"set",
"of",
"success",
"messages"
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L159-L167 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assertMultipleWarningMessage | public function assertMultipleWarningMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'warning messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['warning messages']);
$this->assertWarningMessage($message);
}
} | php | public function assertMultipleWarningMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'warning messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['warning messages']);
$this->assertWarningMessage($message);
}
} | [
"public",
"function",
"assertMultipleWarningMessage",
"(",
"TableNode",
"$",
"messages",
")",
"{",
"$",
"this",
"->",
"assertValidMessageTable",
"(",
"$",
"messages",
",",
"'warning messages'",
")",
";",
"foreach",
"(",
"$",
"messages",
"->",
"getHash",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"array_change_key_case",
"(",
"$",
"value",
")",
";",
"$",
"message",
"=",
"trim",
"(",
"$",
"value",
"[",
"'warning messages'",
"]",
")",
";",
"$",
"this",
"->",
"assertWarningMessage",
"(",
"$",
"message",
")",
";",
"}",
"}"
] | Checks if the current page contains the given set of warning messages
@param array $message
An array of texts to be checked. The first row should consist of the
string "Warning messages".
@Then I should see the following warning messages: | [
"Checks",
"if",
"the",
"current",
"page",
"contains",
"the",
"given",
"set",
"of",
"warning",
"messages"
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L196-L204 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assertNotMultipleWarningMessage | public function assertNotMultipleWarningMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'warning messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['warning messages']);
$this->assertNotWarningMessage($message);
}
} | php | public function assertNotMultipleWarningMessage(TableNode $messages)
{
$this->assertValidMessageTable($messages, 'warning messages');
foreach ($messages->getHash() as $key => $value) {
$value = array_change_key_case($value);
$message = trim($value['warning messages']);
$this->assertNotWarningMessage($message);
}
} | [
"public",
"function",
"assertNotMultipleWarningMessage",
"(",
"TableNode",
"$",
"messages",
")",
"{",
"$",
"this",
"->",
"assertValidMessageTable",
"(",
"$",
"messages",
",",
"'warning messages'",
")",
";",
"foreach",
"(",
"$",
"messages",
"->",
"getHash",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"array_change_key_case",
"(",
"$",
"value",
")",
";",
"$",
"message",
"=",
"trim",
"(",
"$",
"value",
"[",
"'warning messages'",
"]",
")",
";",
"$",
"this",
"->",
"assertNotWarningMessage",
"(",
"$",
"message",
")",
";",
"}",
"}"
] | Checks if the current page does not contain the given set of warning messages
@param array $message
An array of texts to be checked. The first row should consist of the
string "Warning messages".
@Then I should not see the following warning messages: | [
"Checks",
"if",
"the",
"current",
"page",
"does",
"not",
"contain",
"the",
"given",
"set",
"of",
"warning",
"messages"
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L232-L240 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assertValidMessageTable | protected function assertValidMessageTable(TableNode $messages, $expected_header)
{
// Check that the table only contains a single column.
$header_row = $messages->getRow(0);
$column_count = count($header_row);
if ($column_count != 1) {
throw new \RuntimeException("The list of $expected_header should only contain 1 column. It has $column_count columns.");
}
// Check that the correct header is used.
$actual_header = reset($header_row);
if (strtolower(trim($actual_header)) !== $expected_header) {
$capitalized_header = ucfirst($expected_header);
throw new \RuntimeException("The list of $expected_header should have the header '$capitalized_header'.");
}
} | php | protected function assertValidMessageTable(TableNode $messages, $expected_header)
{
// Check that the table only contains a single column.
$header_row = $messages->getRow(0);
$column_count = count($header_row);
if ($column_count != 1) {
throw new \RuntimeException("The list of $expected_header should only contain 1 column. It has $column_count columns.");
}
// Check that the correct header is used.
$actual_header = reset($header_row);
if (strtolower(trim($actual_header)) !== $expected_header) {
$capitalized_header = ucfirst($expected_header);
throw new \RuntimeException("The list of $expected_header should have the header '$capitalized_header'.");
}
} | [
"protected",
"function",
"assertValidMessageTable",
"(",
"TableNode",
"$",
"messages",
",",
"$",
"expected_header",
")",
"{",
"// Check that the table only contains a single column.",
"$",
"header_row",
"=",
"$",
"messages",
"->",
"getRow",
"(",
"0",
")",
";",
"$",
"column_count",
"=",
"count",
"(",
"$",
"header_row",
")",
";",
"if",
"(",
"$",
"column_count",
"!=",
"1",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"The list of $expected_header should only contain 1 column. It has $column_count columns.\"",
")",
";",
"}",
"// Check that the correct header is used.",
"$",
"actual_header",
"=",
"reset",
"(",
"$",
"header_row",
")",
";",
"if",
"(",
"strtolower",
"(",
"trim",
"(",
"$",
"actual_header",
")",
")",
"!==",
"$",
"expected_header",
")",
"{",
"$",
"capitalized_header",
"=",
"ucfirst",
"(",
"$",
"expected_header",
")",
";",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"The list of $expected_header should have the header '$capitalized_header'.\"",
")",
";",
"}",
"}"
] | Checks whether the given list of messages is valid.
This checks whether the list has only one column and has the correct
header.
@param \Behat\Gherkin\Node\TableNode $messages
The list of messages.
@param string $expected_header
The header that should be present in the list. | [
"Checks",
"whether",
"the",
"given",
"list",
"of",
"messages",
"is",
"valid",
"."
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L288-L304 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assert | private function assert($message, $selectorId, $exceptionMsgNone, $exceptionMsgMissing)
{
$selector = $this->getDrupalSelector($selectorId);
$selectorObjects = $this->getSession()->getPage()->findAll("css", $selector);
if (empty($selectorObjects)) {
throw new ExpectationException(sprintf($exceptionMsgNone, $this->getSession()->getCurrentUrl()), $this->getSession()->getDriver());
}
foreach ($selectorObjects as $selectorObject) {
if (strpos(trim($selectorObject->getText()), $message) !== false) {
return;
}
}
throw new ExpectationException(sprintf($exceptionMsgMissing, $this->getSession()->getCurrentUrl(), $message), $this->getSession()->getDriver());
} | php | private function assert($message, $selectorId, $exceptionMsgNone, $exceptionMsgMissing)
{
$selector = $this->getDrupalSelector($selectorId);
$selectorObjects = $this->getSession()->getPage()->findAll("css", $selector);
if (empty($selectorObjects)) {
throw new ExpectationException(sprintf($exceptionMsgNone, $this->getSession()->getCurrentUrl()), $this->getSession()->getDriver());
}
foreach ($selectorObjects as $selectorObject) {
if (strpos(trim($selectorObject->getText()), $message) !== false) {
return;
}
}
throw new ExpectationException(sprintf($exceptionMsgMissing, $this->getSession()->getCurrentUrl(), $message), $this->getSession()->getDriver());
} | [
"private",
"function",
"assert",
"(",
"$",
"message",
",",
"$",
"selectorId",
",",
"$",
"exceptionMsgNone",
",",
"$",
"exceptionMsgMissing",
")",
"{",
"$",
"selector",
"=",
"$",
"this",
"->",
"getDrupalSelector",
"(",
"$",
"selectorId",
")",
";",
"$",
"selectorObjects",
"=",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getPage",
"(",
")",
"->",
"findAll",
"(",
"\"css\"",
",",
"$",
"selector",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"selectorObjects",
")",
")",
"{",
"throw",
"new",
"ExpectationException",
"(",
"sprintf",
"(",
"$",
"exceptionMsgNone",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getCurrentUrl",
"(",
")",
")",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getDriver",
"(",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"selectorObjects",
"as",
"$",
"selectorObject",
")",
"{",
"if",
"(",
"strpos",
"(",
"trim",
"(",
"$",
"selectorObject",
"->",
"getText",
"(",
")",
")",
",",
"$",
"message",
")",
"!==",
"false",
")",
"{",
"return",
";",
"}",
"}",
"throw",
"new",
"ExpectationException",
"(",
"sprintf",
"(",
"$",
"exceptionMsgMissing",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getCurrentUrl",
"(",
")",
",",
"$",
"message",
")",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getDriver",
"(",
")",
")",
";",
"}"
] | Internal callback to check for a specific message in a given context.
@param $message
string The message to be checked
@param $selectorId
string CSS selector name
@param $exceptionMsgNone
string The message being thrown when no message is contained, string
should contain one '%s' as a placeholder for the current URL
@param $exceptionMsgMissing
string The message being thrown when the message is not contained, string
should contain two '%s' as placeholders for the current URL and the message.
@throws \Behat\Mink\Exception\ExpectationException
Thrown when the expected message is not present in the page. | [
"Internal",
"callback",
"to",
"check",
"for",
"a",
"specific",
"message",
"in",
"a",
"given",
"context",
"."
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L323-L336 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MessageContext.php | MessageContext.assertNot | private function assertNot($message, $selectorId, $exceptionMsg)
{
$selector = $this->getDrupalSelector($selectorId);
$selectorObjects = $this->getSession()->getPage()->findAll("css", $selector);
if (!empty($selectorObjects)) {
foreach ($selectorObjects as $selectorObject) {
if (strpos(trim($selectorObject->getText()), $message) !== false) {
throw new ExpectationException(sprintf($exceptionMsg, $this->getSession()->getCurrentUrl(), $message), $this->getSession()->getDriver());
}
}
}
} | php | private function assertNot($message, $selectorId, $exceptionMsg)
{
$selector = $this->getDrupalSelector($selectorId);
$selectorObjects = $this->getSession()->getPage()->findAll("css", $selector);
if (!empty($selectorObjects)) {
foreach ($selectorObjects as $selectorObject) {
if (strpos(trim($selectorObject->getText()), $message) !== false) {
throw new ExpectationException(sprintf($exceptionMsg, $this->getSession()->getCurrentUrl(), $message), $this->getSession()->getDriver());
}
}
}
} | [
"private",
"function",
"assertNot",
"(",
"$",
"message",
",",
"$",
"selectorId",
",",
"$",
"exceptionMsg",
")",
"{",
"$",
"selector",
"=",
"$",
"this",
"->",
"getDrupalSelector",
"(",
"$",
"selectorId",
")",
";",
"$",
"selectorObjects",
"=",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getPage",
"(",
")",
"->",
"findAll",
"(",
"\"css\"",
",",
"$",
"selector",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"selectorObjects",
")",
")",
"{",
"foreach",
"(",
"$",
"selectorObjects",
"as",
"$",
"selectorObject",
")",
"{",
"if",
"(",
"strpos",
"(",
"trim",
"(",
"$",
"selectorObject",
"->",
"getText",
"(",
")",
")",
",",
"$",
"message",
")",
"!==",
"false",
")",
"{",
"throw",
"new",
"ExpectationException",
"(",
"sprintf",
"(",
"$",
"exceptionMsg",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getCurrentUrl",
"(",
")",
",",
"$",
"message",
")",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getDriver",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Internal callback to check if the current page does not contain the given message
@param $message
string The message to be checked
@param $selectorId
string CSS selector name
@param $exceptionMsg
string The message being thrown when the message is contained, string
should contain two '%s' as placeholders for the current URL and the message.
@throws \Behat\Mink\Exception\ExpectationException
Thrown when the expected message is present in the page. | [
"Internal",
"callback",
"to",
"check",
"if",
"the",
"current",
"page",
"does",
"not",
"contain",
"the",
"given",
"message"
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MessageContext.php#L352-L363 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/BatchContext.php | BatchContext.thereIsAnItemInTheSystemQueue | public function thereIsAnItemInTheSystemQueue(TableNode $table)
{
// Gather the data.
$fields = $table->getRowsHash();
// Default data field separately since this is longish.
if (empty($fields['data'])) {
$fields['data'] = json_encode([]);
}
// @see SystemQueue::createItem().
$query = db_insert('queue')
->fields(array(
'name' => $fields['name'] ?: user_password(),
'data' => serialize(json_decode($fields['data'])),
'created' => $fields['created'] ?: REQUEST_TIME,
'expire' => $fields['expire'] ?: 0,
));
if (!$query->execute()) {
throw new Exception('Unable to create the queue item.');
}
} | php | public function thereIsAnItemInTheSystemQueue(TableNode $table)
{
// Gather the data.
$fields = $table->getRowsHash();
// Default data field separately since this is longish.
if (empty($fields['data'])) {
$fields['data'] = json_encode([]);
}
// @see SystemQueue::createItem().
$query = db_insert('queue')
->fields(array(
'name' => $fields['name'] ?: user_password(),
'data' => serialize(json_decode($fields['data'])),
'created' => $fields['created'] ?: REQUEST_TIME,
'expire' => $fields['expire'] ?: 0,
));
if (!$query->execute()) {
throw new Exception('Unable to create the queue item.');
}
} | [
"public",
"function",
"thereIsAnItemInTheSystemQueue",
"(",
"TableNode",
"$",
"table",
")",
"{",
"// Gather the data.",
"$",
"fields",
"=",
"$",
"table",
"->",
"getRowsHash",
"(",
")",
";",
"// Default data field separately since this is longish.",
"if",
"(",
"empty",
"(",
"$",
"fields",
"[",
"'data'",
"]",
")",
")",
"{",
"$",
"fields",
"[",
"'data'",
"]",
"=",
"json_encode",
"(",
"[",
"]",
")",
";",
"}",
"// @see SystemQueue::createItem().",
"$",
"query",
"=",
"db_insert",
"(",
"'queue'",
")",
"->",
"fields",
"(",
"array",
"(",
"'name'",
"=>",
"$",
"fields",
"[",
"'name'",
"]",
"?",
":",
"user_password",
"(",
")",
",",
"'data'",
"=>",
"serialize",
"(",
"json_decode",
"(",
"$",
"fields",
"[",
"'data'",
"]",
")",
")",
",",
"'created'",
"=>",
"$",
"fields",
"[",
"'created'",
"]",
"?",
":",
"REQUEST_TIME",
",",
"'expire'",
"=>",
"$",
"fields",
"[",
"'expire'",
"]",
"?",
":",
"0",
",",
")",
")",
";",
"if",
"(",
"!",
"$",
"query",
"->",
"execute",
"(",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Unable to create the queue item.'",
")",
";",
"}",
"}"
] | Creates a queue item. Defaults inputs if none are available.
Expects the `data` to be a json encoded string.
@Given there is an item in the system queue: | [
"Creates",
"a",
"queue",
"item",
".",
"Defaults",
"inputs",
"if",
"none",
"are",
"available",
"."
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/BatchContext.php#L33-L54 |
jhedstrom/drupalextension | src/Drupal/DrupalExtension/Context/MarkupContext.php | MarkupContext.assertRegionButton | public function assertRegionButton($button, $region)
{
$regionObj = $this->getRegion($region);
$buttonObj = $regionObj->findButton($button);
if (empty($buttonObj)) {
throw new \Exception(sprintf("The button '%s' was not found in the region '%s' on the page %s", $button, $region, $this->getSession()->getCurrentUrl()));
}
} | php | public function assertRegionButton($button, $region)
{
$regionObj = $this->getRegion($region);
$buttonObj = $regionObj->findButton($button);
if (empty($buttonObj)) {
throw new \Exception(sprintf("The button '%s' was not found in the region '%s' on the page %s", $button, $region, $this->getSession()->getCurrentUrl()));
}
} | [
"public",
"function",
"assertRegionButton",
"(",
"$",
"button",
",",
"$",
"region",
")",
"{",
"$",
"regionObj",
"=",
"$",
"this",
"->",
"getRegion",
"(",
"$",
"region",
")",
";",
"$",
"buttonObj",
"=",
"$",
"regionObj",
"->",
"findButton",
"(",
"$",
"button",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"buttonObj",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"sprintf",
"(",
"\"The button '%s' was not found in the region '%s' on the page %s\"",
",",
"$",
"button",
",",
"$",
"region",
",",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getCurrentUrl",
"(",
")",
")",
")",
";",
"}",
"}"
] | Checks if a button with id|name|title|alt|value exists in a region
@Then I should see the button :button in the :region( region)
@Then I should see the :button button in the :region( region)
@param $button
string The id|name|title|alt|value of the button
@param $region
string The region in which the button should be found
@throws \Exception
If region or button within it cannot be found. | [
"Checks",
"if",
"a",
"button",
"with",
"id|name|title|alt|value",
"exists",
"in",
"a",
"region"
] | train | https://github.com/jhedstrom/drupalextension/blob/d117c1a23b83c0e88b6224ed5d1d3458ce255b5a/src/Drupal/DrupalExtension/Context/MarkupContext.php#L51-L59 |
ircmaxell/php-cfg | lib/PHPCfg/Parser.php | Parser.parseExprList | protected function parseExprList(array $expr, $readWrite = self::MODE_NONE): array
{
$vars = array_map([$this, 'parseExprNode'], $expr);
if ($readWrite === self::MODE_READ) {
$vars = array_map([$this, 'readVariable'], $vars);
} elseif ($readWrite === self::MODE_WRITE) {
$vars = array_map([$this, 'writeVariable'], $vars);
}
return $vars;
} | php | protected function parseExprList(array $expr, $readWrite = self::MODE_NONE): array
{
$vars = array_map([$this, 'parseExprNode'], $expr);
if ($readWrite === self::MODE_READ) {
$vars = array_map([$this, 'readVariable'], $vars);
} elseif ($readWrite === self::MODE_WRITE) {
$vars = array_map([$this, 'writeVariable'], $vars);
}
return $vars;
} | [
"protected",
"function",
"parseExprList",
"(",
"array",
"$",
"expr",
",",
"$",
"readWrite",
"=",
"self",
"::",
"MODE_NONE",
")",
":",
"array",
"{",
"$",
"vars",
"=",
"array_map",
"(",
"[",
"$",
"this",
",",
"'parseExprNode'",
"]",
",",
"$",
"expr",
")",
";",
"if",
"(",
"$",
"readWrite",
"===",
"self",
"::",
"MODE_READ",
")",
"{",
"$",
"vars",
"=",
"array_map",
"(",
"[",
"$",
"this",
",",
"'readVariable'",
"]",
",",
"$",
"vars",
")",
";",
"}",
"elseif",
"(",
"$",
"readWrite",
"===",
"self",
"::",
"MODE_WRITE",
")",
"{",
"$",
"vars",
"=",
"array_map",
"(",
"[",
"$",
"this",
",",
"'writeVariable'",
"]",
",",
"$",
"vars",
")",
";",
"}",
"return",
"$",
"vars",
";",
"}"
] | @param Node[] $expr
@param int $readWrite
@return Operand[] | [
"@param",
"Node",
"[]",
"$expr",
"@param",
"int",
"$readWrite"
] | train | https://github.com/ircmaxell/php-cfg/blob/2e8ac7373dce7067691e098950f0a9faf1037d0b/lib/PHPCfg/Parser.php#L700-L710 |
soberwp/models | dist/symfony/yaml/Parser.php | Parser.parse | public function parse($value, $flags = 0)
{
if (\is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (\func_num_args() >= 3) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(2)) {
$flags |= Yaml::PARSE_OBJECT;
}
}
if (\func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= Yaml::PARSE_OBJECT_FOR_MAP;
}
}
if (Yaml::PARSE_KEYS_AS_STRINGS & $flags) {
@trigger_error('Using the Yaml::PARSE_KEYS_AS_STRINGS flag is deprecated since Symfony 3.4 as it will be removed in 4.0. Quote your keys when they are evaluable instead.', E_USER_DEPRECATED);
}
if (false === preg_match('//u', $value)) {
throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename);
}
$this->refs = array();
$mbEncoding = null;
$e = null;
$data = null;
if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8');
}
try {
$data = $this->doParse($value, $flags);
} catch (\Exception $e) {
} catch (\Throwable $e) {
}
if (null !== $mbEncoding) {
mb_internal_encoding($mbEncoding);
}
$this->lines = array();
$this->currentLine = '';
$this->refs = array();
$this->skippedLineNumbers = array();
$this->locallySkippedLineNumbers = array();
if (null !== $e) {
throw $e;
}
return $data;
} | php | public function parse($value, $flags = 0)
{
if (\is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (\func_num_args() >= 3) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if (func_get_arg(2)) {
$flags |= Yaml::PARSE_OBJECT;
}
}
if (\func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= Yaml::PARSE_OBJECT_FOR_MAP;
}
}
if (Yaml::PARSE_KEYS_AS_STRINGS & $flags) {
@trigger_error('Using the Yaml::PARSE_KEYS_AS_STRINGS flag is deprecated since Symfony 3.4 as it will be removed in 4.0. Quote your keys when they are evaluable instead.', E_USER_DEPRECATED);
}
if (false === preg_match('//u', $value)) {
throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename);
}
$this->refs = array();
$mbEncoding = null;
$e = null;
$data = null;
if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8');
}
try {
$data = $this->doParse($value, $flags);
} catch (\Exception $e) {
} catch (\Throwable $e) {
}
if (null !== $mbEncoding) {
mb_internal_encoding($mbEncoding);
}
$this->lines = array();
$this->currentLine = '';
$this->refs = array();
$this->skippedLineNumbers = array();
$this->locallySkippedLineNumbers = array();
if (null !== $e) {
throw $e;
}
return $data;
} | [
"public",
"function",
"parse",
"(",
"$",
"value",
",",
"$",
"flags",
"=",
"0",
")",
"{",
"if",
"(",
"\\",
"is_bool",
"(",
"$",
"flags",
")",
")",
"{",
"@",
"trigger_error",
"(",
"'Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"$",
"flags",
")",
"{",
"$",
"flags",
"=",
"Yaml",
"::",
"PARSE_EXCEPTION_ON_INVALID_TYPE",
";",
"}",
"else",
"{",
"$",
"flags",
"=",
"0",
";",
"}",
"}",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
">=",
"3",
")",
"{",
"@",
"trigger_error",
"(",
"'Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"func_get_arg",
"(",
"2",
")",
")",
"{",
"$",
"flags",
"|=",
"Yaml",
"::",
"PARSE_OBJECT",
";",
"}",
"}",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
">=",
"4",
")",
"{",
"@",
"trigger_error",
"(",
"'Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"func_get_arg",
"(",
"3",
")",
")",
"{",
"$",
"flags",
"|=",
"Yaml",
"::",
"PARSE_OBJECT_FOR_MAP",
";",
"}",
"}",
"if",
"(",
"Yaml",
"::",
"PARSE_KEYS_AS_STRINGS",
"&",
"$",
"flags",
")",
"{",
"@",
"trigger_error",
"(",
"'Using the Yaml::PARSE_KEYS_AS_STRINGS flag is deprecated since Symfony 3.4 as it will be removed in 4.0. Quote your keys when they are evaluable instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"}",
"if",
"(",
"false",
"===",
"preg_match",
"(",
"'//u'",
",",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"'The YAML value does not appear to be valid UTF-8.'",
",",
"-",
"1",
",",
"null",
",",
"$",
"this",
"->",
"filename",
")",
";",
"}",
"$",
"this",
"->",
"refs",
"=",
"array",
"(",
")",
";",
"$",
"mbEncoding",
"=",
"null",
";",
"$",
"e",
"=",
"null",
";",
"$",
"data",
"=",
"null",
";",
"if",
"(",
"2",
"/* MB_OVERLOAD_STRING */",
"&",
"(",
"int",
")",
"ini_get",
"(",
"'mbstring.func_overload'",
")",
")",
"{",
"$",
"mbEncoding",
"=",
"mb_internal_encoding",
"(",
")",
";",
"mb_internal_encoding",
"(",
"'UTF-8'",
")",
";",
"}",
"try",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"doParse",
"(",
"$",
"value",
",",
"$",
"flags",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"e",
")",
"{",
"}",
"if",
"(",
"null",
"!==",
"$",
"mbEncoding",
")",
"{",
"mb_internal_encoding",
"(",
"$",
"mbEncoding",
")",
";",
"}",
"$",
"this",
"->",
"lines",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"currentLine",
"=",
"''",
";",
"$",
"this",
"->",
"refs",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"skippedLineNumbers",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"locallySkippedLineNumbers",
"=",
"array",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"e",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Parses a YAML string to a PHP value.
@param string $value A YAML string
@param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
@return mixed A PHP value
@throws ParseException If the YAML is not valid | [
"Parses",
"a",
"YAML",
"string",
"to",
"a",
"PHP",
"value",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Parser.php#L93-L161 |
soberwp/models | dist/symfony/yaml/Parser.php | Parser.parseValue | private function parseValue($value, $flags, $context)
{
if (0 === strpos($value, '*')) {
if (false !== $pos = strpos($value, '#')) {
$value = substr($value, 1, $pos - 2);
} else {
$value = substr($value, 1);
}
if (!array_key_exists($value, $this->refs)) {
throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
}
return $this->refs[$value];
}
if (self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
$data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
if ('' !== $matches['tag']) {
if ('!!binary' === $matches['tag']) {
return Inline::evaluateBinaryScalar($data);
} elseif ('tagged' === $matches['tag']) {
return new TaggedValue(substr($matches['tag'], 1), $data);
} elseif ('!' !== $matches['tag']) {
@trigger_error($this->getDeprecationMessage(sprintf('Using the custom tag "%s" for the value "%s" is deprecated since Symfony 3.3. It will be replaced by an instance of %s in 4.0.', $matches['tag'], $data, TaggedValue::class)), E_USER_DEPRECATED);
}
}
return $data;
}
try {
$quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null;
// do not take following lines into account when the current line is a quoted single line value
if (null !== $quotation && self::preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) {
return Inline::parse($value, $flags, $this->refs);
}
$lines = array();
while ($this->moveToNextLine()) {
// unquoted strings end before the first unindented line
if (null === $quotation && 0 === $this->getCurrentLineIndentation()) {
$this->moveToPreviousLine();
break;
}
$lines[] = trim($this->currentLine);
// quoted string values end with a line that is terminated with the quotation character
if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) {
break;
}
}
for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
if ('' === $lines[$i]) {
$value .= "\n";
$previousLineBlank = true;
} elseif ($previousLineBlank) {
$value .= $lines[$i];
$previousLineBlank = false;
} else {
$value .= ' '.$lines[$i];
$previousLineBlank = false;
}
}
Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
$parsedValue = Inline::parse($value, $flags, $this->refs);
if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
}
return $parsedValue;
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);
throw $e;
}
} | php | private function parseValue($value, $flags, $context)
{
if (0 === strpos($value, '*')) {
if (false !== $pos = strpos($value, '#')) {
$value = substr($value, 1, $pos - 2);
} else {
$value = substr($value, 1);
}
if (!array_key_exists($value, $this->refs)) {
throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
}
return $this->refs[$value];
}
if (self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
$data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
if ('' !== $matches['tag']) {
if ('!!binary' === $matches['tag']) {
return Inline::evaluateBinaryScalar($data);
} elseif ('tagged' === $matches['tag']) {
return new TaggedValue(substr($matches['tag'], 1), $data);
} elseif ('!' !== $matches['tag']) {
@trigger_error($this->getDeprecationMessage(sprintf('Using the custom tag "%s" for the value "%s" is deprecated since Symfony 3.3. It will be replaced by an instance of %s in 4.0.', $matches['tag'], $data, TaggedValue::class)), E_USER_DEPRECATED);
}
}
return $data;
}
try {
$quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null;
// do not take following lines into account when the current line is a quoted single line value
if (null !== $quotation && self::preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) {
return Inline::parse($value, $flags, $this->refs);
}
$lines = array();
while ($this->moveToNextLine()) {
// unquoted strings end before the first unindented line
if (null === $quotation && 0 === $this->getCurrentLineIndentation()) {
$this->moveToPreviousLine();
break;
}
$lines[] = trim($this->currentLine);
// quoted string values end with a line that is terminated with the quotation character
if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) {
break;
}
}
for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
if ('' === $lines[$i]) {
$value .= "\n";
$previousLineBlank = true;
} elseif ($previousLineBlank) {
$value .= $lines[$i];
$previousLineBlank = false;
} else {
$value .= ' '.$lines[$i];
$previousLineBlank = false;
}
}
Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
$parsedValue = Inline::parse($value, $flags, $this->refs);
if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
}
return $parsedValue;
} catch (ParseException $e) {
$e->setParsedLine($this->getRealCurrentLineNb() + 1);
$e->setSnippet($this->currentLine);
throw $e;
}
} | [
"private",
"function",
"parseValue",
"(",
"$",
"value",
",",
"$",
"flags",
",",
"$",
"context",
")",
"{",
"if",
"(",
"0",
"===",
"strpos",
"(",
"$",
"value",
",",
"'*'",
")",
")",
"{",
"if",
"(",
"false",
"!==",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"value",
",",
"'#'",
")",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"1",
",",
"$",
"pos",
"-",
"2",
")",
";",
"}",
"else",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"1",
")",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"refs",
")",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"sprintf",
"(",
"'Reference \"%s\" does not exist.'",
",",
"$",
"value",
")",
",",
"$",
"this",
"->",
"currentLineNb",
"+",
"1",
",",
"$",
"this",
"->",
"currentLine",
",",
"$",
"this",
"->",
"filename",
")",
";",
"}",
"return",
"$",
"this",
"->",
"refs",
"[",
"$",
"value",
"]",
";",
"}",
"if",
"(",
"self",
"::",
"preg_match",
"(",
"'/^(?:'",
".",
"self",
"::",
"TAG_PATTERN",
".",
"' +)?'",
".",
"self",
"::",
"BLOCK_SCALAR_HEADER_PATTERN",
".",
"'$/'",
",",
"$",
"value",
",",
"$",
"matches",
")",
")",
"{",
"$",
"modifiers",
"=",
"isset",
"(",
"$",
"matches",
"[",
"'modifiers'",
"]",
")",
"?",
"$",
"matches",
"[",
"'modifiers'",
"]",
":",
"''",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"parseBlockScalar",
"(",
"$",
"matches",
"[",
"'separator'",
"]",
",",
"preg_replace",
"(",
"'#\\d+#'",
",",
"''",
",",
"$",
"modifiers",
")",
",",
"(",
"int",
")",
"abs",
"(",
"$",
"modifiers",
")",
")",
";",
"if",
"(",
"''",
"!==",
"$",
"matches",
"[",
"'tag'",
"]",
")",
"{",
"if",
"(",
"'!!binary'",
"===",
"$",
"matches",
"[",
"'tag'",
"]",
")",
"{",
"return",
"Inline",
"::",
"evaluateBinaryScalar",
"(",
"$",
"data",
")",
";",
"}",
"elseif",
"(",
"'tagged'",
"===",
"$",
"matches",
"[",
"'tag'",
"]",
")",
"{",
"return",
"new",
"TaggedValue",
"(",
"substr",
"(",
"$",
"matches",
"[",
"'tag'",
"]",
",",
"1",
")",
",",
"$",
"data",
")",
";",
"}",
"elseif",
"(",
"'!'",
"!==",
"$",
"matches",
"[",
"'tag'",
"]",
")",
"{",
"@",
"trigger_error",
"(",
"$",
"this",
"->",
"getDeprecationMessage",
"(",
"sprintf",
"(",
"'Using the custom tag \"%s\" for the value \"%s\" is deprecated since Symfony 3.3. It will be replaced by an instance of %s in 4.0.'",
",",
"$",
"matches",
"[",
"'tag'",
"]",
",",
"$",
"data",
",",
"TaggedValue",
"::",
"class",
")",
")",
",",
"E_USER_DEPRECATED",
")",
";",
"}",
"}",
"return",
"$",
"data",
";",
"}",
"try",
"{",
"$",
"quotation",
"=",
"''",
"!==",
"$",
"value",
"&&",
"(",
"'\"'",
"===",
"$",
"value",
"[",
"0",
"]",
"||",
"\"'\"",
"===",
"$",
"value",
"[",
"0",
"]",
")",
"?",
"$",
"value",
"[",
"0",
"]",
":",
"null",
";",
"// do not take following lines into account when the current line is a quoted single line value",
"if",
"(",
"null",
"!==",
"$",
"quotation",
"&&",
"self",
"::",
"preg_match",
"(",
"'/^'",
".",
"$",
"quotation",
".",
"'.*'",
".",
"$",
"quotation",
".",
"'(\\s*#.*)?$/'",
",",
"$",
"value",
")",
")",
"{",
"return",
"Inline",
"::",
"parse",
"(",
"$",
"value",
",",
"$",
"flags",
",",
"$",
"this",
"->",
"refs",
")",
";",
"}",
"$",
"lines",
"=",
"array",
"(",
")",
";",
"while",
"(",
"$",
"this",
"->",
"moveToNextLine",
"(",
")",
")",
"{",
"// unquoted strings end before the first unindented line",
"if",
"(",
"null",
"===",
"$",
"quotation",
"&&",
"0",
"===",
"$",
"this",
"->",
"getCurrentLineIndentation",
"(",
")",
")",
"{",
"$",
"this",
"->",
"moveToPreviousLine",
"(",
")",
";",
"break",
";",
"}",
"$",
"lines",
"[",
"]",
"=",
"trim",
"(",
"$",
"this",
"->",
"currentLine",
")",
";",
"// quoted string values end with a line that is terminated with the quotation character",
"if",
"(",
"''",
"!==",
"$",
"this",
"->",
"currentLine",
"&&",
"substr",
"(",
"$",
"this",
"->",
"currentLine",
",",
"-",
"1",
")",
"===",
"$",
"quotation",
")",
"{",
"break",
";",
"}",
"}",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"linesCount",
"=",
"\\",
"count",
"(",
"$",
"lines",
")",
",",
"$",
"previousLineBlank",
"=",
"false",
";",
"$",
"i",
"<",
"$",
"linesCount",
";",
"++",
"$",
"i",
")",
"{",
"if",
"(",
"''",
"===",
"$",
"lines",
"[",
"$",
"i",
"]",
")",
"{",
"$",
"value",
".=",
"\"\\n\"",
";",
"$",
"previousLineBlank",
"=",
"true",
";",
"}",
"elseif",
"(",
"$",
"previousLineBlank",
")",
"{",
"$",
"value",
".=",
"$",
"lines",
"[",
"$",
"i",
"]",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"}",
"else",
"{",
"$",
"value",
".=",
"' '",
".",
"$",
"lines",
"[",
"$",
"i",
"]",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"}",
"}",
"Inline",
"::",
"$",
"parsedLineNumber",
"=",
"$",
"this",
"->",
"getRealCurrentLineNb",
"(",
")",
";",
"$",
"parsedValue",
"=",
"Inline",
"::",
"parse",
"(",
"$",
"value",
",",
"$",
"flags",
",",
"$",
"this",
"->",
"refs",
")",
";",
"if",
"(",
"'mapping'",
"===",
"$",
"context",
"&&",
"\\",
"is_string",
"(",
"$",
"parsedValue",
")",
"&&",
"'\"'",
"!==",
"$",
"value",
"[",
"0",
"]",
"&&",
"\"'\"",
"!==",
"$",
"value",
"[",
"0",
"]",
"&&",
"'['",
"!==",
"$",
"value",
"[",
"0",
"]",
"&&",
"'{'",
"!==",
"$",
"value",
"[",
"0",
"]",
"&&",
"'!'",
"!==",
"$",
"value",
"[",
"0",
"]",
"&&",
"false",
"!==",
"strpos",
"(",
"$",
"parsedValue",
",",
"': '",
")",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"'A colon cannot be used in an unquoted mapping value.'",
",",
"$",
"this",
"->",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
",",
"$",
"value",
",",
"$",
"this",
"->",
"filename",
")",
";",
"}",
"return",
"$",
"parsedValue",
";",
"}",
"catch",
"(",
"ParseException",
"$",
"e",
")",
"{",
"$",
"e",
"->",
"setParsedLine",
"(",
"$",
"this",
"->",
"getRealCurrentLineNb",
"(",
")",
"+",
"1",
")",
";",
"$",
"e",
"->",
"setSnippet",
"(",
"$",
"this",
"->",
"currentLine",
")",
";",
"throw",
"$",
"e",
";",
"}",
"}"
] | Parses a YAML value.
@param string $value A YAML value
@param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
@param string $context The parser context (either sequence or mapping)
@return mixed A PHP value
@throws ParseException When reference does not exist | [
"Parses",
"a",
"YAML",
"value",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Parser.php#L682-L770 |
soberwp/models | dist/symfony/yaml/Parser.php | Parser.parseBlockScalar | private function parseBlockScalar($style, $chomping = '', $indentation = 0)
{
$notEOF = $this->moveToNextLine();
if (!$notEOF) {
return '';
}
$isCurrentLineBlank = $this->isCurrentLineBlank();
$blockLines = array();
// leading blank lines are consumed before determining indentation
while ($notEOF && $isCurrentLineBlank) {
// newline only if not EOF
if ($notEOF = $this->moveToNextLine()) {
$blockLines[] = '';
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
// determine indentation if not specified
if (0 === $indentation) {
if (self::preg_match('/^ +/', $this->currentLine, $matches)) {
$indentation = \strlen($matches[0]);
}
}
if ($indentation > 0) {
$pattern = sprintf('/^ {%d}(.*)$/', $indentation);
while (
$notEOF && (
$isCurrentLineBlank ||
self::preg_match($pattern, $this->currentLine, $matches)
)
) {
if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
$blockLines[] = substr($this->currentLine, $indentation);
} elseif ($isCurrentLineBlank) {
$blockLines[] = '';
} else {
$blockLines[] = $matches[1];
}
// newline only if not EOF
if ($notEOF = $this->moveToNextLine()) {
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
} elseif ($notEOF) {
$blockLines[] = '';
}
if ($notEOF) {
$blockLines[] = '';
$this->moveToPreviousLine();
} elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
$blockLines[] = '';
}
// folded style
if ('>' === $style) {
$text = '';
$previousLineIndented = false;
$previousLineBlank = false;
for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
if ('' === $blockLines[$i]) {
$text .= "\n";
$previousLineIndented = false;
$previousLineBlank = true;
} elseif (' ' === $blockLines[$i][0]) {
$text .= "\n".$blockLines[$i];
$previousLineIndented = true;
$previousLineBlank = false;
} elseif ($previousLineIndented) {
$text .= "\n".$blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
} elseif ($previousLineBlank || 0 === $i) {
$text .= $blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
} else {
$text .= ' '.$blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
}
}
} else {
$text = implode("\n", $blockLines);
}
// deal with trailing newlines
if ('' === $chomping) {
$text = preg_replace('/\n+$/', "\n", $text);
} elseif ('-' === $chomping) {
$text = preg_replace('/\n+$/', '', $text);
}
return $text;
} | php | private function parseBlockScalar($style, $chomping = '', $indentation = 0)
{
$notEOF = $this->moveToNextLine();
if (!$notEOF) {
return '';
}
$isCurrentLineBlank = $this->isCurrentLineBlank();
$blockLines = array();
// leading blank lines are consumed before determining indentation
while ($notEOF && $isCurrentLineBlank) {
// newline only if not EOF
if ($notEOF = $this->moveToNextLine()) {
$blockLines[] = '';
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
// determine indentation if not specified
if (0 === $indentation) {
if (self::preg_match('/^ +/', $this->currentLine, $matches)) {
$indentation = \strlen($matches[0]);
}
}
if ($indentation > 0) {
$pattern = sprintf('/^ {%d}(.*)$/', $indentation);
while (
$notEOF && (
$isCurrentLineBlank ||
self::preg_match($pattern, $this->currentLine, $matches)
)
) {
if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
$blockLines[] = substr($this->currentLine, $indentation);
} elseif ($isCurrentLineBlank) {
$blockLines[] = '';
} else {
$blockLines[] = $matches[1];
}
// newline only if not EOF
if ($notEOF = $this->moveToNextLine()) {
$isCurrentLineBlank = $this->isCurrentLineBlank();
}
}
} elseif ($notEOF) {
$blockLines[] = '';
}
if ($notEOF) {
$blockLines[] = '';
$this->moveToPreviousLine();
} elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
$blockLines[] = '';
}
// folded style
if ('>' === $style) {
$text = '';
$previousLineIndented = false;
$previousLineBlank = false;
for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
if ('' === $blockLines[$i]) {
$text .= "\n";
$previousLineIndented = false;
$previousLineBlank = true;
} elseif (' ' === $blockLines[$i][0]) {
$text .= "\n".$blockLines[$i];
$previousLineIndented = true;
$previousLineBlank = false;
} elseif ($previousLineIndented) {
$text .= "\n".$blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
} elseif ($previousLineBlank || 0 === $i) {
$text .= $blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
} else {
$text .= ' '.$blockLines[$i];
$previousLineIndented = false;
$previousLineBlank = false;
}
}
} else {
$text = implode("\n", $blockLines);
}
// deal with trailing newlines
if ('' === $chomping) {
$text = preg_replace('/\n+$/', "\n", $text);
} elseif ('-' === $chomping) {
$text = preg_replace('/\n+$/', '', $text);
}
return $text;
} | [
"private",
"function",
"parseBlockScalar",
"(",
"$",
"style",
",",
"$",
"chomping",
"=",
"''",
",",
"$",
"indentation",
"=",
"0",
")",
"{",
"$",
"notEOF",
"=",
"$",
"this",
"->",
"moveToNextLine",
"(",
")",
";",
"if",
"(",
"!",
"$",
"notEOF",
")",
"{",
"return",
"''",
";",
"}",
"$",
"isCurrentLineBlank",
"=",
"$",
"this",
"->",
"isCurrentLineBlank",
"(",
")",
";",
"$",
"blockLines",
"=",
"array",
"(",
")",
";",
"// leading blank lines are consumed before determining indentation",
"while",
"(",
"$",
"notEOF",
"&&",
"$",
"isCurrentLineBlank",
")",
"{",
"// newline only if not EOF",
"if",
"(",
"$",
"notEOF",
"=",
"$",
"this",
"->",
"moveToNextLine",
"(",
")",
")",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"''",
";",
"$",
"isCurrentLineBlank",
"=",
"$",
"this",
"->",
"isCurrentLineBlank",
"(",
")",
";",
"}",
"}",
"// determine indentation if not specified",
"if",
"(",
"0",
"===",
"$",
"indentation",
")",
"{",
"if",
"(",
"self",
"::",
"preg_match",
"(",
"'/^ +/'",
",",
"$",
"this",
"->",
"currentLine",
",",
"$",
"matches",
")",
")",
"{",
"$",
"indentation",
"=",
"\\",
"strlen",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
";",
"}",
"}",
"if",
"(",
"$",
"indentation",
">",
"0",
")",
"{",
"$",
"pattern",
"=",
"sprintf",
"(",
"'/^ {%d}(.*)$/'",
",",
"$",
"indentation",
")",
";",
"while",
"(",
"$",
"notEOF",
"&&",
"(",
"$",
"isCurrentLineBlank",
"||",
"self",
"::",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"this",
"->",
"currentLine",
",",
"$",
"matches",
")",
")",
")",
"{",
"if",
"(",
"$",
"isCurrentLineBlank",
"&&",
"\\",
"strlen",
"(",
"$",
"this",
"->",
"currentLine",
")",
">",
"$",
"indentation",
")",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"substr",
"(",
"$",
"this",
"->",
"currentLine",
",",
"$",
"indentation",
")",
";",
"}",
"elseif",
"(",
"$",
"isCurrentLineBlank",
")",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"}",
"// newline only if not EOF",
"if",
"(",
"$",
"notEOF",
"=",
"$",
"this",
"->",
"moveToNextLine",
"(",
")",
")",
"{",
"$",
"isCurrentLineBlank",
"=",
"$",
"this",
"->",
"isCurrentLineBlank",
"(",
")",
";",
"}",
"}",
"}",
"elseif",
"(",
"$",
"notEOF",
")",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"''",
";",
"}",
"if",
"(",
"$",
"notEOF",
")",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"''",
";",
"$",
"this",
"->",
"moveToPreviousLine",
"(",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"notEOF",
"&&",
"!",
"$",
"this",
"->",
"isCurrentLineLastLineInDocument",
"(",
")",
")",
"{",
"$",
"blockLines",
"[",
"]",
"=",
"''",
";",
"}",
"// folded style",
"if",
"(",
"'>'",
"===",
"$",
"style",
")",
"{",
"$",
"text",
"=",
"''",
";",
"$",
"previousLineIndented",
"=",
"false",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"blockLinesCount",
"=",
"\\",
"count",
"(",
"$",
"blockLines",
")",
";",
"$",
"i",
"<",
"$",
"blockLinesCount",
";",
"++",
"$",
"i",
")",
"{",
"if",
"(",
"''",
"===",
"$",
"blockLines",
"[",
"$",
"i",
"]",
")",
"{",
"$",
"text",
".=",
"\"\\n\"",
";",
"$",
"previousLineIndented",
"=",
"false",
";",
"$",
"previousLineBlank",
"=",
"true",
";",
"}",
"elseif",
"(",
"' '",
"===",
"$",
"blockLines",
"[",
"$",
"i",
"]",
"[",
"0",
"]",
")",
"{",
"$",
"text",
".=",
"\"\\n\"",
".",
"$",
"blockLines",
"[",
"$",
"i",
"]",
";",
"$",
"previousLineIndented",
"=",
"true",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"}",
"elseif",
"(",
"$",
"previousLineIndented",
")",
"{",
"$",
"text",
".=",
"\"\\n\"",
".",
"$",
"blockLines",
"[",
"$",
"i",
"]",
";",
"$",
"previousLineIndented",
"=",
"false",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"}",
"elseif",
"(",
"$",
"previousLineBlank",
"||",
"0",
"===",
"$",
"i",
")",
"{",
"$",
"text",
".=",
"$",
"blockLines",
"[",
"$",
"i",
"]",
";",
"$",
"previousLineIndented",
"=",
"false",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"}",
"else",
"{",
"$",
"text",
".=",
"' '",
".",
"$",
"blockLines",
"[",
"$",
"i",
"]",
";",
"$",
"previousLineIndented",
"=",
"false",
";",
"$",
"previousLineBlank",
"=",
"false",
";",
"}",
"}",
"}",
"else",
"{",
"$",
"text",
"=",
"implode",
"(",
"\"\\n\"",
",",
"$",
"blockLines",
")",
";",
"}",
"// deal with trailing newlines",
"if",
"(",
"''",
"===",
"$",
"chomping",
")",
"{",
"$",
"text",
"=",
"preg_replace",
"(",
"'/\\n+$/'",
",",
"\"\\n\"",
",",
"$",
"text",
")",
";",
"}",
"elseif",
"(",
"'-'",
"===",
"$",
"chomping",
")",
"{",
"$",
"text",
"=",
"preg_replace",
"(",
"'/\\n+$/'",
",",
"''",
",",
"$",
"text",
")",
";",
"}",
"return",
"$",
"text",
";",
"}"
] | Parses a block scalar.
@param string $style The style indicator that was used to begin this block scalar (| or >)
@param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
@param int $indentation The indentation indicator that was used to begin this block scalar
@return string The text value | [
"Parses",
"a",
"block",
"scalar",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Parser.php#L781-L881 |
soberwp/models | dist/symfony/yaml/Parser.php | Parser.isNextLineUnIndentedCollection | private function isNextLineUnIndentedCollection()
{
$currentIndentation = $this->getCurrentLineIndentation();
$movements = 0;
do {
$EOF = !$this->moveToNextLine();
if (!$EOF) {
++$movements;
}
} while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
if ($EOF) {
return false;
}
$ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
for ($i = 0; $i < $movements; ++$i) {
$this->moveToPreviousLine();
}
return $ret;
} | php | private function isNextLineUnIndentedCollection()
{
$currentIndentation = $this->getCurrentLineIndentation();
$movements = 0;
do {
$EOF = !$this->moveToNextLine();
if (!$EOF) {
++$movements;
}
} while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
if ($EOF) {
return false;
}
$ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
for ($i = 0; $i < $movements; ++$i) {
$this->moveToPreviousLine();
}
return $ret;
} | [
"private",
"function",
"isNextLineUnIndentedCollection",
"(",
")",
"{",
"$",
"currentIndentation",
"=",
"$",
"this",
"->",
"getCurrentLineIndentation",
"(",
")",
";",
"$",
"movements",
"=",
"0",
";",
"do",
"{",
"$",
"EOF",
"=",
"!",
"$",
"this",
"->",
"moveToNextLine",
"(",
")",
";",
"if",
"(",
"!",
"$",
"EOF",
")",
"{",
"++",
"$",
"movements",
";",
"}",
"}",
"while",
"(",
"!",
"$",
"EOF",
"&&",
"(",
"$",
"this",
"->",
"isCurrentLineEmpty",
"(",
")",
"||",
"$",
"this",
"->",
"isCurrentLineComment",
"(",
")",
")",
")",
";",
"if",
"(",
"$",
"EOF",
")",
"{",
"return",
"false",
";",
"}",
"$",
"ret",
"=",
"$",
"this",
"->",
"getCurrentLineIndentation",
"(",
")",
"===",
"$",
"currentIndentation",
"&&",
"$",
"this",
"->",
"isStringUnIndentedCollectionItem",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"movements",
";",
"++",
"$",
"i",
")",
"{",
"$",
"this",
"->",
"moveToPreviousLine",
"(",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Returns true if the next line starts unindented collection.
@return bool Returns true if the next line starts unindented collection, false otherwise | [
"Returns",
"true",
"if",
"the",
"next",
"line",
"starts",
"unindented",
"collection",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Parser.php#L995-L1019 |
soberwp/models | dist/symfony/yaml/Parser.php | Parser.preg_match | public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0)
{
if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
switch (preg_last_error()) {
case PREG_INTERNAL_ERROR:
$error = 'Internal PCRE error.';
break;
case PREG_BACKTRACK_LIMIT_ERROR:
$error = 'pcre.backtrack_limit reached.';
break;
case PREG_RECURSION_LIMIT_ERROR:
$error = 'pcre.recursion_limit reached.';
break;
case PREG_BAD_UTF8_ERROR:
$error = 'Malformed UTF-8 data.';
break;
case PREG_BAD_UTF8_OFFSET_ERROR:
$error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
break;
default:
$error = 'Error.';
}
throw new ParseException($error);
}
return $ret;
} | php | public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0)
{
if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
switch (preg_last_error()) {
case PREG_INTERNAL_ERROR:
$error = 'Internal PCRE error.';
break;
case PREG_BACKTRACK_LIMIT_ERROR:
$error = 'pcre.backtrack_limit reached.';
break;
case PREG_RECURSION_LIMIT_ERROR:
$error = 'pcre.recursion_limit reached.';
break;
case PREG_BAD_UTF8_ERROR:
$error = 'Malformed UTF-8 data.';
break;
case PREG_BAD_UTF8_OFFSET_ERROR:
$error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
break;
default:
$error = 'Error.';
}
throw new ParseException($error);
}
return $ret;
} | [
"public",
"static",
"function",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"subject",
",",
"&",
"$",
"matches",
"=",
"null",
",",
"$",
"flags",
"=",
"0",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"ret",
"=",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"subject",
",",
"$",
"matches",
",",
"$",
"flags",
",",
"$",
"offset",
")",
")",
"{",
"switch",
"(",
"preg_last_error",
"(",
")",
")",
"{",
"case",
"PREG_INTERNAL_ERROR",
":",
"$",
"error",
"=",
"'Internal PCRE error.'",
";",
"break",
";",
"case",
"PREG_BACKTRACK_LIMIT_ERROR",
":",
"$",
"error",
"=",
"'pcre.backtrack_limit reached.'",
";",
"break",
";",
"case",
"PREG_RECURSION_LIMIT_ERROR",
":",
"$",
"error",
"=",
"'pcre.recursion_limit reached.'",
";",
"break",
";",
"case",
"PREG_BAD_UTF8_ERROR",
":",
"$",
"error",
"=",
"'Malformed UTF-8 data.'",
";",
"break",
";",
"case",
"PREG_BAD_UTF8_OFFSET_ERROR",
":",
"$",
"error",
"=",
"'Offset doesn\\'t correspond to the begin of a valid UTF-8 code point.'",
";",
"break",
";",
"default",
":",
"$",
"error",
"=",
"'Error.'",
";",
"}",
"throw",
"new",
"ParseException",
"(",
"$",
"error",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | A local wrapper for `preg_match` which will throw a ParseException if there
is an internal error in the PCRE engine.
This avoids us needing to check for "false" every time PCRE is used
in the YAML engine
@throws ParseException on a PCRE internal error
@see preg_last_error()
@internal | [
"A",
"local",
"wrapper",
"for",
"preg_match",
"which",
"will",
"throw",
"a",
"ParseException",
"if",
"there",
"is",
"an",
"internal",
"error",
"in",
"the",
"PCRE",
"engine",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Parser.php#L1044-L1071 |
soberwp/models | dist/hassankhan/config/src/FileParser/Php.php | Php.parse | public function parse($path)
{
// Require the file, if it throws an exception, rethrow it
try {
$temp = require $path;
} catch (Exception $exception) {
throw new ParseException(
array(
'message' => 'PHP file threw an exception',
'exception' => $exception,
)
);
}
// If we have a callable, run it and expect an array back
if (is_callable($temp)) {
$temp = call_user_func($temp);
}
// Check for array, if its anything else, throw an exception
if (!is_array($temp)) {
throw new UnsupportedFormatException('PHP file does not return an array');
}
return $temp;
} | php | public function parse($path)
{
// Require the file, if it throws an exception, rethrow it
try {
$temp = require $path;
} catch (Exception $exception) {
throw new ParseException(
array(
'message' => 'PHP file threw an exception',
'exception' => $exception,
)
);
}
// If we have a callable, run it and expect an array back
if (is_callable($temp)) {
$temp = call_user_func($temp);
}
// Check for array, if its anything else, throw an exception
if (!is_array($temp)) {
throw new UnsupportedFormatException('PHP file does not return an array');
}
return $temp;
} | [
"public",
"function",
"parse",
"(",
"$",
"path",
")",
"{",
"// Require the file, if it throws an exception, rethrow it",
"try",
"{",
"$",
"temp",
"=",
"require",
"$",
"path",
";",
"}",
"catch",
"(",
"Exception",
"$",
"exception",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"array",
"(",
"'message'",
"=>",
"'PHP file threw an exception'",
",",
"'exception'",
"=>",
"$",
"exception",
",",
")",
")",
";",
"}",
"// If we have a callable, run it and expect an array back",
"if",
"(",
"is_callable",
"(",
"$",
"temp",
")",
")",
"{",
"$",
"temp",
"=",
"call_user_func",
"(",
"$",
"temp",
")",
";",
"}",
"// Check for array, if its anything else, throw an exception",
"if",
"(",
"!",
"is_array",
"(",
"$",
"temp",
")",
")",
"{",
"throw",
"new",
"UnsupportedFormatException",
"(",
"'PHP file does not return an array'",
")",
";",
"}",
"return",
"$",
"temp",
";",
"}"
] | {@inheritDoc}
Loads a PHP file and gets its' contents as an array
@throws ParseException If the PHP file throws an exception
@throws UnsupportedFormatException If the PHP file does not return an array | [
"{",
"@inheritDoc",
"}",
"Loads",
"a",
"PHP",
"file",
"and",
"gets",
"its",
"contents",
"as",
"an",
"array"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/FileParser/Php.php#L27-L52 |
soberwp/models | src/Model.php | Model.setConfig | protected function setConfig()
{
if ($this->data['config']) {
$this->config = array_replace($this->config, $this->data['config']);
}
} | php | protected function setConfig()
{
if ($this->data['config']) {
$this->config = array_replace($this->config, $this->data['config']);
}
} | [
"protected",
"function",
"setConfig",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"data",
"[",
"'config'",
"]",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"array_replace",
"(",
"$",
"this",
"->",
"config",
",",
"$",
"this",
"->",
"data",
"[",
"'config'",
"]",
")",
";",
"}",
"}"
] | Set config
Merge and/or replace defaults with user config | [
"Set",
"config"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model.php#L57-L62 |
soberwp/models | src/Model.php | Model.setNameLabels | protected function setNameLabels()
{
$this->one = ($this->data['labels.has_one'] ? $this->data['labels.has_one'] : ucfirst($this->name));
$this->many = ($this->data['labels.has_many'] ? $this->data['labels.has_many'] : ucfirst($this->name . 's'));
$this->i18n = ($this->data['labels.text_domain'] ? $this->data['labels.text_domain'] : 'sober');
} | php | protected function setNameLabels()
{
$this->one = ($this->data['labels.has_one'] ? $this->data['labels.has_one'] : ucfirst($this->name));
$this->many = ($this->data['labels.has_many'] ? $this->data['labels.has_many'] : ucfirst($this->name . 's'));
$this->i18n = ($this->data['labels.text_domain'] ? $this->data['labels.text_domain'] : 'sober');
} | [
"protected",
"function",
"setNameLabels",
"(",
")",
"{",
"$",
"this",
"->",
"one",
"=",
"(",
"$",
"this",
"->",
"data",
"[",
"'labels.has_one'",
"]",
"?",
"$",
"this",
"->",
"data",
"[",
"'labels.has_one'",
"]",
":",
"ucfirst",
"(",
"$",
"this",
"->",
"name",
")",
")",
";",
"$",
"this",
"->",
"many",
"=",
"(",
"$",
"this",
"->",
"data",
"[",
"'labels.has_many'",
"]",
"?",
"$",
"this",
"->",
"data",
"[",
"'labels.has_many'",
"]",
":",
"ucfirst",
"(",
"$",
"this",
"->",
"name",
".",
"'s'",
")",
")",
";",
"$",
"this",
"->",
"i18n",
"=",
"(",
"$",
"this",
"->",
"data",
"[",
"'labels.text_domain'",
"]",
"?",
"$",
"this",
"->",
"data",
"[",
"'labels.text_domain'",
"]",
":",
"'sober'",
")",
";",
"}"
] | Set required labels
Based on name, or keys labels.has-one and labels.has-many | [
"Set",
"required",
"labels"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model.php#L69-L74 |
soberwp/models | src/Model.php | Model.setLabels | protected function setLabels()
{
if ($this->data['labels.overrides']) {
$this->labels = array_replace($this->labels, $this->data['labels.overrides']);
}
} | php | protected function setLabels()
{
if ($this->data['labels.overrides']) {
$this->labels = array_replace($this->labels, $this->data['labels.overrides']);
}
} | [
"protected",
"function",
"setLabels",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"data",
"[",
"'labels.overrides'",
"]",
")",
"{",
"$",
"this",
"->",
"labels",
"=",
"array_replace",
"(",
"$",
"this",
"->",
"labels",
",",
"$",
"this",
"->",
"data",
"[",
"'labels.overrides'",
"]",
")",
";",
"}",
"}"
] | Set label overrides
If key labels.overrides exists, add to or replace label defaults | [
"Set",
"label",
"overrides"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model.php#L81-L86 |
soberwp/models | src/Model/Taxonomy.php | Taxonomy.setDefaultConfig | protected function setDefaultConfig()
{
if ($this->data['config']) {
$this->config = $this->data['config'];
}
if (in_array($this->data['type'], ['cat', 'category'])) {
$this->config = ['hierarchical' => true];
}
if ($this->data['links']) {
$this->links = $this->data['links'];
}
return $this;
} | php | protected function setDefaultConfig()
{
if ($this->data['config']) {
$this->config = $this->data['config'];
}
if (in_array($this->data['type'], ['cat', 'category'])) {
$this->config = ['hierarchical' => true];
}
if ($this->data['links']) {
$this->links = $this->data['links'];
}
return $this;
} | [
"protected",
"function",
"setDefaultConfig",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"data",
"[",
"'config'",
"]",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"$",
"this",
"->",
"data",
"[",
"'config'",
"]",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"this",
"->",
"data",
"[",
"'type'",
"]",
",",
"[",
"'cat'",
",",
"'category'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"[",
"'hierarchical'",
"=>",
"true",
"]",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"data",
"[",
"'links'",
"]",
")",
"{",
"$",
"this",
"->",
"links",
"=",
"$",
"this",
"->",
"data",
"[",
"'links'",
"]",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Set config defaults
Make public and change menu position
@return $this | [
"Set",
"config",
"defaults"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model/Taxonomy.php#L31-L44 |
soberwp/models | src/Model/Taxonomy.php | Taxonomy.merge | protected function merge()
{
$this->args = [
'labels' => $this->labels
];
$this->args = array_merge($this->args, $this->config);
} | php | protected function merge()
{
$this->args = [
'labels' => $this->labels
];
$this->args = array_merge($this->args, $this->config);
} | [
"protected",
"function",
"merge",
"(",
")",
"{",
"$",
"this",
"->",
"args",
"=",
"[",
"'labels'",
"=>",
"$",
"this",
"->",
"labels",
"]",
";",
"$",
"this",
"->",
"args",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"args",
",",
"$",
"this",
"->",
"config",
")",
";",
"}"
] | Merge
Args to be passed to WP register_taxonomy()
@return $this | [
"Merge"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model/Taxonomy.php#L85-L91 |
soberwp/models | src/Model/Taxonomy.php | Taxonomy.register | protected function register()
{
if (function_exists('register_extended_taxonomy')) {
register_extended_taxonomy($this->name, $this->links, $this->args);
} else {
register_taxonomy($this->name, $this->links, $this->args);
}
} | php | protected function register()
{
if (function_exists('register_extended_taxonomy')) {
register_extended_taxonomy($this->name, $this->links, $this->args);
} else {
register_taxonomy($this->name, $this->links, $this->args);
}
} | [
"protected",
"function",
"register",
"(",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'register_extended_taxonomy'",
")",
")",
"{",
"register_extended_taxonomy",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"this",
"->",
"links",
",",
"$",
"this",
"->",
"args",
")",
";",
"}",
"else",
"{",
"register_taxonomy",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"this",
"->",
"links",
",",
"$",
"this",
"->",
"args",
")",
";",
"}",
"}"
] | Register Taxonomy
Uses extended-cpts if available.
@see https://github.com/johnbillion/extended-cpts
@return void | [
"Register",
"Taxonomy"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model/Taxonomy.php#L101-L108 |
soberwp/models | dist/symfony/yaml/Inline.php | Inline.parse | public static function parse($value, $flags = 0, $references = array())
{
if (\is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (\func_num_args() >= 3 && !\is_array($references)) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if ($references) {
$flags |= Yaml::PARSE_OBJECT;
}
if (\func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= Yaml::PARSE_OBJECT_FOR_MAP;
}
}
if (\func_num_args() >= 5) {
$references = func_get_arg(4);
} else {
$references = array();
}
}
self::initialize($flags);
$value = trim($value);
if ('' === $value) {
return '';
}
if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
}
$i = 0;
$tag = self::parseTag($value, $i, $flags);
switch ($value[$i]) {
case '[':
$result = self::parseSequence($value, $flags, $i, $references);
++$i;
break;
case '{':
$result = self::parseMapping($value, $flags, $i, $references);
++$i;
break;
default:
$result = self::parseScalar($value, $flags, null, $i, null === $tag, $references);
}
if (null !== $tag) {
return new TaggedValue($tag, $result);
}
// some comments are allowed at the end
if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
}
if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
return $result;
} | php | public static function parse($value, $flags = 0, $references = array())
{
if (\is_bool($flags)) {
@trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
if ($flags) {
$flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
} else {
$flags = 0;
}
}
if (\func_num_args() >= 3 && !\is_array($references)) {
@trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
if ($references) {
$flags |= Yaml::PARSE_OBJECT;
}
if (\func_num_args() >= 4) {
@trigger_error('Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
if (func_get_arg(3)) {
$flags |= Yaml::PARSE_OBJECT_FOR_MAP;
}
}
if (\func_num_args() >= 5) {
$references = func_get_arg(4);
} else {
$references = array();
}
}
self::initialize($flags);
$value = trim($value);
if ('' === $value) {
return '';
}
if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
}
$i = 0;
$tag = self::parseTag($value, $i, $flags);
switch ($value[$i]) {
case '[':
$result = self::parseSequence($value, $flags, $i, $references);
++$i;
break;
case '{':
$result = self::parseMapping($value, $flags, $i, $references);
++$i;
break;
default:
$result = self::parseScalar($value, $flags, null, $i, null === $tag, $references);
}
if (null !== $tag) {
return new TaggedValue($tag, $result);
}
// some comments are allowed at the end
if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
}
if (isset($mbEncoding)) {
mb_internal_encoding($mbEncoding);
}
return $result;
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"value",
",",
"$",
"flags",
"=",
"0",
",",
"$",
"references",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"\\",
"is_bool",
"(",
"$",
"flags",
")",
")",
"{",
"@",
"trigger_error",
"(",
"'Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"$",
"flags",
")",
"{",
"$",
"flags",
"=",
"Yaml",
"::",
"PARSE_EXCEPTION_ON_INVALID_TYPE",
";",
"}",
"else",
"{",
"$",
"flags",
"=",
"0",
";",
"}",
"}",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
">=",
"3",
"&&",
"!",
"\\",
"is_array",
"(",
"$",
"references",
")",
")",
"{",
"@",
"trigger_error",
"(",
"'Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"$",
"references",
")",
"{",
"$",
"flags",
"|=",
"Yaml",
"::",
"PARSE_OBJECT",
";",
"}",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
">=",
"4",
")",
"{",
"@",
"trigger_error",
"(",
"'Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"func_get_arg",
"(",
"3",
")",
")",
"{",
"$",
"flags",
"|=",
"Yaml",
"::",
"PARSE_OBJECT_FOR_MAP",
";",
"}",
"}",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
">=",
"5",
")",
"{",
"$",
"references",
"=",
"func_get_arg",
"(",
"4",
")",
";",
"}",
"else",
"{",
"$",
"references",
"=",
"array",
"(",
")",
";",
"}",
"}",
"self",
"::",
"initialize",
"(",
"$",
"flags",
")",
";",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"''",
"===",
"$",
"value",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"2",
"/* MB_OVERLOAD_STRING */",
"&",
"(",
"int",
")",
"ini_get",
"(",
"'mbstring.func_overload'",
")",
")",
"{",
"$",
"mbEncoding",
"=",
"mb_internal_encoding",
"(",
")",
";",
"mb_internal_encoding",
"(",
"'ASCII'",
")",
";",
"}",
"$",
"i",
"=",
"0",
";",
"$",
"tag",
"=",
"self",
"::",
"parseTag",
"(",
"$",
"value",
",",
"$",
"i",
",",
"$",
"flags",
")",
";",
"switch",
"(",
"$",
"value",
"[",
"$",
"i",
"]",
")",
"{",
"case",
"'['",
":",
"$",
"result",
"=",
"self",
"::",
"parseSequence",
"(",
"$",
"value",
",",
"$",
"flags",
",",
"$",
"i",
",",
"$",
"references",
")",
";",
"++",
"$",
"i",
";",
"break",
";",
"case",
"'{'",
":",
"$",
"result",
"=",
"self",
"::",
"parseMapping",
"(",
"$",
"value",
",",
"$",
"flags",
",",
"$",
"i",
",",
"$",
"references",
")",
";",
"++",
"$",
"i",
";",
"break",
";",
"default",
":",
"$",
"result",
"=",
"self",
"::",
"parseScalar",
"(",
"$",
"value",
",",
"$",
"flags",
",",
"null",
",",
"$",
"i",
",",
"null",
"===",
"$",
"tag",
",",
"$",
"references",
")",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"tag",
")",
"{",
"return",
"new",
"TaggedValue",
"(",
"$",
"tag",
",",
"$",
"result",
")",
";",
"}",
"// some comments are allowed at the end",
"if",
"(",
"preg_replace",
"(",
"'/\\s+#.*$/A'",
",",
"''",
",",
"substr",
"(",
"$",
"value",
",",
"$",
"i",
")",
")",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"sprintf",
"(",
"'Unexpected characters near \"%s\".'",
",",
"substr",
"(",
"$",
"value",
",",
"$",
"i",
")",
")",
",",
"self",
"::",
"$",
"parsedLineNumber",
"+",
"1",
",",
"$",
"value",
",",
"self",
"::",
"$",
"parsedFilename",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"mbEncoding",
")",
")",
"{",
"mb_internal_encoding",
"(",
"$",
"mbEncoding",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Converts a YAML string to a PHP value.
@param string $value A YAML string
@param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
@param array $references Mapping of variable names to values
@return mixed A PHP value
@throws ParseException | [
"Converts",
"a",
"YAML",
"string",
"to",
"a",
"PHP",
"value",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Inline.php#L66-L142 |
soberwp/models | dist/symfony/yaml/Inline.php | Inline.parseSequence | private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
{
$output = array();
$len = \strlen($sequence);
++$i;
// [foo, bar, ...]
while ($i < $len) {
if (']' === $sequence[$i]) {
return $output;
}
if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
++$i;
continue;
}
$tag = self::parseTag($sequence, $i, $flags);
switch ($sequence[$i]) {
case '[':
// nested sequence
$value = self::parseSequence($sequence, $flags, $i, $references);
break;
case '{':
// nested mapping
$value = self::parseMapping($sequence, $flags, $i, $references);
break;
default:
$isQuoted = \in_array($sequence[$i], array('"', "'"));
$value = self::parseScalar($sequence, $flags, array(',', ']'), $i, null === $tag, $references);
// the value can be an array if a reference has been resolved to an array var
if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
// embedded mapping?
try {
$pos = 0;
$value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
} catch (\InvalidArgumentException $e) {
// no, it's not
}
}
--$i;
}
if (null !== $tag) {
$value = new TaggedValue($tag, $value);
}
$output[] = $value;
++$i;
}
throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename);
} | php | private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
{
$output = array();
$len = \strlen($sequence);
++$i;
// [foo, bar, ...]
while ($i < $len) {
if (']' === $sequence[$i]) {
return $output;
}
if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
++$i;
continue;
}
$tag = self::parseTag($sequence, $i, $flags);
switch ($sequence[$i]) {
case '[':
// nested sequence
$value = self::parseSequence($sequence, $flags, $i, $references);
break;
case '{':
// nested mapping
$value = self::parseMapping($sequence, $flags, $i, $references);
break;
default:
$isQuoted = \in_array($sequence[$i], array('"', "'"));
$value = self::parseScalar($sequence, $flags, array(',', ']'), $i, null === $tag, $references);
// the value can be an array if a reference has been resolved to an array var
if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
// embedded mapping?
try {
$pos = 0;
$value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
} catch (\InvalidArgumentException $e) {
// no, it's not
}
}
--$i;
}
if (null !== $tag) {
$value = new TaggedValue($tag, $value);
}
$output[] = $value;
++$i;
}
throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename);
} | [
"private",
"static",
"function",
"parseSequence",
"(",
"$",
"sequence",
",",
"$",
"flags",
",",
"&",
"$",
"i",
"=",
"0",
",",
"$",
"references",
"=",
"array",
"(",
")",
")",
"{",
"$",
"output",
"=",
"array",
"(",
")",
";",
"$",
"len",
"=",
"\\",
"strlen",
"(",
"$",
"sequence",
")",
";",
"++",
"$",
"i",
";",
"// [foo, bar, ...]",
"while",
"(",
"$",
"i",
"<",
"$",
"len",
")",
"{",
"if",
"(",
"']'",
"===",
"$",
"sequence",
"[",
"$",
"i",
"]",
")",
"{",
"return",
"$",
"output",
";",
"}",
"if",
"(",
"','",
"===",
"$",
"sequence",
"[",
"$",
"i",
"]",
"||",
"' '",
"===",
"$",
"sequence",
"[",
"$",
"i",
"]",
")",
"{",
"++",
"$",
"i",
";",
"continue",
";",
"}",
"$",
"tag",
"=",
"self",
"::",
"parseTag",
"(",
"$",
"sequence",
",",
"$",
"i",
",",
"$",
"flags",
")",
";",
"switch",
"(",
"$",
"sequence",
"[",
"$",
"i",
"]",
")",
"{",
"case",
"'['",
":",
"// nested sequence",
"$",
"value",
"=",
"self",
"::",
"parseSequence",
"(",
"$",
"sequence",
",",
"$",
"flags",
",",
"$",
"i",
",",
"$",
"references",
")",
";",
"break",
";",
"case",
"'{'",
":",
"// nested mapping",
"$",
"value",
"=",
"self",
"::",
"parseMapping",
"(",
"$",
"sequence",
",",
"$",
"flags",
",",
"$",
"i",
",",
"$",
"references",
")",
";",
"break",
";",
"default",
":",
"$",
"isQuoted",
"=",
"\\",
"in_array",
"(",
"$",
"sequence",
"[",
"$",
"i",
"]",
",",
"array",
"(",
"'\"'",
",",
"\"'\"",
")",
")",
";",
"$",
"value",
"=",
"self",
"::",
"parseScalar",
"(",
"$",
"sequence",
",",
"$",
"flags",
",",
"array",
"(",
"','",
",",
"']'",
")",
",",
"$",
"i",
",",
"null",
"===",
"$",
"tag",
",",
"$",
"references",
")",
";",
"// the value can be an array if a reference has been resolved to an array var",
"if",
"(",
"\\",
"is_string",
"(",
"$",
"value",
")",
"&&",
"!",
"$",
"isQuoted",
"&&",
"false",
"!==",
"strpos",
"(",
"$",
"value",
",",
"': '",
")",
")",
"{",
"// embedded mapping?",
"try",
"{",
"$",
"pos",
"=",
"0",
";",
"$",
"value",
"=",
"self",
"::",
"parseMapping",
"(",
"'{'",
".",
"$",
"value",
".",
"'}'",
",",
"$",
"flags",
",",
"$",
"pos",
",",
"$",
"references",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"// no, it's not",
"}",
"}",
"--",
"$",
"i",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"tag",
")",
"{",
"$",
"value",
"=",
"new",
"TaggedValue",
"(",
"$",
"tag",
",",
"$",
"value",
")",
";",
"}",
"$",
"output",
"[",
"]",
"=",
"$",
"value",
";",
"++",
"$",
"i",
";",
"}",
"throw",
"new",
"ParseException",
"(",
"sprintf",
"(",
"'Malformed inline YAML string: %s.'",
",",
"$",
"sequence",
")",
",",
"self",
"::",
"$",
"parsedLineNumber",
"+",
"1",
",",
"null",
",",
"self",
"::",
"$",
"parsedFilename",
")",
";",
"}"
] | Parses a YAML sequence.
@param string $sequence
@param int $flags
@param int &$i
@param array $references
@return array
@throws ParseException When malformed inline YAML string is parsed | [
"Parses",
"a",
"YAML",
"sequence",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Inline.php#L410-L465 |
soberwp/models | dist/hassankhan/config/src/Config.php | Config.getParser | private function getParser($extension)
{
foreach ($this->supportedFileParsers as $fileParser) {
if (in_array($extension, $fileParser::getSupportedExtensions($extension))) {
return new $fileParser();
}
}
// If none exist, then throw an exception
throw new UnsupportedFormatException('Unsupported configuration format');
} | php | private function getParser($extension)
{
foreach ($this->supportedFileParsers as $fileParser) {
if (in_array($extension, $fileParser::getSupportedExtensions($extension))) {
return new $fileParser();
}
}
// If none exist, then throw an exception
throw new UnsupportedFormatException('Unsupported configuration format');
} | [
"private",
"function",
"getParser",
"(",
"$",
"extension",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"supportedFileParsers",
"as",
"$",
"fileParser",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"extension",
",",
"$",
"fileParser",
"::",
"getSupportedExtensions",
"(",
"$",
"extension",
")",
")",
")",
"{",
"return",
"new",
"$",
"fileParser",
"(",
")",
";",
"}",
"}",
"// If none exist, then throw an exception",
"throw",
"new",
"UnsupportedFormatException",
"(",
"'Unsupported configuration format'",
")",
";",
"}"
] | Gets a parser for a given file extension
@param string $extension
@return Noodlehaus\FileParser\FileParserInterface
@throws UnsupportedFormatException If `$path` is an unsupported file format | [
"Gets",
"a",
"parser",
"for",
"a",
"given",
"file",
"extension"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/Config.php#L84-L95 |
soberwp/models | dist/hassankhan/config/src/Config.php | Config.getPathFromArray | private function getPathFromArray($path)
{
$paths = array();
foreach ($path as $unverifiedPath) {
try {
// Check if `$unverifiedPath` is optional
// If it exists, then it's added to the list
// If it doesn't, it throws an exception which we catch
if ($unverifiedPath[0] !== '?') {
$paths = array_merge($paths, $this->getValidPath($unverifiedPath));
continue;
}
$optionalPath = ltrim($unverifiedPath, '?');
$paths = array_merge($paths, $this->getValidPath($optionalPath));
} catch (FileNotFoundException $e) {
// If `$unverifiedPath` is optional, then skip it
if ($unverifiedPath[0] === '?') {
continue;
}
// Otherwise rethrow the exception
throw $e;
}
}
return $paths;
} | php | private function getPathFromArray($path)
{
$paths = array();
foreach ($path as $unverifiedPath) {
try {
// Check if `$unverifiedPath` is optional
// If it exists, then it's added to the list
// If it doesn't, it throws an exception which we catch
if ($unverifiedPath[0] !== '?') {
$paths = array_merge($paths, $this->getValidPath($unverifiedPath));
continue;
}
$optionalPath = ltrim($unverifiedPath, '?');
$paths = array_merge($paths, $this->getValidPath($optionalPath));
} catch (FileNotFoundException $e) {
// If `$unverifiedPath` is optional, then skip it
if ($unverifiedPath[0] === '?') {
continue;
}
// Otherwise rethrow the exception
throw $e;
}
}
return $paths;
} | [
"private",
"function",
"getPathFromArray",
"(",
"$",
"path",
")",
"{",
"$",
"paths",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"path",
"as",
"$",
"unverifiedPath",
")",
"{",
"try",
"{",
"// Check if `$unverifiedPath` is optional",
"// If it exists, then it's added to the list",
"// If it doesn't, it throws an exception which we catch",
"if",
"(",
"$",
"unverifiedPath",
"[",
"0",
"]",
"!==",
"'?'",
")",
"{",
"$",
"paths",
"=",
"array_merge",
"(",
"$",
"paths",
",",
"$",
"this",
"->",
"getValidPath",
"(",
"$",
"unverifiedPath",
")",
")",
";",
"continue",
";",
"}",
"$",
"optionalPath",
"=",
"ltrim",
"(",
"$",
"unverifiedPath",
",",
"'?'",
")",
";",
"$",
"paths",
"=",
"array_merge",
"(",
"$",
"paths",
",",
"$",
"this",
"->",
"getValidPath",
"(",
"$",
"optionalPath",
")",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"$",
"e",
")",
"{",
"// If `$unverifiedPath` is optional, then skip it",
"if",
"(",
"$",
"unverifiedPath",
"[",
"0",
"]",
"===",
"'?'",
")",
"{",
"continue",
";",
"}",
"// Otherwise rethrow the exception",
"throw",
"$",
"e",
";",
"}",
"}",
"return",
"$",
"paths",
";",
"}"
] | Gets an array of paths
@param array $path
@return array
@throws FileNotFoundException If a file is not found at `$path` | [
"Gets",
"an",
"array",
"of",
"paths"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/Config.php#L106-L133 |
soberwp/models | dist/hassankhan/config/src/Config.php | Config.getValidPath | private function getValidPath($path)
{
// If `$path` is array
if (is_array($path)) {
return $this->getPathFromArray($path);
}
// If `$path` is a directory
if (is_dir($path)) {
$paths = glob($path . '/*.*');
if (empty($paths)) {
throw new EmptyDirectoryException("Configuration directory: [$path] is empty");
}
return $paths;
}
// If `$path` is not a file, throw an exception
if (!file_exists($path)) {
throw new FileNotFoundException("Configuration file: [$path] cannot be found");
}
return array($path);
} | php | private function getValidPath($path)
{
// If `$path` is array
if (is_array($path)) {
return $this->getPathFromArray($path);
}
// If `$path` is a directory
if (is_dir($path)) {
$paths = glob($path . '/*.*');
if (empty($paths)) {
throw new EmptyDirectoryException("Configuration directory: [$path] is empty");
}
return $paths;
}
// If `$path` is not a file, throw an exception
if (!file_exists($path)) {
throw new FileNotFoundException("Configuration file: [$path] cannot be found");
}
return array($path);
} | [
"private",
"function",
"getValidPath",
"(",
"$",
"path",
")",
"{",
"// If `$path` is array",
"if",
"(",
"is_array",
"(",
"$",
"path",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getPathFromArray",
"(",
"$",
"path",
")",
";",
"}",
"// If `$path` is a directory",
"if",
"(",
"is_dir",
"(",
"$",
"path",
")",
")",
"{",
"$",
"paths",
"=",
"glob",
"(",
"$",
"path",
".",
"'/*.*'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"paths",
")",
")",
"{",
"throw",
"new",
"EmptyDirectoryException",
"(",
"\"Configuration directory: [$path] is empty\"",
")",
";",
"}",
"return",
"$",
"paths",
";",
"}",
"// If `$path` is not a file, throw an exception",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"Configuration file: [$path] cannot be found\"",
")",
";",
"}",
"return",
"array",
"(",
"$",
"path",
")",
";",
"}"
] | Checks `$path` to see if it is either an array, a directory, or a file
@param string|array $path
@return array
@throws EmptyDirectoryException If `$path` is an empty directory
@throws FileNotFoundException If a file is not found at `$path` | [
"Checks",
"$path",
"to",
"see",
"if",
"it",
"is",
"either",
"an",
"array",
"a",
"directory",
"or",
"a",
"file"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/Config.php#L146-L167 |
soberwp/models | src/Loader.php | Loader.getPath | protected function getPath()
{
$default = (file_exists(dirname(get_template_directory()) . '/app') ?
dirname(get_template_directory()) . '/app/models' :
get_stylesheet_directory() . '/models');
$this->path = (has_filter('sober/models/path') ?
apply_filters('sober/models/path', rtrim($this->path)) :
$default);
} | php | protected function getPath()
{
$default = (file_exists(dirname(get_template_directory()) . '/app') ?
dirname(get_template_directory()) . '/app/models' :
get_stylesheet_directory() . '/models');
$this->path = (has_filter('sober/models/path') ?
apply_filters('sober/models/path', rtrim($this->path)) :
$default);
} | [
"protected",
"function",
"getPath",
"(",
")",
"{",
"$",
"default",
"=",
"(",
"file_exists",
"(",
"dirname",
"(",
"get_template_directory",
"(",
")",
")",
".",
"'/app'",
")",
"?",
"dirname",
"(",
"get_template_directory",
"(",
")",
")",
".",
"'/app/models'",
":",
"get_stylesheet_directory",
"(",
")",
".",
"'/models'",
")",
";",
"$",
"this",
"->",
"path",
"=",
"(",
"has_filter",
"(",
"'sober/models/path'",
")",
"?",
"apply_filters",
"(",
"'sober/models/path'",
",",
"rtrim",
"(",
"$",
"this",
"->",
"path",
")",
")",
":",
"$",
"default",
")",
";",
"}"
] | Get custom path | [
"Get",
"custom",
"path"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Loader.php#L25-L34 |
soberwp/models | src/Loader.php | Loader.load | protected function load()
{
if (file_exists($this->path)) {
$path = new \RecursiveDirectoryIterator($this->path);
foreach (new \RecursiveIteratorIterator($path) as $filename => $file) {
if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['json', 'php', 'yml', 'yaml'])) {
$this->config = new Config($file);
($this->isMultiple() ? $this->loadEach() : $this->route($this->config));
}
}
}
} | php | protected function load()
{
if (file_exists($this->path)) {
$path = new \RecursiveDirectoryIterator($this->path);
foreach (new \RecursiveIteratorIterator($path) as $filename => $file) {
if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['json', 'php', 'yml', 'yaml'])) {
$this->config = new Config($file);
($this->isMultiple() ? $this->loadEach() : $this->route($this->config));
}
}
}
} | [
"protected",
"function",
"load",
"(",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"path",
")",
")",
"{",
"$",
"path",
"=",
"new",
"\\",
"RecursiveDirectoryIterator",
"(",
"$",
"this",
"->",
"path",
")",
";",
"foreach",
"(",
"new",
"\\",
"RecursiveIteratorIterator",
"(",
"$",
"path",
")",
"as",
"$",
"filename",
"=>",
"$",
"file",
")",
"{",
"if",
"(",
"in_array",
"(",
"pathinfo",
"(",
"$",
"file",
",",
"PATHINFO_EXTENSION",
")",
",",
"[",
"'json'",
",",
"'php'",
",",
"'yml'",
",",
"'yaml'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"new",
"Config",
"(",
"$",
"file",
")",
";",
"(",
"$",
"this",
"->",
"isMultiple",
"(",
")",
"?",
"$",
"this",
"->",
"loadEach",
"(",
")",
":",
"$",
"this",
"->",
"route",
"(",
"$",
"this",
"->",
"config",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Load | [
"Load"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Loader.php#L39-L50 |
soberwp/models | src/Loader.php | Loader.route | protected function route($config)
{
if (in_array($config['type'], ['post-type', 'cpt', 'posttype', 'post_type'])) {
(new PostType($config))->run();
}
if (in_array($config['type'], ['taxonomy', 'tax', 'category', 'cat', 'tag'])) {
(new Taxonomy($config))->run();
}
} | php | protected function route($config)
{
if (in_array($config['type'], ['post-type', 'cpt', 'posttype', 'post_type'])) {
(new PostType($config))->run();
}
if (in_array($config['type'], ['taxonomy', 'tax', 'category', 'cat', 'tag'])) {
(new Taxonomy($config))->run();
}
} | [
"protected",
"function",
"route",
"(",
"$",
"config",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"config",
"[",
"'type'",
"]",
",",
"[",
"'post-type'",
",",
"'cpt'",
",",
"'posttype'",
",",
"'post_type'",
"]",
")",
")",
"{",
"(",
"new",
"PostType",
"(",
"$",
"config",
")",
")",
"->",
"run",
"(",
")",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"config",
"[",
"'type'",
"]",
",",
"[",
"'taxonomy'",
",",
"'tax'",
",",
"'category'",
",",
"'cat'",
",",
"'tag'",
"]",
")",
")",
"{",
"(",
"new",
"Taxonomy",
"(",
"$",
"config",
")",
")",
"->",
"run",
"(",
")",
";",
"}",
"}"
] | Route to class | [
"Route",
"to",
"class"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Loader.php#L73-L81 |
soberwp/models | dist/hassankhan/config/src/FileParser/Yaml.php | Yaml.parse | public function parse($path)
{
try {
$data = YamlParser::parse(file_get_contents($path), YamlParser::PARSE_CONSTANT);
} catch (Exception $exception) {
throw new ParseException(
array(
'message' => 'Error parsing YAML file',
'exception' => $exception,
)
);
}
return $data;
} | php | public function parse($path)
{
try {
$data = YamlParser::parse(file_get_contents($path), YamlParser::PARSE_CONSTANT);
} catch (Exception $exception) {
throw new ParseException(
array(
'message' => 'Error parsing YAML file',
'exception' => $exception,
)
);
}
return $data;
} | [
"public",
"function",
"parse",
"(",
"$",
"path",
")",
"{",
"try",
"{",
"$",
"data",
"=",
"YamlParser",
"::",
"parse",
"(",
"file_get_contents",
"(",
"$",
"path",
")",
",",
"YamlParser",
"::",
"PARSE_CONSTANT",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"exception",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"array",
"(",
"'message'",
"=>",
"'Error parsing YAML file'",
",",
"'exception'",
"=>",
"$",
"exception",
",",
")",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | {@inheritDoc}
Loads a YAML/YML file as an array
@throws ParseException If If there is an error parsing the YAML file | [
"{",
"@inheritDoc",
"}",
"Loads",
"a",
"YAML",
"/",
"YML",
"file",
"as",
"an",
"array"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/FileParser/Yaml.php#L26-L40 |
soberwp/models | dist/hassankhan/config/src/FileParser/Ini.php | Ini.parse | public function parse($path)
{
$data = @parse_ini_file($path, true);
if (!$data) {
$error = error_get_last();
// parse_ini_file() may return NULL but set no error if the file contains no parsable data
if (!is_array($error)) {
$error["message"] = "No parsable content in file.";
}
// if file contains no parsable data, no error is set, resulting in any previous error
// persisting in error_get_last(). in php 7 this can be addressed with error_clear_last()
if (function_exists("error_clear_last")) {
error_clear_last();
}
throw new ParseException($error);
}
return $this->expandDottedKey($data);
} | php | public function parse($path)
{
$data = @parse_ini_file($path, true);
if (!$data) {
$error = error_get_last();
// parse_ini_file() may return NULL but set no error if the file contains no parsable data
if (!is_array($error)) {
$error["message"] = "No parsable content in file.";
}
// if file contains no parsable data, no error is set, resulting in any previous error
// persisting in error_get_last(). in php 7 this can be addressed with error_clear_last()
if (function_exists("error_clear_last")) {
error_clear_last();
}
throw new ParseException($error);
}
return $this->expandDottedKey($data);
} | [
"public",
"function",
"parse",
"(",
"$",
"path",
")",
"{",
"$",
"data",
"=",
"@",
"parse_ini_file",
"(",
"$",
"path",
",",
"true",
")",
";",
"if",
"(",
"!",
"$",
"data",
")",
"{",
"$",
"error",
"=",
"error_get_last",
"(",
")",
";",
"// parse_ini_file() may return NULL but set no error if the file contains no parsable data",
"if",
"(",
"!",
"is_array",
"(",
"$",
"error",
")",
")",
"{",
"$",
"error",
"[",
"\"message\"",
"]",
"=",
"\"No parsable content in file.\"",
";",
"}",
"// if file contains no parsable data, no error is set, resulting in any previous error",
"// persisting in error_get_last(). in php 7 this can be addressed with error_clear_last()",
"if",
"(",
"function_exists",
"(",
"\"error_clear_last\"",
")",
")",
"{",
"error_clear_last",
"(",
")",
";",
"}",
"throw",
"new",
"ParseException",
"(",
"$",
"error",
")",
";",
"}",
"return",
"$",
"this",
"->",
"expandDottedKey",
"(",
"$",
"data",
")",
";",
"}"
] | {@inheritDoc}
Parses an INI file as an array
@throws ParseException If there is an error parsing the INI file | [
"{",
"@inheritDoc",
"}",
"Parses",
"an",
"INI",
"file",
"as",
"an",
"array"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/FileParser/Ini.php#L26-L48 |
soberwp/models | dist/hassankhan/config/src/FileParser/Ini.php | Ini.expandDottedKey | protected function expandDottedKey($data)
{
foreach ($data as $key => $value) {
if (($found = strpos($key, '.')) !== false) {
$newKey = substr($key, 0, $found);
$remainder = substr($key, $found + 1);
$expandedValue = $this->expandDottedKey(array($remainder => $value));
if (isset($data[$newKey])) {
$data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue);
} else {
$data[$newKey] = $expandedValue;
}
unset($data[$key]);
}
}
return $data;
} | php | protected function expandDottedKey($data)
{
foreach ($data as $key => $value) {
if (($found = strpos($key, '.')) !== false) {
$newKey = substr($key, 0, $found);
$remainder = substr($key, $found + 1);
$expandedValue = $this->expandDottedKey(array($remainder => $value));
if (isset($data[$newKey])) {
$data[$newKey] = array_merge_recursive($data[$newKey], $expandedValue);
} else {
$data[$newKey] = $expandedValue;
}
unset($data[$key]);
}
}
return $data;
} | [
"protected",
"function",
"expandDottedKey",
"(",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"(",
"$",
"found",
"=",
"strpos",
"(",
"$",
"key",
",",
"'.'",
")",
")",
"!==",
"false",
")",
"{",
"$",
"newKey",
"=",
"substr",
"(",
"$",
"key",
",",
"0",
",",
"$",
"found",
")",
";",
"$",
"remainder",
"=",
"substr",
"(",
"$",
"key",
",",
"$",
"found",
"+",
"1",
")",
";",
"$",
"expandedValue",
"=",
"$",
"this",
"->",
"expandDottedKey",
"(",
"array",
"(",
"$",
"remainder",
"=>",
"$",
"value",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"$",
"newKey",
"]",
")",
")",
"{",
"$",
"data",
"[",
"$",
"newKey",
"]",
"=",
"array_merge_recursive",
"(",
"$",
"data",
"[",
"$",
"newKey",
"]",
",",
"$",
"expandedValue",
")",
";",
"}",
"else",
"{",
"$",
"data",
"[",
"$",
"newKey",
"]",
"=",
"$",
"expandedValue",
";",
"}",
"unset",
"(",
"$",
"data",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"return",
"$",
"data",
";",
"}"
] | Expand array with dotted keys to multidimensional array
@param array $data
@return array | [
"Expand",
"array",
"with",
"dotted",
"keys",
"to",
"multidimensional",
"array"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/FileParser/Ini.php#L57-L74 |
soberwp/models | dist/hassankhan/config/src/FileParser/Xml.php | Xml.parse | public function parse($path)
{
libxml_use_internal_errors(true);
$data = simplexml_load_file($path, null, LIBXML_NOERROR);
if ($data === false) {
$errors = libxml_get_errors();
$latestError = array_pop($errors);
$error = array(
'message' => $latestError->message,
'type' => $latestError->level,
'code' => $latestError->code,
'file' => $latestError->file,
'line' => $latestError->line,
);
throw new ParseException($error);
}
$data = json_decode(json_encode($data), true);
return $data;
} | php | public function parse($path)
{
libxml_use_internal_errors(true);
$data = simplexml_load_file($path, null, LIBXML_NOERROR);
if ($data === false) {
$errors = libxml_get_errors();
$latestError = array_pop($errors);
$error = array(
'message' => $latestError->message,
'type' => $latestError->level,
'code' => $latestError->code,
'file' => $latestError->file,
'line' => $latestError->line,
);
throw new ParseException($error);
}
$data = json_decode(json_encode($data), true);
return $data;
} | [
"public",
"function",
"parse",
"(",
"$",
"path",
")",
"{",
"libxml_use_internal_errors",
"(",
"true",
")",
";",
"$",
"data",
"=",
"simplexml_load_file",
"(",
"$",
"path",
",",
"null",
",",
"LIBXML_NOERROR",
")",
";",
"if",
"(",
"$",
"data",
"===",
"false",
")",
"{",
"$",
"errors",
"=",
"libxml_get_errors",
"(",
")",
";",
"$",
"latestError",
"=",
"array_pop",
"(",
"$",
"errors",
")",
";",
"$",
"error",
"=",
"array",
"(",
"'message'",
"=>",
"$",
"latestError",
"->",
"message",
",",
"'type'",
"=>",
"$",
"latestError",
"->",
"level",
",",
"'code'",
"=>",
"$",
"latestError",
"->",
"code",
",",
"'file'",
"=>",
"$",
"latestError",
"->",
"file",
",",
"'line'",
"=>",
"$",
"latestError",
"->",
"line",
",",
")",
";",
"throw",
"new",
"ParseException",
"(",
"$",
"error",
")",
";",
"}",
"$",
"data",
"=",
"json_decode",
"(",
"json_encode",
"(",
"$",
"data",
")",
",",
"true",
")",
";",
"return",
"$",
"data",
";",
"}"
] | {@inheritDoc}
Parses an XML file as an array
@throws ParseException If there is an error parsing the XML file | [
"{",
"@inheritDoc",
"}",
"Parses",
"an",
"XML",
"file",
"as",
"an",
"array"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/hassankhan/config/src/FileParser/Xml.php#L24-L46 |
soberwp/models | dist/symfony/yaml/Unescaper.php | Unescaper.unescapeDoubleQuotedString | public function unescapeDoubleQuotedString($value)
{
$callback = function ($match) {
return $this->unescapeCharacter($match[0]);
};
// evaluate the string
return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value);
} | php | public function unescapeDoubleQuotedString($value)
{
$callback = function ($match) {
return $this->unescapeCharacter($match[0]);
};
// evaluate the string
return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value);
} | [
"public",
"function",
"unescapeDoubleQuotedString",
"(",
"$",
"value",
")",
"{",
"$",
"callback",
"=",
"function",
"(",
"$",
"match",
")",
"{",
"return",
"$",
"this",
"->",
"unescapeCharacter",
"(",
"$",
"match",
"[",
"0",
"]",
")",
";",
"}",
";",
"// evaluate the string",
"return",
"preg_replace_callback",
"(",
"'/'",
".",
"self",
"::",
"REGEX_ESCAPED_CHARACTER",
".",
"'/u'",
",",
"$",
"callback",
",",
"$",
"value",
")",
";",
"}"
] | Unescapes a double quoted string.
@param string $value A double quoted string
@return string The unescaped string | [
"Unescapes",
"a",
"double",
"quoted",
"string",
"."
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/dist/symfony/yaml/Unescaper.php#L50-L58 |
soberwp/models | src/Model/PostType.php | PostType.setDefaultLabels | protected function setDefaultLabels()
{
$this->labels = [
'name' => _x($this->many, 'Post type general name', $this->i18n),
'singular_name' => _x($this->one, 'Post type singular name', $this->i18n),
'menu_name' => _x($this->many, 'Admin Menu text', $this->i18n),
'name_admin_bar' => _x($this->one, 'Add New on Toolbar', $this->i18n),
'add_new_item' => __('Add New ' . $this->one, $this->i18n),
'edit_item' => __('Edit ' . $this->one, $this->i18n),
'new_item' => __('New ' . $this->one, $this->i18n),
'view_item' => __('View ' . $this->one, $this->i18n),
'view_items' => __('View ' . $this->many, $this->i18n),
'search_items' => __('Search ' . $this->many, $this->i18n),
'not_found' => __('No ' . strtolower($this->many) . ' found.', $this->i18n),
'not_found_in_trash' => __('No ' . strtolower($this->many) . ' found in Trash.', $this->i18n),
'parent_item_colon' => __('Parent ' . $this->many . ':', $this->i18n),
'all_items' => __('All ' . $this->many, $this->i18n),
'archives' => __($this->one . ' Archives', $this->i18n),
'attributes' => __($this->one . ' Attributes', $this->i18n),
'insert_into_item' => __('Insert into ' . strtolower($this->one), $this->i18n),
'uploaded_to_this_item' => __('Uploaded to this ' . strtolower($this->one), $this->i18n),
'filter_items_list' => __('Filter ' . strtolower($this->many) . ' list', $this->i18n),
'items_list_navigation' => __($this->many . ' list navigation', $this->i18n),
'items_list' => __($this->many . ' list', $this->i18n)
];
return $this;
} | php | protected function setDefaultLabels()
{
$this->labels = [
'name' => _x($this->many, 'Post type general name', $this->i18n),
'singular_name' => _x($this->one, 'Post type singular name', $this->i18n),
'menu_name' => _x($this->many, 'Admin Menu text', $this->i18n),
'name_admin_bar' => _x($this->one, 'Add New on Toolbar', $this->i18n),
'add_new_item' => __('Add New ' . $this->one, $this->i18n),
'edit_item' => __('Edit ' . $this->one, $this->i18n),
'new_item' => __('New ' . $this->one, $this->i18n),
'view_item' => __('View ' . $this->one, $this->i18n),
'view_items' => __('View ' . $this->many, $this->i18n),
'search_items' => __('Search ' . $this->many, $this->i18n),
'not_found' => __('No ' . strtolower($this->many) . ' found.', $this->i18n),
'not_found_in_trash' => __('No ' . strtolower($this->many) . ' found in Trash.', $this->i18n),
'parent_item_colon' => __('Parent ' . $this->many . ':', $this->i18n),
'all_items' => __('All ' . $this->many, $this->i18n),
'archives' => __($this->one . ' Archives', $this->i18n),
'attributes' => __($this->one . ' Attributes', $this->i18n),
'insert_into_item' => __('Insert into ' . strtolower($this->one), $this->i18n),
'uploaded_to_this_item' => __('Uploaded to this ' . strtolower($this->one), $this->i18n),
'filter_items_list' => __('Filter ' . strtolower($this->many) . ' list', $this->i18n),
'items_list_navigation' => __($this->many . ' list navigation', $this->i18n),
'items_list' => __($this->many . ' list', $this->i18n)
];
return $this;
} | [
"protected",
"function",
"setDefaultLabels",
"(",
")",
"{",
"$",
"this",
"->",
"labels",
"=",
"[",
"'name'",
"=>",
"_x",
"(",
"$",
"this",
"->",
"many",
",",
"'Post type general name'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'singular_name'",
"=>",
"_x",
"(",
"$",
"this",
"->",
"one",
",",
"'Post type singular name'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'menu_name'",
"=>",
"_x",
"(",
"$",
"this",
"->",
"many",
",",
"'Admin Menu text'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'name_admin_bar'",
"=>",
"_x",
"(",
"$",
"this",
"->",
"one",
",",
"'Add New on Toolbar'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'add_new_item'",
"=>",
"__",
"(",
"'Add New '",
".",
"$",
"this",
"->",
"one",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'edit_item'",
"=>",
"__",
"(",
"'Edit '",
".",
"$",
"this",
"->",
"one",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'new_item'",
"=>",
"__",
"(",
"'New '",
".",
"$",
"this",
"->",
"one",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'view_item'",
"=>",
"__",
"(",
"'View '",
".",
"$",
"this",
"->",
"one",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'view_items'",
"=>",
"__",
"(",
"'View '",
".",
"$",
"this",
"->",
"many",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'search_items'",
"=>",
"__",
"(",
"'Search '",
".",
"$",
"this",
"->",
"many",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'not_found'",
"=>",
"__",
"(",
"'No '",
".",
"strtolower",
"(",
"$",
"this",
"->",
"many",
")",
".",
"' found.'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'not_found_in_trash'",
"=>",
"__",
"(",
"'No '",
".",
"strtolower",
"(",
"$",
"this",
"->",
"many",
")",
".",
"' found in Trash.'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'parent_item_colon'",
"=>",
"__",
"(",
"'Parent '",
".",
"$",
"this",
"->",
"many",
".",
"':'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'all_items'",
"=>",
"__",
"(",
"'All '",
".",
"$",
"this",
"->",
"many",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'archives'",
"=>",
"__",
"(",
"$",
"this",
"->",
"one",
".",
"' Archives'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'attributes'",
"=>",
"__",
"(",
"$",
"this",
"->",
"one",
".",
"' Attributes'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'insert_into_item'",
"=>",
"__",
"(",
"'Insert into '",
".",
"strtolower",
"(",
"$",
"this",
"->",
"one",
")",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'uploaded_to_this_item'",
"=>",
"__",
"(",
"'Uploaded to this '",
".",
"strtolower",
"(",
"$",
"this",
"->",
"one",
")",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'filter_items_list'",
"=>",
"__",
"(",
"'Filter '",
".",
"strtolower",
"(",
"$",
"this",
"->",
"many",
")",
".",
"' list'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'items_list_navigation'",
"=>",
"__",
"(",
"$",
"this",
"->",
"many",
".",
"' list navigation'",
",",
"$",
"this",
"->",
"i18n",
")",
",",
"'items_list'",
"=>",
"__",
"(",
"$",
"this",
"->",
"many",
".",
"' list'",
",",
"$",
"this",
"->",
"i18n",
")",
"]",
";",
"return",
"$",
"this",
";",
"}"
] | Set default labels
Create an labels array and implement default singular and plural labels
@return $this | [
"Set",
"default",
"labels"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model/PostType.php#L48-L75 |
soberwp/models | src/Model/PostType.php | PostType.register | protected function register()
{
if (function_exists('register_extended_post_type')) {
register_extended_post_type($this->name, $this->args);
} else {
register_post_type($this->name, $this->args);
}
} | php | protected function register()
{
if (function_exists('register_extended_post_type')) {
register_extended_post_type($this->name, $this->args);
} else {
register_post_type($this->name, $this->args);
}
} | [
"protected",
"function",
"register",
"(",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'register_extended_post_type'",
")",
")",
"{",
"register_extended_post_type",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"this",
"->",
"args",
")",
";",
"}",
"else",
"{",
"register_post_type",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"this",
"->",
"args",
")",
";",
"}",
"}"
] | Register Post Type
Uses extended-cpts if available.
@see https://github.com/johnbillion/extended-cpts
@return void | [
"Register",
"Post",
"Type"
] | train | https://github.com/soberwp/models/blob/d0e052c8281910f6081596b33789fc31a9ed1e68/src/Model/PostType.php#L100-L107 |
browscap/browscap-php | src/Parser/Helper/GetData.php | GetData.getSettings | public function getSettings(string $pattern, array $settings = []) : array
{
// The pattern has been pre-quoted on generation to speed up the pattern search,
// but for this check we need the unquoted version
$unquotedPattern = $this->quoter->pregUnQuote($pattern);
// Try to get settings for the pattern
$addedSettings = $this->getIniPart($unquotedPattern);
// set some additional data
if (0 === count($settings)) {
// The optimization with replaced digits get can now result in setting searches, for which we
// won't find a result - so only add the pattern information, is settings have been found.
//
// If not an empty array will be returned and the calling function can easily check if a pattern
// has been found.
if (0 < count($addedSettings)) {
$settings['browser_name_regex'] = '/^' . $pattern . '$/';
$settings['browser_name_pattern'] = $unquotedPattern;
}
}
// check if parent pattern set, only keep the first one
$parentPattern = null;
if (isset($addedSettings['Parent'])) {
$parentPattern = $addedSettings['Parent'];
if (isset($settings['Parent'])) {
unset($addedSettings['Parent']);
}
}
// merge settings
$settings += $addedSettings;
if (is_string($parentPattern)) {
return $this->getSettings($this->quoter->pregQuote($parentPattern), $settings);
}
return $settings;
} | php | public function getSettings(string $pattern, array $settings = []) : array
{
// The pattern has been pre-quoted on generation to speed up the pattern search,
// but for this check we need the unquoted version
$unquotedPattern = $this->quoter->pregUnQuote($pattern);
// Try to get settings for the pattern
$addedSettings = $this->getIniPart($unquotedPattern);
// set some additional data
if (0 === count($settings)) {
// The optimization with replaced digits get can now result in setting searches, for which we
// won't find a result - so only add the pattern information, is settings have been found.
//
// If not an empty array will be returned and the calling function can easily check if a pattern
// has been found.
if (0 < count($addedSettings)) {
$settings['browser_name_regex'] = '/^' . $pattern . '$/';
$settings['browser_name_pattern'] = $unquotedPattern;
}
}
// check if parent pattern set, only keep the first one
$parentPattern = null;
if (isset($addedSettings['Parent'])) {
$parentPattern = $addedSettings['Parent'];
if (isset($settings['Parent'])) {
unset($addedSettings['Parent']);
}
}
// merge settings
$settings += $addedSettings;
if (is_string($parentPattern)) {
return $this->getSettings($this->quoter->pregQuote($parentPattern), $settings);
}
return $settings;
} | [
"public",
"function",
"getSettings",
"(",
"string",
"$",
"pattern",
",",
"array",
"$",
"settings",
"=",
"[",
"]",
")",
":",
"array",
"{",
"// The pattern has been pre-quoted on generation to speed up the pattern search,",
"// but for this check we need the unquoted version",
"$",
"unquotedPattern",
"=",
"$",
"this",
"->",
"quoter",
"->",
"pregUnQuote",
"(",
"$",
"pattern",
")",
";",
"// Try to get settings for the pattern",
"$",
"addedSettings",
"=",
"$",
"this",
"->",
"getIniPart",
"(",
"$",
"unquotedPattern",
")",
";",
"// set some additional data",
"if",
"(",
"0",
"===",
"count",
"(",
"$",
"settings",
")",
")",
"{",
"// The optimization with replaced digits get can now result in setting searches, for which we",
"// won't find a result - so only add the pattern information, is settings have been found.",
"//",
"// If not an empty array will be returned and the calling function can easily check if a pattern",
"// has been found.",
"if",
"(",
"0",
"<",
"count",
"(",
"$",
"addedSettings",
")",
")",
"{",
"$",
"settings",
"[",
"'browser_name_regex'",
"]",
"=",
"'/^'",
".",
"$",
"pattern",
".",
"'$/'",
";",
"$",
"settings",
"[",
"'browser_name_pattern'",
"]",
"=",
"$",
"unquotedPattern",
";",
"}",
"}",
"// check if parent pattern set, only keep the first one",
"$",
"parentPattern",
"=",
"null",
";",
"if",
"(",
"isset",
"(",
"$",
"addedSettings",
"[",
"'Parent'",
"]",
")",
")",
"{",
"$",
"parentPattern",
"=",
"$",
"addedSettings",
"[",
"'Parent'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"settings",
"[",
"'Parent'",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"addedSettings",
"[",
"'Parent'",
"]",
")",
";",
"}",
"}",
"// merge settings",
"$",
"settings",
"+=",
"$",
"addedSettings",
";",
"if",
"(",
"is_string",
"(",
"$",
"parentPattern",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getSettings",
"(",
"$",
"this",
"->",
"quoter",
"->",
"pregQuote",
"(",
"$",
"parentPattern",
")",
",",
"$",
"settings",
")",
";",
"}",
"return",
"$",
"settings",
";",
"}"
] | Gets the settings for a given pattern (method calls itself to
get the data from the parent patterns)
@param string $pattern
@param array $settings
@throws \UnexpectedValueException
@return array | [
"Gets",
"the",
"settings",
"for",
"a",
"given",
"pattern",
"(",
"method",
"calls",
"itself",
"to",
"get",
"the",
"data",
"from",
"the",
"parent",
"patterns",
")"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Helper/GetData.php#L63-L104 |
browscap/browscap-php | src/Parser/Helper/GetData.php | GetData.getIniPart | private function getIniPart(string $pattern) : array
{
$pattern = strtolower($pattern);
$patternhash = Pattern::getHashForParts($pattern);
$subkey = SubKey::getIniPartCacheSubKey($patternhash);
try {
if (! $this->cache->hasItem('browscap.iniparts.' . $subkey, true)) {
$this->logger->debug('cache key "browscap.iniparts.' . $subkey . '" not found');
return [];
}
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while checking a inipart in the cache', 0, $e));
return [];
}
$success = null;
try {
$file = $this->cache->getItem('browscap.iniparts.' . $subkey, true, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading a inipart from the cache', 0, $e));
return [];
}
if (! $success) {
$this->logger->debug('cache key "browscap.iniparts.' . $subkey . '" not found');
return [];
}
if (! is_array($file) || ! count($file)) {
$this->logger->debug('cache key "browscap.iniparts.' . $subkey . '" was empty');
return [];
}
$propertyFormatter = new PropertyFormatter(new PropertyHolder());
$return = [];
foreach ($file as $buffer) {
[$tmpBuffer, $patterns] = explode("\t", $buffer, 2);
if ($tmpBuffer === $patternhash) {
try {
$return = \ExceptionalJSON\decode($patterns, true);
} catch (DecodeErrorException $e) {
$this->logger->error('data for cache key "browscap.iniparts.' . $subkey . '" are not valid json');
return [];
}
foreach (array_keys($return) as $property) {
$return[$property] = $propertyFormatter->formatPropertyValue(
$return[$property],
(string) $property
);
}
break;
}
}
return $return;
} | php | private function getIniPart(string $pattern) : array
{
$pattern = strtolower($pattern);
$patternhash = Pattern::getHashForParts($pattern);
$subkey = SubKey::getIniPartCacheSubKey($patternhash);
try {
if (! $this->cache->hasItem('browscap.iniparts.' . $subkey, true)) {
$this->logger->debug('cache key "browscap.iniparts.' . $subkey . '" not found');
return [];
}
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while checking a inipart in the cache', 0, $e));
return [];
}
$success = null;
try {
$file = $this->cache->getItem('browscap.iniparts.' . $subkey, true, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading a inipart from the cache', 0, $e));
return [];
}
if (! $success) {
$this->logger->debug('cache key "browscap.iniparts.' . $subkey . '" not found');
return [];
}
if (! is_array($file) || ! count($file)) {
$this->logger->debug('cache key "browscap.iniparts.' . $subkey . '" was empty');
return [];
}
$propertyFormatter = new PropertyFormatter(new PropertyHolder());
$return = [];
foreach ($file as $buffer) {
[$tmpBuffer, $patterns] = explode("\t", $buffer, 2);
if ($tmpBuffer === $patternhash) {
try {
$return = \ExceptionalJSON\decode($patterns, true);
} catch (DecodeErrorException $e) {
$this->logger->error('data for cache key "browscap.iniparts.' . $subkey . '" are not valid json');
return [];
}
foreach (array_keys($return) as $property) {
$return[$property] = $propertyFormatter->formatPropertyValue(
$return[$property],
(string) $property
);
}
break;
}
}
return $return;
} | [
"private",
"function",
"getIniPart",
"(",
"string",
"$",
"pattern",
")",
":",
"array",
"{",
"$",
"pattern",
"=",
"strtolower",
"(",
"$",
"pattern",
")",
";",
"$",
"patternhash",
"=",
"Pattern",
"::",
"getHashForParts",
"(",
"$",
"pattern",
")",
";",
"$",
"subkey",
"=",
"SubKey",
"::",
"getIniPartCacheSubKey",
"(",
"$",
"patternhash",
")",
";",
"try",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
"->",
"hasItem",
"(",
"'browscap.iniparts.'",
".",
"$",
"subkey",
",",
"true",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'cache key \"browscap.iniparts.'",
".",
"$",
"subkey",
".",
"'\" not found'",
")",
";",
"return",
"[",
"]",
";",
"}",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while checking a inipart in the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"return",
"[",
"]",
";",
"}",
"$",
"success",
"=",
"null",
";",
"try",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"cache",
"->",
"getItem",
"(",
"'browscap.iniparts.'",
".",
"$",
"subkey",
",",
"true",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while reading a inipart from the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"$",
"success",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'cache key \"browscap.iniparts.'",
".",
"$",
"subkey",
".",
"'\" not found'",
")",
";",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"file",
")",
"||",
"!",
"count",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'cache key \"browscap.iniparts.'",
".",
"$",
"subkey",
".",
"'\" was empty'",
")",
";",
"return",
"[",
"]",
";",
"}",
"$",
"propertyFormatter",
"=",
"new",
"PropertyFormatter",
"(",
"new",
"PropertyHolder",
"(",
")",
")",
";",
"$",
"return",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"file",
"as",
"$",
"buffer",
")",
"{",
"[",
"$",
"tmpBuffer",
",",
"$",
"patterns",
"]",
"=",
"explode",
"(",
"\"\\t\"",
",",
"$",
"buffer",
",",
"2",
")",
";",
"if",
"(",
"$",
"tmpBuffer",
"===",
"$",
"patternhash",
")",
"{",
"try",
"{",
"$",
"return",
"=",
"\\",
"ExceptionalJSON",
"\\",
"decode",
"(",
"$",
"patterns",
",",
"true",
")",
";",
"}",
"catch",
"(",
"DecodeErrorException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'data for cache key \"browscap.iniparts.'",
".",
"$",
"subkey",
".",
"'\" are not valid json'",
")",
";",
"return",
"[",
"]",
";",
"}",
"foreach",
"(",
"array_keys",
"(",
"$",
"return",
")",
"as",
"$",
"property",
")",
"{",
"$",
"return",
"[",
"$",
"property",
"]",
"=",
"$",
"propertyFormatter",
"->",
"formatPropertyValue",
"(",
"$",
"return",
"[",
"$",
"property",
"]",
",",
"(",
"string",
")",
"$",
"property",
")",
";",
"}",
"break",
";",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] | Gets the relevant part (array of settings) of the ini file for a given pattern.
@param string $pattern
@return array | [
"Gets",
"the",
"relevant",
"part",
"(",
"array",
"of",
"settings",
")",
"of",
"the",
"ini",
"file",
"for",
"a",
"given",
"pattern",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Helper/GetData.php#L113-L180 |
browscap/browscap-php | src/Formatter/PhpGetBrowser.php | PhpGetBrowser.setData | public function setData(array $settings) : void
{
foreach ($settings as $key => $value) {
$this->data[strtolower($key)] = $value;
}
} | php | public function setData(array $settings) : void
{
foreach ($settings as $key => $value) {
$this->data[strtolower($key)] = $value;
}
} | [
"public",
"function",
"setData",
"(",
"array",
"$",
"settings",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"settings",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"data",
"[",
"strtolower",
"(",
"$",
"key",
")",
"]",
"=",
"$",
"value",
";",
"}",
"}"
] | Sets the data (done by the parser)
@param array $settings | [
"Sets",
"the",
"data",
"(",
"done",
"by",
"the",
"parser",
")"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Formatter/PhpGetBrowser.php#L81-L86 |
browscap/browscap-php | src/Formatter/PhpGetBrowser.php | PhpGetBrowser.getData | public function getData() : \stdClass
{
$output = new \stdClass();
$propertyNames = array_keys($this->defaultProperties);
foreach ($propertyNames as $property) {
$key = strtolower($property);
if (array_key_exists($key, $this->data)) {
$output->{$key} = $this->data[$key];
} elseif ('parent' !== $key) {
$output->{$key} = $this->defaultProperties[$property];
}
}
// Don't want to normally do this, just if it exists in the data file
// for our test runs
if (array_key_exists('patternid', $this->data)) {
$output->patternid = $this->data['patternid'];
}
return $output;
} | php | public function getData() : \stdClass
{
$output = new \stdClass();
$propertyNames = array_keys($this->defaultProperties);
foreach ($propertyNames as $property) {
$key = strtolower($property);
if (array_key_exists($key, $this->data)) {
$output->{$key} = $this->data[$key];
} elseif ('parent' !== $key) {
$output->{$key} = $this->defaultProperties[$property];
}
}
// Don't want to normally do this, just if it exists in the data file
// for our test runs
if (array_key_exists('patternid', $this->data)) {
$output->patternid = $this->data['patternid'];
}
return $output;
} | [
"public",
"function",
"getData",
"(",
")",
":",
"\\",
"stdClass",
"{",
"$",
"output",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"$",
"propertyNames",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"defaultProperties",
")",
";",
"foreach",
"(",
"$",
"propertyNames",
"as",
"$",
"property",
")",
"{",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"property",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"data",
")",
")",
"{",
"$",
"output",
"->",
"{",
"$",
"key",
"}",
"=",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
";",
"}",
"elseif",
"(",
"'parent'",
"!==",
"$",
"key",
")",
"{",
"$",
"output",
"->",
"{",
"$",
"key",
"}",
"=",
"$",
"this",
"->",
"defaultProperties",
"[",
"$",
"property",
"]",
";",
"}",
"}",
"// Don't want to normally do this, just if it exists in the data file",
"// for our test runs",
"if",
"(",
"array_key_exists",
"(",
"'patternid'",
",",
"$",
"this",
"->",
"data",
")",
")",
"{",
"$",
"output",
"->",
"patternid",
"=",
"$",
"this",
"->",
"data",
"[",
"'patternid'",
"]",
";",
"}",
"return",
"$",
"output",
";",
"}"
] | Gets the data (in the preferred format)
@return \stdClass | [
"Gets",
"the",
"data",
"(",
"in",
"the",
"preferred",
"format",
")"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Formatter/PhpGetBrowser.php#L93-L115 |
browscap/browscap-php | src/Helper/Support.php | Support.getUserAgent | public function getUserAgent() : string
{
$userAgent = '';
foreach ($this->userAgentHeaders as $header) {
if (array_key_exists($header, $this->source)
&& $this->source[$header]
) {
$userAgent = $this->cleanParam($this->source[$header]);
break;
}
}
return $userAgent;
} | php | public function getUserAgent() : string
{
$userAgent = '';
foreach ($this->userAgentHeaders as $header) {
if (array_key_exists($header, $this->source)
&& $this->source[$header]
) {
$userAgent = $this->cleanParam($this->source[$header]);
break;
}
}
return $userAgent;
} | [
"public",
"function",
"getUserAgent",
"(",
")",
":",
"string",
"{",
"$",
"userAgent",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"userAgentHeaders",
"as",
"$",
"header",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"header",
",",
"$",
"this",
"->",
"source",
")",
"&&",
"$",
"this",
"->",
"source",
"[",
"$",
"header",
"]",
")",
"{",
"$",
"userAgent",
"=",
"$",
"this",
"->",
"cleanParam",
"(",
"$",
"this",
"->",
"source",
"[",
"$",
"header",
"]",
")",
";",
"break",
";",
"}",
"}",
"return",
"$",
"userAgent",
";",
"}"
] | detect the useragent
@return string | [
"detect",
"the",
"useragent"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Helper/Support.php#L48-L63 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.getVersion | public function getVersion() : ?int
{
if (null === $this->version) {
$success = null;
try {
$version = $this->getItem('browscap.version', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data version from the cache', 0, $e));
$version = null;
}
if (null !== $version && $success) {
$this->version = (int) $version;
}
}
return $this->version;
} | php | public function getVersion() : ?int
{
if (null === $this->version) {
$success = null;
try {
$version = $this->getItem('browscap.version', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data version from the cache', 0, $e));
$version = null;
}
if (null !== $version && $success) {
$this->version = (int) $version;
}
}
return $this->version;
} | [
"public",
"function",
"getVersion",
"(",
")",
":",
"?",
"int",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"version",
")",
"{",
"$",
"success",
"=",
"null",
";",
"try",
"{",
"$",
"version",
"=",
"$",
"this",
"->",
"getItem",
"(",
"'browscap.version'",
",",
"false",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while reading the data version from the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"$",
"version",
"=",
"null",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"version",
"&&",
"$",
"success",
")",
"{",
"$",
"this",
"->",
"version",
"=",
"(",
"int",
")",
"$",
"version",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"version",
";",
"}"
] | Gets the version of the Browscap data
@return int | [
"Gets",
"the",
"version",
"of",
"the",
"Browscap",
"data"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L66-L84 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.getReleaseDate | public function getReleaseDate() : ?string
{
if (null === $this->releaseDate) {
$success = null;
try {
$releaseDate = $this->getItem('browscap.releaseDate', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data release date from the cache', 0, $e));
$releaseDate = null;
}
if (null !== $releaseDate && $success) {
$this->releaseDate = $releaseDate;
}
}
return $this->releaseDate;
} | php | public function getReleaseDate() : ?string
{
if (null === $this->releaseDate) {
$success = null;
try {
$releaseDate = $this->getItem('browscap.releaseDate', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data release date from the cache', 0, $e));
$releaseDate = null;
}
if (null !== $releaseDate && $success) {
$this->releaseDate = $releaseDate;
}
}
return $this->releaseDate;
} | [
"public",
"function",
"getReleaseDate",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"releaseDate",
")",
"{",
"$",
"success",
"=",
"null",
";",
"try",
"{",
"$",
"releaseDate",
"=",
"$",
"this",
"->",
"getItem",
"(",
"'browscap.releaseDate'",
",",
"false",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while reading the data release date from the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"$",
"releaseDate",
"=",
"null",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"releaseDate",
"&&",
"$",
"success",
")",
"{",
"$",
"this",
"->",
"releaseDate",
"=",
"$",
"releaseDate",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"releaseDate",
";",
"}"
] | Gets the release date of the Browscap data
@return string|null | [
"Gets",
"the",
"release",
"date",
"of",
"the",
"Browscap",
"data"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L91-L109 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.getType | public function getType() : ?string
{
if (null === $this->type) {
$success = null;
try {
$type = $this->getItem('browscap.type', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data type from the cache', 0, $e));
$type = null;
}
if (null !== $type && $success) {
$this->type = $type;
}
}
return $this->type;
} | php | public function getType() : ?string
{
if (null === $this->type) {
$success = null;
try {
$type = $this->getItem('browscap.type', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data type from the cache', 0, $e));
$type = null;
}
if (null !== $type && $success) {
$this->type = $type;
}
}
return $this->type;
} | [
"public",
"function",
"getType",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"type",
")",
"{",
"$",
"success",
"=",
"null",
";",
"try",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"getItem",
"(",
"'browscap.type'",
",",
"false",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while reading the data type from the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"$",
"type",
"=",
"null",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"type",
"&&",
"$",
"success",
")",
"{",
"$",
"this",
"->",
"type",
"=",
"$",
"type",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"type",
";",
"}"
] | Gets the type of the Browscap data | [
"Gets",
"the",
"type",
"of",
"the",
"Browscap",
"data"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L114-L132 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.getItem | public function getItem(string $cacheId, bool $withVersion = true, ?bool &$success = null)
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
if (! $this->cache->has($cacheId)) {
$success = false;
return null;
}
$data = $this->cache->get($cacheId);
if (! is_array($data) || ! array_key_exists('content', $data)) {
$success = false;
return null;
}
$success = true;
return unserialize($data['content']);
} | php | public function getItem(string $cacheId, bool $withVersion = true, ?bool &$success = null)
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
if (! $this->cache->has($cacheId)) {
$success = false;
return null;
}
$data = $this->cache->get($cacheId);
if (! is_array($data) || ! array_key_exists('content', $data)) {
$success = false;
return null;
}
$success = true;
return unserialize($data['content']);
} | [
"public",
"function",
"getItem",
"(",
"string",
"$",
"cacheId",
",",
"bool",
"$",
"withVersion",
"=",
"true",
",",
"?",
"bool",
"&",
"$",
"success",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"withVersion",
")",
"{",
"$",
"cacheId",
".=",
"'.'",
".",
"$",
"this",
"->",
"getVersion",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
"->",
"has",
"(",
"$",
"cacheId",
")",
")",
"{",
"$",
"success",
"=",
"false",
";",
"return",
"null",
";",
"}",
"$",
"data",
"=",
"$",
"this",
"->",
"cache",
"->",
"get",
"(",
"$",
"cacheId",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
"||",
"!",
"array_key_exists",
"(",
"'content'",
",",
"$",
"data",
")",
")",
"{",
"$",
"success",
"=",
"false",
";",
"return",
"null",
";",
"}",
"$",
"success",
"=",
"true",
";",
"return",
"unserialize",
"(",
"$",
"data",
"[",
"'content'",
"]",
")",
";",
"}"
] | Get an item.
@param string $cacheId
@param bool $withVersion
@param bool $success
@throws \Psr\SimpleCache\InvalidArgumentException
@return mixed Data on success, null on failure | [
"Get",
"an",
"item",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L145-L168 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.setItem | public function setItem(string $cacheId, $content, bool $withVersion = true) : bool
{
// Get the whole PHP code
$data = [
'content' => serialize($content),
];
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
// Save and return
return $this->cache->set($cacheId, $data);
} | php | public function setItem(string $cacheId, $content, bool $withVersion = true) : bool
{
// Get the whole PHP code
$data = [
'content' => serialize($content),
];
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
// Save and return
return $this->cache->set($cacheId, $data);
} | [
"public",
"function",
"setItem",
"(",
"string",
"$",
"cacheId",
",",
"$",
"content",
",",
"bool",
"$",
"withVersion",
"=",
"true",
")",
":",
"bool",
"{",
"// Get the whole PHP code",
"$",
"data",
"=",
"[",
"'content'",
"=>",
"serialize",
"(",
"$",
"content",
")",
",",
"]",
";",
"if",
"(",
"$",
"withVersion",
")",
"{",
"$",
"cacheId",
".=",
"'.'",
".",
"$",
"this",
"->",
"getVersion",
"(",
")",
";",
"}",
"// Save and return",
"return",
"$",
"this",
"->",
"cache",
"->",
"set",
"(",
"$",
"cacheId",
",",
"$",
"data",
")",
";",
"}"
] | save the content into an php file
@param string $cacheId The cache id
@param mixed $content The content to store
@param bool $withVersion
@throws \Psr\SimpleCache\InvalidArgumentException
@return bool whether the file was correctly written to the disk | [
"save",
"the",
"content",
"into",
"an",
"php",
"file"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L181-L194 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.hasItem | public function hasItem(string $cacheId, bool $withVersion = true) : bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->has($cacheId);
} | php | public function hasItem(string $cacheId, bool $withVersion = true) : bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->has($cacheId);
} | [
"public",
"function",
"hasItem",
"(",
"string",
"$",
"cacheId",
",",
"bool",
"$",
"withVersion",
"=",
"true",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"withVersion",
")",
"{",
"$",
"cacheId",
".=",
"'.'",
".",
"$",
"this",
"->",
"getVersion",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"cache",
"->",
"has",
"(",
"$",
"cacheId",
")",
";",
"}"
] | Test if an item exists.
@param string $cacheId
@param bool $withVersion
@throws \Psr\SimpleCache\InvalidArgumentException
@return bool | [
"Test",
"if",
"an",
"item",
"exists",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L206-L213 |
browscap/browscap-php | src/Cache/BrowscapCache.php | BrowscapCache.removeItem | public function removeItem(string $cacheId, bool $withVersion = true) : bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->delete($cacheId);
} | php | public function removeItem(string $cacheId, bool $withVersion = true) : bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->delete($cacheId);
} | [
"public",
"function",
"removeItem",
"(",
"string",
"$",
"cacheId",
",",
"bool",
"$",
"withVersion",
"=",
"true",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"withVersion",
")",
"{",
"$",
"cacheId",
".=",
"'.'",
".",
"$",
"this",
"->",
"getVersion",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"cache",
"->",
"delete",
"(",
"$",
"cacheId",
")",
";",
"}"
] | Remove an item.
@param string $cacheId
@param bool $withVersion
@throws \Psr\SimpleCache\InvalidArgumentException
@return bool | [
"Remove",
"an",
"item",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Cache/BrowscapCache.php#L225-L232 |
browscap/browscap-php | src/Parser/Helper/SubKey.php | SubKey.getAllPatternCacheSubkeys | public static function getAllPatternCacheSubkeys() : array
{
$subkeys = [];
$chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
foreach ($chars as $charOne) {
foreach ($chars as $charTwo) {
$subkeys[$charOne . $charTwo] = '';
}
}
return $subkeys;
} | php | public static function getAllPatternCacheSubkeys() : array
{
$subkeys = [];
$chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
foreach ($chars as $charOne) {
foreach ($chars as $charTwo) {
$subkeys[$charOne . $charTwo] = '';
}
}
return $subkeys;
} | [
"public",
"static",
"function",
"getAllPatternCacheSubkeys",
"(",
")",
":",
"array",
"{",
"$",
"subkeys",
"=",
"[",
"]",
";",
"$",
"chars",
"=",
"[",
"'0'",
",",
"'1'",
",",
"'2'",
",",
"'3'",
",",
"'4'",
",",
"'5'",
",",
"'6'",
",",
"'7'",
",",
"'8'",
",",
"'9'",
",",
"'a'",
",",
"'b'",
",",
"'c'",
",",
"'d'",
",",
"'e'",
",",
"'f'",
"]",
";",
"foreach",
"(",
"$",
"chars",
"as",
"$",
"charOne",
")",
"{",
"foreach",
"(",
"$",
"chars",
"as",
"$",
"charTwo",
")",
"{",
"$",
"subkeys",
"[",
"$",
"charOne",
".",
"$",
"charTwo",
"]",
"=",
"''",
";",
"}",
"}",
"return",
"$",
"subkeys",
";",
"}"
] | Gets all subkeys for the pattern cache files
@return string[] | [
"Gets",
"all",
"subkeys",
"for",
"the",
"pattern",
"cache",
"files"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Helper/SubKey.php#L32-L44 |
browscap/browscap-php | src/Parser/Helper/SubKey.php | SubKey.getAllIniPartCacheSubKeys | public static function getAllIniPartCacheSubKeys() : array
{
$subKeys = [];
$chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
foreach ($chars as $charOne) {
foreach ($chars as $charTwo) {
foreach ($chars as $charThree) {
$subKeys[] = $charOne . $charTwo . $charThree;
}
}
}
return $subKeys;
} | php | public static function getAllIniPartCacheSubKeys() : array
{
$subKeys = [];
$chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
foreach ($chars as $charOne) {
foreach ($chars as $charTwo) {
foreach ($chars as $charThree) {
$subKeys[] = $charOne . $charTwo . $charThree;
}
}
}
return $subKeys;
} | [
"public",
"static",
"function",
"getAllIniPartCacheSubKeys",
"(",
")",
":",
"array",
"{",
"$",
"subKeys",
"=",
"[",
"]",
";",
"$",
"chars",
"=",
"[",
"'0'",
",",
"'1'",
",",
"'2'",
",",
"'3'",
",",
"'4'",
",",
"'5'",
",",
"'6'",
",",
"'7'",
",",
"'8'",
",",
"'9'",
",",
"'a'",
",",
"'b'",
",",
"'c'",
",",
"'d'",
",",
"'e'",
",",
"'f'",
"]",
";",
"foreach",
"(",
"$",
"chars",
"as",
"$",
"charOne",
")",
"{",
"foreach",
"(",
"$",
"chars",
"as",
"$",
"charTwo",
")",
"{",
"foreach",
"(",
"$",
"chars",
"as",
"$",
"charThree",
")",
"{",
"$",
"subKeys",
"[",
"]",
"=",
"$",
"charOne",
".",
"$",
"charTwo",
".",
"$",
"charThree",
";",
"}",
"}",
"}",
"return",
"$",
"subKeys",
";",
"}"
] | Gets all sub keys for the inipart cache files
@return string[] | [
"Gets",
"all",
"sub",
"keys",
"for",
"the",
"inipart",
"cache",
"files"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Helper/SubKey.php#L63-L77 |
browscap/browscap-php | src/Command/ParserCommand.php | ParserCommand.execute | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
$browscap = new Browscap($cache, $logger);
/** @var string $uaArgument */
$uaArgument = $input->getArgument('user-agent');
try {
$result = $browscap->getBrowser($uaArgument);
} catch (Exception $e) {
$logger->debug($e);
return 11;
}
try {
$output->writeln(\ExceptionalJSON\encode($result, JSON_PRETTY_PRINT));
} catch (EncodeErrorException $e) {
$logger->error($e);
return 11;
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
$browscap = new Browscap($cache, $logger);
/** @var string $uaArgument */
$uaArgument = $input->getArgument('user-agent');
try {
$result = $browscap->getBrowser($uaArgument);
} catch (Exception $e) {
$logger->debug($e);
return 11;
}
try {
$output->writeln(\ExceptionalJSON\encode($result, JSON_PRETTY_PRINT));
} catch (EncodeErrorException $e) {
$logger->error($e);
return 11;
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"int",
"{",
"$",
"logger",
"=",
"LoggerHelper",
"::",
"createDefaultLogger",
"(",
"$",
"output",
")",
";",
"/** @var string $cacheOption */",
"$",
"cacheOption",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'cache'",
")",
";",
"$",
"fileCache",
"=",
"new",
"FilesystemCache",
"(",
"$",
"cacheOption",
")",
";",
"$",
"cache",
"=",
"new",
"SimpleCacheAdapter",
"(",
"$",
"fileCache",
")",
";",
"$",
"browscap",
"=",
"new",
"Browscap",
"(",
"$",
"cache",
",",
"$",
"logger",
")",
";",
"/** @var string $uaArgument */",
"$",
"uaArgument",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'user-agent'",
")",
";",
"try",
"{",
"$",
"result",
"=",
"$",
"browscap",
"->",
"getBrowser",
"(",
"$",
"uaArgument",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"11",
";",
"}",
"try",
"{",
"$",
"output",
"->",
"writeln",
"(",
"\\",
"ExceptionalJSON",
"\\",
"encode",
"(",
"$",
"result",
",",
"JSON_PRETTY_PRINT",
")",
")",
";",
"}",
"catch",
"(",
"EncodeErrorException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"error",
"(",
"$",
"e",
")",
";",
"return",
"11",
";",
"}",
"return",
"0",
";",
"}"
] | @param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return int | [
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Input",
"\\",
"InputInterface",
"$input",
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Output",
"\\",
"OutputInterface",
"$output"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Command/ParserCommand.php#L61-L92 |
browscap/browscap-php | src/Parser/Helper/Pattern.php | Pattern.getHashForPattern | public static function getHashForPattern(string $pattern, bool $variants = false) : array
{
$regex = '/^([^\.\*\?\s\r\n\\\\]+).*$/';
$pattern = substr($pattern, 0, 32);
$matches = [];
if (! preg_match($regex, $pattern, $matches)) {
return [md5('')];
}
if (! isset($matches[1])) {
return [md5('')];
}
$string = $matches[1];
if (true === $variants) {
$patternStarts = [];
for ($i = strlen($string); 1 <= $i; --$i) {
$string = substr($string, 0, $i);
$patternStarts[] = md5($string);
}
// Add empty pattern start to include patterns that start with "*",
// e.g. "*FAST Enterprise Crawler*"
$patternStarts[] = md5('');
return $patternStarts;
}
return [md5($string)];
} | php | public static function getHashForPattern(string $pattern, bool $variants = false) : array
{
$regex = '/^([^\.\*\?\s\r\n\\\\]+).*$/';
$pattern = substr($pattern, 0, 32);
$matches = [];
if (! preg_match($regex, $pattern, $matches)) {
return [md5('')];
}
if (! isset($matches[1])) {
return [md5('')];
}
$string = $matches[1];
if (true === $variants) {
$patternStarts = [];
for ($i = strlen($string); 1 <= $i; --$i) {
$string = substr($string, 0, $i);
$patternStarts[] = md5($string);
}
// Add empty pattern start to include patterns that start with "*",
// e.g. "*FAST Enterprise Crawler*"
$patternStarts[] = md5('');
return $patternStarts;
}
return [md5($string)];
} | [
"public",
"static",
"function",
"getHashForPattern",
"(",
"string",
"$",
"pattern",
",",
"bool",
"$",
"variants",
"=",
"false",
")",
":",
"array",
"{",
"$",
"regex",
"=",
"'/^([^\\.\\*\\?\\s\\r\\n\\\\\\\\]+).*$/'",
";",
"$",
"pattern",
"=",
"substr",
"(",
"$",
"pattern",
",",
"0",
",",
"32",
")",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"pattern",
",",
"$",
"matches",
")",
")",
"{",
"return",
"[",
"md5",
"(",
"''",
")",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
")",
"{",
"return",
"[",
"md5",
"(",
"''",
")",
"]",
";",
"}",
"$",
"string",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"if",
"(",
"true",
"===",
"$",
"variants",
")",
"{",
"$",
"patternStarts",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"strlen",
"(",
"$",
"string",
")",
";",
"1",
"<=",
"$",
"i",
";",
"--",
"$",
"i",
")",
"{",
"$",
"string",
"=",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"$",
"i",
")",
";",
"$",
"patternStarts",
"[",
"]",
"=",
"md5",
"(",
"$",
"string",
")",
";",
"}",
"// Add empty pattern start to include patterns that start with \"*\",",
"// e.g. \"*FAST Enterprise Crawler*\"",
"$",
"patternStarts",
"[",
"]",
"=",
"md5",
"(",
"''",
")",
";",
"return",
"$",
"patternStarts",
";",
"}",
"return",
"[",
"md5",
"(",
"$",
"string",
")",
"]",
";",
"}"
] | Gets a hash or an array of hashes from the first characters of a pattern/user agent, that can
be used for a fast comparison, by comparing only the hashes, without having to match the
complete pattern against the user agent.
With the variants options, all variants from the maximum number of pattern characters to one
character will be returned. This is required in some cases, the a placeholder is used very
early in the pattern.
Example:
Pattern: "Mozilla/* (Nintendo 3DS; *) Version/*"
User agent: "Mozilla/5.0 (Nintendo 3DS; U; ; en) Version/1.7567.US"
In this case the has for the pattern is created for "Mozilla/" while the pattern
for the hash for user agent is created for "Mozilla/5.0". The variants option
results in an array with hashes for "Mozilla/5.0", "Mozilla/5.", "Mozilla/5",
"Mozilla/" ... "M", so that the pattern hash is included.
@param string $pattern
@param bool $variants
@return string[] | [
"Gets",
"a",
"hash",
"or",
"an",
"array",
"of",
"hashes",
"from",
"the",
"first",
"characters",
"of",
"a",
"pattern",
"/",
"user",
"agent",
"that",
"can",
"be",
"used",
"for",
"a",
"fast",
"comparison",
"by",
"comparing",
"only",
"the",
"hashes",
"without",
"having",
"to",
"match",
"the",
"complete",
"pattern",
"against",
"the",
"user",
"agent",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Helper/Pattern.php#L39-L71 |
browscap/browscap-php | src/Data/PropertyHolder.php | PropertyHolder.checkValueInArray | public function checkValueInArray(string $property, string $value) : string
{
switch ($property) {
case 'Browser_Type':
$allowedValues = [
'Useragent Anonymizer' => 1,
'Browser' => 1,
'Offline Browser' => 1,
'Multimedia Player' => 1,
'Library' => 1,
'Feed Reader' => 1,
'Email Client' => 1,
'Bot/Crawler' => 1,
'Application' => 1,
'Tool' => 1,
'unknown' => 1,
];
break;
case 'Device_Type':
$allowedValues = [
'Console' => 1,
'TV Device' => 1,
'Tablet' => 1,
'Mobile Phone' => 1,
'Smartphone' => 1, // actual mobile phone with touchscreen
'Feature Phone' => 1, // older mobile phone
'Mobile Device' => 1,
'FonePad' => 1, // Tablet sized device with the capability to make phone calls
'Desktop' => 1,
'Ebook Reader' => 1,
'Car Entertainment System' => 1,
'Digital Camera' => 1,
'unknown' => 1,
];
break;
case 'Device_Pointing_Method':
// This property is taken from http://www.scientiamobile.com/wurflCapability
$allowedValues = [
'joystick' => 1,
'stylus' => 1,
'touchscreen' => 1,
'clickwheel' => 1,
'trackpad' => 1,
'trackball' => 1,
'mouse' => 1,
'unknown' => 1,
];
break;
case 'Browser_Bits':
case 'Platform_Bits':
$allowedValues = [
'0' => 1,
'8' => 1,
'16' => 1,
'32' => 1,
'64' => 1,
];
break;
default:
throw new \InvalidArgumentException('Property "' . $property . '" is not defined to be validated');
}
if (array_key_exists($value, $allowedValues)) {
return $value;
}
throw new \InvalidArgumentException(
'invalid value given for Property "' . $property . '": given value "' . $value . '", allowed: '
. \ExceptionalJSON\encode($allowedValues)
);
} | php | public function checkValueInArray(string $property, string $value) : string
{
switch ($property) {
case 'Browser_Type':
$allowedValues = [
'Useragent Anonymizer' => 1,
'Browser' => 1,
'Offline Browser' => 1,
'Multimedia Player' => 1,
'Library' => 1,
'Feed Reader' => 1,
'Email Client' => 1,
'Bot/Crawler' => 1,
'Application' => 1,
'Tool' => 1,
'unknown' => 1,
];
break;
case 'Device_Type':
$allowedValues = [
'Console' => 1,
'TV Device' => 1,
'Tablet' => 1,
'Mobile Phone' => 1,
'Smartphone' => 1, // actual mobile phone with touchscreen
'Feature Phone' => 1, // older mobile phone
'Mobile Device' => 1,
'FonePad' => 1, // Tablet sized device with the capability to make phone calls
'Desktop' => 1,
'Ebook Reader' => 1,
'Car Entertainment System' => 1,
'Digital Camera' => 1,
'unknown' => 1,
];
break;
case 'Device_Pointing_Method':
// This property is taken from http://www.scientiamobile.com/wurflCapability
$allowedValues = [
'joystick' => 1,
'stylus' => 1,
'touchscreen' => 1,
'clickwheel' => 1,
'trackpad' => 1,
'trackball' => 1,
'mouse' => 1,
'unknown' => 1,
];
break;
case 'Browser_Bits':
case 'Platform_Bits':
$allowedValues = [
'0' => 1,
'8' => 1,
'16' => 1,
'32' => 1,
'64' => 1,
];
break;
default:
throw new \InvalidArgumentException('Property "' . $property . '" is not defined to be validated');
}
if (array_key_exists($value, $allowedValues)) {
return $value;
}
throw new \InvalidArgumentException(
'invalid value given for Property "' . $property . '": given value "' . $value . '", allowed: '
. \ExceptionalJSON\encode($allowedValues)
);
} | [
"public",
"function",
"checkValueInArray",
"(",
"string",
"$",
"property",
",",
"string",
"$",
"value",
")",
":",
"string",
"{",
"switch",
"(",
"$",
"property",
")",
"{",
"case",
"'Browser_Type'",
":",
"$",
"allowedValues",
"=",
"[",
"'Useragent Anonymizer'",
"=>",
"1",
",",
"'Browser'",
"=>",
"1",
",",
"'Offline Browser'",
"=>",
"1",
",",
"'Multimedia Player'",
"=>",
"1",
",",
"'Library'",
"=>",
"1",
",",
"'Feed Reader'",
"=>",
"1",
",",
"'Email Client'",
"=>",
"1",
",",
"'Bot/Crawler'",
"=>",
"1",
",",
"'Application'",
"=>",
"1",
",",
"'Tool'",
"=>",
"1",
",",
"'unknown'",
"=>",
"1",
",",
"]",
";",
"break",
";",
"case",
"'Device_Type'",
":",
"$",
"allowedValues",
"=",
"[",
"'Console'",
"=>",
"1",
",",
"'TV Device'",
"=>",
"1",
",",
"'Tablet'",
"=>",
"1",
",",
"'Mobile Phone'",
"=>",
"1",
",",
"'Smartphone'",
"=>",
"1",
",",
"// actual mobile phone with touchscreen",
"'Feature Phone'",
"=>",
"1",
",",
"// older mobile phone",
"'Mobile Device'",
"=>",
"1",
",",
"'FonePad'",
"=>",
"1",
",",
"// Tablet sized device with the capability to make phone calls",
"'Desktop'",
"=>",
"1",
",",
"'Ebook Reader'",
"=>",
"1",
",",
"'Car Entertainment System'",
"=>",
"1",
",",
"'Digital Camera'",
"=>",
"1",
",",
"'unknown'",
"=>",
"1",
",",
"]",
";",
"break",
";",
"case",
"'Device_Pointing_Method'",
":",
"// This property is taken from http://www.scientiamobile.com/wurflCapability",
"$",
"allowedValues",
"=",
"[",
"'joystick'",
"=>",
"1",
",",
"'stylus'",
"=>",
"1",
",",
"'touchscreen'",
"=>",
"1",
",",
"'clickwheel'",
"=>",
"1",
",",
"'trackpad'",
"=>",
"1",
",",
"'trackball'",
"=>",
"1",
",",
"'mouse'",
"=>",
"1",
",",
"'unknown'",
"=>",
"1",
",",
"]",
";",
"break",
";",
"case",
"'Browser_Bits'",
":",
"case",
"'Platform_Bits'",
":",
"$",
"allowedValues",
"=",
"[",
"'0'",
"=>",
"1",
",",
"'8'",
"=>",
"1",
",",
"'16'",
"=>",
"1",
",",
"'32'",
"=>",
"1",
",",
"'64'",
"=>",
"1",
",",
"]",
";",
"break",
";",
"default",
":",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Property \"'",
".",
"$",
"property",
".",
"'\" is not defined to be validated'",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"$",
"value",
",",
"$",
"allowedValues",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'invalid value given for Property \"'",
".",
"$",
"property",
".",
"'\": given value \"'",
".",
"$",
"value",
".",
"'\", allowed: '",
".",
"\\",
"ExceptionalJSON",
"\\",
"encode",
"(",
"$",
"allowedValues",
")",
")",
";",
"}"
] | @param string $property
@param string $value
@throws \InvalidArgumentException
@return string | [
"@param",
"string",
"$property",
"@param",
"string",
"$value"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Data/PropertyHolder.php#L130-L204 |
browscap/browscap-php | src/Helper/LoggerHelper.php | LoggerHelper.createDefaultLogger | public static function createDefaultLogger(OutputInterface $output) : LoggerInterface
{
$logger = new Logger('browscap');
$consoleLogger = new ConsoleLogger($output);
$psrHandler = new PsrHandler($consoleLogger);
$logger->pushHandler($psrHandler);
/** @var callable $memoryProcessor */
$memoryProcessor = new MemoryUsageProcessor(true);
$logger->pushProcessor($memoryProcessor);
/** @var callable $peakMemoryProcessor */
$peakMemoryProcessor = new MemoryPeakUsageProcessor(true);
$logger->pushProcessor($peakMemoryProcessor);
ErrorHandler::register($logger);
return $logger;
} | php | public static function createDefaultLogger(OutputInterface $output) : LoggerInterface
{
$logger = new Logger('browscap');
$consoleLogger = new ConsoleLogger($output);
$psrHandler = new PsrHandler($consoleLogger);
$logger->pushHandler($psrHandler);
/** @var callable $memoryProcessor */
$memoryProcessor = new MemoryUsageProcessor(true);
$logger->pushProcessor($memoryProcessor);
/** @var callable $peakMemoryProcessor */
$peakMemoryProcessor = new MemoryPeakUsageProcessor(true);
$logger->pushProcessor($peakMemoryProcessor);
ErrorHandler::register($logger);
return $logger;
} | [
"public",
"static",
"function",
"createDefaultLogger",
"(",
"OutputInterface",
"$",
"output",
")",
":",
"LoggerInterface",
"{",
"$",
"logger",
"=",
"new",
"Logger",
"(",
"'browscap'",
")",
";",
"$",
"consoleLogger",
"=",
"new",
"ConsoleLogger",
"(",
"$",
"output",
")",
";",
"$",
"psrHandler",
"=",
"new",
"PsrHandler",
"(",
"$",
"consoleLogger",
")",
";",
"$",
"logger",
"->",
"pushHandler",
"(",
"$",
"psrHandler",
")",
";",
"/** @var callable $memoryProcessor */",
"$",
"memoryProcessor",
"=",
"new",
"MemoryUsageProcessor",
"(",
"true",
")",
";",
"$",
"logger",
"->",
"pushProcessor",
"(",
"$",
"memoryProcessor",
")",
";",
"/** @var callable $peakMemoryProcessor */",
"$",
"peakMemoryProcessor",
"=",
"new",
"MemoryPeakUsageProcessor",
"(",
"true",
")",
";",
"$",
"logger",
"->",
"pushProcessor",
"(",
"$",
"peakMemoryProcessor",
")",
";",
"ErrorHandler",
"::",
"register",
"(",
"$",
"logger",
")",
";",
"return",
"$",
"logger",
";",
"}"
] | creates a \Monolog\Logger instance
@param \Symfony\Component\Console\Output\OutputInterface $output
@return LoggerInterface | [
"creates",
"a",
"\\",
"Monolog",
"\\",
"Logger",
"instance"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Helper/LoggerHelper.php#L31-L50 |
browscap/browscap-php | src/Helper/Filesystem.php | Filesystem.dumpFile | public function dumpFile($filename, $content, ?int $mode = 0666) : void
{
$dir = dirname($filename);
if (! is_dir($dir)) {
$this->mkdir($dir);
} elseif (! is_writable($dir)) {
throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
}
// "tempnam" did not work with VFSStream for tests
$tmpFile = dirname($filename) . '/temp_' . md5(time() . basename($filename));
if (false === @file_put_contents($tmpFile, $content)) {
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
}
try {
$this->rename($tmpFile, $filename, true);
} catch (IOException $e) {
unlink($tmpFile);
throw $e;
}
if (null !== $mode) {
$this->chmod($filename, $mode);
}
} | php | public function dumpFile($filename, $content, ?int $mode = 0666) : void
{
$dir = dirname($filename);
if (! is_dir($dir)) {
$this->mkdir($dir);
} elseif (! is_writable($dir)) {
throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
}
// "tempnam" did not work with VFSStream for tests
$tmpFile = dirname($filename) . '/temp_' . md5(time() . basename($filename));
if (false === @file_put_contents($tmpFile, $content)) {
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
}
try {
$this->rename($tmpFile, $filename, true);
} catch (IOException $e) {
unlink($tmpFile);
throw $e;
}
if (null !== $mode) {
$this->chmod($filename, $mode);
}
} | [
"public",
"function",
"dumpFile",
"(",
"$",
"filename",
",",
"$",
"content",
",",
"?",
"int",
"$",
"mode",
"=",
"0666",
")",
":",
"void",
"{",
"$",
"dir",
"=",
"dirname",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"$",
"this",
"->",
"mkdir",
"(",
"$",
"dir",
")",
";",
"}",
"elseif",
"(",
"!",
"is_writable",
"(",
"$",
"dir",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"sprintf",
"(",
"'Unable to write to the \"%s\" directory.'",
",",
"$",
"dir",
")",
",",
"0",
",",
"null",
",",
"$",
"dir",
")",
";",
"}",
"// \"tempnam\" did not work with VFSStream for tests",
"$",
"tmpFile",
"=",
"dirname",
"(",
"$",
"filename",
")",
".",
"'/temp_'",
".",
"md5",
"(",
"time",
"(",
")",
".",
"basename",
"(",
"$",
"filename",
")",
")",
";",
"if",
"(",
"false",
"===",
"@",
"file_put_contents",
"(",
"$",
"tmpFile",
",",
"$",
"content",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"sprintf",
"(",
"'Failed to write file \"%s\".'",
",",
"$",
"filename",
")",
",",
"0",
",",
"null",
",",
"$",
"filename",
")",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"rename",
"(",
"$",
"tmpFile",
",",
"$",
"filename",
",",
"true",
")",
";",
"}",
"catch",
"(",
"IOException",
"$",
"e",
")",
"{",
"unlink",
"(",
"$",
"tmpFile",
")",
";",
"throw",
"$",
"e",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"mode",
")",
"{",
"$",
"this",
"->",
"chmod",
"(",
"$",
"filename",
",",
"$",
"mode",
")",
";",
"}",
"}"
] | Atomically dumps content into a file.
@param string $filename The file to be written to.
@param string $content The data to write into the file.
@param int|null $mode The file mode (octal). If null, file permissions are not modified
Deprecated since version 2.3.12, to be removed in 3.0.
@throws IOException If the file cannot be written to. | [
"Atomically",
"dumps",
"content",
"into",
"a",
"file",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Helper/Filesystem.php#L24-L52 |
browscap/browscap-php | src/BrowscapUpdater.php | BrowscapUpdater.convertFile | public function convertFile(string $iniFile) : void
{
if (empty($iniFile)) {
throw new FileNameMissingException('the file name can not be empty');
}
if (! is_readable($iniFile)) {
throw new FileNotFoundException('it was not possible to read the local file ' . $iniFile);
}
$iniString = file_get_contents($iniFile);
if (false === $iniString) {
throw new ErrorReadingFileException('an error occured while converting the local file into the cache');
}
$this->convertString($iniString);
} | php | public function convertFile(string $iniFile) : void
{
if (empty($iniFile)) {
throw new FileNameMissingException('the file name can not be empty');
}
if (! is_readable($iniFile)) {
throw new FileNotFoundException('it was not possible to read the local file ' . $iniFile);
}
$iniString = file_get_contents($iniFile);
if (false === $iniString) {
throw new ErrorReadingFileException('an error occured while converting the local file into the cache');
}
$this->convertString($iniString);
} | [
"public",
"function",
"convertFile",
"(",
"string",
"$",
"iniFile",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"iniFile",
")",
")",
"{",
"throw",
"new",
"FileNameMissingException",
"(",
"'the file name can not be empty'",
")",
";",
"}",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"iniFile",
")",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"'it was not possible to read the local file '",
".",
"$",
"iniFile",
")",
";",
"}",
"$",
"iniString",
"=",
"file_get_contents",
"(",
"$",
"iniFile",
")",
";",
"if",
"(",
"false",
"===",
"$",
"iniString",
")",
"{",
"throw",
"new",
"ErrorReadingFileException",
"(",
"'an error occured while converting the local file into the cache'",
")",
";",
"}",
"$",
"this",
"->",
"convertString",
"(",
"$",
"iniString",
")",
";",
"}"
] | reads and parses an ini file and writes the results into the cache
@param string $iniFile
@throws \BrowscapPHP\Exception\FileNameMissingException
@throws \BrowscapPHP\Exception\FileNotFoundException
@throws \BrowscapPHP\Exception\ErrorReadingFileException | [
"reads",
"and",
"parses",
"an",
"ini",
"file",
"and",
"writes",
"the",
"results",
"into",
"the",
"cache"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/BrowscapUpdater.php#L90-L107 |
browscap/browscap-php | src/BrowscapUpdater.php | BrowscapUpdater.convertString | public function convertString(string $iniString) : void
{
try {
$cachedVersion = $this->cache->getItem('browscap.version', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data version from the cache', 0, $e));
return;
}
$converter = new Converter($this->logger, $this->cache);
$this->storeContent($converter, $iniString, $cachedVersion);
} | php | public function convertString(string $iniString) : void
{
try {
$cachedVersion = $this->cache->getItem('browscap.version', false, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the data version from the cache', 0, $e));
return;
}
$converter = new Converter($this->logger, $this->cache);
$this->storeContent($converter, $iniString, $cachedVersion);
} | [
"public",
"function",
"convertString",
"(",
"string",
"$",
"iniString",
")",
":",
"void",
"{",
"try",
"{",
"$",
"cachedVersion",
"=",
"$",
"this",
"->",
"cache",
"->",
"getItem",
"(",
"'browscap.version'",
",",
"false",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while reading the data version from the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"return",
";",
"}",
"$",
"converter",
"=",
"new",
"Converter",
"(",
"$",
"this",
"->",
"logger",
",",
"$",
"this",
"->",
"cache",
")",
";",
"$",
"this",
"->",
"storeContent",
"(",
"$",
"converter",
",",
"$",
"iniString",
",",
"$",
"cachedVersion",
")",
";",
"}"
] | reads and parses an ini string and writes the results into the cache
@param string $iniString | [
"reads",
"and",
"parses",
"an",
"ini",
"string",
"and",
"writes",
"the",
"results",
"into",
"the",
"cache"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/BrowscapUpdater.php#L114-L127 |
browscap/browscap-php | src/BrowscapUpdater.php | BrowscapUpdater.fetch | public function fetch(string $file, string $remoteFile = IniLoaderInterface::PHP_INI) : void
{
try {
$cachedVersion = $this->checkUpdate();
} catch (NoNewVersionException $e) {
return;
} catch (NoCachedVersionException $e) {
$cachedVersion = 0;
}
$this->logger->debug('started fetching remote file');
$loader = new IniLoader();
$loader->setRemoteFilename($remoteFile);
$uri = $loader->getRemoteIniUrl();
try {
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $this->client->request('get', $uri, ['connect_timeout' => $this->connectTimeout]);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s',
$uri
),
0,
$e
);
}
if (200 !== $response->getStatusCode()) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
)
);
}
try {
$content = $response->getBody()->getContents();
} catch (\Exception $e) {
throw new FetcherException('an error occured while fetching remote data', 0, $e);
}
if (empty($content)) {
$error = error_get_last();
throw FetcherException::httpError($uri, $error['message']);
}
$this->logger->debug('finished fetching remote file');
$this->logger->debug('started storing remote file into local file');
$content = $this->sanitizeContent($content);
$converter = new Converter($this->logger, $this->cache);
$iniVersion = $converter->getIniVersion($content);
if ($iniVersion > $cachedVersion) {
$fs = new Filesystem();
$fs->dumpFile($file, $content);
}
$this->logger->debug('finished storing remote file into local file');
} | php | public function fetch(string $file, string $remoteFile = IniLoaderInterface::PHP_INI) : void
{
try {
$cachedVersion = $this->checkUpdate();
} catch (NoNewVersionException $e) {
return;
} catch (NoCachedVersionException $e) {
$cachedVersion = 0;
}
$this->logger->debug('started fetching remote file');
$loader = new IniLoader();
$loader->setRemoteFilename($remoteFile);
$uri = $loader->getRemoteIniUrl();
try {
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $this->client->request('get', $uri, ['connect_timeout' => $this->connectTimeout]);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s',
$uri
),
0,
$e
);
}
if (200 !== $response->getStatusCode()) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
)
);
}
try {
$content = $response->getBody()->getContents();
} catch (\Exception $e) {
throw new FetcherException('an error occured while fetching remote data', 0, $e);
}
if (empty($content)) {
$error = error_get_last();
throw FetcherException::httpError($uri, $error['message']);
}
$this->logger->debug('finished fetching remote file');
$this->logger->debug('started storing remote file into local file');
$content = $this->sanitizeContent($content);
$converter = new Converter($this->logger, $this->cache);
$iniVersion = $converter->getIniVersion($content);
if ($iniVersion > $cachedVersion) {
$fs = new Filesystem();
$fs->dumpFile($file, $content);
}
$this->logger->debug('finished storing remote file into local file');
} | [
"public",
"function",
"fetch",
"(",
"string",
"$",
"file",
",",
"string",
"$",
"remoteFile",
"=",
"IniLoaderInterface",
"::",
"PHP_INI",
")",
":",
"void",
"{",
"try",
"{",
"$",
"cachedVersion",
"=",
"$",
"this",
"->",
"checkUpdate",
"(",
")",
";",
"}",
"catch",
"(",
"NoNewVersionException",
"$",
"e",
")",
"{",
"return",
";",
"}",
"catch",
"(",
"NoCachedVersionException",
"$",
"e",
")",
"{",
"$",
"cachedVersion",
"=",
"0",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'started fetching remote file'",
")",
";",
"$",
"loader",
"=",
"new",
"IniLoader",
"(",
")",
";",
"$",
"loader",
"->",
"setRemoteFilename",
"(",
"$",
"remoteFile",
")",
";",
"$",
"uri",
"=",
"$",
"loader",
"->",
"getRemoteIniUrl",
"(",
")",
";",
"try",
"{",
"/** @var \\Psr\\Http\\Message\\ResponseInterface $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"request",
"(",
"'get'",
",",
"$",
"uri",
",",
"[",
"'connect_timeout'",
"=>",
"$",
"this",
"->",
"connectTimeout",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"GuzzleException",
"$",
"e",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching remote data from URI %s'",
",",
"$",
"uri",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"200",
"!==",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching remote data from URI %s: StatusCode was %d'",
",",
"$",
"uri",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
")",
";",
"}",
"try",
"{",
"$",
"content",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"'an error occured while fetching remote data'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"content",
")",
")",
"{",
"$",
"error",
"=",
"error_get_last",
"(",
")",
";",
"throw",
"FetcherException",
"::",
"httpError",
"(",
"$",
"uri",
",",
"$",
"error",
"[",
"'message'",
"]",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'finished fetching remote file'",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'started storing remote file into local file'",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"sanitizeContent",
"(",
"$",
"content",
")",
";",
"$",
"converter",
"=",
"new",
"Converter",
"(",
"$",
"this",
"->",
"logger",
",",
"$",
"this",
"->",
"cache",
")",
";",
"$",
"iniVersion",
"=",
"$",
"converter",
"->",
"getIniVersion",
"(",
"$",
"content",
")",
";",
"if",
"(",
"$",
"iniVersion",
">",
"$",
"cachedVersion",
")",
"{",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"$",
"fs",
"->",
"dumpFile",
"(",
"$",
"file",
",",
"$",
"content",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'finished storing remote file into local file'",
")",
";",
"}"
] | fetches a remote file and stores it into a local folder
@param string $file The name of the file where to store the remote content
@param string $remoteFile The code for the remote file to load
@throws \BrowscapPHP\Exception\FetcherException
@throws \BrowscapPHP\Helper\Exception
@throws \BrowscapPHP\Exception\ErrorCachedVersionException | [
"fetches",
"a",
"remote",
"file",
"and",
"stores",
"it",
"into",
"a",
"local",
"folder"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/BrowscapUpdater.php#L139-L206 |
browscap/browscap-php | src/BrowscapUpdater.php | BrowscapUpdater.update | public function update(string $remoteFile = IniLoaderInterface::PHP_INI) : void
{
$this->logger->debug('started fetching remote file');
try {
$cachedVersion = $this->checkUpdate();
} catch (NoNewVersionException $e) {
return;
} catch (NoCachedVersionException $e) {
$cachedVersion = 0;
}
$loader = new IniLoader();
$loader->setRemoteFilename($remoteFile);
$uri = $loader->getRemoteIniUrl();
try {
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $this->client->request('get', $uri, ['connect_timeout' => $this->connectTimeout]);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s',
$uri
),
0,
$e
);
}
if (200 !== $response->getStatusCode()) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
)
);
}
try {
$content = $response->getBody()->getContents();
} catch (\Exception $e) {
throw new FetcherException('an error occured while fetching remote data', 0, $e);
}
if (empty($content)) {
$error = error_get_last();
throw FetcherException::httpError($uri, $error['message'] ?? '');
}
$this->logger->debug('finished fetching remote file');
$this->logger->debug('started updating cache from remote file');
$converter = new Converter($this->logger, $this->cache);
$this->storeContent($converter, $content, $cachedVersion);
$this->logger->debug('finished updating cache from remote file');
} | php | public function update(string $remoteFile = IniLoaderInterface::PHP_INI) : void
{
$this->logger->debug('started fetching remote file');
try {
$cachedVersion = $this->checkUpdate();
} catch (NoNewVersionException $e) {
return;
} catch (NoCachedVersionException $e) {
$cachedVersion = 0;
}
$loader = new IniLoader();
$loader->setRemoteFilename($remoteFile);
$uri = $loader->getRemoteIniUrl();
try {
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $this->client->request('get', $uri, ['connect_timeout' => $this->connectTimeout]);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s',
$uri
),
0,
$e
);
}
if (200 !== $response->getStatusCode()) {
throw new FetcherException(
sprintf(
'an error occured while fetching remote data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
)
);
}
try {
$content = $response->getBody()->getContents();
} catch (\Exception $e) {
throw new FetcherException('an error occured while fetching remote data', 0, $e);
}
if (empty($content)) {
$error = error_get_last();
throw FetcherException::httpError($uri, $error['message'] ?? '');
}
$this->logger->debug('finished fetching remote file');
$this->logger->debug('started updating cache from remote file');
$converter = new Converter($this->logger, $this->cache);
$this->storeContent($converter, $content, $cachedVersion);
$this->logger->debug('finished updating cache from remote file');
} | [
"public",
"function",
"update",
"(",
"string",
"$",
"remoteFile",
"=",
"IniLoaderInterface",
"::",
"PHP_INI",
")",
":",
"void",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'started fetching remote file'",
")",
";",
"try",
"{",
"$",
"cachedVersion",
"=",
"$",
"this",
"->",
"checkUpdate",
"(",
")",
";",
"}",
"catch",
"(",
"NoNewVersionException",
"$",
"e",
")",
"{",
"return",
";",
"}",
"catch",
"(",
"NoCachedVersionException",
"$",
"e",
")",
"{",
"$",
"cachedVersion",
"=",
"0",
";",
"}",
"$",
"loader",
"=",
"new",
"IniLoader",
"(",
")",
";",
"$",
"loader",
"->",
"setRemoteFilename",
"(",
"$",
"remoteFile",
")",
";",
"$",
"uri",
"=",
"$",
"loader",
"->",
"getRemoteIniUrl",
"(",
")",
";",
"try",
"{",
"/** @var \\Psr\\Http\\Message\\ResponseInterface $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"request",
"(",
"'get'",
",",
"$",
"uri",
",",
"[",
"'connect_timeout'",
"=>",
"$",
"this",
"->",
"connectTimeout",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"GuzzleException",
"$",
"e",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching remote data from URI %s'",
",",
"$",
"uri",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"200",
"!==",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching remote data from URI %s: StatusCode was %d'",
",",
"$",
"uri",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
")",
";",
"}",
"try",
"{",
"$",
"content",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"'an error occured while fetching remote data'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"content",
")",
")",
"{",
"$",
"error",
"=",
"error_get_last",
"(",
")",
";",
"throw",
"FetcherException",
"::",
"httpError",
"(",
"$",
"uri",
",",
"$",
"error",
"[",
"'message'",
"]",
"??",
"''",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'finished fetching remote file'",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'started updating cache from remote file'",
")",
";",
"$",
"converter",
"=",
"new",
"Converter",
"(",
"$",
"this",
"->",
"logger",
",",
"$",
"this",
"->",
"cache",
")",
";",
"$",
"this",
"->",
"storeContent",
"(",
"$",
"converter",
",",
"$",
"content",
",",
"$",
"cachedVersion",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'finished updating cache from remote file'",
")",
";",
"}"
] | fetches a remote file, parses it and writes the result into the cache
if the local stored information are in the same version as the remote data no actions are
taken
@param string $remoteFile The code for the remote file to load
@throws \BrowscapPHP\Exception\FetcherException
@throws \BrowscapPHP\Helper\Exception
@throws \BrowscapPHP\Exception\ErrorCachedVersionException | [
"fetches",
"a",
"remote",
"file",
"parses",
"it",
"and",
"writes",
"the",
"result",
"into",
"the",
"cache",
"if",
"the",
"local",
"stored",
"information",
"are",
"in",
"the",
"same",
"version",
"as",
"the",
"remote",
"data",
"no",
"actions",
"are",
"taken"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/BrowscapUpdater.php#L219-L279 |
browscap/browscap-php | src/BrowscapUpdater.php | BrowscapUpdater.checkUpdate | public function checkUpdate() : ?int
{
$success = null;
try {
$cachedVersion = $this->cache->getItem('browscap.version', false, $success);
} catch (InvalidArgumentException $e) {
throw new ErrorCachedVersionException('an error occured while reading the data version from the cache', 0, $e);
}
if (! $cachedVersion) {
// could not load version from cache
throw new NoCachedVersionException('there is no cached version available, please update from remote');
}
$uri = (new IniLoader())->getRemoteVersionUrl();
try {
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $this->client->request('get', $uri, ['connect_timeout' => $this->connectTimeout]);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching version data from URI %s',
$uri
),
0,
$e
);
}
if (200 !== $response->getStatusCode()) {
throw new FetcherException(
sprintf(
'an error occured while fetching version data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
)
);
}
try {
$remoteVersion = $response->getBody()->getContents();
} catch (\Throwable $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching version data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
),
0,
$e
);
}
if (! $remoteVersion) {
// could not load remote version
throw new FetcherException(
'could not load version from remote location'
);
}
if ($cachedVersion && $remoteVersion && $remoteVersion <= $cachedVersion) {
throw new NoNewVersionException('there is no newer version available');
}
$this->logger->info(
'a newer version is available, local version: ' . $cachedVersion . ', remote version: ' . $remoteVersion
);
return (int) $cachedVersion;
} | php | public function checkUpdate() : ?int
{
$success = null;
try {
$cachedVersion = $this->cache->getItem('browscap.version', false, $success);
} catch (InvalidArgumentException $e) {
throw new ErrorCachedVersionException('an error occured while reading the data version from the cache', 0, $e);
}
if (! $cachedVersion) {
// could not load version from cache
throw new NoCachedVersionException('there is no cached version available, please update from remote');
}
$uri = (new IniLoader())->getRemoteVersionUrl();
try {
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $this->client->request('get', $uri, ['connect_timeout' => $this->connectTimeout]);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching version data from URI %s',
$uri
),
0,
$e
);
}
if (200 !== $response->getStatusCode()) {
throw new FetcherException(
sprintf(
'an error occured while fetching version data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
)
);
}
try {
$remoteVersion = $response->getBody()->getContents();
} catch (\Throwable $e) {
throw new FetcherException(
sprintf(
'an error occured while fetching version data from URI %s: StatusCode was %d',
$uri,
$response->getStatusCode()
),
0,
$e
);
}
if (! $remoteVersion) {
// could not load remote version
throw new FetcherException(
'could not load version from remote location'
);
}
if ($cachedVersion && $remoteVersion && $remoteVersion <= $cachedVersion) {
throw new NoNewVersionException('there is no newer version available');
}
$this->logger->info(
'a newer version is available, local version: ' . $cachedVersion . ', remote version: ' . $remoteVersion
);
return (int) $cachedVersion;
} | [
"public",
"function",
"checkUpdate",
"(",
")",
":",
"?",
"int",
"{",
"$",
"success",
"=",
"null",
";",
"try",
"{",
"$",
"cachedVersion",
"=",
"$",
"this",
"->",
"cache",
"->",
"getItem",
"(",
"'browscap.version'",
",",
"false",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"throw",
"new",
"ErrorCachedVersionException",
"(",
"'an error occured while reading the data version from the cache'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"!",
"$",
"cachedVersion",
")",
"{",
"// could not load version from cache",
"throw",
"new",
"NoCachedVersionException",
"(",
"'there is no cached version available, please update from remote'",
")",
";",
"}",
"$",
"uri",
"=",
"(",
"new",
"IniLoader",
"(",
")",
")",
"->",
"getRemoteVersionUrl",
"(",
")",
";",
"try",
"{",
"/** @var \\Psr\\Http\\Message\\ResponseInterface $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"request",
"(",
"'get'",
",",
"$",
"uri",
",",
"[",
"'connect_timeout'",
"=>",
"$",
"this",
"->",
"connectTimeout",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"GuzzleException",
"$",
"e",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching version data from URI %s'",
",",
"$",
"uri",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"200",
"!==",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching version data from URI %s: StatusCode was %d'",
",",
"$",
"uri",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
")",
";",
"}",
"try",
"{",
"$",
"remoteVersion",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"e",
")",
"{",
"throw",
"new",
"FetcherException",
"(",
"sprintf",
"(",
"'an error occured while fetching version data from URI %s: StatusCode was %d'",
",",
"$",
"uri",
",",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"!",
"$",
"remoteVersion",
")",
"{",
"// could not load remote version",
"throw",
"new",
"FetcherException",
"(",
"'could not load version from remote location'",
")",
";",
"}",
"if",
"(",
"$",
"cachedVersion",
"&&",
"$",
"remoteVersion",
"&&",
"$",
"remoteVersion",
"<=",
"$",
"cachedVersion",
")",
"{",
"throw",
"new",
"NoNewVersionException",
"(",
"'there is no newer version available'",
")",
";",
"}",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'a newer version is available, local version: '",
".",
"$",
"cachedVersion",
".",
"', remote version: '",
".",
"$",
"remoteVersion",
")",
";",
"return",
"(",
"int",
")",
"$",
"cachedVersion",
";",
"}"
] | checks if an update on a remote location for the local file or the cache
@throws \BrowscapPHP\Exception\FetcherException
@throws \BrowscapPHP\Exception\NoCachedVersionException
@throws \BrowscapPHP\Exception\ErrorCachedVersionException
@throws \BrowscapPHP\Exception\NoNewVersionException
@return int|null The actual cached version if a newer version is available, null otherwise | [
"checks",
"if",
"an",
"update",
"on",
"a",
"remote",
"location",
"for",
"the",
"local",
"file",
"or",
"the",
"cache"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/BrowscapUpdater.php#L291-L362 |
browscap/browscap-php | src/BrowscapUpdater.php | BrowscapUpdater.storeContent | private function storeContent(ConverterInterface $converter, string $content, ?int $cachedVersion) : void
{
$iniString = $this->sanitizeContent($content);
$iniVersion = $converter->getIniVersion($iniString);
if (! $cachedVersion || $iniVersion > $cachedVersion) {
$converter->storeVersion();
$converter->convertString($iniString);
}
} | php | private function storeContent(ConverterInterface $converter, string $content, ?int $cachedVersion) : void
{
$iniString = $this->sanitizeContent($content);
$iniVersion = $converter->getIniVersion($iniString);
if (! $cachedVersion || $iniVersion > $cachedVersion) {
$converter->storeVersion();
$converter->convertString($iniString);
}
} | [
"private",
"function",
"storeContent",
"(",
"ConverterInterface",
"$",
"converter",
",",
"string",
"$",
"content",
",",
"?",
"int",
"$",
"cachedVersion",
")",
":",
"void",
"{",
"$",
"iniString",
"=",
"$",
"this",
"->",
"sanitizeContent",
"(",
"$",
"content",
")",
";",
"$",
"iniVersion",
"=",
"$",
"converter",
"->",
"getIniVersion",
"(",
"$",
"iniString",
")",
";",
"if",
"(",
"!",
"$",
"cachedVersion",
"||",
"$",
"iniVersion",
">",
"$",
"cachedVersion",
")",
"{",
"$",
"converter",
"->",
"storeVersion",
"(",
")",
";",
"$",
"converter",
"->",
"convertString",
"(",
"$",
"iniString",
")",
";",
"}",
"}"
] | reads and parses an ini string and writes the results into the cache
@param \BrowscapPHP\Helper\ConverterInterface $converter
@param string $content
@param int|null $cachedVersion | [
"reads",
"and",
"parses",
"an",
"ini",
"string",
"and",
"writes",
"the",
"results",
"into",
"the",
"cache"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/BrowscapUpdater.php#L380-L389 |
browscap/browscap-php | src/Command/FetchCommand.php | FetchCommand.execute | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
/** @var string $file */
$file = $input->getArgument('file');
if (! $file) {
$file = $this->defaultIniFile;
}
$output->writeln(sprintf('write fetched file to %s', $file));
$logger->info('started fetching remote file');
$browscap = new BrowscapUpdater($cache, $logger);
/** @var string $remoteFileOption */
$remoteFileOption = $input->getOption('remote-file');
try {
$browscap->fetch($file, $remoteFileOption);
} catch (ErrorCachedVersionException $e) {
$logger->debug($e);
return 3;
} catch (FetcherException $e) {
$logger->debug($e);
return 9;
} catch (Exception $e) {
$logger->debug($e);
return 10;
}
$logger->info('finished fetching remote file');
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
/** @var string $file */
$file = $input->getArgument('file');
if (! $file) {
$file = $this->defaultIniFile;
}
$output->writeln(sprintf('write fetched file to %s', $file));
$logger->info('started fetching remote file');
$browscap = new BrowscapUpdater($cache, $logger);
/** @var string $remoteFileOption */
$remoteFileOption = $input->getOption('remote-file');
try {
$browscap->fetch($file, $remoteFileOption);
} catch (ErrorCachedVersionException $e) {
$logger->debug($e);
return 3;
} catch (FetcherException $e) {
$logger->debug($e);
return 9;
} catch (Exception $e) {
$logger->debug($e);
return 10;
}
$logger->info('finished fetching remote file');
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"int",
"{",
"$",
"logger",
"=",
"LoggerHelper",
"::",
"createDefaultLogger",
"(",
"$",
"output",
")",
";",
"/** @var string $cacheOption */",
"$",
"cacheOption",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'cache'",
")",
";",
"$",
"fileCache",
"=",
"new",
"FilesystemCache",
"(",
"$",
"cacheOption",
")",
";",
"$",
"cache",
"=",
"new",
"SimpleCacheAdapter",
"(",
"$",
"fileCache",
")",
";",
"/** @var string $file */",
"$",
"file",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'file'",
")",
";",
"if",
"(",
"!",
"$",
"file",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"defaultIniFile",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'write fetched file to %s'",
",",
"$",
"file",
")",
")",
";",
"$",
"logger",
"->",
"info",
"(",
"'started fetching remote file'",
")",
";",
"$",
"browscap",
"=",
"new",
"BrowscapUpdater",
"(",
"$",
"cache",
",",
"$",
"logger",
")",
";",
"/** @var string $remoteFileOption */",
"$",
"remoteFileOption",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'remote-file'",
")",
";",
"try",
"{",
"$",
"browscap",
"->",
"fetch",
"(",
"$",
"file",
",",
"$",
"remoteFileOption",
")",
";",
"}",
"catch",
"(",
"ErrorCachedVersionException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"3",
";",
"}",
"catch",
"(",
"FetcherException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"9",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"10",
";",
"}",
"$",
"logger",
"->",
"info",
"(",
"'finished fetching remote file'",
")",
";",
"return",
"0",
";",
"}"
] | @param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return int | [
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Input",
"\\",
"InputInterface",
"$input",
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Output",
"\\",
"OutputInterface",
"$output"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Command/FetchCommand.php#L77-L120 |
browscap/browscap-php | src/Parser/Helper/GetPattern.php | GetPattern.getPatterns | public function getPatterns(string $userAgent) : \Generator
{
$starts = Pattern::getHashForPattern($userAgent, true);
$length = strlen($userAgent);
// add special key to fall back to the default browser
$starts[] = str_repeat('z', 32);
// get patterns, first for the given browser and if that is not found,
// for the default browser (with a special key)
foreach ($starts as $tmpStart) {
$tmpSubkey = SubKey::getPatternCacheSubkey($tmpStart);
try {
if (! $this->cache->hasItem('browscap.patterns.' . $tmpSubkey, true)) {
$this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
continue;
}
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while checking a pattern in the cache', 0, $e));
continue;
}
$success = null;
try {
$file = $this->cache->getItem('browscap.patterns.' . $tmpSubkey, true, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the pattern data data from the cache', 0, $e));
continue;
}
if (! $success) {
$this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
continue;
}
if (! is_array($file) || ! count($file)) {
$this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" was empty');
continue;
}
$found = false;
foreach ($file as $buffer) {
[$tmpBuffer, $len, $patterns] = explode("\t", $buffer, 3);
if ($tmpBuffer === $tmpStart) {
if ($len <= $length) {
yield trim($patterns);
}
$found = true;
} elseif (true === $found) {
break;
}
}
}
yield '';
} | php | public function getPatterns(string $userAgent) : \Generator
{
$starts = Pattern::getHashForPattern($userAgent, true);
$length = strlen($userAgent);
// add special key to fall back to the default browser
$starts[] = str_repeat('z', 32);
// get patterns, first for the given browser and if that is not found,
// for the default browser (with a special key)
foreach ($starts as $tmpStart) {
$tmpSubkey = SubKey::getPatternCacheSubkey($tmpStart);
try {
if (! $this->cache->hasItem('browscap.patterns.' . $tmpSubkey, true)) {
$this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
continue;
}
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while checking a pattern in the cache', 0, $e));
continue;
}
$success = null;
try {
$file = $this->cache->getItem('browscap.patterns.' . $tmpSubkey, true, $success);
} catch (InvalidArgumentException $e) {
$this->logger->error(new \InvalidArgumentException('an error occured while reading the pattern data data from the cache', 0, $e));
continue;
}
if (! $success) {
$this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
continue;
}
if (! is_array($file) || ! count($file)) {
$this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" was empty');
continue;
}
$found = false;
foreach ($file as $buffer) {
[$tmpBuffer, $len, $patterns] = explode("\t", $buffer, 3);
if ($tmpBuffer === $tmpStart) {
if ($len <= $length) {
yield trim($patterns);
}
$found = true;
} elseif (true === $found) {
break;
}
}
}
yield '';
} | [
"public",
"function",
"getPatterns",
"(",
"string",
"$",
"userAgent",
")",
":",
"\\",
"Generator",
"{",
"$",
"starts",
"=",
"Pattern",
"::",
"getHashForPattern",
"(",
"$",
"userAgent",
",",
"true",
")",
";",
"$",
"length",
"=",
"strlen",
"(",
"$",
"userAgent",
")",
";",
"// add special key to fall back to the default browser",
"$",
"starts",
"[",
"]",
"=",
"str_repeat",
"(",
"'z'",
",",
"32",
")",
";",
"// get patterns, first for the given browser and if that is not found,",
"// for the default browser (with a special key)",
"foreach",
"(",
"$",
"starts",
"as",
"$",
"tmpStart",
")",
"{",
"$",
"tmpSubkey",
"=",
"SubKey",
"::",
"getPatternCacheSubkey",
"(",
"$",
"tmpStart",
")",
";",
"try",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
"->",
"hasItem",
"(",
"'browscap.patterns.'",
".",
"$",
"tmpSubkey",
",",
"true",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'cache key \"browscap.patterns.'",
".",
"$",
"tmpSubkey",
".",
"'\" not found'",
")",
";",
"continue",
";",
"}",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while checking a pattern in the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"continue",
";",
"}",
"$",
"success",
"=",
"null",
";",
"try",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"cache",
"->",
"getItem",
"(",
"'browscap.patterns.'",
".",
"$",
"tmpSubkey",
",",
"true",
",",
"$",
"success",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"new",
"\\",
"InvalidArgumentException",
"(",
"'an error occured while reading the pattern data data from the cache'",
",",
"0",
",",
"$",
"e",
")",
")",
";",
"continue",
";",
"}",
"if",
"(",
"!",
"$",
"success",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'cache key \"browscap.patterns.'",
".",
"$",
"tmpSubkey",
".",
"'\" not found'",
")",
";",
"continue",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"file",
")",
"||",
"!",
"count",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'cache key \"browscap.patterns.'",
".",
"$",
"tmpSubkey",
".",
"'\" was empty'",
")",
";",
"continue",
";",
"}",
"$",
"found",
"=",
"false",
";",
"foreach",
"(",
"$",
"file",
"as",
"$",
"buffer",
")",
"{",
"[",
"$",
"tmpBuffer",
",",
"$",
"len",
",",
"$",
"patterns",
"]",
"=",
"explode",
"(",
"\"\\t\"",
",",
"$",
"buffer",
",",
"3",
")",
";",
"if",
"(",
"$",
"tmpBuffer",
"===",
"$",
"tmpStart",
")",
"{",
"if",
"(",
"$",
"len",
"<=",
"$",
"length",
")",
"{",
"yield",
"trim",
"(",
"$",
"patterns",
")",
";",
"}",
"$",
"found",
"=",
"true",
";",
"}",
"elseif",
"(",
"true",
"===",
"$",
"found",
")",
"{",
"break",
";",
"}",
"}",
"}",
"yield",
"''",
";",
"}"
] | Gets some possible patterns that have to be matched against the user agent. With the given
user agent string, we can optimize the search for potential patterns:
- We check the first characters of the user agent (or better: a hash, generated from it)
- We compare the length of the pattern with the length of the user agent
(the pattern cannot be longer than the user agent!)
@param string $userAgent
@return \Generator | [
"Gets",
"some",
"possible",
"patterns",
"that",
"have",
"to",
"be",
"matched",
"against",
"the",
"user",
"agent",
".",
"With",
"the",
"given",
"user",
"agent",
"string",
"we",
"can",
"optimize",
"the",
"search",
"for",
"potential",
"patterns",
":",
"-",
"We",
"check",
"the",
"first",
"characters",
"of",
"the",
"user",
"agent",
"(",
"or",
"better",
":",
"a",
"hash",
"generated",
"from",
"it",
")",
"-",
"We",
"compare",
"the",
"length",
"of",
"the",
"pattern",
"with",
"the",
"length",
"of",
"the",
"user",
"agent",
"(",
"the",
"pattern",
"cannot",
"be",
"longer",
"than",
"the",
"user",
"agent!",
")"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Helper/GetPattern.php#L52-L117 |
browscap/browscap-php | src/Command/ConvertCommand.php | ConvertCommand.execute | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
$logger->info('initializing converting process');
$browscap = new BrowscapUpdater($cache, $logger);
$logger->info('started converting local file');
/** @var string $file */
$file = $input->getArgument('file');
if (! $file) {
$file = $this->defaultIniFile;
}
$output->writeln(sprintf('converting file %s', $file));
try {
$browscap->convertFile($file);
} catch (Exception\FileNameMissingException $e) {
$logger->debug($e);
return 6;
} catch (Exception\FileNotFoundException $e) {
$logger->debug($e);
return 7;
} catch (Exception\ErrorReadingFileException $e) {
$logger->debug($e);
return 8;
}
$logger->info('finished converting local file');
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
$logger->info('initializing converting process');
$browscap = new BrowscapUpdater($cache, $logger);
$logger->info('started converting local file');
/** @var string $file */
$file = $input->getArgument('file');
if (! $file) {
$file = $this->defaultIniFile;
}
$output->writeln(sprintf('converting file %s', $file));
try {
$browscap->convertFile($file);
} catch (Exception\FileNameMissingException $e) {
$logger->debug($e);
return 6;
} catch (Exception\FileNotFoundException $e) {
$logger->debug($e);
return 7;
} catch (Exception\ErrorReadingFileException $e) {
$logger->debug($e);
return 8;
}
$logger->info('finished converting local file');
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"int",
"{",
"$",
"logger",
"=",
"LoggerHelper",
"::",
"createDefaultLogger",
"(",
"$",
"output",
")",
";",
"/** @var string $cacheOption */",
"$",
"cacheOption",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'cache'",
")",
";",
"$",
"fileCache",
"=",
"new",
"FilesystemCache",
"(",
"$",
"cacheOption",
")",
";",
"$",
"cache",
"=",
"new",
"SimpleCacheAdapter",
"(",
"$",
"fileCache",
")",
";",
"$",
"logger",
"->",
"info",
"(",
"'initializing converting process'",
")",
";",
"$",
"browscap",
"=",
"new",
"BrowscapUpdater",
"(",
"$",
"cache",
",",
"$",
"logger",
")",
";",
"$",
"logger",
"->",
"info",
"(",
"'started converting local file'",
")",
";",
"/** @var string $file */",
"$",
"file",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'file'",
")",
";",
"if",
"(",
"!",
"$",
"file",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"defaultIniFile",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'converting file %s'",
",",
"$",
"file",
")",
")",
";",
"try",
"{",
"$",
"browscap",
"->",
"convertFile",
"(",
"$",
"file",
")",
";",
"}",
"catch",
"(",
"Exception",
"\\",
"FileNameMissingException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"6",
";",
"}",
"catch",
"(",
"Exception",
"\\",
"FileNotFoundException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"7",
";",
"}",
"catch",
"(",
"Exception",
"\\",
"ErrorReadingFileException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
"$",
"e",
")",
";",
"return",
"8",
";",
"}",
"$",
"logger",
"->",
"info",
"(",
"'finished converting local file'",
")",
";",
"return",
"0",
";",
"}"
] | @param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return int | [
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Input",
"\\",
"InputInterface",
"$input",
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Output",
"\\",
"OutputInterface",
"$output"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Command/ConvertCommand.php#L66-L108 |
browscap/browscap-php | src/IniParser/IniParser.php | IniParser.createIniParts | public function createIniParts(string $content) : \Generator
{
// get all patterns from the ini file in the correct order,
// so that we can calculate with index number of the resulting array,
// which part to use when the ini file is splitted into its sections.
preg_match_all('/(?<=\[)(?:[^\r\n]+)(?=\])/m', $content, $patternPositions);
$patternPositions = $patternPositions[0];
// split the ini file into sections and save the data in one line with a hash of the beloging
// pattern (filtered in the previous step)
$iniParts = preg_split('/\[[^\r\n]+\]/', $content);
if (false === $iniParts) {
throw new \UnexpectedValueException('an error occured while splitting content into parts');
}
$contents = [];
$propertyFormatter = new PropertyFormatter(new PropertyHolder());
foreach ($patternPositions as $position => $pattern) {
$pattern = strtolower($pattern);
$patternhash = Pattern::getHashForParts($pattern);
$subkey = SubKey::getIniPartCacheSubKey($patternhash);
if (! isset($contents[$subkey])) {
$contents[$subkey] = [];
}
if (!array_key_exists($position + 1, $iniParts)) {
throw new \OutOfRangeException(sprintf('could not find position %d inside iniparts', $position + 1));
}
$browserProperties = parse_ini_string($iniParts[($position + 1)], false, INI_SCANNER_RAW);
if (false === $browserProperties) {
throw new \UnexpectedValueException(sprintf('could ini parse position %d inside iniparts', $position + 1));
}
foreach (array_keys($browserProperties) as $property) {
$browserProperties[$property] = $propertyFormatter->formatPropertyValue(
$browserProperties[$property],
$property
);
}
try {
// the position has to be moved by one, because the header of the ini file
// is also returned as a part
$contents[$subkey][] = $patternhash . "\t" . \ExceptionalJSON\encode(
$browserProperties,
JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
);
} catch (EncodeErrorException $e) {
throw new \UnexpectedValueException('json encoding content failed', 0, $e);
}
}
unset($patternPositions, $iniParts);
$subkeys = array_flip(SubKey::getAllIniPartCacheSubKeys());
foreach ($contents as $subkey => $cacheContent) {
yield $subkey => $cacheContent;
unset($subkeys[$subkey]);
}
foreach (array_keys($subkeys) as $subkey) {
$subkey = (string) $subkey;
yield $subkey => '';
}
} | php | public function createIniParts(string $content) : \Generator
{
// get all patterns from the ini file in the correct order,
// so that we can calculate with index number of the resulting array,
// which part to use when the ini file is splitted into its sections.
preg_match_all('/(?<=\[)(?:[^\r\n]+)(?=\])/m', $content, $patternPositions);
$patternPositions = $patternPositions[0];
// split the ini file into sections and save the data in one line with a hash of the beloging
// pattern (filtered in the previous step)
$iniParts = preg_split('/\[[^\r\n]+\]/', $content);
if (false === $iniParts) {
throw new \UnexpectedValueException('an error occured while splitting content into parts');
}
$contents = [];
$propertyFormatter = new PropertyFormatter(new PropertyHolder());
foreach ($patternPositions as $position => $pattern) {
$pattern = strtolower($pattern);
$patternhash = Pattern::getHashForParts($pattern);
$subkey = SubKey::getIniPartCacheSubKey($patternhash);
if (! isset($contents[$subkey])) {
$contents[$subkey] = [];
}
if (!array_key_exists($position + 1, $iniParts)) {
throw new \OutOfRangeException(sprintf('could not find position %d inside iniparts', $position + 1));
}
$browserProperties = parse_ini_string($iniParts[($position + 1)], false, INI_SCANNER_RAW);
if (false === $browserProperties) {
throw new \UnexpectedValueException(sprintf('could ini parse position %d inside iniparts', $position + 1));
}
foreach (array_keys($browserProperties) as $property) {
$browserProperties[$property] = $propertyFormatter->formatPropertyValue(
$browserProperties[$property],
$property
);
}
try {
// the position has to be moved by one, because the header of the ini file
// is also returned as a part
$contents[$subkey][] = $patternhash . "\t" . \ExceptionalJSON\encode(
$browserProperties,
JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
);
} catch (EncodeErrorException $e) {
throw new \UnexpectedValueException('json encoding content failed', 0, $e);
}
}
unset($patternPositions, $iniParts);
$subkeys = array_flip(SubKey::getAllIniPartCacheSubKeys());
foreach ($contents as $subkey => $cacheContent) {
yield $subkey => $cacheContent;
unset($subkeys[$subkey]);
}
foreach (array_keys($subkeys) as $subkey) {
$subkey = (string) $subkey;
yield $subkey => '';
}
} | [
"public",
"function",
"createIniParts",
"(",
"string",
"$",
"content",
")",
":",
"\\",
"Generator",
"{",
"// get all patterns from the ini file in the correct order,",
"// so that we can calculate with index number of the resulting array,",
"// which part to use when the ini file is splitted into its sections.",
"preg_match_all",
"(",
"'/(?<=\\[)(?:[^\\r\\n]+)(?=\\])/m'",
",",
"$",
"content",
",",
"$",
"patternPositions",
")",
";",
"$",
"patternPositions",
"=",
"$",
"patternPositions",
"[",
"0",
"]",
";",
"// split the ini file into sections and save the data in one line with a hash of the beloging",
"// pattern (filtered in the previous step)",
"$",
"iniParts",
"=",
"preg_split",
"(",
"'/\\[[^\\r\\n]+\\]/'",
",",
"$",
"content",
")",
";",
"if",
"(",
"false",
"===",
"$",
"iniParts",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'an error occured while splitting content into parts'",
")",
";",
"}",
"$",
"contents",
"=",
"[",
"]",
";",
"$",
"propertyFormatter",
"=",
"new",
"PropertyFormatter",
"(",
"new",
"PropertyHolder",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"patternPositions",
"as",
"$",
"position",
"=>",
"$",
"pattern",
")",
"{",
"$",
"pattern",
"=",
"strtolower",
"(",
"$",
"pattern",
")",
";",
"$",
"patternhash",
"=",
"Pattern",
"::",
"getHashForParts",
"(",
"$",
"pattern",
")",
";",
"$",
"subkey",
"=",
"SubKey",
"::",
"getIniPartCacheSubKey",
"(",
"$",
"patternhash",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"contents",
"[",
"$",
"subkey",
"]",
")",
")",
"{",
"$",
"contents",
"[",
"$",
"subkey",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"position",
"+",
"1",
",",
"$",
"iniParts",
")",
")",
"{",
"throw",
"new",
"\\",
"OutOfRangeException",
"(",
"sprintf",
"(",
"'could not find position %d inside iniparts'",
",",
"$",
"position",
"+",
"1",
")",
")",
";",
"}",
"$",
"browserProperties",
"=",
"parse_ini_string",
"(",
"$",
"iniParts",
"[",
"(",
"$",
"position",
"+",
"1",
")",
"]",
",",
"false",
",",
"INI_SCANNER_RAW",
")",
";",
"if",
"(",
"false",
"===",
"$",
"browserProperties",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"sprintf",
"(",
"'could ini parse position %d inside iniparts'",
",",
"$",
"position",
"+",
"1",
")",
")",
";",
"}",
"foreach",
"(",
"array_keys",
"(",
"$",
"browserProperties",
")",
"as",
"$",
"property",
")",
"{",
"$",
"browserProperties",
"[",
"$",
"property",
"]",
"=",
"$",
"propertyFormatter",
"->",
"formatPropertyValue",
"(",
"$",
"browserProperties",
"[",
"$",
"property",
"]",
",",
"$",
"property",
")",
";",
"}",
"try",
"{",
"// the position has to be moved by one, because the header of the ini file",
"// is also returned as a part",
"$",
"contents",
"[",
"$",
"subkey",
"]",
"[",
"]",
"=",
"$",
"patternhash",
".",
"\"\\t\"",
".",
"\\",
"ExceptionalJSON",
"\\",
"encode",
"(",
"$",
"browserProperties",
",",
"JSON_HEX_TAG",
"|",
"JSON_HEX_APOS",
"|",
"JSON_HEX_QUOT",
"|",
"JSON_HEX_AMP",
")",
";",
"}",
"catch",
"(",
"EncodeErrorException",
"$",
"e",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'json encoding content failed'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"}",
"unset",
"(",
"$",
"patternPositions",
",",
"$",
"iniParts",
")",
";",
"$",
"subkeys",
"=",
"array_flip",
"(",
"SubKey",
"::",
"getAllIniPartCacheSubKeys",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"contents",
"as",
"$",
"subkey",
"=>",
"$",
"cacheContent",
")",
"{",
"yield",
"$",
"subkey",
"=>",
"$",
"cacheContent",
";",
"unset",
"(",
"$",
"subkeys",
"[",
"$",
"subkey",
"]",
")",
";",
"}",
"foreach",
"(",
"array_keys",
"(",
"$",
"subkeys",
")",
"as",
"$",
"subkey",
")",
"{",
"$",
"subkey",
"=",
"(",
"string",
")",
"$",
"subkey",
";",
"yield",
"$",
"subkey",
"=>",
"''",
";",
"}",
"}"
] | Creates new ini part cache files
@param string $content
@throws \OutOfRangeException
@throws \UnexpectedValueException
@return \Generator | [
"Creates",
"new",
"ini",
"part",
"cache",
"files"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/IniParser/IniParser.php#L38-L109 |
browscap/browscap-php | src/IniParser/IniParser.php | IniParser.createPatterns | public function createPatterns($content) : \Generator
{
// get all relevant patterns from the INI file
// - containing "*" or "?"
// - not containing "*" or "?", but not having a comment
preg_match_all(
'/(?<=\[)(?:[^\r\n]*[?*][^\r\n]*)(?=\])|(?<=\[)(?:[^\r\n*?]+)(?=\])(?![^\[]*Comment=)/m',
$content,
$matches
);
if (empty($matches[0]) || ! is_array($matches[0])) {
yield '' => '';
return;
}
$quoterHelper = new Quoter();
$matches = $matches[0];
usort($matches, [$this, 'compareBcStrings']);
// build an array to structure the data. this requires some memory, but we need this step to be able to
// sort the data in the way we need it (see below).
$data = [];
foreach ($matches as $pattern) {
if ('GJK_Browscap_Version' === $pattern) {
continue;
}
$pattern = strtolower($pattern);
$patternhash = Pattern::getHashForPattern($pattern, false)[0];
$tmpLength = Pattern::getPatternLength($pattern);
// special handling of default entry
if (0 === $tmpLength) {
$patternhash = str_repeat('z', 32);
}
if (! isset($data[$patternhash])) {
$data[$patternhash] = [];
}
if (! isset($data[$patternhash][$tmpLength])) {
$data[$patternhash][$tmpLength] = [];
}
$pattern = $quoterHelper->pregQuote($pattern);
// Check if the pattern contains digits - in this case we replace them with a digit regular expression,
// so that very similar patterns (e.g. only with different browser version numbers) can be compressed.
// This helps to speed up the first (and most expensive) part of the pattern search a lot.
if (false !== strpbrk($pattern, '0123456789')) {
$compressedPattern = preg_replace('/\d/', '[\d]', $pattern);
if (! in_array($compressedPattern, $data[$patternhash][$tmpLength])) {
$data[$patternhash][$tmpLength][] = $compressedPattern;
}
} else {
$data[$patternhash][$tmpLength][] = $pattern;
}
}
unset($matches);
// sorting of the data is important to check the patterns later in the correct order, because
// we need to check the most specific (=longest) patterns first, and the least specific
// (".*" for "Default Browser") last.
//
// sort by pattern start to group them
ksort($data);
// and then by pattern length (longest first)
foreach (array_keys($data) as $key) {
krsort($data[$key]);
}
// write optimized file (grouped by the first character of the has, generated from the pattern
// start) with multiple patterns joined by tabs. this is to speed up loading of the data (small
// array with pattern strings instead of an large array with single patterns) and also enables
// us to search for multiple patterns in one preg_match call for a fast first search
// (3-10 faster), followed by a detailed search for each single pattern.
$contents = [];
foreach ($data as $patternhash => $tmpEntries) {
if (empty($tmpEntries)) {
continue;
}
$subkey = SubKey::getPatternCacheSubkey($patternhash);
if (! isset($contents[$subkey])) {
$contents[$subkey] = [];
}
foreach ($tmpEntries as $tmpLength => $tmpPatterns) {
if (empty($tmpPatterns)) {
continue;
}
$chunks = array_chunk($tmpPatterns, self::COUNT_PATTERN);
foreach ($chunks as $chunk) {
$contents[$subkey][] = $patternhash . "\t" . $tmpLength . "\t" . implode("\t", $chunk);
}
}
}
unset($data);
$subkeys = SubKey::getAllPatternCacheSubkeys();
foreach ($contents as $subkey => $content) {
yield $subkey => $content;
unset($subkeys[$subkey]);
}
foreach (array_keys($subkeys) as $subkey) {
$subkey = (string) $subkey;
yield $subkey => '';
}
} | php | public function createPatterns($content) : \Generator
{
// get all relevant patterns from the INI file
// - containing "*" or "?"
// - not containing "*" or "?", but not having a comment
preg_match_all(
'/(?<=\[)(?:[^\r\n]*[?*][^\r\n]*)(?=\])|(?<=\[)(?:[^\r\n*?]+)(?=\])(?![^\[]*Comment=)/m',
$content,
$matches
);
if (empty($matches[0]) || ! is_array($matches[0])) {
yield '' => '';
return;
}
$quoterHelper = new Quoter();
$matches = $matches[0];
usort($matches, [$this, 'compareBcStrings']);
// build an array to structure the data. this requires some memory, but we need this step to be able to
// sort the data in the way we need it (see below).
$data = [];
foreach ($matches as $pattern) {
if ('GJK_Browscap_Version' === $pattern) {
continue;
}
$pattern = strtolower($pattern);
$patternhash = Pattern::getHashForPattern($pattern, false)[0];
$tmpLength = Pattern::getPatternLength($pattern);
// special handling of default entry
if (0 === $tmpLength) {
$patternhash = str_repeat('z', 32);
}
if (! isset($data[$patternhash])) {
$data[$patternhash] = [];
}
if (! isset($data[$patternhash][$tmpLength])) {
$data[$patternhash][$tmpLength] = [];
}
$pattern = $quoterHelper->pregQuote($pattern);
// Check if the pattern contains digits - in this case we replace them with a digit regular expression,
// so that very similar patterns (e.g. only with different browser version numbers) can be compressed.
// This helps to speed up the first (and most expensive) part of the pattern search a lot.
if (false !== strpbrk($pattern, '0123456789')) {
$compressedPattern = preg_replace('/\d/', '[\d]', $pattern);
if (! in_array($compressedPattern, $data[$patternhash][$tmpLength])) {
$data[$patternhash][$tmpLength][] = $compressedPattern;
}
} else {
$data[$patternhash][$tmpLength][] = $pattern;
}
}
unset($matches);
// sorting of the data is important to check the patterns later in the correct order, because
// we need to check the most specific (=longest) patterns first, and the least specific
// (".*" for "Default Browser") last.
//
// sort by pattern start to group them
ksort($data);
// and then by pattern length (longest first)
foreach (array_keys($data) as $key) {
krsort($data[$key]);
}
// write optimized file (grouped by the first character of the has, generated from the pattern
// start) with multiple patterns joined by tabs. this is to speed up loading of the data (small
// array with pattern strings instead of an large array with single patterns) and also enables
// us to search for multiple patterns in one preg_match call for a fast first search
// (3-10 faster), followed by a detailed search for each single pattern.
$contents = [];
foreach ($data as $patternhash => $tmpEntries) {
if (empty($tmpEntries)) {
continue;
}
$subkey = SubKey::getPatternCacheSubkey($patternhash);
if (! isset($contents[$subkey])) {
$contents[$subkey] = [];
}
foreach ($tmpEntries as $tmpLength => $tmpPatterns) {
if (empty($tmpPatterns)) {
continue;
}
$chunks = array_chunk($tmpPatterns, self::COUNT_PATTERN);
foreach ($chunks as $chunk) {
$contents[$subkey][] = $patternhash . "\t" . $tmpLength . "\t" . implode("\t", $chunk);
}
}
}
unset($data);
$subkeys = SubKey::getAllPatternCacheSubkeys();
foreach ($contents as $subkey => $content) {
yield $subkey => $content;
unset($subkeys[$subkey]);
}
foreach (array_keys($subkeys) as $subkey) {
$subkey = (string) $subkey;
yield $subkey => '';
}
} | [
"public",
"function",
"createPatterns",
"(",
"$",
"content",
")",
":",
"\\",
"Generator",
"{",
"// get all relevant patterns from the INI file",
"// - containing \"*\" or \"?\"",
"// - not containing \"*\" or \"?\", but not having a comment",
"preg_match_all",
"(",
"'/(?<=\\[)(?:[^\\r\\n]*[?*][^\\r\\n]*)(?=\\])|(?<=\\[)(?:[^\\r\\n*?]+)(?=\\])(?![^\\[]*Comment=)/m'",
",",
"$",
"content",
",",
"$",
"matches",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
"||",
"!",
"is_array",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
")",
"{",
"yield",
"''",
"=>",
"''",
";",
"return",
";",
"}",
"$",
"quoterHelper",
"=",
"new",
"Quoter",
"(",
")",
";",
"$",
"matches",
"=",
"$",
"matches",
"[",
"0",
"]",
";",
"usort",
"(",
"$",
"matches",
",",
"[",
"$",
"this",
",",
"'compareBcStrings'",
"]",
")",
";",
"// build an array to structure the data. this requires some memory, but we need this step to be able to",
"// sort the data in the way we need it (see below).",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"matches",
"as",
"$",
"pattern",
")",
"{",
"if",
"(",
"'GJK_Browscap_Version'",
"===",
"$",
"pattern",
")",
"{",
"continue",
";",
"}",
"$",
"pattern",
"=",
"strtolower",
"(",
"$",
"pattern",
")",
";",
"$",
"patternhash",
"=",
"Pattern",
"::",
"getHashForPattern",
"(",
"$",
"pattern",
",",
"false",
")",
"[",
"0",
"]",
";",
"$",
"tmpLength",
"=",
"Pattern",
"::",
"getPatternLength",
"(",
"$",
"pattern",
")",
";",
"// special handling of default entry",
"if",
"(",
"0",
"===",
"$",
"tmpLength",
")",
"{",
"$",
"patternhash",
"=",
"str_repeat",
"(",
"'z'",
",",
"32",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"$",
"patternhash",
"]",
")",
")",
"{",
"$",
"data",
"[",
"$",
"patternhash",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"$",
"patternhash",
"]",
"[",
"$",
"tmpLength",
"]",
")",
")",
"{",
"$",
"data",
"[",
"$",
"patternhash",
"]",
"[",
"$",
"tmpLength",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"pattern",
"=",
"$",
"quoterHelper",
"->",
"pregQuote",
"(",
"$",
"pattern",
")",
";",
"// Check if the pattern contains digits - in this case we replace them with a digit regular expression,",
"// so that very similar patterns (e.g. only with different browser version numbers) can be compressed.",
"// This helps to speed up the first (and most expensive) part of the pattern search a lot.",
"if",
"(",
"false",
"!==",
"strpbrk",
"(",
"$",
"pattern",
",",
"'0123456789'",
")",
")",
"{",
"$",
"compressedPattern",
"=",
"preg_replace",
"(",
"'/\\d/'",
",",
"'[\\d]'",
",",
"$",
"pattern",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"compressedPattern",
",",
"$",
"data",
"[",
"$",
"patternhash",
"]",
"[",
"$",
"tmpLength",
"]",
")",
")",
"{",
"$",
"data",
"[",
"$",
"patternhash",
"]",
"[",
"$",
"tmpLength",
"]",
"[",
"]",
"=",
"$",
"compressedPattern",
";",
"}",
"}",
"else",
"{",
"$",
"data",
"[",
"$",
"patternhash",
"]",
"[",
"$",
"tmpLength",
"]",
"[",
"]",
"=",
"$",
"pattern",
";",
"}",
"}",
"unset",
"(",
"$",
"matches",
")",
";",
"// sorting of the data is important to check the patterns later in the correct order, because",
"// we need to check the most specific (=longest) patterns first, and the least specific",
"// (\".*\" for \"Default Browser\") last.",
"//",
"// sort by pattern start to group them",
"ksort",
"(",
"$",
"data",
")",
";",
"// and then by pattern length (longest first)",
"foreach",
"(",
"array_keys",
"(",
"$",
"data",
")",
"as",
"$",
"key",
")",
"{",
"krsort",
"(",
"$",
"data",
"[",
"$",
"key",
"]",
")",
";",
"}",
"// write optimized file (grouped by the first character of the has, generated from the pattern",
"// start) with multiple patterns joined by tabs. this is to speed up loading of the data (small",
"// array with pattern strings instead of an large array with single patterns) and also enables",
"// us to search for multiple patterns in one preg_match call for a fast first search",
"// (3-10 faster), followed by a detailed search for each single pattern.",
"$",
"contents",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"patternhash",
"=>",
"$",
"tmpEntries",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tmpEntries",
")",
")",
"{",
"continue",
";",
"}",
"$",
"subkey",
"=",
"SubKey",
"::",
"getPatternCacheSubkey",
"(",
"$",
"patternhash",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"contents",
"[",
"$",
"subkey",
"]",
")",
")",
"{",
"$",
"contents",
"[",
"$",
"subkey",
"]",
"=",
"[",
"]",
";",
"}",
"foreach",
"(",
"$",
"tmpEntries",
"as",
"$",
"tmpLength",
"=>",
"$",
"tmpPatterns",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tmpPatterns",
")",
")",
"{",
"continue",
";",
"}",
"$",
"chunks",
"=",
"array_chunk",
"(",
"$",
"tmpPatterns",
",",
"self",
"::",
"COUNT_PATTERN",
")",
";",
"foreach",
"(",
"$",
"chunks",
"as",
"$",
"chunk",
")",
"{",
"$",
"contents",
"[",
"$",
"subkey",
"]",
"[",
"]",
"=",
"$",
"patternhash",
".",
"\"\\t\"",
".",
"$",
"tmpLength",
".",
"\"\\t\"",
".",
"implode",
"(",
"\"\\t\"",
",",
"$",
"chunk",
")",
";",
"}",
"}",
"}",
"unset",
"(",
"$",
"data",
")",
";",
"$",
"subkeys",
"=",
"SubKey",
"::",
"getAllPatternCacheSubkeys",
"(",
")",
";",
"foreach",
"(",
"$",
"contents",
"as",
"$",
"subkey",
"=>",
"$",
"content",
")",
"{",
"yield",
"$",
"subkey",
"=>",
"$",
"content",
";",
"unset",
"(",
"$",
"subkeys",
"[",
"$",
"subkey",
"]",
")",
";",
"}",
"foreach",
"(",
"array_keys",
"(",
"$",
"subkeys",
")",
"as",
"$",
"subkey",
")",
"{",
"$",
"subkey",
"=",
"(",
"string",
")",
"$",
"subkey",
";",
"yield",
"$",
"subkey",
"=>",
"''",
";",
"}",
"}"
] | Creates new pattern cache files
@param string $content
@return \Generator | [
"Creates",
"new",
"pattern",
"cache",
"files"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/IniParser/IniParser.php#L118-L238 |
browscap/browscap-php | src/IniParser/IniParser.php | IniParser.compareBcStrings | private function compareBcStrings(string $a, string $b) : int
{
$a_len = strlen($a);
$b_len = strlen($b);
if ($a_len > $b_len) {
return -1;
}
if ($a_len < $b_len) {
return 1;
}
$a_len = strlen(str_replace(['*', '?'], '', $a));
$b_len = strlen(str_replace(['*', '?'], '', $b));
if ($a_len > $b_len) {
return -1;
}
if ($a_len < $b_len) {
return 1;
}
return 0;
} | php | private function compareBcStrings(string $a, string $b) : int
{
$a_len = strlen($a);
$b_len = strlen($b);
if ($a_len > $b_len) {
return -1;
}
if ($a_len < $b_len) {
return 1;
}
$a_len = strlen(str_replace(['*', '?'], '', $a));
$b_len = strlen(str_replace(['*', '?'], '', $b));
if ($a_len > $b_len) {
return -1;
}
if ($a_len < $b_len) {
return 1;
}
return 0;
} | [
"private",
"function",
"compareBcStrings",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"int",
"{",
"$",
"a_len",
"=",
"strlen",
"(",
"$",
"a",
")",
";",
"$",
"b_len",
"=",
"strlen",
"(",
"$",
"b",
")",
";",
"if",
"(",
"$",
"a_len",
">",
"$",
"b_len",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"$",
"a_len",
"<",
"$",
"b_len",
")",
"{",
"return",
"1",
";",
"}",
"$",
"a_len",
"=",
"strlen",
"(",
"str_replace",
"(",
"[",
"'*'",
",",
"'?'",
"]",
",",
"''",
",",
"$",
"a",
")",
")",
";",
"$",
"b_len",
"=",
"strlen",
"(",
"str_replace",
"(",
"[",
"'*'",
",",
"'?'",
"]",
",",
"''",
",",
"$",
"b",
")",
")",
";",
"if",
"(",
"$",
"a_len",
">",
"$",
"b_len",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"$",
"a_len",
"<",
"$",
"b_len",
")",
"{",
"return",
"1",
";",
"}",
"return",
"0",
";",
"}"
] | @param string $a
@param string $b
@return int | [
"@param",
"string",
"$a",
"@param",
"string",
"$b"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/IniParser/IniParser.php#L246-L271 |
browscap/browscap-php | src/Command/CheckUpdateCommand.php | CheckUpdateCommand.execute | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
$logger->debug('started checking for new version of remote file');
$browscap = new BrowscapUpdater($cache, $logger);
try {
$browscap->checkUpdate();
} catch (NoCachedVersionException $e) {
return 1;
} catch (NoNewVersionException $e) {
// no newer version available
$logger->info('there is no newer version available');
return 2;
} catch (ErrorCachedVersionException $e) {
$logger->info($e);
return 3;
} catch (FetcherException $e) {
$logger->info($e);
return 4;
} catch (\Throwable $e) {
$logger->info($e);
return 5;
}
$logger->debug('finished checking for new version of remote file');
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output) : int
{
$logger = LoggerHelper::createDefaultLogger($output);
/** @var string $cacheOption */
$cacheOption = $input->getOption('cache');
$fileCache = new FilesystemCache($cacheOption);
$cache = new SimpleCacheAdapter($fileCache);
$logger->debug('started checking for new version of remote file');
$browscap = new BrowscapUpdater($cache, $logger);
try {
$browscap->checkUpdate();
} catch (NoCachedVersionException $e) {
return 1;
} catch (NoNewVersionException $e) {
// no newer version available
$logger->info('there is no newer version available');
return 2;
} catch (ErrorCachedVersionException $e) {
$logger->info($e);
return 3;
} catch (FetcherException $e) {
$logger->info($e);
return 4;
} catch (\Throwable $e) {
$logger->info($e);
return 5;
}
$logger->debug('finished checking for new version of remote file');
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"int",
"{",
"$",
"logger",
"=",
"LoggerHelper",
"::",
"createDefaultLogger",
"(",
"$",
"output",
")",
";",
"/** @var string $cacheOption */",
"$",
"cacheOption",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'cache'",
")",
";",
"$",
"fileCache",
"=",
"new",
"FilesystemCache",
"(",
"$",
"cacheOption",
")",
";",
"$",
"cache",
"=",
"new",
"SimpleCacheAdapter",
"(",
"$",
"fileCache",
")",
";",
"$",
"logger",
"->",
"debug",
"(",
"'started checking for new version of remote file'",
")",
";",
"$",
"browscap",
"=",
"new",
"BrowscapUpdater",
"(",
"$",
"cache",
",",
"$",
"logger",
")",
";",
"try",
"{",
"$",
"browscap",
"->",
"checkUpdate",
"(",
")",
";",
"}",
"catch",
"(",
"NoCachedVersionException",
"$",
"e",
")",
"{",
"return",
"1",
";",
"}",
"catch",
"(",
"NoNewVersionException",
"$",
"e",
")",
"{",
"// no newer version available",
"$",
"logger",
"->",
"info",
"(",
"'there is no newer version available'",
")",
";",
"return",
"2",
";",
"}",
"catch",
"(",
"ErrorCachedVersionException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"info",
"(",
"$",
"e",
")",
";",
"return",
"3",
";",
"}",
"catch",
"(",
"FetcherException",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"info",
"(",
"$",
"e",
")",
";",
"return",
"4",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"e",
")",
"{",
"$",
"logger",
"->",
"info",
"(",
"$",
"e",
")",
";",
"return",
"5",
";",
"}",
"$",
"logger",
"->",
"debug",
"(",
"'finished checking for new version of remote file'",
")",
";",
"return",
"0",
";",
"}"
] | @param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return int | [
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Input",
"\\",
"InputInterface",
"$input",
"@param",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Console",
"\\",
"Output",
"\\",
"OutputInterface",
"$output"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Command/CheckUpdateCommand.php#L57-L96 |
browscap/browscap-php | src/Helper/IniLoader.php | IniLoader.setRemoteFilename | public function setRemoteFilename(string $name) : void
{
if (empty($name)) {
throw new Exception(
'the filename can not be empty',
Exception::INI_FILE_MISSING
);
}
$this->remoteFilename = $name;
} | php | public function setRemoteFilename(string $name) : void
{
if (empty($name)) {
throw new Exception(
'the filename can not be empty',
Exception::INI_FILE_MISSING
);
}
$this->remoteFilename = $name;
} | [
"public",
"function",
"setRemoteFilename",
"(",
"string",
"$",
"name",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'the filename can not be empty'",
",",
"Exception",
"::",
"INI_FILE_MISSING",
")",
";",
"}",
"$",
"this",
"->",
"remoteFilename",
"=",
"$",
"name",
";",
"}"
] | sets the name of the local ini file
@param string $name the file name
@throws \BrowscapPHP\Helper\Exception | [
"sets",
"the",
"name",
"of",
"the",
"local",
"ini",
"file"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Helper/IniLoader.php#L42-L52 |
browscap/browscap-php | src/Formatter/LegacyFormatter.php | LegacyFormatter.getData | public function getData() : \stdClass
{
$output = new \stdClass();
foreach ($this->data as $key => $property) {
if ($this->options['lowercase']) {
$key = strtolower($key);
}
$output->{$key} = $property;
}
return $output;
} | php | public function getData() : \stdClass
{
$output = new \stdClass();
foreach ($this->data as $key => $property) {
if ($this->options['lowercase']) {
$key = strtolower($key);
}
$output->{$key} = $property;
}
return $output;
} | [
"public",
"function",
"getData",
"(",
")",
":",
"\\",
"stdClass",
"{",
"$",
"output",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"as",
"$",
"key",
"=>",
"$",
"property",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"options",
"[",
"'lowercase'",
"]",
")",
"{",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"key",
")",
";",
"}",
"$",
"output",
"->",
"{",
"$",
"key",
"}",
"=",
"$",
"property",
";",
"}",
"return",
"$",
"output",
";",
"}"
] | Gets the data (in the preferred format)
@return \stdClass | [
"Gets",
"the",
"data",
"(",
"in",
"the",
"preferred",
"format",
")"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Formatter/LegacyFormatter.php#L59-L72 |
browscap/browscap-php | src/Exception/FetcherException.php | FetcherException.httpError | public static function httpError(string $resource, string $error) : self
{
return new self(
sprintf('Could not fetch HTTP resource "%s": %s', $resource, $error)
);
} | php | public static function httpError(string $resource, string $error) : self
{
return new self(
sprintf('Could not fetch HTTP resource "%s": %s', $resource, $error)
);
} | [
"public",
"static",
"function",
"httpError",
"(",
"string",
"$",
"resource",
",",
"string",
"$",
"error",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"sprintf",
"(",
"'Could not fetch HTTP resource \"%s\": %s'",
",",
"$",
"resource",
",",
"$",
"error",
")",
")",
";",
"}"
] | @param string $resource
@param string $error
@return FetcherException | [
"@param",
"string",
"$resource",
"@param",
"string",
"$error"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Exception/FetcherException.php#L17-L22 |
browscap/browscap-php | src/Parser/Ini.php | Ini.getBrowser | public function getBrowser(string $userAgent) : ?FormatterInterface
{
$userAgent = strtolower($userAgent);
$formatter = null;
foreach ($this->patternHelper->getPatterns($userAgent) as $patterns) {
$patternToMatch = '/^(?:' . str_replace("\t", ')|(?:', $patterns) . ')$/i';
if (! preg_match($patternToMatch, $userAgent)) {
continue;
}
// strtok() requires less memory than explode()
$pattern = strtok($patterns, "\t");
while (false !== $pattern) {
$pattern = str_replace('[\d]', '(\d)', $pattern);
$quotedPattern = '/^' . $pattern . '$/i';
$matches = [];
if (preg_match($quotedPattern, $userAgent, $matches)) {
// Insert the digits back into the pattern, so that we can search the settings for it
if (1 < count($matches)) {
array_shift($matches);
foreach ($matches as $oneMatch) {
$numPos = strpos($pattern, '(\d)');
$pattern = substr_replace($pattern, $oneMatch, $numPos, 4);
}
}
// Try to get settings - as digits have been replaced to speed up the pattern search (up to 90 faster),
// we won't always find the data in the first step - so check if settings have been found and if not,
// search for the next pattern.
$settings = $this->dataHelper->getSettings($pattern);
if (0 < count($settings)) {
$formatter = $this->formatter;
$formatter->setData($settings);
break 2;
}
}
$pattern = strtok("\t");
}
}
return $formatter;
} | php | public function getBrowser(string $userAgent) : ?FormatterInterface
{
$userAgent = strtolower($userAgent);
$formatter = null;
foreach ($this->patternHelper->getPatterns($userAgent) as $patterns) {
$patternToMatch = '/^(?:' . str_replace("\t", ')|(?:', $patterns) . ')$/i';
if (! preg_match($patternToMatch, $userAgent)) {
continue;
}
// strtok() requires less memory than explode()
$pattern = strtok($patterns, "\t");
while (false !== $pattern) {
$pattern = str_replace('[\d]', '(\d)', $pattern);
$quotedPattern = '/^' . $pattern . '$/i';
$matches = [];
if (preg_match($quotedPattern, $userAgent, $matches)) {
// Insert the digits back into the pattern, so that we can search the settings for it
if (1 < count($matches)) {
array_shift($matches);
foreach ($matches as $oneMatch) {
$numPos = strpos($pattern, '(\d)');
$pattern = substr_replace($pattern, $oneMatch, $numPos, 4);
}
}
// Try to get settings - as digits have been replaced to speed up the pattern search (up to 90 faster),
// we won't always find the data in the first step - so check if settings have been found and if not,
// search for the next pattern.
$settings = $this->dataHelper->getSettings($pattern);
if (0 < count($settings)) {
$formatter = $this->formatter;
$formatter->setData($settings);
break 2;
}
}
$pattern = strtok("\t");
}
}
return $formatter;
} | [
"public",
"function",
"getBrowser",
"(",
"string",
"$",
"userAgent",
")",
":",
"?",
"FormatterInterface",
"{",
"$",
"userAgent",
"=",
"strtolower",
"(",
"$",
"userAgent",
")",
";",
"$",
"formatter",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"patternHelper",
"->",
"getPatterns",
"(",
"$",
"userAgent",
")",
"as",
"$",
"patterns",
")",
"{",
"$",
"patternToMatch",
"=",
"'/^(?:'",
".",
"str_replace",
"(",
"\"\\t\"",
",",
"')|(?:'",
",",
"$",
"patterns",
")",
".",
"')$/i'",
";",
"if",
"(",
"!",
"preg_match",
"(",
"$",
"patternToMatch",
",",
"$",
"userAgent",
")",
")",
"{",
"continue",
";",
"}",
"// strtok() requires less memory than explode()",
"$",
"pattern",
"=",
"strtok",
"(",
"$",
"patterns",
",",
"\"\\t\"",
")",
";",
"while",
"(",
"false",
"!==",
"$",
"pattern",
")",
"{",
"$",
"pattern",
"=",
"str_replace",
"(",
"'[\\d]'",
",",
"'(\\d)'",
",",
"$",
"pattern",
")",
";",
"$",
"quotedPattern",
"=",
"'/^'",
".",
"$",
"pattern",
".",
"'$/i'",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"if",
"(",
"preg_match",
"(",
"$",
"quotedPattern",
",",
"$",
"userAgent",
",",
"$",
"matches",
")",
")",
"{",
"// Insert the digits back into the pattern, so that we can search the settings for it",
"if",
"(",
"1",
"<",
"count",
"(",
"$",
"matches",
")",
")",
"{",
"array_shift",
"(",
"$",
"matches",
")",
";",
"foreach",
"(",
"$",
"matches",
"as",
"$",
"oneMatch",
")",
"{",
"$",
"numPos",
"=",
"strpos",
"(",
"$",
"pattern",
",",
"'(\\d)'",
")",
";",
"$",
"pattern",
"=",
"substr_replace",
"(",
"$",
"pattern",
",",
"$",
"oneMatch",
",",
"$",
"numPos",
",",
"4",
")",
";",
"}",
"}",
"// Try to get settings - as digits have been replaced to speed up the pattern search (up to 90 faster),",
"// we won't always find the data in the first step - so check if settings have been found and if not,",
"// search for the next pattern.",
"$",
"settings",
"=",
"$",
"this",
"->",
"dataHelper",
"->",
"getSettings",
"(",
"$",
"pattern",
")",
";",
"if",
"(",
"0",
"<",
"count",
"(",
"$",
"settings",
")",
")",
"{",
"$",
"formatter",
"=",
"$",
"this",
"->",
"formatter",
";",
"$",
"formatter",
"->",
"setData",
"(",
"$",
"settings",
")",
";",
"break",
"2",
";",
"}",
"}",
"$",
"pattern",
"=",
"strtok",
"(",
"\"\\t\"",
")",
";",
"}",
"}",
"return",
"$",
"formatter",
";",
"}"
] | Gets the browser data formatr for the given user agent
(or null if no data avaailble, no even the default browser)
@param string $userAgent
@throws \UnexpectedValueException
@return FormatterInterface|null | [
"Gets",
"the",
"browser",
"data",
"formatr",
"for",
"the",
"given",
"user",
"agent",
"(",
"or",
"null",
"if",
"no",
"data",
"avaailble",
"no",
"even",
"the",
"default",
"browser",
")"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Parser/Ini.php#L59-L107 |
browscap/browscap-php | src/Browscap.php | Browscap.getParser | public function getParser() : ParserInterface
{
if (null === $this->parser) {
$patternHelper = new Parser\Helper\GetPattern($this->cache, $this->logger);
$dataHelper = new Parser\Helper\GetData($this->cache, $this->logger, new Quoter());
$this->parser = new Parser\Ini($patternHelper, $dataHelper, $this->formatter);
}
return $this->parser;
} | php | public function getParser() : ParserInterface
{
if (null === $this->parser) {
$patternHelper = new Parser\Helper\GetPattern($this->cache, $this->logger);
$dataHelper = new Parser\Helper\GetData($this->cache, $this->logger, new Quoter());
$this->parser = new Parser\Ini($patternHelper, $dataHelper, $this->formatter);
}
return $this->parser;
} | [
"public",
"function",
"getParser",
"(",
")",
":",
"ParserInterface",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"parser",
")",
"{",
"$",
"patternHelper",
"=",
"new",
"Parser",
"\\",
"Helper",
"\\",
"GetPattern",
"(",
"$",
"this",
"->",
"cache",
",",
"$",
"this",
"->",
"logger",
")",
";",
"$",
"dataHelper",
"=",
"new",
"Parser",
"\\",
"Helper",
"\\",
"GetData",
"(",
"$",
"this",
"->",
"cache",
",",
"$",
"this",
"->",
"logger",
",",
"new",
"Quoter",
"(",
")",
")",
";",
"$",
"this",
"->",
"parser",
"=",
"new",
"Parser",
"\\",
"Ini",
"(",
"$",
"patternHelper",
",",
"$",
"dataHelper",
",",
"$",
"this",
"->",
"formatter",
")",
";",
"}",
"return",
"$",
"this",
"->",
"parser",
";",
"}"
] | returns an instance of the used parser class
@return \BrowscapPHP\Parser\ParserInterface | [
"returns",
"an",
"instance",
"of",
"the",
"used",
"parser",
"class"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Browscap.php#L82-L92 |
browscap/browscap-php | src/Browscap.php | Browscap.getBrowser | public function getBrowser(string $userAgent = null) : \stdClass
{
if (null === $this->cache->getVersion()) {
// there is no active/warm cache available
throw new Exception('there is no active cache available, please use the BrowscapUpdater and run the update command');
}
// Automatically detect the useragent
if (! is_string($userAgent)) {
$support = new Helper\Support($_SERVER);
$userAgent = $support->getUserAgent();
}
try {
// try to get browser data
$formatter = $this->getParser()->getBrowser($userAgent);
} catch (\UnexpectedValueException $e) {
$this->logger->error(sprintf('could not parse useragent "%s"', $userAgent));
$formatter = null;
}
// if return is still NULL, updates are disabled... in this
// case we return an empty formatter instance
if (null === $formatter) {
$formatter = $this->formatter;
}
return $formatter->getData();
} | php | public function getBrowser(string $userAgent = null) : \stdClass
{
if (null === $this->cache->getVersion()) {
// there is no active/warm cache available
throw new Exception('there is no active cache available, please use the BrowscapUpdater and run the update command');
}
// Automatically detect the useragent
if (! is_string($userAgent)) {
$support = new Helper\Support($_SERVER);
$userAgent = $support->getUserAgent();
}
try {
// try to get browser data
$formatter = $this->getParser()->getBrowser($userAgent);
} catch (\UnexpectedValueException $e) {
$this->logger->error(sprintf('could not parse useragent "%s"', $userAgent));
$formatter = null;
}
// if return is still NULL, updates are disabled... in this
// case we return an empty formatter instance
if (null === $formatter) {
$formatter = $this->formatter;
}
return $formatter->getData();
} | [
"public",
"function",
"getBrowser",
"(",
"string",
"$",
"userAgent",
"=",
"null",
")",
":",
"\\",
"stdClass",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"cache",
"->",
"getVersion",
"(",
")",
")",
"{",
"// there is no active/warm cache available",
"throw",
"new",
"Exception",
"(",
"'there is no active cache available, please use the BrowscapUpdater and run the update command'",
")",
";",
"}",
"// Automatically detect the useragent",
"if",
"(",
"!",
"is_string",
"(",
"$",
"userAgent",
")",
")",
"{",
"$",
"support",
"=",
"new",
"Helper",
"\\",
"Support",
"(",
"$",
"_SERVER",
")",
";",
"$",
"userAgent",
"=",
"$",
"support",
"->",
"getUserAgent",
"(",
")",
";",
"}",
"try",
"{",
"// try to get browser data",
"$",
"formatter",
"=",
"$",
"this",
"->",
"getParser",
"(",
")",
"->",
"getBrowser",
"(",
"$",
"userAgent",
")",
";",
"}",
"catch",
"(",
"\\",
"UnexpectedValueException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"sprintf",
"(",
"'could not parse useragent \"%s\"'",
",",
"$",
"userAgent",
")",
")",
";",
"$",
"formatter",
"=",
"null",
";",
"}",
"// if return is still NULL, updates are disabled... in this",
"// case we return an empty formatter instance",
"if",
"(",
"null",
"===",
"$",
"formatter",
")",
"{",
"$",
"formatter",
"=",
"$",
"this",
"->",
"formatter",
";",
"}",
"return",
"$",
"formatter",
"->",
"getData",
"(",
")",
";",
"}"
] | parses the given user agent to get the information about the browser
if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it
@param string $userAgent the user agent string
@throws \BrowscapPHP\Exception
@return \stdClass the object containing the browsers details. | [
"parses",
"the",
"given",
"user",
"agent",
"to",
"get",
"the",
"information",
"about",
"the",
"browser"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Browscap.php#L105-L133 |
browscap/browscap-php | src/Helper/Quoter.php | Quoter.pregQuote | public function pregQuote(string $user_agent, string $delimiter = '/') : string
{
$pattern = preg_quote($user_agent, $delimiter);
// the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
return str_replace(['\*', '\?', '\\x'], ['.*', '.', '\\\\x'], $pattern);
} | php | public function pregQuote(string $user_agent, string $delimiter = '/') : string
{
$pattern = preg_quote($user_agent, $delimiter);
// the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
return str_replace(['\*', '\?', '\\x'], ['.*', '.', '\\\\x'], $pattern);
} | [
"public",
"function",
"pregQuote",
"(",
"string",
"$",
"user_agent",
",",
"string",
"$",
"delimiter",
"=",
"'/'",
")",
":",
"string",
"{",
"$",
"pattern",
"=",
"preg_quote",
"(",
"$",
"user_agent",
",",
"$",
"delimiter",
")",
";",
"// the \\\\x replacement is a fix for \"Der gro\\xdfe BilderSauger 2.00u\" user agent match",
"return",
"str_replace",
"(",
"[",
"'\\*'",
",",
"'\\?'",
",",
"'\\\\x'",
"]",
",",
"[",
"'.*'",
",",
"'.'",
",",
"'\\\\\\\\x'",
"]",
",",
"$",
"pattern",
")",
";",
"}"
] | Converts browscap match patterns into preg match patterns.
@param string $user_agent
@param string $delimiter
@return string | [
"Converts",
"browscap",
"match",
"patterns",
"into",
"preg",
"match",
"patterns",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Helper/Quoter.php#L19-L25 |
browscap/browscap-php | src/Helper/Quoter.php | Quoter.pregUnQuote | public function pregUnQuote(string $pattern) : string
{
// Fast check, because most parent pattern like 'DefaultProperties' don't need a replacement
if (!preg_match('/[^a-z\s]/i', $pattern)) {
return $pattern;
}
$origPattern = $pattern;
// Undo the \\x replacement, that is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
// @source https://github.com/browscap/browscap-php
$pattern = preg_replace(
['/(?<!\\\\)\\.\\*/', '/(?<!\\\\)\\./', '/(?<!\\\\)\\\\x/'],
['\\*', '\\?', '\\x'],
$pattern
);
if (null === $pattern) {
throw new \UnexpectedValueException(
sprintf('an error occured while handling pattern %s', $origPattern)
);
}
// Undo preg_quote
$pattern = str_replace(
[
'\\\\', '\\+', '\\*', '\\?', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=',
'\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '\\.', '\\/',
],
[
'\\', '+', '*', '?', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':',
'-', '.', '/',
],
$pattern
);
return $pattern;
} | php | public function pregUnQuote(string $pattern) : string
{
// Fast check, because most parent pattern like 'DefaultProperties' don't need a replacement
if (!preg_match('/[^a-z\s]/i', $pattern)) {
return $pattern;
}
$origPattern = $pattern;
// Undo the \\x replacement, that is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
// @source https://github.com/browscap/browscap-php
$pattern = preg_replace(
['/(?<!\\\\)\\.\\*/', '/(?<!\\\\)\\./', '/(?<!\\\\)\\\\x/'],
['\\*', '\\?', '\\x'],
$pattern
);
if (null === $pattern) {
throw new \UnexpectedValueException(
sprintf('an error occured while handling pattern %s', $origPattern)
);
}
// Undo preg_quote
$pattern = str_replace(
[
'\\\\', '\\+', '\\*', '\\?', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=',
'\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '\\.', '\\/',
],
[
'\\', '+', '*', '?', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':',
'-', '.', '/',
],
$pattern
);
return $pattern;
} | [
"public",
"function",
"pregUnQuote",
"(",
"string",
"$",
"pattern",
")",
":",
"string",
"{",
"// Fast check, because most parent pattern like 'DefaultProperties' don't need a replacement",
"if",
"(",
"!",
"preg_match",
"(",
"'/[^a-z\\s]/i'",
",",
"$",
"pattern",
")",
")",
"{",
"return",
"$",
"pattern",
";",
"}",
"$",
"origPattern",
"=",
"$",
"pattern",
";",
"// Undo the \\\\x replacement, that is a fix for \"Der gro\\xdfe BilderSauger 2.00u\" user agent match",
"// @source https://github.com/browscap/browscap-php",
"$",
"pattern",
"=",
"preg_replace",
"(",
"[",
"'/(?<!\\\\\\\\)\\\\.\\\\*/'",
",",
"'/(?<!\\\\\\\\)\\\\./'",
",",
"'/(?<!\\\\\\\\)\\\\\\\\x/'",
"]",
",",
"[",
"'\\\\*'",
",",
"'\\\\?'",
",",
"'\\\\x'",
"]",
",",
"$",
"pattern",
")",
";",
"if",
"(",
"null",
"===",
"$",
"pattern",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"sprintf",
"(",
"'an error occured while handling pattern %s'",
",",
"$",
"origPattern",
")",
")",
";",
"}",
"// Undo preg_quote",
"$",
"pattern",
"=",
"str_replace",
"(",
"[",
"'\\\\\\\\'",
",",
"'\\\\+'",
",",
"'\\\\*'",
",",
"'\\\\?'",
",",
"'\\\\['",
",",
"'\\\\^'",
",",
"'\\\\]'",
",",
"'\\\\$'",
",",
"'\\\\('",
",",
"'\\\\)'",
",",
"'\\\\{'",
",",
"'\\\\}'",
",",
"'\\\\='",
",",
"'\\\\!'",
",",
"'\\\\<'",
",",
"'\\\\>'",
",",
"'\\\\|'",
",",
"'\\\\:'",
",",
"'\\\\-'",
",",
"'\\\\.'",
",",
"'\\\\/'",
",",
"]",
",",
"[",
"'\\\\'",
",",
"'+'",
",",
"'*'",
",",
"'?'",
",",
"'['",
",",
"'^'",
",",
"']'",
",",
"'$'",
",",
"'('",
",",
"')'",
",",
"'{'",
",",
"'}'",
",",
"'='",
",",
"'!'",
",",
"'<'",
",",
"'>'",
",",
"'|'",
",",
"':'",
",",
"'-'",
",",
"'.'",
",",
"'/'",
",",
"]",
",",
"$",
"pattern",
")",
";",
"return",
"$",
"pattern",
";",
"}"
] | Reverts the quoting of a pattern.
@param string $pattern
@throws \UnexpectedValueException
@return string | [
"Reverts",
"the",
"quoting",
"of",
"a",
"pattern",
"."
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Helper/Quoter.php#L36-L73 |
browscap/browscap-php | src/Data/PropertyFormatter.php | PropertyFormatter.formatPropertyValue | public function formatPropertyValue($value, string $property)
{
switch ($this->propertyHolder->getPropertyType($property)) {
case PropertyHolder::TYPE_BOOLEAN:
if (true === $value || 'true' === $value || '1' === $value) {
return true;
}
return false;
break;
case PropertyHolder::TYPE_IN_ARRAY:
try {
return $this->propertyHolder->checkValueInArray($property, (string) $value);
} catch (\InvalidArgumentException $ex) {
return '';
}
break;
}
return $value;
} | php | public function formatPropertyValue($value, string $property)
{
switch ($this->propertyHolder->getPropertyType($property)) {
case PropertyHolder::TYPE_BOOLEAN:
if (true === $value || 'true' === $value || '1' === $value) {
return true;
}
return false;
break;
case PropertyHolder::TYPE_IN_ARRAY:
try {
return $this->propertyHolder->checkValueInArray($property, (string) $value);
} catch (\InvalidArgumentException $ex) {
return '';
}
break;
}
return $value;
} | [
"public",
"function",
"formatPropertyValue",
"(",
"$",
"value",
",",
"string",
"$",
"property",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"propertyHolder",
"->",
"getPropertyType",
"(",
"$",
"property",
")",
")",
"{",
"case",
"PropertyHolder",
"::",
"TYPE_BOOLEAN",
":",
"if",
"(",
"true",
"===",
"$",
"value",
"||",
"'true'",
"===",
"$",
"value",
"||",
"'1'",
"===",
"$",
"value",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"break",
";",
"case",
"PropertyHolder",
"::",
"TYPE_IN_ARRAY",
":",
"try",
"{",
"return",
"$",
"this",
"->",
"propertyHolder",
"->",
"checkValueInArray",
"(",
"$",
"property",
",",
"(",
"string",
")",
"$",
"value",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"ex",
")",
"{",
"return",
"''",
";",
"}",
"break",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | formats the name of a property
@param bool|string $value
@param string $property
@return bool|string | [
"formats",
"the",
"name",
"of",
"a",
"property"
] | train | https://github.com/browscap/browscap-php/blob/b6ca3db5df6015ecae8cdd3a488cd53ab1a31e49/src/Data/PropertyFormatter.php#L31-L53 |
artkonekt/appshell | src/Console/Commands/SuperCommand.php | SuperCommand.askEmail | protected function askEmail()
{
$email = $this->ask('E-mail');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error("'$email' is not an email address.");
exit(2);
} elseif (UserProxy::where('email', $email)->first()) {
$this->error("User '$email' already exists");
exit(3);
}
return $email;
} | php | protected function askEmail()
{
$email = $this->ask('E-mail');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error("'$email' is not an email address.");
exit(2);
} elseif (UserProxy::where('email', $email)->first()) {
$this->error("User '$email' already exists");
exit(3);
}
return $email;
} | [
"protected",
"function",
"askEmail",
"(",
")",
"{",
"$",
"email",
"=",
"$",
"this",
"->",
"ask",
"(",
"'E-mail'",
")",
";",
"if",
"(",
"!",
"filter_var",
"(",
"$",
"email",
",",
"FILTER_VALIDATE_EMAIL",
")",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"\"'$email' is not an email address.\"",
")",
";",
"exit",
"(",
"2",
")",
";",
"}",
"elseif",
"(",
"UserProxy",
"::",
"where",
"(",
"'email'",
",",
"$",
"email",
")",
"->",
"first",
"(",
")",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"\"User '$email' already exists\"",
")",
";",
"exit",
"(",
"3",
")",
";",
"}",
"return",
"$",
"email",
";",
"}"
] | Asks for and validates E-mail address
@return string | [
"Asks",
"for",
"and",
"validates",
"E",
"-",
"mail",
"address"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Console/Commands/SuperCommand.php#L58-L71 |
artkonekt/appshell | src/Console/Commands/SuperCommand.php | SuperCommand.fetchRole | protected function fetchRole($roleName)
{
$role = RoleProxy::where('name', $roleName)->first();
if (! $role) {
if (! $this->confirm("Role '$roleName' doesn't exists. Create it?")) {
$this->warn('Nothing has been done.');
exit(1);
}
$role = $this->createRole($roleName);
$this->info("Role '$roleName' has been created (id: {$role->id})'");
}
return $role;
} | php | protected function fetchRole($roleName)
{
$role = RoleProxy::where('name', $roleName)->first();
if (! $role) {
if (! $this->confirm("Role '$roleName' doesn't exists. Create it?")) {
$this->warn('Nothing has been done.');
exit(1);
}
$role = $this->createRole($roleName);
$this->info("Role '$roleName' has been created (id: {$role->id})'");
}
return $role;
} | [
"protected",
"function",
"fetchRole",
"(",
"$",
"roleName",
")",
"{",
"$",
"role",
"=",
"RoleProxy",
"::",
"where",
"(",
"'name'",
",",
"$",
"roleName",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"$",
"role",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"confirm",
"(",
"\"Role '$roleName' doesn't exists. Create it?\"",
")",
")",
"{",
"$",
"this",
"->",
"warn",
"(",
"'Nothing has been done.'",
")",
";",
"exit",
"(",
"1",
")",
";",
"}",
"$",
"role",
"=",
"$",
"this",
"->",
"createRole",
"(",
"$",
"roleName",
")",
";",
"$",
"this",
"->",
"info",
"(",
"\"Role '$roleName' has been created (id: {$role->id})'\"",
")",
";",
"}",
"return",
"$",
"role",
";",
"}"
] | @param $roleName
@return Role | [
"@param",
"$roleName"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Console/Commands/SuperCommand.php#L78-L92 |
artkonekt/appshell | src/Console/Commands/SuperCommand.php | SuperCommand.createRole | protected function createRole($name)
{
$role = RoleProxy::create(['name' => $name])->fresh();
$role->givePermissionTo(ResourcePermissions::allPermissionsFor('user'));
$role->givePermissionTo(ResourcePermissions::allPermissionsFor('role'));
return $role;
} | php | protected function createRole($name)
{
$role = RoleProxy::create(['name' => $name])->fresh();
$role->givePermissionTo(ResourcePermissions::allPermissionsFor('user'));
$role->givePermissionTo(ResourcePermissions::allPermissionsFor('role'));
return $role;
} | [
"protected",
"function",
"createRole",
"(",
"$",
"name",
")",
"{",
"$",
"role",
"=",
"RoleProxy",
"::",
"create",
"(",
"[",
"'name'",
"=>",
"$",
"name",
"]",
")",
"->",
"fresh",
"(",
")",
";",
"$",
"role",
"->",
"givePermissionTo",
"(",
"ResourcePermissions",
"::",
"allPermissionsFor",
"(",
"'user'",
")",
")",
";",
"$",
"role",
"->",
"givePermissionTo",
"(",
"ResourcePermissions",
"::",
"allPermissionsFor",
"(",
"'role'",
")",
")",
";",
"return",
"$",
"role",
";",
"}"
] | @param $name
@return Role | [
"@param",
"$name"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Console/Commands/SuperCommand.php#L99-L107 |
artkonekt/appshell | src/Icons/EnumIconMapper.php | EnumIconMapper.registerEnumIcons | public function registerEnumIcons($enumClass, array $icons)
{
$this->map = array_merge($this->map, [shorten($enumClass) => $icons]);
} | php | public function registerEnumIcons($enumClass, array $icons)
{
$this->map = array_merge($this->map, [shorten($enumClass) => $icons]);
} | [
"public",
"function",
"registerEnumIcons",
"(",
"$",
"enumClass",
",",
"array",
"$",
"icons",
")",
"{",
"$",
"this",
"->",
"map",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"map",
",",
"[",
"shorten",
"(",
"$",
"enumClass",
")",
"=>",
"$",
"icons",
"]",
")",
";",
"}"
] | Register icon mapping for a specific enum class
@param string $enumClass
@param array $icons | [
"Register",
"icon",
"mapping",
"for",
"a",
"specific",
"enum",
"class"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Icons/EnumIconMapper.php#L27-L30 |
artkonekt/appshell | src/Icons/EnumIconMapper.php | EnumIconMapper.icon | public function icon(Enum $enum)
{
return array_get(
$this->map,
sprintf('%s.%s', shorten(get_class($enum)), $enum->value()),
config('konekt.app_shell.icon.default', 'default')
);
} | php | public function icon(Enum $enum)
{
return array_get(
$this->map,
sprintf('%s.%s', shorten(get_class($enum)), $enum->value()),
config('konekt.app_shell.icon.default', 'default')
);
} | [
"public",
"function",
"icon",
"(",
"Enum",
"$",
"enum",
")",
"{",
"return",
"array_get",
"(",
"$",
"this",
"->",
"map",
",",
"sprintf",
"(",
"'%s.%s'",
",",
"shorten",
"(",
"get_class",
"(",
"$",
"enum",
")",
")",
",",
"$",
"enum",
"->",
"value",
"(",
")",
")",
",",
"config",
"(",
"'konekt.app_shell.icon.default'",
",",
"'default'",
")",
")",
";",
"}"
] | Returns the icon for the given enum instance
@param Enum $enum
@return mixed | [
"Returns",
"the",
"icon",
"for",
"the",
"given",
"enum",
"instance"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Icons/EnumIconMapper.php#L39-L46 |
artkonekt/appshell | src/Http/Controllers/AppShellViewAware.php | AppShellViewAware.appShellView | protected function appShellView($view = null, $data = [], $mergeData = [])
{
if (null === $this->viewNS) {
$this->viewNS = config('konekt.app_shell.views.namespace');
}
if (!str_contains($view, '::')) {
$view = sprintf('%s::%s', $this->viewNS, $view);
} elseif (starts_with($view, 'appshell::')) {
$view = str_replace_first('appshell::', $this->viewNS . '::', $view);
}
return view($view, $data, $mergeData);
} | php | protected function appShellView($view = null, $data = [], $mergeData = [])
{
if (null === $this->viewNS) {
$this->viewNS = config('konekt.app_shell.views.namespace');
}
if (!str_contains($view, '::')) {
$view = sprintf('%s::%s', $this->viewNS, $view);
} elseif (starts_with($view, 'appshell::')) {
$view = str_replace_first('appshell::', $this->viewNS . '::', $view);
}
return view($view, $data, $mergeData);
} | [
"protected",
"function",
"appShellView",
"(",
"$",
"view",
"=",
"null",
",",
"$",
"data",
"=",
"[",
"]",
",",
"$",
"mergeData",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"viewNS",
")",
"{",
"$",
"this",
"->",
"viewNS",
"=",
"config",
"(",
"'konekt.app_shell.views.namespace'",
")",
";",
"}",
"if",
"(",
"!",
"str_contains",
"(",
"$",
"view",
",",
"'::'",
")",
")",
"{",
"$",
"view",
"=",
"sprintf",
"(",
"'%s::%s'",
",",
"$",
"this",
"->",
"viewNS",
",",
"$",
"view",
")",
";",
"}",
"elseif",
"(",
"starts_with",
"(",
"$",
"view",
",",
"'appshell::'",
")",
")",
"{",
"$",
"view",
"=",
"str_replace_first",
"(",
"'appshell::'",
",",
"$",
"this",
"->",
"viewNS",
".",
"'::'",
",",
"$",
"view",
")",
";",
"}",
"return",
"view",
"(",
"$",
"view",
",",
"$",
"data",
",",
"$",
"mergeData",
")",
";",
"}"
] | A tiny wrapper for view() method that handles cases when the
'appshell::' view namespace gets customized, or the cases
when no namespace gets specified by adding a namespace
@param string $view
@param array $data
@param array $mergeData
@return \Illuminate\View\View|\Illuminate\Contracts\View\Factory | [
"A",
"tiny",
"wrapper",
"for",
"view",
"()",
"method",
"that",
"handles",
"cases",
"when",
"the",
"appshell",
"::",
"view",
"namespace",
"gets",
"customized",
"or",
"the",
"cases",
"when",
"no",
"namespace",
"gets",
"specified",
"by",
"adding",
"a",
"namespace"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Controllers/AppShellViewAware.php#L30-L43 |
artkonekt/appshell | src/Providers/ModuleServiceProvider.php | ModuleServiceProvider.registerThirdPartyProviders | protected function registerThirdPartyProviders()
{
if (
'testing' == $this->app->environment()
||
version_compare(Application::VERSION, '5.5.0', '<')
) {
$this->registerMenuComponent();
$this->registerFormComponent();
$this->registerFlashComponent();
$this->registerBreadcrumbsComponent();
$this->registerSluggableComponent();
}
$this->mergeBreadCrumbsConfig();
} | php | protected function registerThirdPartyProviders()
{
if (
'testing' == $this->app->environment()
||
version_compare(Application::VERSION, '5.5.0', '<')
) {
$this->registerMenuComponent();
$this->registerFormComponent();
$this->registerFlashComponent();
$this->registerBreadcrumbsComponent();
$this->registerSluggableComponent();
}
$this->mergeBreadCrumbsConfig();
} | [
"protected",
"function",
"registerThirdPartyProviders",
"(",
")",
"{",
"if",
"(",
"'testing'",
"==",
"$",
"this",
"->",
"app",
"->",
"environment",
"(",
")",
"||",
"version_compare",
"(",
"Application",
"::",
"VERSION",
",",
"'5.5.0'",
",",
"'<'",
")",
")",
"{",
"$",
"this",
"->",
"registerMenuComponent",
"(",
")",
";",
"$",
"this",
"->",
"registerFormComponent",
"(",
")",
";",
"$",
"this",
"->",
"registerFlashComponent",
"(",
")",
";",
"$",
"this",
"->",
"registerBreadcrumbsComponent",
"(",
")",
";",
"$",
"this",
"->",
"registerSluggableComponent",
"(",
")",
";",
"}",
"$",
"this",
"->",
"mergeBreadCrumbsConfig",
"(",
")",
";",
"}"
] | Registers 3rd party providers, AppShell is built on top of
They are:
- Konekt Menu,
- Laravel Collective Forms
- Laracasts Flash
- DaveJamesMiller Breadcrumbs | [
"Registers",
"3rd",
"party",
"providers",
"AppShell",
"is",
"built",
"on",
"top",
"of"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Providers/ModuleServiceProvider.php#L128-L143 |
artkonekt/appshell | src/Providers/ModuleServiceProvider.php | ModuleServiceProvider.initializeMenus | protected function initializeMenus()
{
foreach ($this->config('menu') as $name => $config) {
Menu::create($name, $config);
}
// Add default menu items to sidebar
if ($appshellMenu = Menu::get('appshell')) {
// CRM Group
$crm = $appshellMenu->addItem('crm_group', __('CRM'));
$crm
->addSubItem('customers', __('Customers'), ['route' => 'appshell.customer.index'])
->data('icon', 'accounts-list')
->allowIfUserCan('list customers');
// Settings Group
$settings = $appshellMenu->addItem('settings_group', __('Settings'));
$settings
->addSubItem('users', __('Users'), ['route' => 'appshell.user.index'])
->data('icon', 'accounts')
->allowIfUserCan('list users');
$settings
->addSubItem('roles', __('Permissions'), ['route' => 'appshell.role.index'])
->data('icon', 'shield-security')
->allowIfUserCan('list roles');
$settings
->addSubItem('settings', __('Settings'), ['route' => 'appshell.settings.index'])
->data('icon', 'settings')
->allowIfUserCan('list settings');
}
} | php | protected function initializeMenus()
{
foreach ($this->config('menu') as $name => $config) {
Menu::create($name, $config);
}
// Add default menu items to sidebar
if ($appshellMenu = Menu::get('appshell')) {
// CRM Group
$crm = $appshellMenu->addItem('crm_group', __('CRM'));
$crm
->addSubItem('customers', __('Customers'), ['route' => 'appshell.customer.index'])
->data('icon', 'accounts-list')
->allowIfUserCan('list customers');
// Settings Group
$settings = $appshellMenu->addItem('settings_group', __('Settings'));
$settings
->addSubItem('users', __('Users'), ['route' => 'appshell.user.index'])
->data('icon', 'accounts')
->allowIfUserCan('list users');
$settings
->addSubItem('roles', __('Permissions'), ['route' => 'appshell.role.index'])
->data('icon', 'shield-security')
->allowIfUserCan('list roles');
$settings
->addSubItem('settings', __('Settings'), ['route' => 'appshell.settings.index'])
->data('icon', 'settings')
->allowIfUserCan('list settings');
}
} | [
"protected",
"function",
"initializeMenus",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"config",
"(",
"'menu'",
")",
"as",
"$",
"name",
"=>",
"$",
"config",
")",
"{",
"Menu",
"::",
"create",
"(",
"$",
"name",
",",
"$",
"config",
")",
";",
"}",
"// Add default menu items to sidebar",
"if",
"(",
"$",
"appshellMenu",
"=",
"Menu",
"::",
"get",
"(",
"'appshell'",
")",
")",
"{",
"// CRM Group",
"$",
"crm",
"=",
"$",
"appshellMenu",
"->",
"addItem",
"(",
"'crm_group'",
",",
"__",
"(",
"'CRM'",
")",
")",
";",
"$",
"crm",
"->",
"addSubItem",
"(",
"'customers'",
",",
"__",
"(",
"'Customers'",
")",
",",
"[",
"'route'",
"=>",
"'appshell.customer.index'",
"]",
")",
"->",
"data",
"(",
"'icon'",
",",
"'accounts-list'",
")",
"->",
"allowIfUserCan",
"(",
"'list customers'",
")",
";",
"// Settings Group",
"$",
"settings",
"=",
"$",
"appshellMenu",
"->",
"addItem",
"(",
"'settings_group'",
",",
"__",
"(",
"'Settings'",
")",
")",
";",
"$",
"settings",
"->",
"addSubItem",
"(",
"'users'",
",",
"__",
"(",
"'Users'",
")",
",",
"[",
"'route'",
"=>",
"'appshell.user.index'",
"]",
")",
"->",
"data",
"(",
"'icon'",
",",
"'accounts'",
")",
"->",
"allowIfUserCan",
"(",
"'list users'",
")",
";",
"$",
"settings",
"->",
"addSubItem",
"(",
"'roles'",
",",
"__",
"(",
"'Permissions'",
")",
",",
"[",
"'route'",
"=>",
"'appshell.role.index'",
"]",
")",
"->",
"data",
"(",
"'icon'",
",",
"'shield-security'",
")",
"->",
"allowIfUserCan",
"(",
"'list roles'",
")",
";",
"$",
"settings",
"->",
"addSubItem",
"(",
"'settings'",
",",
"__",
"(",
"'Settings'",
")",
",",
"[",
"'route'",
"=>",
"'appshell.settings.index'",
"]",
")",
"->",
"data",
"(",
"'icon'",
",",
"'settings'",
")",
"->",
"allowIfUserCan",
"(",
"'list settings'",
")",
";",
"}",
"}"
] | Initializes menus set in the configuration | [
"Initializes",
"menus",
"set",
"in",
"the",
"configuration"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Providers/ModuleServiceProvider.php#L161-L193 |
artkonekt/appshell | src/Providers/ModuleServiceProvider.php | ModuleServiceProvider.registerFormComponent | private function registerFormComponent()
{
$this->app->register(\Collective\Html\HtmlServiceProvider::class);
$this->concord->registerAlias('Form', \Collective\Html\FormFacade::class);
$this->concord->registerAlias('Html', \Collective\Html\HtmlFacade::class);
} | php | private function registerFormComponent()
{
$this->app->register(\Collective\Html\HtmlServiceProvider::class);
$this->concord->registerAlias('Form', \Collective\Html\FormFacade::class);
$this->concord->registerAlias('Html', \Collective\Html\HtmlFacade::class);
} | [
"private",
"function",
"registerFormComponent",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"register",
"(",
"\\",
"Collective",
"\\",
"Html",
"\\",
"HtmlServiceProvider",
"::",
"class",
")",
";",
"$",
"this",
"->",
"concord",
"->",
"registerAlias",
"(",
"'Form'",
",",
"\\",
"Collective",
"\\",
"Html",
"\\",
"FormFacade",
"::",
"class",
")",
";",
"$",
"this",
"->",
"concord",
"->",
"registerAlias",
"(",
"'Html'",
",",
"\\",
"Collective",
"\\",
"Html",
"\\",
"HtmlFacade",
"::",
"class",
")",
";",
"}"
] | Register Laravel Collective Form Component | [
"Register",
"Laravel",
"Collective",
"Form",
"Component"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Providers/ModuleServiceProvider.php#L212-L217 |
artkonekt/appshell | src/Providers/ModuleServiceProvider.php | ModuleServiceProvider.registerMenuComponent | private function registerMenuComponent()
{
$this->app->register(\Konekt\Menu\MenuServiceProvider::class);
$this->concord->registerAlias('Menu', \Konekt\Menu\Facades\Menu::class);
} | php | private function registerMenuComponent()
{
$this->app->register(\Konekt\Menu\MenuServiceProvider::class);
$this->concord->registerAlias('Menu', \Konekt\Menu\Facades\Menu::class);
} | [
"private",
"function",
"registerMenuComponent",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"register",
"(",
"\\",
"Konekt",
"\\",
"Menu",
"\\",
"MenuServiceProvider",
"::",
"class",
")",
";",
"$",
"this",
"->",
"concord",
"->",
"registerAlias",
"(",
"'Menu'",
",",
"\\",
"Konekt",
"\\",
"Menu",
"\\",
"Facades",
"\\",
"Menu",
"::",
"class",
")",
";",
"}"
] | Registers Konekt Menu Component | [
"Registers",
"Konekt",
"Menu",
"Component"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Providers/ModuleServiceProvider.php#L222-L226 |
artkonekt/appshell | src/Providers/ModuleServiceProvider.php | ModuleServiceProvider.registerBreadcrumbsComponent | private function registerBreadcrumbsComponent()
{
// Register The Breadcrumbs Component
if (class_exists('\\DaveJamesMiller\\Breadcrumbs\\ServiceProvider')) { // Breadcrumbs v3.x - Laravel 5.4
$this->app->register(\DaveJamesMiller\Breadcrumbs\ServiceProvider::class);
$this->concord->registerAlias('Breadcrumbs', \DaveJamesMiller\Breadcrumbs\Facade::class);
} else { // Breadcrumbs v4.x, v5.x - Laravel 5.5+
$this->app->register(\DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::class);
$this->concord->registerAlias('Breadcrumbs', \DaveJamesMiller\Breadcrumbs\Facades\Breadcrumbs::class);
}
} | php | private function registerBreadcrumbsComponent()
{
// Register The Breadcrumbs Component
if (class_exists('\\DaveJamesMiller\\Breadcrumbs\\ServiceProvider')) { // Breadcrumbs v3.x - Laravel 5.4
$this->app->register(\DaveJamesMiller\Breadcrumbs\ServiceProvider::class);
$this->concord->registerAlias('Breadcrumbs', \DaveJamesMiller\Breadcrumbs\Facade::class);
} else { // Breadcrumbs v4.x, v5.x - Laravel 5.5+
$this->app->register(\DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::class);
$this->concord->registerAlias('Breadcrumbs', \DaveJamesMiller\Breadcrumbs\Facades\Breadcrumbs::class);
}
} | [
"private",
"function",
"registerBreadcrumbsComponent",
"(",
")",
"{",
"// Register The Breadcrumbs Component",
"if",
"(",
"class_exists",
"(",
"'\\\\DaveJamesMiller\\\\Breadcrumbs\\\\ServiceProvider'",
")",
")",
"{",
"// Breadcrumbs v3.x - Laravel 5.4",
"$",
"this",
"->",
"app",
"->",
"register",
"(",
"\\",
"DaveJamesMiller",
"\\",
"Breadcrumbs",
"\\",
"ServiceProvider",
"::",
"class",
")",
";",
"$",
"this",
"->",
"concord",
"->",
"registerAlias",
"(",
"'Breadcrumbs'",
",",
"\\",
"DaveJamesMiller",
"\\",
"Breadcrumbs",
"\\",
"Facade",
"::",
"class",
")",
";",
"}",
"else",
"{",
"// Breadcrumbs v4.x, v5.x - Laravel 5.5+",
"$",
"this",
"->",
"app",
"->",
"register",
"(",
"\\",
"DaveJamesMiller",
"\\",
"Breadcrumbs",
"\\",
"BreadcrumbsServiceProvider",
"::",
"class",
")",
";",
"$",
"this",
"->",
"concord",
"->",
"registerAlias",
"(",
"'Breadcrumbs'",
",",
"\\",
"DaveJamesMiller",
"\\",
"Breadcrumbs",
"\\",
"Facades",
"\\",
"Breadcrumbs",
"::",
"class",
")",
";",
"}",
"}"
] | Register the breadcrumbs component, also merge the config from within the box config | [
"Register",
"the",
"breadcrumbs",
"component",
"also",
"merge",
"the",
"config",
"from",
"within",
"the",
"box",
"config"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Providers/ModuleServiceProvider.php#L239-L249 |
artkonekt/appshell | src/Http/Middleware/AclMiddleware.php | AclMiddleware.handle | public function handle($request, Closure $next, $permission = null)
{
$permission = $permission ?: $this->getNecessaryPermission($request->route()->getAction());
if (false !== $permission) {
if (! $request->user()->can($permission)) {
abort(403);
}
}
return $next($request);
} | php | public function handle($request, Closure $next, $permission = null)
{
$permission = $permission ?: $this->getNecessaryPermission($request->route()->getAction());
if (false !== $permission) {
if (! $request->user()->can($permission)) {
abort(403);
}
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
",",
"$",
"permission",
"=",
"null",
")",
"{",
"$",
"permission",
"=",
"$",
"permission",
"?",
":",
"$",
"this",
"->",
"getNecessaryPermission",
"(",
"$",
"request",
"->",
"route",
"(",
")",
"->",
"getAction",
"(",
")",
")",
";",
"if",
"(",
"false",
"!==",
"$",
"permission",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"user",
"(",
")",
"->",
"can",
"(",
"$",
"permission",
")",
")",
"{",
"abort",
"(",
"403",
")",
";",
"}",
"}",
"return",
"$",
"next",
"(",
"$",
"request",
")",
";",
"}"
] | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param null $permission
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Middleware/AclMiddleware.php#L20-L31 |
artkonekt/appshell | src/Http/Middleware/AclMiddleware.php | AclMiddleware.getNecessaryPermission | protected function getNecessaryPermission($action)
{
$parsed = $this->parseAction($action);
return ResourcePermissions::permissionFor($parsed['resource'], $parsed['action']);
} | php | protected function getNecessaryPermission($action)
{
$parsed = $this->parseAction($action);
return ResourcePermissions::permissionFor($parsed['resource'], $parsed['action']);
} | [
"protected",
"function",
"getNecessaryPermission",
"(",
"$",
"action",
")",
"{",
"$",
"parsed",
"=",
"$",
"this",
"->",
"parseAction",
"(",
"$",
"action",
")",
";",
"return",
"ResourcePermissions",
"::",
"permissionFor",
"(",
"$",
"parsed",
"[",
"'resource'",
"]",
",",
"$",
"parsed",
"[",
"'action'",
"]",
")",
";",
"}"
] | Returns permission name like 'edit users', 'list users' etc based on resource and action
@param $action
@return bool|string Returns the permission name or false if no matching action was found | [
"Returns",
"permission",
"name",
"like",
"edit",
"users",
"list",
"users",
"etc",
"based",
"on",
"resource",
"and",
"action"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Middleware/AclMiddleware.php#L40-L45 |
artkonekt/appshell | src/Http/Middleware/AclMiddleware.php | AclMiddleware.parseAction | protected function parseAction($action)
{
// Remove namespace
$parts = explode('\\', $action['uses']);
$ctrlAndAction = end($parts);
// Split controller and action
$parts = explode('@', $ctrlAndAction);
$controller = $parts[0];
$action = end($parts);
$resource = strtolower(str_replace('Controller', '', $controller));
return [
'action' => $action,
'resource' => $resource
];
} | php | protected function parseAction($action)
{
// Remove namespace
$parts = explode('\\', $action['uses']);
$ctrlAndAction = end($parts);
// Split controller and action
$parts = explode('@', $ctrlAndAction);
$controller = $parts[0];
$action = end($parts);
$resource = strtolower(str_replace('Controller', '', $controller));
return [
'action' => $action,
'resource' => $resource
];
} | [
"protected",
"function",
"parseAction",
"(",
"$",
"action",
")",
"{",
"// Remove namespace",
"$",
"parts",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"action",
"[",
"'uses'",
"]",
")",
";",
"$",
"ctrlAndAction",
"=",
"end",
"(",
"$",
"parts",
")",
";",
"// Split controller and action",
"$",
"parts",
"=",
"explode",
"(",
"'@'",
",",
"$",
"ctrlAndAction",
")",
";",
"$",
"controller",
"=",
"$",
"parts",
"[",
"0",
"]",
";",
"$",
"action",
"=",
"end",
"(",
"$",
"parts",
")",
";",
"$",
"resource",
"=",
"strtolower",
"(",
"str_replace",
"(",
"'Controller'",
",",
"''",
",",
"$",
"controller",
")",
")",
";",
"return",
"[",
"'action'",
"=>",
"$",
"action",
",",
"'resource'",
"=>",
"$",
"resource",
"]",
";",
"}"
] | @param array $action
@return array | [
"@param",
"array",
"$action"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Middleware/AclMiddleware.php#L52-L68 |
artkonekt/appshell | src/Listeners/UpdateUserLoginData.php | UpdateUserLoginData.handle | public function handle(Login $event)
{
if (config('konekt.app_shell.disable.login_counter')) {
return;
}
$event->user->last_login_at = Carbon::now();
$event->user->login_count += 1;
$event->user->save();
} | php | public function handle(Login $event)
{
if (config('konekt.app_shell.disable.login_counter')) {
return;
}
$event->user->last_login_at = Carbon::now();
$event->user->login_count += 1;
$event->user->save();
} | [
"public",
"function",
"handle",
"(",
"Login",
"$",
"event",
")",
"{",
"if",
"(",
"config",
"(",
"'konekt.app_shell.disable.login_counter'",
")",
")",
"{",
"return",
";",
"}",
"$",
"event",
"->",
"user",
"->",
"last_login_at",
"=",
"Carbon",
"::",
"now",
"(",
")",
";",
"$",
"event",
"->",
"user",
"->",
"login_count",
"+=",
"1",
";",
"$",
"event",
"->",
"user",
"->",
"save",
"(",
")",
";",
"}"
] | Updates user's login data
@param Login $event | [
"Updates",
"user",
"s",
"login",
"data"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Listeners/UpdateUserLoginData.php#L24-L33 |
artkonekt/appshell | src/Http/Controllers/UserController.php | UserController.store | public function store(CreateUser $request)
{
$request->merge(['password' => bcrypt($request->get('password'))]);
try {
$user = UserProxy::create($request->except('roles'));
$user->syncRoles($request->roles());
flash()->success(__('User has been created'));
} catch (\Exception $e) {
flash()->error(__('Error: :msg', ['msg' => $e->getMessage()]));
return redirect()->back();
}
//@todo process route prefixes based on box config
return redirect(route('appshell.user.index'));
} | php | public function store(CreateUser $request)
{
$request->merge(['password' => bcrypt($request->get('password'))]);
try {
$user = UserProxy::create($request->except('roles'));
$user->syncRoles($request->roles());
flash()->success(__('User has been created'));
} catch (\Exception $e) {
flash()->error(__('Error: :msg', ['msg' => $e->getMessage()]));
return redirect()->back();
}
//@todo process route prefixes based on box config
return redirect(route('appshell.user.index'));
} | [
"public",
"function",
"store",
"(",
"CreateUser",
"$",
"request",
")",
"{",
"$",
"request",
"->",
"merge",
"(",
"[",
"'password'",
"=>",
"bcrypt",
"(",
"$",
"request",
"->",
"get",
"(",
"'password'",
")",
")",
"]",
")",
";",
"try",
"{",
"$",
"user",
"=",
"UserProxy",
"::",
"create",
"(",
"$",
"request",
"->",
"except",
"(",
"'roles'",
")",
")",
";",
"$",
"user",
"->",
"syncRoles",
"(",
"$",
"request",
"->",
"roles",
"(",
")",
")",
";",
"flash",
"(",
")",
"->",
"success",
"(",
"__",
"(",
"'User has been created'",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"flash",
"(",
")",
"->",
"error",
"(",
"__",
"(",
"'Error: :msg'",
",",
"[",
"'msg'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
")",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"}",
"//@todo process route prefixes based on box config",
"return",
"redirect",
"(",
"route",
"(",
"'appshell.user.index'",
")",
")",
";",
"}"
] | @param CreateUser $request
@return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector | [
"@param",
"CreateUser",
"$request"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Controllers/UserController.php#L53-L69 |
artkonekt/appshell | src/Http/Controllers/UserController.php | UserController.edit | public function edit(User $user)
{
return $this->appShellView('user.edit', [
'user' => $user,
'types' => UserTypeProxy::choices(),
'roles' => RoleProxy::all()
]);
} | php | public function edit(User $user)
{
return $this->appShellView('user.edit', [
'user' => $user,
'types' => UserTypeProxy::choices(),
'roles' => RoleProxy::all()
]);
} | [
"public",
"function",
"edit",
"(",
"User",
"$",
"user",
")",
"{",
"return",
"$",
"this",
"->",
"appShellView",
"(",
"'user.edit'",
",",
"[",
"'user'",
"=>",
"$",
"user",
",",
"'types'",
"=>",
"UserTypeProxy",
"::",
"choices",
"(",
")",
",",
"'roles'",
"=>",
"RoleProxy",
"::",
"all",
"(",
")",
"]",
")",
";",
"}"
] | @param User $user
@return \Illuminate\Contracts\View\Factory|\Illuminate\View\View | [
"@param",
"User",
"$user"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Controllers/UserController.php#L88-L95 |
artkonekt/appshell | src/Http/Controllers/UserController.php | UserController.update | public function update(User $user, UpdateUser $request)
{
$data = $request->except(['password', 'roles']);
if ($request->wantsPasswordChange()) {
$data['password'] = bcrypt($request->getNewPassword());
}
try {
$user->update($data);
$user->syncRoles($request->roles());
$flashMessage = __(':name has been updated.', ['name' => $user->name]);
if ($request->wantsPasswordChange()) {
$flashMessage .= ' ' . __("The user's password has changed");
}
flash()->success($flashMessage);
} catch (\Exception $e) {
flash()->error(__('Error: :msg', ['msg' => $e->getMessage()]));
return redirect()->back();
}
return redirect(route('appshell.user.show', $user));
} | php | public function update(User $user, UpdateUser $request)
{
$data = $request->except(['password', 'roles']);
if ($request->wantsPasswordChange()) {
$data['password'] = bcrypt($request->getNewPassword());
}
try {
$user->update($data);
$user->syncRoles($request->roles());
$flashMessage = __(':name has been updated.', ['name' => $user->name]);
if ($request->wantsPasswordChange()) {
$flashMessage .= ' ' . __("The user's password has changed");
}
flash()->success($flashMessage);
} catch (\Exception $e) {
flash()->error(__('Error: :msg', ['msg' => $e->getMessage()]));
return redirect()->back();
}
return redirect(route('appshell.user.show', $user));
} | [
"public",
"function",
"update",
"(",
"User",
"$",
"user",
",",
"UpdateUser",
"$",
"request",
")",
"{",
"$",
"data",
"=",
"$",
"request",
"->",
"except",
"(",
"[",
"'password'",
",",
"'roles'",
"]",
")",
";",
"if",
"(",
"$",
"request",
"->",
"wantsPasswordChange",
"(",
")",
")",
"{",
"$",
"data",
"[",
"'password'",
"]",
"=",
"bcrypt",
"(",
"$",
"request",
"->",
"getNewPassword",
"(",
")",
")",
";",
"}",
"try",
"{",
"$",
"user",
"->",
"update",
"(",
"$",
"data",
")",
";",
"$",
"user",
"->",
"syncRoles",
"(",
"$",
"request",
"->",
"roles",
"(",
")",
")",
";",
"$",
"flashMessage",
"=",
"__",
"(",
"':name has been updated.'",
",",
"[",
"'name'",
"=>",
"$",
"user",
"->",
"name",
"]",
")",
";",
"if",
"(",
"$",
"request",
"->",
"wantsPasswordChange",
"(",
")",
")",
"{",
"$",
"flashMessage",
".=",
"' '",
".",
"__",
"(",
"\"The user's password has changed\"",
")",
";",
"}",
"flash",
"(",
")",
"->",
"success",
"(",
"$",
"flashMessage",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"flash",
"(",
")",
"->",
"error",
"(",
"__",
"(",
"'Error: :msg'",
",",
"[",
"'msg'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
")",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"}",
"return",
"redirect",
"(",
"route",
"(",
"'appshell.user.show'",
",",
"$",
"user",
")",
")",
";",
"}"
] | @param User $user
@param UpdateUser $request
@return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector | [
"@param",
"User",
"$user",
"@param",
"UpdateUser",
"$request"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Controllers/UserController.php#L103-L127 |
artkonekt/appshell | src/Http/Controllers/UserController.php | UserController.destroy | public function destroy(User $user)
{
if ($user->id == Auth::user()->id) {
flash()->error(__("You can't delete your self. What's wrong dude? Do you want to talk about it?"));
return redirect()->back();
}
try {
$user->delete();
flash()->info(__('User has been deleted'));
} catch (\Exception $e) {
flash()->error(__('Error: :msg', ['msg' => $e->getMessage()]));
}
return redirect(route('appshell.user.index'));
} | php | public function destroy(User $user)
{
if ($user->id == Auth::user()->id) {
flash()->error(__("You can't delete your self. What's wrong dude? Do you want to talk about it?"));
return redirect()->back();
}
try {
$user->delete();
flash()->info(__('User has been deleted'));
} catch (\Exception $e) {
flash()->error(__('Error: :msg', ['msg' => $e->getMessage()]));
}
return redirect(route('appshell.user.index'));
} | [
"public",
"function",
"destroy",
"(",
"User",
"$",
"user",
")",
"{",
"if",
"(",
"$",
"user",
"->",
"id",
"==",
"Auth",
"::",
"user",
"(",
")",
"->",
"id",
")",
"{",
"flash",
"(",
")",
"->",
"error",
"(",
"__",
"(",
"\"You can't delete your self. What's wrong dude? Do you want to talk about it?\"",
")",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"}",
"try",
"{",
"$",
"user",
"->",
"delete",
"(",
")",
";",
"flash",
"(",
")",
"->",
"info",
"(",
"__",
"(",
"'User has been deleted'",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"flash",
"(",
")",
"->",
"error",
"(",
"__",
"(",
"'Error: :msg'",
",",
"[",
"'msg'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
")",
")",
";",
"}",
"return",
"redirect",
"(",
"route",
"(",
"'appshell.user.index'",
")",
")",
";",
"}"
] | Delete a user
@param User $user
@return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector | [
"Delete",
"a",
"user"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Http/Controllers/UserController.php#L136-L153 |
artkonekt/appshell | src/resources/database/migrations/2017_06_12_073443_create_appshell_permissions.php | CreateAppshellPermissions.up | public function up()
{
$adminRole = RoleProxy::create(['name' => 'admin']);
$adminRole->givePermissionTo(
ResourcePermissions::createPermissionsForResource($this->resources)
);
$admins = UserProxy::where(['type' => UserType::ADMIN])->get();
$admins->each->assignRole($adminRole);
} | php | public function up()
{
$adminRole = RoleProxy::create(['name' => 'admin']);
$adminRole->givePermissionTo(
ResourcePermissions::createPermissionsForResource($this->resources)
);
$admins = UserProxy::where(['type' => UserType::ADMIN])->get();
$admins->each->assignRole($adminRole);
} | [
"public",
"function",
"up",
"(",
")",
"{",
"$",
"adminRole",
"=",
"RoleProxy",
"::",
"create",
"(",
"[",
"'name'",
"=>",
"'admin'",
"]",
")",
";",
"$",
"adminRole",
"->",
"givePermissionTo",
"(",
"ResourcePermissions",
"::",
"createPermissionsForResource",
"(",
"$",
"this",
"->",
"resources",
")",
")",
";",
"$",
"admins",
"=",
"UserProxy",
"::",
"where",
"(",
"[",
"'type'",
"=>",
"UserType",
"::",
"ADMIN",
"]",
")",
"->",
"get",
"(",
")",
";",
"$",
"admins",
"->",
"each",
"->",
"assignRole",
"(",
"$",
"adminRole",
")",
";",
"}"
] | Run the migrations.
@return void | [
"Run",
"the",
"migrations",
"."
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/resources/database/migrations/2017_06_12_073443_create_appshell_permissions.php#L18-L28 |
artkonekt/appshell | src/resources/database/migrations/2017_06_12_073443_create_appshell_permissions.php | CreateAppshellPermissions.down | public function down()
{
$adminRole = RoleProxy::where(['name' => 'admin'])->first();
if ($adminRole) {
$admins = UserProxy::where(['type' => UserType::ADMIN])->get();
$admins->each->removeRole($adminRole);
}
ResourcePermissions::deletePermissionsForResource($this->resources);
$adminRole->delete();
} | php | public function down()
{
$adminRole = RoleProxy::where(['name' => 'admin'])->first();
if ($adminRole) {
$admins = UserProxy::where(['type' => UserType::ADMIN])->get();
$admins->each->removeRole($adminRole);
}
ResourcePermissions::deletePermissionsForResource($this->resources);
$adminRole->delete();
} | [
"public",
"function",
"down",
"(",
")",
"{",
"$",
"adminRole",
"=",
"RoleProxy",
"::",
"where",
"(",
"[",
"'name'",
"=>",
"'admin'",
"]",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"$",
"adminRole",
")",
"{",
"$",
"admins",
"=",
"UserProxy",
"::",
"where",
"(",
"[",
"'type'",
"=>",
"UserType",
"::",
"ADMIN",
"]",
")",
"->",
"get",
"(",
")",
";",
"$",
"admins",
"->",
"each",
"->",
"removeRole",
"(",
"$",
"adminRole",
")",
";",
"}",
"ResourcePermissions",
"::",
"deletePermissionsForResource",
"(",
"$",
"this",
"->",
"resources",
")",
";",
"$",
"adminRole",
"->",
"delete",
"(",
")",
";",
"}"
] | Reverse the migrations.
@return void | [
"Reverse",
"the",
"migrations",
"."
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/resources/database/migrations/2017_06_12_073443_create_appshell_permissions.php#L35-L47 |
artkonekt/appshell | src/Breadcrumbs/HasBreadcrumbs.php | HasBreadcrumbs.loadBreadcrumbs | public function loadBreadcrumbs()
{
if (!$this->config('breadcrumbs')) {
return false;
}
$file = sprintf('%s/%s/%s',
$this->basePath,
$this->convention->routesFolder(),
'breadcrumbs.php'
);
if (file_exists($file)) {
require $file;
}
} | php | public function loadBreadcrumbs()
{
if (!$this->config('breadcrumbs')) {
return false;
}
$file = sprintf('%s/%s/%s',
$this->basePath,
$this->convention->routesFolder(),
'breadcrumbs.php'
);
if (file_exists($file)) {
require $file;
}
} | [
"public",
"function",
"loadBreadcrumbs",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"config",
"(",
"'breadcrumbs'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"file",
"=",
"sprintf",
"(",
"'%s/%s/%s'",
",",
"$",
"this",
"->",
"basePath",
",",
"$",
"this",
"->",
"convention",
"->",
"routesFolder",
"(",
")",
",",
"'breadcrumbs.php'",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"require",
"$",
"file",
";",
"}",
"}"
] | Loads definitions from breadcrumbs file in case it's enabled in the config
@return bool | [
"Loads",
"definitions",
"from",
"breadcrumbs",
"file",
"in",
"case",
"it",
"s",
"enabled",
"in",
"the",
"config"
] | train | https://github.com/artkonekt/appshell/blob/2ec5d9b36cf65eec619d7daa37ab66d0fd4d9d3b/src/Breadcrumbs/HasBreadcrumbs.php#L21-L36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.