repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
list | docstring
stringlengths 3
47.2k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
locomotivemtl/charcoal-cms | src/Charcoal/Cms/AbstractEvent.php | AbstractEvent.verifyDates | public function verifyDates()
{
if (!$this->startDate()) {
$this->setStartDate('now');
}
if (!$this->endDate()) {
$this->setEndDate($this->startDate());
}
if (!$this->publishDate()) {
$this->setPublishDate('now');
}
} | php | public function verifyDates()
{
if (!$this->startDate()) {
$this->setStartDate('now');
}
if (!$this->endDate()) {
$this->setEndDate($this->startDate());
}
if (!$this->publishDate()) {
$this->setPublishDate('now');
}
} | [
"public",
"function",
"verifyDates",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"startDate",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setStartDate",
"(",
"'now'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"endDate",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setEndDate",
"(",
"$",
"this",
"->",
"startDate",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"publishDate",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setPublishDate",
"(",
"'now'",
")",
";",
"}",
"}"
]
| Some dates cannot be null
@return void | [
"Some",
"dates",
"cannot",
"be",
"null"
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/AbstractEvent.php#L133-L146 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/Support/Helpers/DateHelper.php | DateHelper.getDateCase | private function getDateCase()
{
$from = $this->from;
$to = $this->to;
// single date event
if (!$to || $to->format('Ymd') === $from->format('Ymd')) {
return 'single';
}
$fromDate = [
'day' => $from->format('d'),
'month' => $from->format('m'),
'year' => $from->format('y')
];
$toDate = [
'day' => $to->format('d'),
'month' => $to->format('m'),
'year' => $to->format('y')
];
$case = null;
$case = $fromDate['day'] !== $toDate['day'] ? 'different_day' : $case;
$case = $fromDate['month'] !== $toDate['month'] ? 'different_month' : $case;
$case = $fromDate['year'] !== $toDate['year'] ? 'different_year' : $case;
return $case;
} | php | private function getDateCase()
{
$from = $this->from;
$to = $this->to;
// single date event
if (!$to || $to->format('Ymd') === $from->format('Ymd')) {
return 'single';
}
$fromDate = [
'day' => $from->format('d'),
'month' => $from->format('m'),
'year' => $from->format('y')
];
$toDate = [
'day' => $to->format('d'),
'month' => $to->format('m'),
'year' => $to->format('y')
];
$case = null;
$case = $fromDate['day'] !== $toDate['day'] ? 'different_day' : $case;
$case = $fromDate['month'] !== $toDate['month'] ? 'different_month' : $case;
$case = $fromDate['year'] !== $toDate['year'] ? 'different_year' : $case;
return $case;
} | [
"private",
"function",
"getDateCase",
"(",
")",
"{",
"$",
"from",
"=",
"$",
"this",
"->",
"from",
";",
"$",
"to",
"=",
"$",
"this",
"->",
"to",
";",
"// single date event",
"if",
"(",
"!",
"$",
"to",
"||",
"$",
"to",
"->",
"format",
"(",
"'Ymd'",
")",
"===",
"$",
"from",
"->",
"format",
"(",
"'Ymd'",
")",
")",
"{",
"return",
"'single'",
";",
"}",
"$",
"fromDate",
"=",
"[",
"'day'",
"=>",
"$",
"from",
"->",
"format",
"(",
"'d'",
")",
",",
"'month'",
"=>",
"$",
"from",
"->",
"format",
"(",
"'m'",
")",
",",
"'year'",
"=>",
"$",
"from",
"->",
"format",
"(",
"'y'",
")",
"]",
";",
"$",
"toDate",
"=",
"[",
"'day'",
"=>",
"$",
"to",
"->",
"format",
"(",
"'d'",
")",
",",
"'month'",
"=>",
"$",
"to",
"->",
"format",
"(",
"'m'",
")",
",",
"'year'",
"=>",
"$",
"to",
"->",
"format",
"(",
"'y'",
")",
"]",
";",
"$",
"case",
"=",
"null",
";",
"$",
"case",
"=",
"$",
"fromDate",
"[",
"'day'",
"]",
"!==",
"$",
"toDate",
"[",
"'day'",
"]",
"?",
"'different_day'",
":",
"$",
"case",
";",
"$",
"case",
"=",
"$",
"fromDate",
"[",
"'month'",
"]",
"!==",
"$",
"toDate",
"[",
"'month'",
"]",
"?",
"'different_month'",
":",
"$",
"case",
";",
"$",
"case",
"=",
"$",
"fromDate",
"[",
"'year'",
"]",
"!==",
"$",
"toDate",
"[",
"'year'",
"]",
"?",
"'different_year'",
":",
"$",
"case",
";",
"return",
"$",
"case",
";",
"}"
]
| Get the usage case by comparing two dates.
@return string | [
"Get",
"the",
"usage",
"case",
"by",
"comparing",
"two",
"dates",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Helpers/DateHelper.php#L120-L148 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/Support/Helpers/DateHelper.php | DateHelper.getTimeCase | private function getTimeCase()
{
$from = $this->from;
$to = $this->to;
// Single hour event
if (!$to || $to->format('Hi') === $from->format('Hi')) {
if ($to->format('i') == 0) {
return 'single_round';
}
return 'single';
}
$fromTime = [
'hour' => $from->format('H'),
'minute' => $from->format('i'),
];
$toTime = [
'hour' => $to->format('H'),
'minute' => $to->format('i'),
];
$case = null;
$case = $fromTime['hour'] !== $toTime['hour'] ? 'different_time' : $case;
$case = $fromTime['minute'] == 0 ? 'different_time_round' : $case;
$case = $fromTime['minute'] != $toTime['minute'] ? 'different_time' : $case;
return $case;
} | php | private function getTimeCase()
{
$from = $this->from;
$to = $this->to;
// Single hour event
if (!$to || $to->format('Hi') === $from->format('Hi')) {
if ($to->format('i') == 0) {
return 'single_round';
}
return 'single';
}
$fromTime = [
'hour' => $from->format('H'),
'minute' => $from->format('i'),
];
$toTime = [
'hour' => $to->format('H'),
'minute' => $to->format('i'),
];
$case = null;
$case = $fromTime['hour'] !== $toTime['hour'] ? 'different_time' : $case;
$case = $fromTime['minute'] == 0 ? 'different_time_round' : $case;
$case = $fromTime['minute'] != $toTime['minute'] ? 'different_time' : $case;
return $case;
} | [
"private",
"function",
"getTimeCase",
"(",
")",
"{",
"$",
"from",
"=",
"$",
"this",
"->",
"from",
";",
"$",
"to",
"=",
"$",
"this",
"->",
"to",
";",
"// Single hour event",
"if",
"(",
"!",
"$",
"to",
"||",
"$",
"to",
"->",
"format",
"(",
"'Hi'",
")",
"===",
"$",
"from",
"->",
"format",
"(",
"'Hi'",
")",
")",
"{",
"if",
"(",
"$",
"to",
"->",
"format",
"(",
"'i'",
")",
"==",
"0",
")",
"{",
"return",
"'single_round'",
";",
"}",
"return",
"'single'",
";",
"}",
"$",
"fromTime",
"=",
"[",
"'hour'",
"=>",
"$",
"from",
"->",
"format",
"(",
"'H'",
")",
",",
"'minute'",
"=>",
"$",
"from",
"->",
"format",
"(",
"'i'",
")",
",",
"]",
";",
"$",
"toTime",
"=",
"[",
"'hour'",
"=>",
"$",
"to",
"->",
"format",
"(",
"'H'",
")",
",",
"'minute'",
"=>",
"$",
"to",
"->",
"format",
"(",
"'i'",
")",
",",
"]",
";",
"$",
"case",
"=",
"null",
";",
"$",
"case",
"=",
"$",
"fromTime",
"[",
"'hour'",
"]",
"!==",
"$",
"toTime",
"[",
"'hour'",
"]",
"?",
"'different_time'",
":",
"$",
"case",
";",
"$",
"case",
"=",
"$",
"fromTime",
"[",
"'minute'",
"]",
"==",
"0",
"?",
"'different_time_round'",
":",
"$",
"case",
";",
"$",
"case",
"=",
"$",
"fromTime",
"[",
"'minute'",
"]",
"!=",
"$",
"toTime",
"[",
"'minute'",
"]",
"?",
"'different_time'",
":",
"$",
"case",
";",
"return",
"$",
"case",
";",
"}"
]
| Get the usage case by comparing two hours.
@return string | [
"Get",
"the",
"usage",
"case",
"by",
"comparing",
"two",
"hours",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Helpers/DateHelper.php#L154-L184 | train |
vanilla/garden-schema | src/Validation.php | Validation.getCode | public function getCode(): int {
if ($status = $this->getMainCode()) {
return $status;
}
if ($this->isValid()) {
return 200;
}
// There was no status so loop through the errors and look for the highest one.
$max = 0;
foreach ($this->getRawErrors() as $error) {
if (isset($error['code']) && $error['code'] > $max) {
$max = $error['code'];
}
}
return $max ?: 400;
} | php | public function getCode(): int {
if ($status = $this->getMainCode()) {
return $status;
}
if ($this->isValid()) {
return 200;
}
// There was no status so loop through the errors and look for the highest one.
$max = 0;
foreach ($this->getRawErrors() as $error) {
if (isset($error['code']) && $error['code'] > $max) {
$max = $error['code'];
}
}
return $max ?: 400;
} | [
"public",
"function",
"getCode",
"(",
")",
":",
"int",
"{",
"if",
"(",
"$",
"status",
"=",
"$",
"this",
"->",
"getMainCode",
"(",
")",
")",
"{",
"return",
"$",
"status",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isValid",
"(",
")",
")",
"{",
"return",
"200",
";",
"}",
"// There was no status so loop through the errors and look for the highest one.",
"$",
"max",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"getRawErrors",
"(",
")",
"as",
"$",
"error",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"error",
"[",
"'code'",
"]",
")",
"&&",
"$",
"error",
"[",
"'code'",
"]",
">",
"$",
"max",
")",
"{",
"$",
"max",
"=",
"$",
"error",
"[",
"'code'",
"]",
";",
"}",
"}",
"return",
"$",
"max",
"?",
":",
"400",
";",
"}"
]
| Get the error code.
The code is an HTTP response code and should be of the 4xx variety.
@return int Returns an error code. | [
"Get",
"the",
"error",
"code",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L65-L83 | train |
vanilla/garden-schema | src/Validation.php | Validation.getFullMessage | public function getFullMessage(): string {
$paras = [];
if (!empty($this->getMainMessage())) {
$paras[] = $this->getMainMessage();
} elseif ($this->getErrorCount() === 0) {
return '';
}
if (isset($this->errors[''])) {
$paras[] = $this->formatErrorList('', $this->errors['']);
}
foreach ($this->errors as $field => $errors) {
if ($field === '') {
continue;
}
$paras[] = $this->formatErrorList($field, $errors);
}
$result = implode("\n\n", $paras);
return $result;
} | php | public function getFullMessage(): string {
$paras = [];
if (!empty($this->getMainMessage())) {
$paras[] = $this->getMainMessage();
} elseif ($this->getErrorCount() === 0) {
return '';
}
if (isset($this->errors[''])) {
$paras[] = $this->formatErrorList('', $this->errors['']);
}
foreach ($this->errors as $field => $errors) {
if ($field === '') {
continue;
}
$paras[] = $this->formatErrorList($field, $errors);
}
$result = implode("\n\n", $paras);
return $result;
} | [
"public",
"function",
"getFullMessage",
"(",
")",
":",
"string",
"{",
"$",
"paras",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"getMainMessage",
"(",
")",
")",
")",
"{",
"$",
"paras",
"[",
"]",
"=",
"$",
"this",
"->",
"getMainMessage",
"(",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"getErrorCount",
"(",
")",
"===",
"0",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"errors",
"[",
"''",
"]",
")",
")",
"{",
"$",
"paras",
"[",
"]",
"=",
"$",
"this",
"->",
"formatErrorList",
"(",
"''",
",",
"$",
"this",
"->",
"errors",
"[",
"''",
"]",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"errors",
"as",
"$",
"field",
"=>",
"$",
"errors",
")",
"{",
"if",
"(",
"$",
"field",
"===",
"''",
")",
"{",
"continue",
";",
"}",
"$",
"paras",
"[",
"]",
"=",
"$",
"this",
"->",
"formatErrorList",
"(",
"$",
"field",
",",
"$",
"errors",
")",
";",
"}",
"$",
"result",
"=",
"implode",
"(",
"\"\\n\\n\"",
",",
"$",
"paras",
")",
";",
"return",
"$",
"result",
";",
"}"
]
| Get the full error message separated by field.
@return string Returns the error message. | [
"Get",
"the",
"full",
"error",
"message",
"separated",
"by",
"field",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L143-L165 | train |
vanilla/garden-schema | src/Validation.php | Validation.setMainMessage | public function setMainMessage(string $message, bool $translate = true) {
$this->mainMessage = $translate ? $this->translate($message) : $message;
return $this;
} | php | public function setMainMessage(string $message, bool $translate = true) {
$this->mainMessage = $translate ? $this->translate($message) : $message;
return $this;
} | [
"public",
"function",
"setMainMessage",
"(",
"string",
"$",
"message",
",",
"bool",
"$",
"translate",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"mainMessage",
"=",
"$",
"translate",
"?",
"$",
"this",
"->",
"translate",
"(",
"$",
"message",
")",
":",
"$",
"message",
";",
"return",
"$",
"this",
";",
"}"
]
| Set the main error message.
@param string $message The new message.
@param bool $translate Whether or not to translate the message.
@return $this | [
"Set",
"the",
"main",
"error",
"message",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L186-L189 | train |
vanilla/garden-schema | src/Validation.php | Validation.getErrorCount | public function getErrorCount($field = null) {
if ($field === null) {
return iterator_count($this->getRawErrors());
} elseif (empty($this->errors[$field])) {
return 0;
} else {
return count($this->errors[$field]);
}
} | php | public function getErrorCount($field = null) {
if ($field === null) {
return iterator_count($this->getRawErrors());
} elseif (empty($this->errors[$field])) {
return 0;
} else {
return count($this->errors[$field]);
}
} | [
"public",
"function",
"getErrorCount",
"(",
"$",
"field",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"field",
"===",
"null",
")",
"{",
"return",
"iterator_count",
"(",
"$",
"this",
"->",
"getRawErrors",
"(",
")",
")",
";",
"}",
"elseif",
"(",
"empty",
"(",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"0",
";",
"}",
"else",
"{",
"return",
"count",
"(",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
")",
";",
"}",
"}"
]
| Get the error count, optionally for a particular field.
@param string|null $field The name of a field or an empty string for all errors.
@return int Returns the error count. | [
"Get",
"the",
"error",
"count",
"optionally",
"for",
"a",
"particular",
"field",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L197-L205 | train |
vanilla/garden-schema | src/Validation.php | Validation.formatErrorList | private function formatErrorList(string $field, array $errors) {
if (empty($field)) {
$fieldName = '';
$colon = '%s%s';
$sep = "\n";
} else {
$fieldName = $this->formatFieldName($field);
$colon = $this->translate('%s: %s');
$sep = "\n ";
if (count($errors) > 1) {
$colon = rtrim(sprintf($colon, '%s', "")).$sep.'%s';
}
}
$messages = $this->errorMessages($field, $errors);
$result = sprintf($colon, $fieldName, implode($sep, $messages));
return $result;
} | php | private function formatErrorList(string $field, array $errors) {
if (empty($field)) {
$fieldName = '';
$colon = '%s%s';
$sep = "\n";
} else {
$fieldName = $this->formatFieldName($field);
$colon = $this->translate('%s: %s');
$sep = "\n ";
if (count($errors) > 1) {
$colon = rtrim(sprintf($colon, '%s', "")).$sep.'%s';
}
}
$messages = $this->errorMessages($field, $errors);
$result = sprintf($colon, $fieldName, implode($sep, $messages));
return $result;
} | [
"private",
"function",
"formatErrorList",
"(",
"string",
"$",
"field",
",",
"array",
"$",
"errors",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"field",
")",
")",
"{",
"$",
"fieldName",
"=",
"''",
";",
"$",
"colon",
"=",
"'%s%s'",
";",
"$",
"sep",
"=",
"\"\\n\"",
";",
"}",
"else",
"{",
"$",
"fieldName",
"=",
"$",
"this",
"->",
"formatFieldName",
"(",
"$",
"field",
")",
";",
"$",
"colon",
"=",
"$",
"this",
"->",
"translate",
"(",
"'%s: %s'",
")",
";",
"$",
"sep",
"=",
"\"\\n \"",
";",
"if",
"(",
"count",
"(",
"$",
"errors",
")",
">",
"1",
")",
"{",
"$",
"colon",
"=",
"rtrim",
"(",
"sprintf",
"(",
"$",
"colon",
",",
"'%s'",
",",
"\"\"",
")",
")",
".",
"$",
"sep",
".",
"'%s'",
";",
"}",
"}",
"$",
"messages",
"=",
"$",
"this",
"->",
"errorMessages",
"(",
"$",
"field",
",",
"$",
"errors",
")",
";",
"$",
"result",
"=",
"sprintf",
"(",
"$",
"colon",
",",
"$",
"fieldName",
",",
"implode",
"(",
"$",
"sep",
",",
"$",
"messages",
")",
")",
";",
"return",
"$",
"result",
";",
"}"
]
| Format a field's errors.
@param string $field The field name.
@param array $errors The field's errors.
@return string Returns the error messages, translated and formatted. | [
"Format",
"a",
"field",
"s",
"errors",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L214-L231 | train |
vanilla/garden-schema | src/Validation.php | Validation.formatFieldName | protected function formatFieldName(string $field): string {
if ($this->getTranslateFieldNames()) {
return $this->translate($field);
} else {
return $field;
}
} | php | protected function formatFieldName(string $field): string {
if ($this->getTranslateFieldNames()) {
return $this->translate($field);
} else {
return $field;
}
} | [
"protected",
"function",
"formatFieldName",
"(",
"string",
"$",
"field",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"getTranslateFieldNames",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"translate",
"(",
"$",
"field",
")",
";",
"}",
"else",
"{",
"return",
"$",
"field",
";",
"}",
"}"
]
| Format the name of a field.
@param string $field The field name to format.
@return string Returns the formatted field name. | [
"Format",
"the",
"name",
"of",
"a",
"field",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L239-L245 | train |
vanilla/garden-schema | src/Validation.php | Validation.errorMessages | private function errorMessages(string $field, array $errors): array {
$messages = [];
foreach ($errors as $error) {
$messages[] = $this->formatErrorMessage($error + ['field' => $field]);
}
return $messages;
} | php | private function errorMessages(string $field, array $errors): array {
$messages = [];
foreach ($errors as $error) {
$messages[] = $this->formatErrorMessage($error + ['field' => $field]);
}
return $messages;
} | [
"private",
"function",
"errorMessages",
"(",
"string",
"$",
"field",
",",
"array",
"$",
"errors",
")",
":",
"array",
"{",
"$",
"messages",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"errors",
"as",
"$",
"error",
")",
"{",
"$",
"messages",
"[",
"]",
"=",
"$",
"this",
"->",
"formatErrorMessage",
"(",
"$",
"error",
"+",
"[",
"'field'",
"=>",
"$",
"field",
"]",
")",
";",
"}",
"return",
"$",
"messages",
";",
"}"
]
| Format an array of error messages.
@param string $field The name of the field.
@param array $errors The errors array from a field.
@return array Returns the error array. | [
"Format",
"an",
"array",
"of",
"error",
"messages",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L272-L279 | train |
vanilla/garden-schema | src/Validation.php | Validation.formatErrorMessage | private function formatErrorMessage(array $error) {
if (isset($error['messageCode'])) {
$messageCode = $error['messageCode'];
} elseif (isset($error['message'])) {
return $error['message'];
} else {
$messageCode = $error['error'];
}
// Massage the field name for better formatting.
$msg = $this->formatMessage($messageCode, $error);
return $msg;
} | php | private function formatErrorMessage(array $error) {
if (isset($error['messageCode'])) {
$messageCode = $error['messageCode'];
} elseif (isset($error['message'])) {
return $error['message'];
} else {
$messageCode = $error['error'];
}
// Massage the field name for better formatting.
$msg = $this->formatMessage($messageCode, $error);
return $msg;
} | [
"private",
"function",
"formatErrorMessage",
"(",
"array",
"$",
"error",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"error",
"[",
"'messageCode'",
"]",
")",
")",
"{",
"$",
"messageCode",
"=",
"$",
"error",
"[",
"'messageCode'",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"error",
"[",
"'message'",
"]",
")",
")",
"{",
"return",
"$",
"error",
"[",
"'message'",
"]",
";",
"}",
"else",
"{",
"$",
"messageCode",
"=",
"$",
"error",
"[",
"'error'",
"]",
";",
"}",
"// Massage the field name for better formatting.",
"$",
"msg",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"$",
"messageCode",
",",
"$",
"error",
")",
";",
"return",
"$",
"msg",
";",
"}"
]
| Get the error message for an error row.
@param array $error The error row.
@return string Returns a formatted/translated error message. | [
"Get",
"the",
"error",
"message",
"for",
"an",
"error",
"row",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L307-L319 | train |
vanilla/garden-schema | src/Validation.php | Validation.formatMessage | private function formatMessage($format, $context = []) {
$format = $this->translate($format);
$msg = preg_replace_callback('`({[^{}]+})`', function ($m) use ($context) {
$args = array_filter(array_map('trim', explode(',', trim($m[1], '{}'))));
$field = array_shift($args);
switch ($field) {
case 'value':
return $this->formatValue($context[$field] ?? null);
case 'field':
$field = $context['field'] ?: 'value';
return $this->formatFieldName($field);
default:
return $this->formatField(isset($context[$field]) ? $context[$field] : null, $args);
}
}, $format);
return $msg;
} | php | private function formatMessage($format, $context = []) {
$format = $this->translate($format);
$msg = preg_replace_callback('`({[^{}]+})`', function ($m) use ($context) {
$args = array_filter(array_map('trim', explode(',', trim($m[1], '{}'))));
$field = array_shift($args);
switch ($field) {
case 'value':
return $this->formatValue($context[$field] ?? null);
case 'field':
$field = $context['field'] ?: 'value';
return $this->formatFieldName($field);
default:
return $this->formatField(isset($context[$field]) ? $context[$field] : null, $args);
}
}, $format);
return $msg;
} | [
"private",
"function",
"formatMessage",
"(",
"$",
"format",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"format",
"=",
"$",
"this",
"->",
"translate",
"(",
"$",
"format",
")",
";",
"$",
"msg",
"=",
"preg_replace_callback",
"(",
"'`({[^{}]+})`'",
",",
"function",
"(",
"$",
"m",
")",
"use",
"(",
"$",
"context",
")",
"{",
"$",
"args",
"=",
"array_filter",
"(",
"array_map",
"(",
"'trim'",
",",
"explode",
"(",
"','",
",",
"trim",
"(",
"$",
"m",
"[",
"1",
"]",
",",
"'{}'",
")",
")",
")",
")",
";",
"$",
"field",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"switch",
"(",
"$",
"field",
")",
"{",
"case",
"'value'",
":",
"return",
"$",
"this",
"->",
"formatValue",
"(",
"$",
"context",
"[",
"$",
"field",
"]",
"??",
"null",
")",
";",
"case",
"'field'",
":",
"$",
"field",
"=",
"$",
"context",
"[",
"'field'",
"]",
"?",
":",
"'value'",
";",
"return",
"$",
"this",
"->",
"formatFieldName",
"(",
"$",
"field",
")",
";",
"default",
":",
"return",
"$",
"this",
"->",
"formatField",
"(",
"isset",
"(",
"$",
"context",
"[",
"$",
"field",
"]",
")",
"?",
"$",
"context",
"[",
"$",
"field",
"]",
":",
"null",
",",
"$",
"args",
")",
";",
"}",
"}",
",",
"$",
"format",
")",
";",
"return",
"$",
"msg",
";",
"}"
]
| Expand and translate a message format against an array of values.
@param string $format The message format.
@param array $context The context arguments to apply to the message.
@return string Returns a formatted string. | [
"Expand",
"and",
"translate",
"a",
"message",
"format",
"against",
"an",
"array",
"of",
"values",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L328-L346 | train |
vanilla/garden-schema | src/Validation.php | Validation.formatField | private function formatField($value, array $args = []) {
if ($value === null) {
$r = $this->translate('null');
} elseif ($value === true) {
$r = $this->translate('true');
} elseif ($value === false) {
$r = $this->translate('false');
} elseif (is_string($value)) {
$r = $this->translate($value);
} elseif (is_numeric($value)) {
$r = $value;
} elseif (is_array($value)) {
$argArray = array_map([$this, 'formatField'], $value);
$r = implode(', ', $argArray);
} elseif ($value instanceof \DateTimeInterface) {
$r = $value->format('c');
} else {
$r = $value;
}
$format = array_shift($args);
switch ($format) {
case 'plural':
$singular = array_shift($args);
$plural = array_shift($args) ?: $singular.'s';
$count = is_array($value) ? count($value) : $value;
$r = $count == 1 ? $singular : $plural;
break;
}
return (string)$r;
} | php | private function formatField($value, array $args = []) {
if ($value === null) {
$r = $this->translate('null');
} elseif ($value === true) {
$r = $this->translate('true');
} elseif ($value === false) {
$r = $this->translate('false');
} elseif (is_string($value)) {
$r = $this->translate($value);
} elseif (is_numeric($value)) {
$r = $value;
} elseif (is_array($value)) {
$argArray = array_map([$this, 'formatField'], $value);
$r = implode(', ', $argArray);
} elseif ($value instanceof \DateTimeInterface) {
$r = $value->format('c');
} else {
$r = $value;
}
$format = array_shift($args);
switch ($format) {
case 'plural':
$singular = array_shift($args);
$plural = array_shift($args) ?: $singular.'s';
$count = is_array($value) ? count($value) : $value;
$r = $count == 1 ? $singular : $plural;
break;
}
return (string)$r;
} | [
"private",
"function",
"formatField",
"(",
"$",
"value",
",",
"array",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"r",
"=",
"$",
"this",
"->",
"translate",
"(",
"'null'",
")",
";",
"}",
"elseif",
"(",
"$",
"value",
"===",
"true",
")",
"{",
"$",
"r",
"=",
"$",
"this",
"->",
"translate",
"(",
"'true'",
")",
";",
"}",
"elseif",
"(",
"$",
"value",
"===",
"false",
")",
"{",
"$",
"r",
"=",
"$",
"this",
"->",
"translate",
"(",
"'false'",
")",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"r",
"=",
"$",
"this",
"->",
"translate",
"(",
"$",
"value",
")",
";",
"}",
"elseif",
"(",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"$",
"r",
"=",
"$",
"value",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"argArray",
"=",
"array_map",
"(",
"[",
"$",
"this",
",",
"'formatField'",
"]",
",",
"$",
"value",
")",
";",
"$",
"r",
"=",
"implode",
"(",
"', '",
",",
"$",
"argArray",
")",
";",
"}",
"elseif",
"(",
"$",
"value",
"instanceof",
"\\",
"DateTimeInterface",
")",
"{",
"$",
"r",
"=",
"$",
"value",
"->",
"format",
"(",
"'c'",
")",
";",
"}",
"else",
"{",
"$",
"r",
"=",
"$",
"value",
";",
"}",
"$",
"format",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"'plural'",
":",
"$",
"singular",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"$",
"plural",
"=",
"array_shift",
"(",
"$",
"args",
")",
"?",
":",
"$",
"singular",
".",
"'s'",
";",
"$",
"count",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"count",
"(",
"$",
"value",
")",
":",
"$",
"value",
";",
"$",
"r",
"=",
"$",
"count",
"==",
"1",
"?",
"$",
"singular",
":",
"$",
"plural",
";",
"break",
";",
"}",
"return",
"(",
"string",
")",
"$",
"r",
";",
"}"
]
| Translate an argument being placed in an error message.
@param mixed $value The argument to translate.
@param array $args Formatting arguments.
@return string Returns the translated string. | [
"Translate",
"an",
"argument",
"being",
"placed",
"in",
"an",
"error",
"message",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L373-L404 | train |
vanilla/garden-schema | src/Validation.php | Validation.pluckError | private function pluckError(array $error) {
$row = array_intersect_key(
$error,
['field' => 1, 'error' => 1, 'code' => 1]
);
$row['message'] = $this->formatErrorMessage($error);
return $row;
} | php | private function pluckError(array $error) {
$row = array_intersect_key(
$error,
['field' => 1, 'error' => 1, 'code' => 1]
);
$row['message'] = $this->formatErrorMessage($error);
return $row;
} | [
"private",
"function",
"pluckError",
"(",
"array",
"$",
"error",
")",
"{",
"$",
"row",
"=",
"array_intersect_key",
"(",
"$",
"error",
",",
"[",
"'field'",
"=>",
"1",
",",
"'error'",
"=>",
"1",
",",
"'code'",
"=>",
"1",
"]",
")",
";",
"$",
"row",
"[",
"'message'",
"]",
"=",
"$",
"this",
"->",
"formatErrorMessage",
"(",
"$",
"error",
")",
";",
"return",
"$",
"row",
";",
"}"
]
| Format a raw error row for consumption.
@param array $error The error to format.
@return array Returns the error stripped of default values. | [
"Format",
"a",
"raw",
"error",
"row",
"for",
"consumption",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L427-L435 | train |
vanilla/garden-schema | src/Validation.php | Validation.getFieldErrors | public function getFieldErrors(string $field): array {
if (empty($this->errors[$field])) {
return [];
} else {
$result = [];
foreach ($this->errors[$field] as $error) {
$result[] = $this->pluckError($error + ['field' => $field]);
}
return $result;
}
} | php | public function getFieldErrors(string $field): array {
if (empty($this->errors[$field])) {
return [];
} else {
$result = [];
foreach ($this->errors[$field] as $error) {
$result[] = $this->pluckError($error + ['field' => $field]);
}
return $result;
}
} | [
"public",
"function",
"getFieldErrors",
"(",
"string",
"$",
"field",
")",
":",
"array",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
"as",
"$",
"error",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"this",
"->",
"pluckError",
"(",
"$",
"error",
"+",
"[",
"'field'",
"=>",
"$",
"field",
"]",
")",
";",
"}",
"return",
"$",
"result",
";",
"}",
"}"
]
| Get the errors for a specific field.
@param string $field The full path to the field.
@return array Returns an array of errors. | [
"Get",
"the",
"errors",
"for",
"a",
"specific",
"field",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L443-L453 | train |
vanilla/garden-schema | src/Validation.php | Validation.isValidField | public function isValidField(string $field): bool {
$result = empty($this->errors[$field]);
return $result;
} | php | public function isValidField(string $field): bool {
$result = empty($this->errors[$field]);
return $result;
} | [
"public",
"function",
"isValidField",
"(",
"string",
"$",
"field",
")",
":",
"bool",
"{",
"$",
"result",
"=",
"empty",
"(",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
")",
";",
"return",
"$",
"result",
";",
"}"
]
| Check whether or not a particular field is has errors.
@param string $field The name of the field to check for validity.
@return bool Returns true if the field has no errors, false otherwise. | [
"Check",
"whether",
"or",
"not",
"a",
"particular",
"field",
"is",
"has",
"errors",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L461-L464 | train |
vanilla/garden-schema | src/Validation.php | Validation.merge | public function merge(Validation $validation, $name = '') {
$paths = $validation->errors;
foreach ($paths as $path => $errors) {
foreach ($errors as $error) {
if (strlen($name) > 0) {
// We are merging a sub-schema error that did not occur on a particular property of the sub-schema.
if ($path === '') {
$fullPath = $name;
} else {
$fullPath = "{$name}/{$path}";
}
$this->addError($fullPath, $error['error'], $error);
}
}
}
return $this;
} | php | public function merge(Validation $validation, $name = '') {
$paths = $validation->errors;
foreach ($paths as $path => $errors) {
foreach ($errors as $error) {
if (strlen($name) > 0) {
// We are merging a sub-schema error that did not occur on a particular property of the sub-schema.
if ($path === '') {
$fullPath = $name;
} else {
$fullPath = "{$name}/{$path}";
}
$this->addError($fullPath, $error['error'], $error);
}
}
}
return $this;
} | [
"public",
"function",
"merge",
"(",
"Validation",
"$",
"validation",
",",
"$",
"name",
"=",
"''",
")",
"{",
"$",
"paths",
"=",
"$",
"validation",
"->",
"errors",
";",
"foreach",
"(",
"$",
"paths",
"as",
"$",
"path",
"=>",
"$",
"errors",
")",
"{",
"foreach",
"(",
"$",
"errors",
"as",
"$",
"error",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"name",
")",
">",
"0",
")",
"{",
"// We are merging a sub-schema error that did not occur on a particular property of the sub-schema.",
"if",
"(",
"$",
"path",
"===",
"''",
")",
"{",
"$",
"fullPath",
"=",
"$",
"name",
";",
"}",
"else",
"{",
"$",
"fullPath",
"=",
"\"{$name}/{$path}\"",
";",
"}",
"$",
"this",
"->",
"addError",
"(",
"$",
"fullPath",
",",
"$",
"error",
"[",
"'error'",
"]",
",",
"$",
"error",
")",
";",
"}",
"}",
"}",
"return",
"$",
"this",
";",
"}"
]
| Merge another validation object with this one.
@param Validation $validation The validation object to merge.
@param string $name The path to merge to. Use this parameter when the validation object is meant to be a subset of this one.
@return $this | [
"Merge",
"another",
"validation",
"object",
"with",
"this",
"one",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L473-L490 | train |
vanilla/garden-schema | src/Validation.php | Validation.addError | public function addError(string $field, string $error, $options = []) {
if (empty($error)) {
throw new \InvalidArgumentException('The error code cannot be empty.', 500);
} elseif (!in_array(gettype($options), ['integer', 'array'], true)) {
throw new \InvalidArgumentException('$options must be an integer or array.', 500);
}
if (is_int($options)) {
trigger_error('Passing an integer for $options in Validation::addError() is deprecated.', E_USER_DEPRECATED);
$options = ['code' => $options];
} elseif (isset($options['status'])) {
trigger_error('Validation::addError() expects $options[\'number\'], not $options[\'status\'].', E_USER_DEPRECATED);
$options['code'] = $options['status'];
unset($options['status']);
}
$row = ['error' => $error] + $options;
$this->errors[$field][] = $row;
return $this;
} | php | public function addError(string $field, string $error, $options = []) {
if (empty($error)) {
throw new \InvalidArgumentException('The error code cannot be empty.', 500);
} elseif (!in_array(gettype($options), ['integer', 'array'], true)) {
throw new \InvalidArgumentException('$options must be an integer or array.', 500);
}
if (is_int($options)) {
trigger_error('Passing an integer for $options in Validation::addError() is deprecated.', E_USER_DEPRECATED);
$options = ['code' => $options];
} elseif (isset($options['status'])) {
trigger_error('Validation::addError() expects $options[\'number\'], not $options[\'status\'].', E_USER_DEPRECATED);
$options['code'] = $options['status'];
unset($options['status']);
}
$row = ['error' => $error] + $options;
$this->errors[$field][] = $row;
return $this;
} | [
"public",
"function",
"addError",
"(",
"string",
"$",
"field",
",",
"string",
"$",
"error",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"error",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The error code cannot be empty.'",
",",
"500",
")",
";",
"}",
"elseif",
"(",
"!",
"in_array",
"(",
"gettype",
"(",
"$",
"options",
")",
",",
"[",
"'integer'",
",",
"'array'",
"]",
",",
"true",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'$options must be an integer or array.'",
",",
"500",
")",
";",
"}",
"if",
"(",
"is_int",
"(",
"$",
"options",
")",
")",
"{",
"trigger_error",
"(",
"'Passing an integer for $options in Validation::addError() is deprecated.'",
",",
"E_USER_DEPRECATED",
")",
";",
"$",
"options",
"=",
"[",
"'code'",
"=>",
"$",
"options",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"options",
"[",
"'status'",
"]",
")",
")",
"{",
"trigger_error",
"(",
"'Validation::addError() expects $options[\\'number\\'], not $options[\\'status\\'].'",
",",
"E_USER_DEPRECATED",
")",
";",
"$",
"options",
"[",
"'code'",
"]",
"=",
"$",
"options",
"[",
"'status'",
"]",
";",
"unset",
"(",
"$",
"options",
"[",
"'status'",
"]",
")",
";",
"}",
"$",
"row",
"=",
"[",
"'error'",
"=>",
"$",
"error",
"]",
"+",
"$",
"options",
";",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
"[",
"]",
"=",
"$",
"row",
";",
"return",
"$",
"this",
";",
"}"
]
| Add an error.
@param string $field The name and path of the field to add or an empty string if this is a global error.
@param string $error The message code.
@param array $options An array of additional information to add to the error entry or a numeric error code.
- **messageCode**: A specific message translation code for the final error.
- **number**: An error number for the error.
- Error specific fields can be added to format a custom error message.
@return $this | [
"Add",
"an",
"error",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L504-L523 | train |
vanilla/garden-schema | src/Validation.php | Validation.getConcatMessage | public function getConcatMessage($field = null, string $sep = ' ', bool $punctuate = true): string {
$sentence = $this->translate('%s.');
$errors = $field === null ? $this->getRawErrors() : ($this->errors[$field] ?? []);
// Generate the message by concatenating all of the errors together.
$messages = [];
foreach ($errors as $field => $error) {
$message = $this->formatErrorMessage($error + ['field' => $field]);
if ($punctuate && preg_match('`\PP$`u', $message)) {
$message = sprintf($sentence, $message);
}
$messages[] = $message;
}
return implode($sep, $messages);
} | php | public function getConcatMessage($field = null, string $sep = ' ', bool $punctuate = true): string {
$sentence = $this->translate('%s.');
$errors = $field === null ? $this->getRawErrors() : ($this->errors[$field] ?? []);
// Generate the message by concatenating all of the errors together.
$messages = [];
foreach ($errors as $field => $error) {
$message = $this->formatErrorMessage($error + ['field' => $field]);
if ($punctuate && preg_match('`\PP$`u', $message)) {
$message = sprintf($sentence, $message);
}
$messages[] = $message;
}
return implode($sep, $messages);
} | [
"public",
"function",
"getConcatMessage",
"(",
"$",
"field",
"=",
"null",
",",
"string",
"$",
"sep",
"=",
"' '",
",",
"bool",
"$",
"punctuate",
"=",
"true",
")",
":",
"string",
"{",
"$",
"sentence",
"=",
"$",
"this",
"->",
"translate",
"(",
"'%s.'",
")",
";",
"$",
"errors",
"=",
"$",
"field",
"===",
"null",
"?",
"$",
"this",
"->",
"getRawErrors",
"(",
")",
":",
"(",
"$",
"this",
"->",
"errors",
"[",
"$",
"field",
"]",
"??",
"[",
"]",
")",
";",
"// Generate the message by concatenating all of the errors together.",
"$",
"messages",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"errors",
"as",
"$",
"field",
"=>",
"$",
"error",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"formatErrorMessage",
"(",
"$",
"error",
"+",
"[",
"'field'",
"=>",
"$",
"field",
"]",
")",
";",
"if",
"(",
"$",
"punctuate",
"&&",
"preg_match",
"(",
"'`\\PP$`u'",
",",
"$",
"message",
")",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"$",
"sentence",
",",
"$",
"message",
")",
";",
"}",
"$",
"messages",
"[",
"]",
"=",
"$",
"message",
";",
"}",
"return",
"implode",
"(",
"$",
"sep",
",",
"$",
"messages",
")",
";",
"}"
]
| Generate a global error string by concatenating field errors.
@param string|null $field The name of a field to concatenate errors for.
@param string $sep The error message separator.
@param bool $punctuate Whether or not to automatically add punctuation to errors if they don't have it already.
@return string Returns an error message. | [
"Generate",
"a",
"global",
"error",
"string",
"by",
"concatenating",
"field",
"errors",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L557-L572 | train |
vanilla/garden-schema | src/Validation.php | Validation.getSummaryMessage | public function getSummaryMessage(): string {
if ($main = $this->getMainMessage()) {
return $main;
} elseif ($this->isValid()) {
return $this->translate('Validation succeeded.');
} else {
return $this->translate('Validation failed.');
}
} | php | public function getSummaryMessage(): string {
if ($main = $this->getMainMessage()) {
return $main;
} elseif ($this->isValid()) {
return $this->translate('Validation succeeded.');
} else {
return $this->translate('Validation failed.');
}
} | [
"public",
"function",
"getSummaryMessage",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"main",
"=",
"$",
"this",
"->",
"getMainMessage",
"(",
")",
")",
"{",
"return",
"$",
"main",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"isValid",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"translate",
"(",
"'Validation succeeded.'",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"translate",
"(",
"'Validation failed.'",
")",
";",
"}",
"}"
]
| Get just the summary message for the validation.
@return string Returns the message. | [
"Get",
"just",
"the",
"summary",
"message",
"for",
"the",
"validation",
"."
]
| 17da87a83d15d45cfedc4d27cf800618160e1cbf | https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Validation.php#L604-L612 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php | EventManagerAwareTrait.eventsList | public function eventsList()
{
$eventList = $this->eventManager()->entries();
foreach ($eventList as $event) {
yield $this->eventFormatShort($event);
}
} | php | public function eventsList()
{
$eventList = $this->eventManager()->entries();
foreach ($eventList as $event) {
yield $this->eventFormatShort($event);
}
} | [
"public",
"function",
"eventsList",
"(",
")",
"{",
"$",
"eventList",
"=",
"$",
"this",
"->",
"eventManager",
"(",
")",
"->",
"entries",
"(",
")",
";",
"foreach",
"(",
"$",
"eventList",
"as",
"$",
"event",
")",
"{",
"yield",
"$",
"this",
"->",
"eventFormatShort",
"(",
"$",
"event",
")",
";",
"}",
"}"
]
| Formatted event list
Return the entries for the current page
@return \Generator|void | [
"Formatted",
"event",
"list",
"Return",
"the",
"entries",
"for",
"the",
"current",
"page"
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php#L40-L46 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php | EventManagerAwareTrait.eventArchiveList | public function eventArchiveList()
{
$entries = $this->eventManager()->archive();
foreach ($entries as $entry) {
yield $this->eventFormatShort($entry);
}
} | php | public function eventArchiveList()
{
$entries = $this->eventManager()->archive();
foreach ($entries as $entry) {
yield $this->eventFormatShort($entry);
}
} | [
"public",
"function",
"eventArchiveList",
"(",
")",
"{",
"$",
"entries",
"=",
"$",
"this",
"->",
"eventManager",
"(",
")",
"->",
"archive",
"(",
")",
";",
"foreach",
"(",
"$",
"entries",
"as",
"$",
"entry",
")",
"{",
"yield",
"$",
"this",
"->",
"eventFormatShort",
"(",
"$",
"entry",
")",
";",
"}",
"}"
]
| Formatted event archive list
Returns the entries for the current page.
@return \Generator|void | [
"Formatted",
"event",
"archive",
"list",
"Returns",
"the",
"entries",
"for",
"the",
"current",
"page",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php#L53-L59 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php | EventManagerAwareTrait.currentEvent | public function currentEvent()
{
if ($this->currentEvent) {
return $this->currentEvent;
}
// The the current event
$event = $this->eventManager()->entry();
// Format the event
if ($event) {
$this->currentEvent = $this->eventFormatFull($event);
}
return $this->currentEvent;
} | php | public function currentEvent()
{
if ($this->currentEvent) {
return $this->currentEvent;
}
// The the current event
$event = $this->eventManager()->entry();
// Format the event
if ($event) {
$this->currentEvent = $this->eventFormatFull($event);
}
return $this->currentEvent;
} | [
"public",
"function",
"currentEvent",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"currentEvent",
")",
"{",
"return",
"$",
"this",
"->",
"currentEvent",
";",
"}",
"// The the current event",
"$",
"event",
"=",
"$",
"this",
"->",
"eventManager",
"(",
")",
"->",
"entry",
"(",
")",
";",
"// Format the event",
"if",
"(",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"currentEvent",
"=",
"$",
"this",
"->",
"eventFormatFull",
"(",
"$",
"event",
")",
";",
"}",
"return",
"$",
"this",
"->",
"currentEvent",
";",
"}"
]
| Current event.
@return array The properties of the current event. | [
"Current",
"event",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/EventManagerAwareTrait.php#L65-L80 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.templateIdentClass | public function templateIdentClass()
{
$templateIdent = $this->templateIdent();
$property = $this->property('template_ident');
$key = $property->ident();
if ($property instanceof SelectablePropertyInterface) {
if ($property->hasChoice($templateIdent)) {
$choice = $property->choice($templateIdent);
$keys = [ 'controller', 'template', 'class' ];
foreach ($keys as $key) {
if (isset($choice[$key])) {
return $choice[$key];
}
}
}
} else {
return $templateIdent;
}
} | php | public function templateIdentClass()
{
$templateIdent = $this->templateIdent();
$property = $this->property('template_ident');
$key = $property->ident();
if ($property instanceof SelectablePropertyInterface) {
if ($property->hasChoice($templateIdent)) {
$choice = $property->choice($templateIdent);
$keys = [ 'controller', 'template', 'class' ];
foreach ($keys as $key) {
if (isset($choice[$key])) {
return $choice[$key];
}
}
}
} else {
return $templateIdent;
}
} | [
"public",
"function",
"templateIdentClass",
"(",
")",
"{",
"$",
"templateIdent",
"=",
"$",
"this",
"->",
"templateIdent",
"(",
")",
";",
"$",
"property",
"=",
"$",
"this",
"->",
"property",
"(",
"'template_ident'",
")",
";",
"$",
"key",
"=",
"$",
"property",
"->",
"ident",
"(",
")",
";",
"if",
"(",
"$",
"property",
"instanceof",
"SelectablePropertyInterface",
")",
"{",
"if",
"(",
"$",
"property",
"->",
"hasChoice",
"(",
"$",
"templateIdent",
")",
")",
"{",
"$",
"choice",
"=",
"$",
"property",
"->",
"choice",
"(",
"$",
"templateIdent",
")",
";",
"$",
"keys",
"=",
"[",
"'controller'",
",",
"'template'",
",",
"'class'",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"choice",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"choice",
"[",
"$",
"key",
"]",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"return",
"$",
"templateIdent",
";",
"}",
"}"
]
| Retrieve the template identifier as class path.
@return mixed | [
"Retrieve",
"the",
"template",
"identifier",
"as",
"class",
"path",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L97-L116 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.setTemplateOptions | public function setTemplateOptions($options)
{
$this->areTemplateOptionsFinalized = false;
if (is_numeric($options)) {
$options = null;
} elseif (is_string($options)) {
$options = json_decode($options, true);
}
$this->templateOptions = $options;
return $this;
} | php | public function setTemplateOptions($options)
{
$this->areTemplateOptionsFinalized = false;
if (is_numeric($options)) {
$options = null;
} elseif (is_string($options)) {
$options = json_decode($options, true);
}
$this->templateOptions = $options;
return $this;
} | [
"public",
"function",
"setTemplateOptions",
"(",
"$",
"options",
")",
"{",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"=",
"false",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"options",
")",
")",
"{",
"$",
"options",
"=",
"null",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"options",
")",
")",
"{",
"$",
"options",
"=",
"json_decode",
"(",
"$",
"options",
",",
"true",
")",
";",
"}",
"$",
"this",
"->",
"templateOptions",
"=",
"$",
"options",
";",
"return",
"$",
"this",
";",
"}"
]
| Customize the template's options.
@param mixed $options Template options.
@return self | [
"Customize",
"the",
"template",
"s",
"options",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L149-L162 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.hasTemplateOptions | public function hasTemplateOptions()
{
if ($this->templateOptionsStructure()) {
return (bool)count(
iterator_to_array(
$this->templateOptionsStructure()->properties()
)
);
}
return false;
} | php | public function hasTemplateOptions()
{
if ($this->templateOptionsStructure()) {
return (bool)count(
iterator_to_array(
$this->templateOptionsStructure()->properties()
)
);
}
return false;
} | [
"public",
"function",
"hasTemplateOptions",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"templateOptionsStructure",
"(",
")",
")",
"{",
"return",
"(",
"bool",
")",
"count",
"(",
"iterator_to_array",
"(",
"$",
"this",
"->",
"templateOptionsStructure",
"(",
")",
"->",
"properties",
"(",
")",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Validate the model has template options properties.
@return boolean | [
"Validate",
"the",
"model",
"has",
"template",
"options",
"properties",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L179-L190 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.templateOptionsMetadata | public function templateOptionsMetadata()
{
if ($this->areTemplateOptionsFinalized === false) {
$this->areTemplateOptionsFinalized = true;
$this->prepareTemplateOptions();
}
return $this->templateOptionsMetadata;
} | php | public function templateOptionsMetadata()
{
if ($this->areTemplateOptionsFinalized === false) {
$this->areTemplateOptionsFinalized = true;
$this->prepareTemplateOptions();
}
return $this->templateOptionsMetadata;
} | [
"public",
"function",
"templateOptionsMetadata",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"=",
"true",
";",
"$",
"this",
"->",
"prepareTemplateOptions",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"templateOptionsMetadata",
";",
"}"
]
| Retrieve the object's template options metadata.
@return StructureMetadata|null | [
"Retrieve",
"the",
"object",
"s",
"template",
"options",
"metadata",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L197-L205 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.templateOptionsStructure | public function templateOptionsStructure()
{
if ($this->areTemplateOptionsFinalized === false) {
$this->areTemplateOptionsFinalized = true;
$this->prepareTemplateOptions();
}
$key = 'template_options';
$prop = $this->property($key);
$val = $this->propertyValue($key);
$obj = $prop->structureVal($val, $this->templateOptionsMetadata());
return $obj;
} | php | public function templateOptionsStructure()
{
if ($this->areTemplateOptionsFinalized === false) {
$this->areTemplateOptionsFinalized = true;
$this->prepareTemplateOptions();
}
$key = 'template_options';
$prop = $this->property($key);
$val = $this->propertyValue($key);
$obj = $prop->structureVal($val, $this->templateOptionsMetadata());
return $obj;
} | [
"public",
"function",
"templateOptionsStructure",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"=",
"true",
";",
"$",
"this",
"->",
"prepareTemplateOptions",
"(",
")",
";",
"}",
"$",
"key",
"=",
"'template_options'",
";",
"$",
"prop",
"=",
"$",
"this",
"->",
"property",
"(",
"$",
"key",
")",
";",
"$",
"val",
"=",
"$",
"this",
"->",
"propertyValue",
"(",
"$",
"key",
")",
";",
"$",
"obj",
"=",
"$",
"prop",
"->",
"structureVal",
"(",
"$",
"val",
",",
"$",
"this",
"->",
"templateOptionsMetadata",
"(",
")",
")",
";",
"return",
"$",
"obj",
";",
"}"
]
| Retrieve the object's template options as a structured model.
@return ModelInterface|ModelInterface[]|null | [
"Retrieve",
"the",
"object",
"s",
"template",
"options",
"as",
"a",
"structured",
"model",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L212-L225 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.assertValidTemplateStructureDependencies | final protected function assertValidTemplateStructureDependencies()
{
if (!$this instanceof TemplateableInterface) {
throw new RuntimeException(sprintf(
'Class [%s] must implement [%s]',
get_class($this),
TemplateableInterface::class
));
}
$prop = $this->property('template_options');
if (!$prop instanceof TemplateOptionsProperty) {
throw new RuntimeException(sprintf(
'Property "%s" must use [%s]',
$prop->ident(),
TemplateOptionsProperty::class
));
}
} | php | final protected function assertValidTemplateStructureDependencies()
{
if (!$this instanceof TemplateableInterface) {
throw new RuntimeException(sprintf(
'Class [%s] must implement [%s]',
get_class($this),
TemplateableInterface::class
));
}
$prop = $this->property('template_options');
if (!$prop instanceof TemplateOptionsProperty) {
throw new RuntimeException(sprintf(
'Property "%s" must use [%s]',
$prop->ident(),
TemplateOptionsProperty::class
));
}
} | [
"final",
"protected",
"function",
"assertValidTemplateStructureDependencies",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"instanceof",
"TemplateableInterface",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Class [%s] must implement [%s]'",
",",
"get_class",
"(",
"$",
"this",
")",
",",
"TemplateableInterface",
"::",
"class",
")",
")",
";",
"}",
"$",
"prop",
"=",
"$",
"this",
"->",
"property",
"(",
"'template_options'",
")",
";",
"if",
"(",
"!",
"$",
"prop",
"instanceof",
"TemplateOptionsProperty",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Property \"%s\" must use [%s]'",
",",
"$",
"prop",
"->",
"ident",
"(",
")",
",",
"TemplateOptionsProperty",
"::",
"class",
")",
")",
";",
"}",
"}"
]
| Asserts that the templateable class meets the requirements,
throws an Exception if not.
Requirements:
1. The class implements the {@see TemplateableInterface} and
2. The model's "template_options" property uses the {@see TemplateOptionsProperty}.
@throws RuntimeException If the model does not implement its requirements.
@return void | [
"Asserts",
"that",
"the",
"templateable",
"class",
"meets",
"the",
"requirements",
"throws",
"an",
"Exception",
"if",
"not",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L239-L257 | train |
locomotivemtl/charcoal-cms | src/Charcoal/Cms/TemplateableTrait.php | TemplateableTrait.saveTemplateOptions | protected function saveTemplateOptions(array $properties = null)
{
if ($properties === null) {
$properties = $this->defaultTemplateProperties();
}
if ($this->areTemplateOptionsFinalized === false) {
$this->areTemplateOptionsFinalized = true;
$this->prepareTemplateOptions();
}
$key = 'template_options';
$prop = $this->property($key);
$prop->setStructureMetadata($this->templateOptionsMetadata());
} | php | protected function saveTemplateOptions(array $properties = null)
{
if ($properties === null) {
$properties = $this->defaultTemplateProperties();
}
if ($this->areTemplateOptionsFinalized === false) {
$this->areTemplateOptionsFinalized = true;
$this->prepareTemplateOptions();
}
$key = 'template_options';
$prop = $this->property($key);
$prop->setStructureMetadata($this->templateOptionsMetadata());
} | [
"protected",
"function",
"saveTemplateOptions",
"(",
"array",
"$",
"properties",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"properties",
"===",
"null",
")",
"{",
"$",
"properties",
"=",
"$",
"this",
"->",
"defaultTemplateProperties",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"areTemplateOptionsFinalized",
"=",
"true",
";",
"$",
"this",
"->",
"prepareTemplateOptions",
"(",
")",
";",
"}",
"$",
"key",
"=",
"'template_options'",
";",
"$",
"prop",
"=",
"$",
"this",
"->",
"property",
"(",
"$",
"key",
")",
";",
"$",
"prop",
"->",
"setStructureMetadata",
"(",
"$",
"this",
"->",
"templateOptionsMetadata",
"(",
")",
")",
";",
"}"
]
| Save the template options structure.
@param (PropertyInterface|string)[]|null $properties The template properties to parse.
@return void | [
"Save",
"the",
"template",
"options",
"structure",
"."
]
| 3467caebdebdaaa226d223a905ebcc3e24fdca16 | https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/TemplateableTrait.php#L389-L403 | train |
composer-php52/composer-php52 | lib/xrstf/Composer52/ClassLoader.php | xrstf_Composer52_ClassLoader.add | public function add($prefix, $paths, $prepend = false) {
if (!$prefix) {
if ($prepend) {
$this->fallbackDirs = array_merge(
(array) $paths,
$this->fallbackDirs
);
}
else {
$this->fallbackDirs = array_merge(
$this->fallbackDirs,
(array) $paths
);
}
return;
}
if (!isset($this->prefixes[$prefix])) {
$this->prefixes[$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixes[$prefix] = array_merge(
(array) $paths,
$this->prefixes[$prefix]
);
}
else {
$this->prefixes[$prefix] = array_merge(
$this->prefixes[$prefix],
(array) $paths
);
}
} | php | public function add($prefix, $paths, $prepend = false) {
if (!$prefix) {
if ($prepend) {
$this->fallbackDirs = array_merge(
(array) $paths,
$this->fallbackDirs
);
}
else {
$this->fallbackDirs = array_merge(
$this->fallbackDirs,
(array) $paths
);
}
return;
}
if (!isset($this->prefixes[$prefix])) {
$this->prefixes[$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixes[$prefix] = array_merge(
(array) $paths,
$this->prefixes[$prefix]
);
}
else {
$this->prefixes[$prefix] = array_merge(
$this->prefixes[$prefix],
(array) $paths
);
}
} | [
"public",
"function",
"add",
"(",
"$",
"prefix",
",",
"$",
"paths",
",",
"$",
"prepend",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"prefix",
")",
"{",
"if",
"(",
"$",
"prepend",
")",
"{",
"$",
"this",
"->",
"fallbackDirs",
"=",
"array_merge",
"(",
"(",
"array",
")",
"$",
"paths",
",",
"$",
"this",
"->",
"fallbackDirs",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"fallbackDirs",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"fallbackDirs",
",",
"(",
"array",
")",
"$",
"paths",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
")",
")",
"{",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
"=",
"(",
"array",
")",
"$",
"paths",
";",
"return",
";",
"}",
"if",
"(",
"$",
"prepend",
")",
"{",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
"=",
"array_merge",
"(",
"(",
"array",
")",
"$",
"paths",
",",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
",",
"(",
"array",
")",
"$",
"paths",
")",
";",
"}",
"}"
]
| Registers a set of classes, merging with any others previously set.
@param string $prefix the classes prefix
@param array|string $paths the location(s) of the classes
@param bool $prepend prepend the location(s) | [
"Registers",
"a",
"set",
"of",
"classes",
"merging",
"with",
"any",
"others",
"previously",
"set",
"."
]
| bd41459d5e27df8d33057842b32377c39e97a5a8 | https://github.com/composer-php52/composer-php52/blob/bd41459d5e27df8d33057842b32377c39e97a5a8/lib/xrstf/Composer52/ClassLoader.php#L93-L128 | train |
composer-php52/composer-php52 | lib/xrstf/Composer52/ClassLoader.php | xrstf_Composer52_ClassLoader.set | public function set($prefix, $paths) {
if (!$prefix) {
$this->fallbackDirs = (array) $paths;
return;
}
$this->prefixes[$prefix] = (array) $paths;
} | php | public function set($prefix, $paths) {
if (!$prefix) {
$this->fallbackDirs = (array) $paths;
return;
}
$this->prefixes[$prefix] = (array) $paths;
} | [
"public",
"function",
"set",
"(",
"$",
"prefix",
",",
"$",
"paths",
")",
"{",
"if",
"(",
"!",
"$",
"prefix",
")",
"{",
"$",
"this",
"->",
"fallbackDirs",
"=",
"(",
"array",
")",
"$",
"paths",
";",
"return",
";",
"}",
"$",
"this",
"->",
"prefixes",
"[",
"$",
"prefix",
"]",
"=",
"(",
"array",
")",
"$",
"paths",
";",
"}"
]
| Registers a set of classes, replacing any others previously set.
@param string $prefix the classes prefix
@param array|string $paths the location(s) of the classes | [
"Registers",
"a",
"set",
"of",
"classes",
"replacing",
"any",
"others",
"previously",
"set",
"."
]
| bd41459d5e27df8d33057842b32377c39e97a5a8 | https://github.com/composer-php52/composer-php52/blob/bd41459d5e27df8d33057842b32377c39e97a5a8/lib/xrstf/Composer52/ClassLoader.php#L136-L143 | train |
silverstripe/silverstripe-taxonomy | src/TaxonomyTerm.php | TaxonomyTerm.getTaxonomyType | public function getTaxonomyType()
{
$taxonomy = $this->getTaxonomy();
if ($taxonomy->Type() && $taxonomy->Type()->exists()) {
return $taxonomy->Type()->Name;
}
return '';
} | php | public function getTaxonomyType()
{
$taxonomy = $this->getTaxonomy();
if ($taxonomy->Type() && $taxonomy->Type()->exists()) {
return $taxonomy->Type()->Name;
}
return '';
} | [
"public",
"function",
"getTaxonomyType",
"(",
")",
"{",
"$",
"taxonomy",
"=",
"$",
"this",
"->",
"getTaxonomy",
"(",
")",
";",
"if",
"(",
"$",
"taxonomy",
"->",
"Type",
"(",
")",
"&&",
"$",
"taxonomy",
"->",
"Type",
"(",
")",
"->",
"exists",
"(",
")",
")",
"{",
"return",
"$",
"taxonomy",
"->",
"Type",
"(",
")",
"->",
"Name",
";",
"}",
"return",
"''",
";",
"}"
]
| Get the type of the top-level ancestor if it is set
@return string | [
"Get",
"the",
"type",
"of",
"the",
"top",
"-",
"level",
"ancestor",
"if",
"it",
"is",
"set"
]
| e16d0aeaa249a92089e6feaeb40ab2ad40d20250 | https://github.com/silverstripe/silverstripe-taxonomy/blob/e16d0aeaa249a92089e6feaeb40ab2ad40d20250/src/TaxonomyTerm.php#L125-L132 | train |
danslo/CleanCheckoutCore | src/Observer/RedirectToCheckoutObserver.php | RedirectToCheckoutObserver.execute | public function execute(Observer $observer)
{
if (!$this->scopeConfig->getValue(self::CONFIG_PATH_REDIRECT_TO_CHECKOUT, ScopeInterface::SCOPE_STORE)) {
return;
}
/** @var Http $request */
$request = $observer->getData('request');
$request->setParam('return_url', $this->url->getUrl('checkout'));
} | php | public function execute(Observer $observer)
{
if (!$this->scopeConfig->getValue(self::CONFIG_PATH_REDIRECT_TO_CHECKOUT, ScopeInterface::SCOPE_STORE)) {
return;
}
/** @var Http $request */
$request = $observer->getData('request');
$request->setParam('return_url', $this->url->getUrl('checkout'));
} | [
"public",
"function",
"execute",
"(",
"Observer",
"$",
"observer",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"scopeConfig",
"->",
"getValue",
"(",
"self",
"::",
"CONFIG_PATH_REDIRECT_TO_CHECKOUT",
",",
"ScopeInterface",
"::",
"SCOPE_STORE",
")",
")",
"{",
"return",
";",
"}",
"/** @var Http $request */",
"$",
"request",
"=",
"$",
"observer",
"->",
"getData",
"(",
"'request'",
")",
";",
"$",
"request",
"->",
"setParam",
"(",
"'return_url'",
",",
"$",
"this",
"->",
"url",
"->",
"getUrl",
"(",
"'checkout'",
")",
")",
";",
"}"
]
| Redirects directly to checkout on adding product, if we're configured to do so.
@param Observer $observer
@return void | [
"Redirects",
"directly",
"to",
"checkout",
"on",
"adding",
"product",
"if",
"we",
"re",
"configured",
"to",
"do",
"so",
"."
]
| cf38862ba72db42c7d0fe31413665473ef65585b | https://github.com/danslo/CleanCheckoutCore/blob/cf38862ba72db42c7d0fe31413665473ef65585b/src/Observer/RedirectToCheckoutObserver.php#L45-L54 | train |
silverstripe/silverstripe-taxonomy | src/TaxonomyAdmin.php | TaxonomyAdmin.getList | public function getList()
{
if ($this->modelClass === TaxonomyTerm::class) {
$list = parent::getList();
return $list->filter('ParentID', '0');
}
return parent::getList();
} | php | public function getList()
{
if ($this->modelClass === TaxonomyTerm::class) {
$list = parent::getList();
return $list->filter('ParentID', '0');
}
return parent::getList();
} | [
"public",
"function",
"getList",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"modelClass",
"===",
"TaxonomyTerm",
"::",
"class",
")",
"{",
"$",
"list",
"=",
"parent",
"::",
"getList",
"(",
")",
";",
"return",
"$",
"list",
"->",
"filter",
"(",
"'ParentID'",
",",
"'0'",
")",
";",
"}",
"return",
"parent",
"::",
"getList",
"(",
")",
";",
"}"
]
| If terms are the models being managed, filter for only top-level terms - no children
@return SS_List | [
"If",
"terms",
"are",
"the",
"models",
"being",
"managed",
"filter",
"for",
"only",
"top",
"-",
"level",
"terms",
"-",
"no",
"children"
]
| e16d0aeaa249a92089e6feaeb40ab2ad40d20250 | https://github.com/silverstripe/silverstripe-taxonomy/blob/e16d0aeaa249a92089e6feaeb40ab2ad40d20250/src/TaxonomyAdmin.php#L30-L37 | train |
danslo/CleanCheckoutCore | src/Plugin/ModifyCheckoutLayoutPlugin.php | ModifyCheckoutLayoutPlugin.disableAuthentication | private function disableAuthentication($jsLayout)
{
if ($this->scopeConfig->getValue(self::CONFIG_DISABLE_LOGIN_PATH, ScopeInterface::SCOPE_STORE)) {
unset($jsLayout['components']['checkout']['children']['authentication']);
}
return $jsLayout;
} | php | private function disableAuthentication($jsLayout)
{
if ($this->scopeConfig->getValue(self::CONFIG_DISABLE_LOGIN_PATH, ScopeInterface::SCOPE_STORE)) {
unset($jsLayout['components']['checkout']['children']['authentication']);
}
return $jsLayout;
} | [
"private",
"function",
"disableAuthentication",
"(",
"$",
"jsLayout",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"scopeConfig",
"->",
"getValue",
"(",
"self",
"::",
"CONFIG_DISABLE_LOGIN_PATH",
",",
"ScopeInterface",
"::",
"SCOPE_STORE",
")",
")",
"{",
"unset",
"(",
"$",
"jsLayout",
"[",
"'components'",
"]",
"[",
"'checkout'",
"]",
"[",
"'children'",
"]",
"[",
"'authentication'",
"]",
")",
";",
"}",
"return",
"$",
"jsLayout",
";",
"}"
]
| Disables authentication modal.
@param array $jsLayout
@return array | [
"Disables",
"authentication",
"modal",
"."
]
| cf38862ba72db42c7d0fe31413665473ef65585b | https://github.com/danslo/CleanCheckoutCore/blob/cf38862ba72db42c7d0fe31413665473ef65585b/src/Plugin/ModifyCheckoutLayoutPlugin.php#L59-L65 | train |
danslo/CleanCheckoutCore | src/Plugin/ModifyCheckoutLayoutPlugin.php | ModifyCheckoutLayoutPlugin.changeCartItemsSortOrder | private function changeCartItemsSortOrder($jsLayout)
{
if ($this->scopeConfig->getValue(self::CONFIG_MOVE_CART_ITEMS_PATH, ScopeInterface::SCOPE_STORE)) {
$jsLayout['components']['checkout']['children']['sidebar']['children']['summary']['children']['cart_items']
['sortOrder'] = 0;
}
return $jsLayout;
} | php | private function changeCartItemsSortOrder($jsLayout)
{
if ($this->scopeConfig->getValue(self::CONFIG_MOVE_CART_ITEMS_PATH, ScopeInterface::SCOPE_STORE)) {
$jsLayout['components']['checkout']['children']['sidebar']['children']['summary']['children']['cart_items']
['sortOrder'] = 0;
}
return $jsLayout;
} | [
"private",
"function",
"changeCartItemsSortOrder",
"(",
"$",
"jsLayout",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"scopeConfig",
"->",
"getValue",
"(",
"self",
"::",
"CONFIG_MOVE_CART_ITEMS_PATH",
",",
"ScopeInterface",
"::",
"SCOPE_STORE",
")",
")",
"{",
"$",
"jsLayout",
"[",
"'components'",
"]",
"[",
"'checkout'",
"]",
"[",
"'children'",
"]",
"[",
"'sidebar'",
"]",
"[",
"'children'",
"]",
"[",
"'summary'",
"]",
"[",
"'children'",
"]",
"[",
"'cart_items'",
"]",
"[",
"'sortOrder'",
"]",
"=",
"0",
";",
"}",
"return",
"$",
"jsLayout",
";",
"}"
]
| Changes cart items to be above totals in the cart summary.
@param array $jsLayout
@return array | [
"Changes",
"cart",
"items",
"to",
"be",
"above",
"totals",
"in",
"the",
"cart",
"summary",
"."
]
| cf38862ba72db42c7d0fe31413665473ef65585b | https://github.com/danslo/CleanCheckoutCore/blob/cf38862ba72db42c7d0fe31413665473ef65585b/src/Plugin/ModifyCheckoutLayoutPlugin.php#L73-L80 | train |
danslo/CleanCheckoutCore | src/Plugin/ModifyCheckoutLayoutPlugin.php | ModifyCheckoutLayoutPlugin.disableDiscountComponent | private function disableDiscountComponent($jsLayout)
{
if ($this->scopeConfig->getValue(self::CONFIG_DISABLE_DISCOUNT_PATH, ScopeInterface::SCOPE_STORE)) {
unset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['afterMethods']['children']['discount']);
}
return $jsLayout;
} | php | private function disableDiscountComponent($jsLayout)
{
if ($this->scopeConfig->getValue(self::CONFIG_DISABLE_DISCOUNT_PATH, ScopeInterface::SCOPE_STORE)) {
unset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
['payment']['children']['afterMethods']['children']['discount']);
}
return $jsLayout;
} | [
"private",
"function",
"disableDiscountComponent",
"(",
"$",
"jsLayout",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"scopeConfig",
"->",
"getValue",
"(",
"self",
"::",
"CONFIG_DISABLE_DISCOUNT_PATH",
",",
"ScopeInterface",
"::",
"SCOPE_STORE",
")",
")",
"{",
"unset",
"(",
"$",
"jsLayout",
"[",
"'components'",
"]",
"[",
"'checkout'",
"]",
"[",
"'children'",
"]",
"[",
"'steps'",
"]",
"[",
"'children'",
"]",
"[",
"'billing-step'",
"]",
"[",
"'children'",
"]",
"[",
"'payment'",
"]",
"[",
"'children'",
"]",
"[",
"'afterMethods'",
"]",
"[",
"'children'",
"]",
"[",
"'discount'",
"]",
")",
";",
"}",
"return",
"$",
"jsLayout",
";",
"}"
]
| Disables the discount component after payment step.
@param array $jsLayout
@return array | [
"Disables",
"the",
"discount",
"component",
"after",
"payment",
"step",
"."
]
| cf38862ba72db42c7d0fe31413665473ef65585b | https://github.com/danslo/CleanCheckoutCore/blob/cf38862ba72db42c7d0fe31413665473ef65585b/src/Plugin/ModifyCheckoutLayoutPlugin.php#L146-L153 | train |
php-xapi/client | src/Api/StatementsApiClient.php | StatementsApiClient.doGetStatements | private function doGetStatements($url, array $urlParameters = array())
{
$request = $this->requestHandler->createRequest('get', $url, $urlParameters);
$response = $this->requestHandler->executeRequest($request, array(200));
$contentType = $response->getHeader('Content-Type')[0];
$body = (string) $response->getBody();
$attachments = array();
if (false !== strpos($contentType, 'application/json')) {
$serializedStatement = $body;
} else {
$boundary = substr($contentType, strpos($contentType, '=') + 1);
$parts = $this->parseMultipartResponseBody($body, $boundary);
$serializedStatement = $parts[0]['content'];
unset($parts[0]);
foreach ($parts as $part) {
$attachments[$part['headers']['X-Experience-API-Hash'][0]] = array(
'type' => $part['headers']['Content-Type'][0],
'content' => $part['content'],
);
}
}
if (isset($urlParameters['statementId']) || isset($urlParameters['voidedStatementId'])) {
return $this->statementSerializer->deserializeStatement($serializedStatement, $attachments);
} else {
return $this->statementResultSerializer->deserializeStatementResult($serializedStatement, $attachments);
}
} | php | private function doGetStatements($url, array $urlParameters = array())
{
$request = $this->requestHandler->createRequest('get', $url, $urlParameters);
$response = $this->requestHandler->executeRequest($request, array(200));
$contentType = $response->getHeader('Content-Type')[0];
$body = (string) $response->getBody();
$attachments = array();
if (false !== strpos($contentType, 'application/json')) {
$serializedStatement = $body;
} else {
$boundary = substr($contentType, strpos($contentType, '=') + 1);
$parts = $this->parseMultipartResponseBody($body, $boundary);
$serializedStatement = $parts[0]['content'];
unset($parts[0]);
foreach ($parts as $part) {
$attachments[$part['headers']['X-Experience-API-Hash'][0]] = array(
'type' => $part['headers']['Content-Type'][0],
'content' => $part['content'],
);
}
}
if (isset($urlParameters['statementId']) || isset($urlParameters['voidedStatementId'])) {
return $this->statementSerializer->deserializeStatement($serializedStatement, $attachments);
} else {
return $this->statementResultSerializer->deserializeStatementResult($serializedStatement, $attachments);
}
} | [
"private",
"function",
"doGetStatements",
"(",
"$",
"url",
",",
"array",
"$",
"urlParameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"requestHandler",
"->",
"createRequest",
"(",
"'get'",
",",
"$",
"url",
",",
"$",
"urlParameters",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"requestHandler",
"->",
"executeRequest",
"(",
"$",
"request",
",",
"array",
"(",
"200",
")",
")",
";",
"$",
"contentType",
"=",
"$",
"response",
"->",
"getHeader",
"(",
"'Content-Type'",
")",
"[",
"0",
"]",
";",
"$",
"body",
"=",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"$",
"attachments",
"=",
"array",
"(",
")",
";",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"contentType",
",",
"'application/json'",
")",
")",
"{",
"$",
"serializedStatement",
"=",
"$",
"body",
";",
"}",
"else",
"{",
"$",
"boundary",
"=",
"substr",
"(",
"$",
"contentType",
",",
"strpos",
"(",
"$",
"contentType",
",",
"'='",
")",
"+",
"1",
")",
";",
"$",
"parts",
"=",
"$",
"this",
"->",
"parseMultipartResponseBody",
"(",
"$",
"body",
",",
"$",
"boundary",
")",
";",
"$",
"serializedStatement",
"=",
"$",
"parts",
"[",
"0",
"]",
"[",
"'content'",
"]",
";",
"unset",
"(",
"$",
"parts",
"[",
"0",
"]",
")",
";",
"foreach",
"(",
"$",
"parts",
"as",
"$",
"part",
")",
"{",
"$",
"attachments",
"[",
"$",
"part",
"[",
"'headers'",
"]",
"[",
"'X-Experience-API-Hash'",
"]",
"[",
"0",
"]",
"]",
"=",
"array",
"(",
"'type'",
"=>",
"$",
"part",
"[",
"'headers'",
"]",
"[",
"'Content-Type'",
"]",
"[",
"0",
"]",
",",
"'content'",
"=>",
"$",
"part",
"[",
"'content'",
"]",
",",
")",
";",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"urlParameters",
"[",
"'statementId'",
"]",
")",
"||",
"isset",
"(",
"$",
"urlParameters",
"[",
"'voidedStatementId'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"statementSerializer",
"->",
"deserializeStatement",
"(",
"$",
"serializedStatement",
",",
"$",
"attachments",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"statementResultSerializer",
"->",
"deserializeStatementResult",
"(",
"$",
"serializedStatement",
",",
"$",
"attachments",
")",
";",
"}",
"}"
]
| Fetch one or more Statements.
@param string $url URL to request
@param array $urlParameters URL parameters
@return Statement|StatementResult | [
"Fetch",
"one",
"or",
"more",
"Statements",
"."
]
| 4e5ebba48d90a8731dae53f44d5fd92d6a79a3bf | https://github.com/php-xapi/client/blob/4e5ebba48d90a8731dae53f44d5fd92d6a79a3bf/src/Api/StatementsApiClient.php#L238-L269 | train |
php-xapi/client | src/Api/DocumentApiClient.php | DocumentApiClient.doStoreDocument | protected function doStoreDocument($method, $uri, $urlParameters, Document $document)
{
$request = $this->requestHandler->createRequest(
$method,
$uri,
$urlParameters,
$this->documentDataSerializer->serializeDocumentData($document->getData())
);
$this->requestHandler->executeRequest($request, array(204));
} | php | protected function doStoreDocument($method, $uri, $urlParameters, Document $document)
{
$request = $this->requestHandler->createRequest(
$method,
$uri,
$urlParameters,
$this->documentDataSerializer->serializeDocumentData($document->getData())
);
$this->requestHandler->executeRequest($request, array(204));
} | [
"protected",
"function",
"doStoreDocument",
"(",
"$",
"method",
",",
"$",
"uri",
",",
"$",
"urlParameters",
",",
"Document",
"$",
"document",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"requestHandler",
"->",
"createRequest",
"(",
"$",
"method",
",",
"$",
"uri",
",",
"$",
"urlParameters",
",",
"$",
"this",
"->",
"documentDataSerializer",
"->",
"serializeDocumentData",
"(",
"$",
"document",
"->",
"getData",
"(",
")",
")",
")",
";",
"$",
"this",
"->",
"requestHandler",
"->",
"executeRequest",
"(",
"$",
"request",
",",
"array",
"(",
"204",
")",
")",
";",
"}"
]
| Stores a document.
@param string $method HTTP method to use
@param string $uri Endpoint URI
@param array $urlParameters URL parameters
@param Document $document The document to store | [
"Stores",
"a",
"document",
"."
]
| 4e5ebba48d90a8731dae53f44d5fd92d6a79a3bf | https://github.com/php-xapi/client/blob/4e5ebba48d90a8731dae53f44d5fd92d6a79a3bf/src/Api/DocumentApiClient.php#L50-L59 | train |
php-xapi/client | src/Api/DocumentApiClient.php | DocumentApiClient.doGetDocument | protected function doGetDocument($uri, array $urlParameters)
{
$request = $this->requestHandler->createRequest('get', $uri, $urlParameters);
$response = $this->requestHandler->executeRequest($request, array(200));
$document = $this->deserializeDocument((string) $response->getBody());
return $document;
} | php | protected function doGetDocument($uri, array $urlParameters)
{
$request = $this->requestHandler->createRequest('get', $uri, $urlParameters);
$response = $this->requestHandler->executeRequest($request, array(200));
$document = $this->deserializeDocument((string) $response->getBody());
return $document;
} | [
"protected",
"function",
"doGetDocument",
"(",
"$",
"uri",
",",
"array",
"$",
"urlParameters",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"requestHandler",
"->",
"createRequest",
"(",
"'get'",
",",
"$",
"uri",
",",
"$",
"urlParameters",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"requestHandler",
"->",
"executeRequest",
"(",
"$",
"request",
",",
"array",
"(",
"200",
")",
")",
";",
"$",
"document",
"=",
"$",
"this",
"->",
"deserializeDocument",
"(",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"return",
"$",
"document",
";",
"}"
]
| Returns a document.
@param string $uri The endpoint URI
@param array $urlParameters The URL parameters
@return Document The document | [
"Returns",
"a",
"document",
"."
]
| 4e5ebba48d90a8731dae53f44d5fd92d6a79a3bf | https://github.com/php-xapi/client/blob/4e5ebba48d90a8731dae53f44d5fd92d6a79a3bf/src/Api/DocumentApiClient.php#L81-L88 | train |
prolic/HumusAmqp | src/AbstractOptions.php | AbstractOptions.__isset | public function __isset($key)
{
$getter = 'get' . str_replace('_', '', $key);
return method_exists($this, $getter) && null !== $this->__get($key);
} | php | public function __isset($key)
{
$getter = 'get' . str_replace('_', '', $key);
return method_exists($this, $getter) && null !== $this->__get($key);
} | [
"public",
"function",
"__isset",
"(",
"$",
"key",
")",
"{",
"$",
"getter",
"=",
"'get'",
".",
"str_replace",
"(",
"'_'",
",",
"''",
",",
"$",
"key",
")",
";",
"return",
"method_exists",
"(",
"$",
"this",
",",
"$",
"getter",
")",
"&&",
"null",
"!==",
"$",
"this",
"->",
"__get",
"(",
"$",
"key",
")",
";",
"}"
]
| Test if a configuration property is null
@see ParameterObject::__isset()
@param string $key
@return bool | [
"Test",
"if",
"a",
"configuration",
"property",
"is",
"null"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/AbstractOptions.php#L167-L172 | train |
prolic/HumusAmqp | src/AbstractConsumer.php | AbstractConsumer.handleProcessFlag | protected function handleProcessFlag(Envelope $envelope, DeliveryResult $flag)
{
$this->countMessagesConsumed++;
switch ($flag) {
case DeliveryResult::MSG_REJECT():
$this->queue->nack($envelope->getDeliveryTag(), Constants::AMQP_NOPARAM);
$this->logger->debug('Rejected message', $this->extractMessageInformation($envelope));
break;
case DeliveryResult::MSG_REJECT_REQUEUE():
$this->queue->nack($envelope->getDeliveryTag(), Constants::AMQP_REQUEUE);
$this->logger->debug('Rejected and requeued message', $this->extractMessageInformation($envelope));
break;
case DeliveryResult::MSG_ACK():
$this->countMessagesUnacked++;
$this->lastDeliveryTag = $envelope->getDeliveryTag();
$this->timestampLastMessage = microtime(true);
$this->ack();
break;
case DeliveryResult::MSG_DEFER():
$this->countMessagesUnacked++;
$this->lastDeliveryTag = $envelope->getDeliveryTag();
$this->timestampLastMessage = microtime(true);
break;
}
} | php | protected function handleProcessFlag(Envelope $envelope, DeliveryResult $flag)
{
$this->countMessagesConsumed++;
switch ($flag) {
case DeliveryResult::MSG_REJECT():
$this->queue->nack($envelope->getDeliveryTag(), Constants::AMQP_NOPARAM);
$this->logger->debug('Rejected message', $this->extractMessageInformation($envelope));
break;
case DeliveryResult::MSG_REJECT_REQUEUE():
$this->queue->nack($envelope->getDeliveryTag(), Constants::AMQP_REQUEUE);
$this->logger->debug('Rejected and requeued message', $this->extractMessageInformation($envelope));
break;
case DeliveryResult::MSG_ACK():
$this->countMessagesUnacked++;
$this->lastDeliveryTag = $envelope->getDeliveryTag();
$this->timestampLastMessage = microtime(true);
$this->ack();
break;
case DeliveryResult::MSG_DEFER():
$this->countMessagesUnacked++;
$this->lastDeliveryTag = $envelope->getDeliveryTag();
$this->timestampLastMessage = microtime(true);
break;
}
} | [
"protected",
"function",
"handleProcessFlag",
"(",
"Envelope",
"$",
"envelope",
",",
"DeliveryResult",
"$",
"flag",
")",
"{",
"$",
"this",
"->",
"countMessagesConsumed",
"++",
";",
"switch",
"(",
"$",
"flag",
")",
"{",
"case",
"DeliveryResult",
"::",
"MSG_REJECT",
"(",
")",
":",
"$",
"this",
"->",
"queue",
"->",
"nack",
"(",
"$",
"envelope",
"->",
"getDeliveryTag",
"(",
")",
",",
"Constants",
"::",
"AMQP_NOPARAM",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Rejected message'",
",",
"$",
"this",
"->",
"extractMessageInformation",
"(",
"$",
"envelope",
")",
")",
";",
"break",
";",
"case",
"DeliveryResult",
"::",
"MSG_REJECT_REQUEUE",
"(",
")",
":",
"$",
"this",
"->",
"queue",
"->",
"nack",
"(",
"$",
"envelope",
"->",
"getDeliveryTag",
"(",
")",
",",
"Constants",
"::",
"AMQP_REQUEUE",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Rejected and requeued message'",
",",
"$",
"this",
"->",
"extractMessageInformation",
"(",
"$",
"envelope",
")",
")",
";",
"break",
";",
"case",
"DeliveryResult",
"::",
"MSG_ACK",
"(",
")",
":",
"$",
"this",
"->",
"countMessagesUnacked",
"++",
";",
"$",
"this",
"->",
"lastDeliveryTag",
"=",
"$",
"envelope",
"->",
"getDeliveryTag",
"(",
")",
";",
"$",
"this",
"->",
"timestampLastMessage",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"this",
"->",
"ack",
"(",
")",
";",
"break",
";",
"case",
"DeliveryResult",
"::",
"MSG_DEFER",
"(",
")",
":",
"$",
"this",
"->",
"countMessagesUnacked",
"++",
";",
"$",
"this",
"->",
"lastDeliveryTag",
"=",
"$",
"envelope",
"->",
"getDeliveryTag",
"(",
")",
";",
"$",
"this",
"->",
"timestampLastMessage",
"=",
"microtime",
"(",
"true",
")",
";",
"break",
";",
"}",
"}"
]
| Handle process flag
@param Envelope $envelope
@param $flag
@return void | [
"Handle",
"process",
"flag"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/AbstractConsumer.php#L286-L311 | train |
prolic/HumusAmqp | src/AbstractConsumer.php | AbstractConsumer.ack | protected function ack()
{
$this->queue->ack($this->lastDeliveryTag, Constants::AMQP_MULTIPLE);
$this->lastDeliveryTag = null;
$delta = $this->timestampLastMessage - $this->timestampLastAck;
$this->logger->info(sprintf(
'Acknowledged %d messages at %.0f msg/s',
$this->countMessagesUnacked,
$delta ? $this->countMessagesUnacked / $delta : 0
));
$this->timestampLastAck = microtime(true);
$this->countMessagesUnacked = 0;
} | php | protected function ack()
{
$this->queue->ack($this->lastDeliveryTag, Constants::AMQP_MULTIPLE);
$this->lastDeliveryTag = null;
$delta = $this->timestampLastMessage - $this->timestampLastAck;
$this->logger->info(sprintf(
'Acknowledged %d messages at %.0f msg/s',
$this->countMessagesUnacked,
$delta ? $this->countMessagesUnacked / $delta : 0
));
$this->timestampLastAck = microtime(true);
$this->countMessagesUnacked = 0;
} | [
"protected",
"function",
"ack",
"(",
")",
"{",
"$",
"this",
"->",
"queue",
"->",
"ack",
"(",
"$",
"this",
"->",
"lastDeliveryTag",
",",
"Constants",
"::",
"AMQP_MULTIPLE",
")",
";",
"$",
"this",
"->",
"lastDeliveryTag",
"=",
"null",
";",
"$",
"delta",
"=",
"$",
"this",
"->",
"timestampLastMessage",
"-",
"$",
"this",
"->",
"timestampLastAck",
";",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"sprintf",
"(",
"'Acknowledged %d messages at %.0f msg/s'",
",",
"$",
"this",
"->",
"countMessagesUnacked",
",",
"$",
"delta",
"?",
"$",
"this",
"->",
"countMessagesUnacked",
"/",
"$",
"delta",
":",
"0",
")",
")",
";",
"$",
"this",
"->",
"timestampLastAck",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"this",
"->",
"countMessagesUnacked",
"=",
"0",
";",
"}"
]
| Acknowledge all deferred messages
This will be called every time the block size (see prefetch_count) or timeout is reached
@return void | [
"Acknowledge",
"all",
"deferred",
"messages"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/AbstractConsumer.php#L320-L334 | train |
prolic/HumusAmqp | src/AbstractConsumer.php | AbstractConsumer.nackAll | protected function nackAll($requeue = false)
{
$delta = $this->timestampLastMessage - $this->timestampLastAck;
$this->logger->info(sprintf(
'Not acknowledged %d messages at %.0f msg/s',
$this->countMessagesUnacked,
$delta ? $this->countMessagesUnacked / $delta : 0
));
$flags = Constants::AMQP_MULTIPLE;
if ($requeue) {
$flags |= Constants::AMQP_REQUEUE;
}
$this->queue->nack($this->lastDeliveryTag, $flags);
$this->lastDeliveryTag = null;
$this->countMessagesUnacked = 0;
} | php | protected function nackAll($requeue = false)
{
$delta = $this->timestampLastMessage - $this->timestampLastAck;
$this->logger->info(sprintf(
'Not acknowledged %d messages at %.0f msg/s',
$this->countMessagesUnacked,
$delta ? $this->countMessagesUnacked / $delta : 0
));
$flags = Constants::AMQP_MULTIPLE;
if ($requeue) {
$flags |= Constants::AMQP_REQUEUE;
}
$this->queue->nack($this->lastDeliveryTag, $flags);
$this->lastDeliveryTag = null;
$this->countMessagesUnacked = 0;
} | [
"protected",
"function",
"nackAll",
"(",
"$",
"requeue",
"=",
"false",
")",
"{",
"$",
"delta",
"=",
"$",
"this",
"->",
"timestampLastMessage",
"-",
"$",
"this",
"->",
"timestampLastAck",
";",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"sprintf",
"(",
"'Not acknowledged %d messages at %.0f msg/s'",
",",
"$",
"this",
"->",
"countMessagesUnacked",
",",
"$",
"delta",
"?",
"$",
"this",
"->",
"countMessagesUnacked",
"/",
"$",
"delta",
":",
"0",
")",
")",
";",
"$",
"flags",
"=",
"Constants",
"::",
"AMQP_MULTIPLE",
";",
"if",
"(",
"$",
"requeue",
")",
"{",
"$",
"flags",
"|=",
"Constants",
"::",
"AMQP_REQUEUE",
";",
"}",
"$",
"this",
"->",
"queue",
"->",
"nack",
"(",
"$",
"this",
"->",
"lastDeliveryTag",
",",
"$",
"flags",
")",
";",
"$",
"this",
"->",
"lastDeliveryTag",
"=",
"null",
";",
"$",
"this",
"->",
"countMessagesUnacked",
"=",
"0",
";",
"}"
]
| Send nack for all deferred messages
@param bool $requeue
@return void | [
"Send",
"nack",
"for",
"all",
"deferred",
"messages"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/AbstractConsumer.php#L342-L361 | train |
prolic/HumusAmqp | src/AbstractConsumer.php | AbstractConsumer.ackOrNackBlock | protected function ackOrNackBlock()
{
if (! $this->lastDeliveryTag) {
return;
}
$result = $this->flushDeferred();
switch ($result) {
case FlushDeferredResult::MSG_ACK():
$this->ack();
break;
case FlushDeferredResult::MSG_REJECT():
$this->nackAll(false);
break;
case FlushDeferredResult::MSG_REJECT_REQUEUE():
$this->nackAll(true);
break;
}
} | php | protected function ackOrNackBlock()
{
if (! $this->lastDeliveryTag) {
return;
}
$result = $this->flushDeferred();
switch ($result) {
case FlushDeferredResult::MSG_ACK():
$this->ack();
break;
case FlushDeferredResult::MSG_REJECT():
$this->nackAll(false);
break;
case FlushDeferredResult::MSG_REJECT_REQUEUE():
$this->nackAll(true);
break;
}
} | [
"protected",
"function",
"ackOrNackBlock",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"lastDeliveryTag",
")",
"{",
"return",
";",
"}",
"$",
"result",
"=",
"$",
"this",
"->",
"flushDeferred",
"(",
")",
";",
"switch",
"(",
"$",
"result",
")",
"{",
"case",
"FlushDeferredResult",
"::",
"MSG_ACK",
"(",
")",
":",
"$",
"this",
"->",
"ack",
"(",
")",
";",
"break",
";",
"case",
"FlushDeferredResult",
"::",
"MSG_REJECT",
"(",
")",
":",
"$",
"this",
"->",
"nackAll",
"(",
"false",
")",
";",
"break",
";",
"case",
"FlushDeferredResult",
"::",
"MSG_REJECT_REQUEUE",
"(",
")",
":",
"$",
"this",
"->",
"nackAll",
"(",
"true",
")",
";",
"break",
";",
"}",
"}"
]
| Handle deferred acknowledgments
@return void | [
"Handle",
"deferred",
"acknowledgments"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/AbstractConsumer.php#L368-L387 | train |
prolic/HumusAmqp | src/JsonRpc/JsonRpcServer.php | JsonRpcServer.sendReply | protected function sendReply(Response $response, Envelope $envelope)
{
$attributes = [
'content_type' => 'application/json',
'content_encoding' => 'UTF-8',
'delivery_mode' => 2,
'correlation_id' => $envelope->getCorrelationId(),
'app_id' => $this->appId,
'headers' => [
'jsonrpc' => JsonRpcResponse::JSONRPC_VERSION,
],
];
if ($response->isError()) {
$payload = [
'error' => [
'code' => $response->error()->code(),
'message' => $response->error()->message(),
],
'data' => $response->data(),
];
} else {
$payload = [
'result' => $response->result(),
];
}
$message = json_encode($payload);
if (json_last_error() !== JSON_ERROR_NONE) {
$message = json_encode([
'error' => [
'code' => JsonRpcError::ERROR_CODE_32603,
'message' => 'Internal error',
],
]);
}
$this->exchange->publish($message, $envelope->getReplyTo(), Constants::AMQP_NOPARAM, $attributes);
} | php | protected function sendReply(Response $response, Envelope $envelope)
{
$attributes = [
'content_type' => 'application/json',
'content_encoding' => 'UTF-8',
'delivery_mode' => 2,
'correlation_id' => $envelope->getCorrelationId(),
'app_id' => $this->appId,
'headers' => [
'jsonrpc' => JsonRpcResponse::JSONRPC_VERSION,
],
];
if ($response->isError()) {
$payload = [
'error' => [
'code' => $response->error()->code(),
'message' => $response->error()->message(),
],
'data' => $response->data(),
];
} else {
$payload = [
'result' => $response->result(),
];
}
$message = json_encode($payload);
if (json_last_error() !== JSON_ERROR_NONE) {
$message = json_encode([
'error' => [
'code' => JsonRpcError::ERROR_CODE_32603,
'message' => 'Internal error',
],
]);
}
$this->exchange->publish($message, $envelope->getReplyTo(), Constants::AMQP_NOPARAM, $attributes);
} | [
"protected",
"function",
"sendReply",
"(",
"Response",
"$",
"response",
",",
"Envelope",
"$",
"envelope",
")",
"{",
"$",
"attributes",
"=",
"[",
"'content_type'",
"=>",
"'application/json'",
",",
"'content_encoding'",
"=>",
"'UTF-8'",
",",
"'delivery_mode'",
"=>",
"2",
",",
"'correlation_id'",
"=>",
"$",
"envelope",
"->",
"getCorrelationId",
"(",
")",
",",
"'app_id'",
"=>",
"$",
"this",
"->",
"appId",
",",
"'headers'",
"=>",
"[",
"'jsonrpc'",
"=>",
"JsonRpcResponse",
"::",
"JSONRPC_VERSION",
",",
"]",
",",
"]",
";",
"if",
"(",
"$",
"response",
"->",
"isError",
"(",
")",
")",
"{",
"$",
"payload",
"=",
"[",
"'error'",
"=>",
"[",
"'code'",
"=>",
"$",
"response",
"->",
"error",
"(",
")",
"->",
"code",
"(",
")",
",",
"'message'",
"=>",
"$",
"response",
"->",
"error",
"(",
")",
"->",
"message",
"(",
")",
",",
"]",
",",
"'data'",
"=>",
"$",
"response",
"->",
"data",
"(",
")",
",",
"]",
";",
"}",
"else",
"{",
"$",
"payload",
"=",
"[",
"'result'",
"=>",
"$",
"response",
"->",
"result",
"(",
")",
",",
"]",
";",
"}",
"$",
"message",
"=",
"json_encode",
"(",
"$",
"payload",
")",
";",
"if",
"(",
"json_last_error",
"(",
")",
"!==",
"JSON_ERROR_NONE",
")",
"{",
"$",
"message",
"=",
"json_encode",
"(",
"[",
"'error'",
"=>",
"[",
"'code'",
"=>",
"JsonRpcError",
"::",
"ERROR_CODE_32603",
",",
"'message'",
"=>",
"'Internal error'",
",",
"]",
",",
"]",
")",
";",
"}",
"$",
"this",
"->",
"exchange",
"->",
"publish",
"(",
"$",
"message",
",",
"$",
"envelope",
"->",
"getReplyTo",
"(",
")",
",",
"Constants",
"::",
"AMQP_NOPARAM",
",",
"$",
"attributes",
")",
";",
"}"
]
| Send reply to rpc client
@param Response $response
@param Envelope $envelope | [
"Send",
"reply",
"to",
"rpc",
"client"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/JsonRpc/JsonRpcServer.php#L217-L256 | train |
SocalNick/ScnSocialAuth | src/ScnSocialAuth/Controller/UserController.php | UserController.setScnAuthAdapterChain | public function setScnAuthAdapterChain(\ZfcUser\Authentication\Adapter\AdapterChain $chain)
{
$this->scnAuthAdapterChain = $chain;
return $this;
} | php | public function setScnAuthAdapterChain(\ZfcUser\Authentication\Adapter\AdapterChain $chain)
{
$this->scnAuthAdapterChain = $chain;
return $this;
} | [
"public",
"function",
"setScnAuthAdapterChain",
"(",
"\\",
"ZfcUser",
"\\",
"Authentication",
"\\",
"Adapter",
"\\",
"AdapterChain",
"$",
"chain",
")",
"{",
"$",
"this",
"->",
"scnAuthAdapterChain",
"=",
"$",
"chain",
";",
"return",
"$",
"this",
";",
"}"
]
| Set the scnAuthAdapterChain
@param \ZfcUser\Authentication\Adapter\AdapterChain
@return UserController | [
"Set",
"the",
"scnAuthAdapterChain"
]
| 601b9b3a240b58838dd9c6dedbeb59bcffb37fc3 | https://github.com/SocalNick/ScnSocialAuth/blob/601b9b3a240b58838dd9c6dedbeb59bcffb37fc3/src/ScnSocialAuth/Controller/UserController.php#L246-L251 | train |
SocalNick/ScnSocialAuth | src/ScnSocialAuth/Authentication/Adapter/HybridAuth.php | HybridAuth.bitbucketToLocalUser | protected function bitbucketToLocalUser($userProfile)
{
$localUser = $this->instantiateLocalUser();
$localUser->setDisplayName($userProfile->displayName)
->setPassword(__FUNCTION__)
->setEmail($userProfile->email);
$this->insert($localUser, 'github', $userProfile);
return $localUser;
} | php | protected function bitbucketToLocalUser($userProfile)
{
$localUser = $this->instantiateLocalUser();
$localUser->setDisplayName($userProfile->displayName)
->setPassword(__FUNCTION__)
->setEmail($userProfile->email);
$this->insert($localUser, 'github', $userProfile);
return $localUser;
} | [
"protected",
"function",
"bitbucketToLocalUser",
"(",
"$",
"userProfile",
")",
"{",
"$",
"localUser",
"=",
"$",
"this",
"->",
"instantiateLocalUser",
"(",
")",
";",
"$",
"localUser",
"->",
"setDisplayName",
"(",
"$",
"userProfile",
"->",
"displayName",
")",
"->",
"setPassword",
"(",
"__FUNCTION__",
")",
"->",
"setEmail",
"(",
"$",
"userProfile",
"->",
"email",
")",
";",
"$",
"this",
"->",
"insert",
"(",
"$",
"localUser",
",",
"'github'",
",",
"$",
"userProfile",
")",
";",
"return",
"$",
"localUser",
";",
"}"
]
| BitBucket to Local User
@param $userProfile
@return mixed | [
"BitBucket",
"to",
"Local",
"User"
]
| 601b9b3a240b58838dd9c6dedbeb59bcffb37fc3 | https://github.com/SocalNick/ScnSocialAuth/blob/601b9b3a240b58838dd9c6dedbeb59bcffb37fc3/src/ScnSocialAuth/Authentication/Adapter/HybridAuth.php#L298-L307 | train |
SocalNick/ScnSocialAuth | src/ScnSocialAuth/Mapper/UserProvider.php | UserProvider.insert | public function insert($entity, $tableName = null, HydratorInterface $hydrator = null)
{
return parent::insert($entity, $tableName, $hydrator);
} | php | public function insert($entity, $tableName = null, HydratorInterface $hydrator = null)
{
return parent::insert($entity, $tableName, $hydrator);
} | [
"public",
"function",
"insert",
"(",
"$",
"entity",
",",
"$",
"tableName",
"=",
"null",
",",
"HydratorInterface",
"$",
"hydrator",
"=",
"null",
")",
"{",
"return",
"parent",
"::",
"insert",
"(",
"$",
"entity",
",",
"$",
"tableName",
",",
"$",
"hydrator",
")",
";",
"}"
]
| Proxy to parent protected method
@param object|array $entity
@param string|TableIdentifier|null $tableName
@param HydratorInterface|null $hydrator
@return ResultInterface | [
"Proxy",
"to",
"parent",
"protected",
"method"
]
| 601b9b3a240b58838dd9c6dedbeb59bcffb37fc3 | https://github.com/SocalNick/ScnSocialAuth/blob/601b9b3a240b58838dd9c6dedbeb59bcffb37fc3/src/ScnSocialAuth/Mapper/UserProvider.php#L84-L87 | train |
prolic/HumusAmqp | src/JsonRpc/JsonRpcClient.php | JsonRpcClient.addRequest | public function addRequest(Request $request)
{
$attributes = $this->createAttributes($request);
$exchange = $this->getExchange($request->server());
$message = json_encode($request->params());
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception\InvalidArgumentException('Error during json encoding');
}
$exchange->publish($message, $request->routingKey(), Constants::AMQP_NOPARAM, $attributes);
if (null !== $request->id()) {
$this->requestIds[] = $request->id();
}
if (0 !== $request->expiration() && ceil($request->expiration() / 1000) > $this->timeout) {
$this->timeout = ceil($request->expiration() / 1000);
}
++$this->countRequests;
} | php | public function addRequest(Request $request)
{
$attributes = $this->createAttributes($request);
$exchange = $this->getExchange($request->server());
$message = json_encode($request->params());
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception\InvalidArgumentException('Error during json encoding');
}
$exchange->publish($message, $request->routingKey(), Constants::AMQP_NOPARAM, $attributes);
if (null !== $request->id()) {
$this->requestIds[] = $request->id();
}
if (0 !== $request->expiration() && ceil($request->expiration() / 1000) > $this->timeout) {
$this->timeout = ceil($request->expiration() / 1000);
}
++$this->countRequests;
} | [
"public",
"function",
"addRequest",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"attributes",
"=",
"$",
"this",
"->",
"createAttributes",
"(",
"$",
"request",
")",
";",
"$",
"exchange",
"=",
"$",
"this",
"->",
"getExchange",
"(",
"$",
"request",
"->",
"server",
"(",
")",
")",
";",
"$",
"message",
"=",
"json_encode",
"(",
"$",
"request",
"->",
"params",
"(",
")",
")",
";",
"if",
"(",
"json_last_error",
"(",
")",
"!==",
"JSON_ERROR_NONE",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"InvalidArgumentException",
"(",
"'Error during json encoding'",
")",
";",
"}",
"$",
"exchange",
"->",
"publish",
"(",
"$",
"message",
",",
"$",
"request",
"->",
"routingKey",
"(",
")",
",",
"Constants",
"::",
"AMQP_NOPARAM",
",",
"$",
"attributes",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"request",
"->",
"id",
"(",
")",
")",
"{",
"$",
"this",
"->",
"requestIds",
"[",
"]",
"=",
"$",
"request",
"->",
"id",
"(",
")",
";",
"}",
"if",
"(",
"0",
"!==",
"$",
"request",
"->",
"expiration",
"(",
")",
"&&",
"ceil",
"(",
"$",
"request",
"->",
"expiration",
"(",
")",
"/",
"1000",
")",
">",
"$",
"this",
"->",
"timeout",
")",
"{",
"$",
"this",
"->",
"timeout",
"=",
"ceil",
"(",
"$",
"request",
"->",
"expiration",
"(",
")",
"/",
"1000",
")",
";",
"}",
"++",
"$",
"this",
"->",
"countRequests",
";",
"}"
]
| Add a request to rpc client
@param Request $request
@throws Exception\InvalidArgumentException | [
"Add",
"a",
"request",
"to",
"rpc",
"client"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/JsonRpc/JsonRpcClient.php#L101-L124 | train |
prolic/HumusAmqp | src/JsonRpc/JsonRpcClient.php | JsonRpcClient.getResponseCollection | public function getResponseCollection(float $timeout = 0): ResponseCollection
{
if ($timeout < $this->timeout) {
$timeout = $this->timeout;
}
$now = microtime(true);
$responseCollection = new JsonRpcResponseCollection();
do {
$message = $this->queue->get(Constants::AMQP_AUTOACK);
if ($message instanceof Envelope) {
$responseCollection->addResponse($this->responseFromEnvelope($message));
} else {
usleep($this->waitMillis * 1000);
}
$time = microtime(true);
} while (
$responseCollection->count() < $this->countRequests
&& (0 == $timeout || ($timeout > 0 && (($time - $now) < $timeout)))
);
$this->requestIds = [];
$this->timeout = 0;
$this->countRequests = 0;
return $responseCollection;
} | php | public function getResponseCollection(float $timeout = 0): ResponseCollection
{
if ($timeout < $this->timeout) {
$timeout = $this->timeout;
}
$now = microtime(true);
$responseCollection = new JsonRpcResponseCollection();
do {
$message = $this->queue->get(Constants::AMQP_AUTOACK);
if ($message instanceof Envelope) {
$responseCollection->addResponse($this->responseFromEnvelope($message));
} else {
usleep($this->waitMillis * 1000);
}
$time = microtime(true);
} while (
$responseCollection->count() < $this->countRequests
&& (0 == $timeout || ($timeout > 0 && (($time - $now) < $timeout)))
);
$this->requestIds = [];
$this->timeout = 0;
$this->countRequests = 0;
return $responseCollection;
} | [
"public",
"function",
"getResponseCollection",
"(",
"float",
"$",
"timeout",
"=",
"0",
")",
":",
"ResponseCollection",
"{",
"if",
"(",
"$",
"timeout",
"<",
"$",
"this",
"->",
"timeout",
")",
"{",
"$",
"timeout",
"=",
"$",
"this",
"->",
"timeout",
";",
"}",
"$",
"now",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"responseCollection",
"=",
"new",
"JsonRpcResponseCollection",
"(",
")",
";",
"do",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"queue",
"->",
"get",
"(",
"Constants",
"::",
"AMQP_AUTOACK",
")",
";",
"if",
"(",
"$",
"message",
"instanceof",
"Envelope",
")",
"{",
"$",
"responseCollection",
"->",
"addResponse",
"(",
"$",
"this",
"->",
"responseFromEnvelope",
"(",
"$",
"message",
")",
")",
";",
"}",
"else",
"{",
"usleep",
"(",
"$",
"this",
"->",
"waitMillis",
"*",
"1000",
")",
";",
"}",
"$",
"time",
"=",
"microtime",
"(",
"true",
")",
";",
"}",
"while",
"(",
"$",
"responseCollection",
"->",
"count",
"(",
")",
"<",
"$",
"this",
"->",
"countRequests",
"&&",
"(",
"0",
"==",
"$",
"timeout",
"||",
"(",
"$",
"timeout",
">",
"0",
"&&",
"(",
"(",
"$",
"time",
"-",
"$",
"now",
")",
"<",
"$",
"timeout",
")",
")",
")",
")",
";",
"$",
"this",
"->",
"requestIds",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"timeout",
"=",
"0",
";",
"$",
"this",
"->",
"countRequests",
"=",
"0",
";",
"return",
"$",
"responseCollection",
";",
"}"
]
| Get response collection
@param float $timeout in seconds
@return ResponseCollection | [
"Get",
"response",
"collection"
]
| 2a90a259493c244624e9591e7bd144e9d4e70cbe | https://github.com/prolic/HumusAmqp/blob/2a90a259493c244624e9591e7bd144e9d4e70cbe/src/JsonRpc/JsonRpcClient.php#L132-L160 | train |
Islandora-CLAW/Crayfish | Recast/src/Controller/RecastController.php | RecastController.findPredicateForObject | private function findPredicateForObject(\EasyRdf_Graph $graph, $object)
{
$properties = $graph->reversePropertyUris($object);
foreach ($properties as $p) {
return $p;
}
return null;
} | php | private function findPredicateForObject(\EasyRdf_Graph $graph, $object)
{
$properties = $graph->reversePropertyUris($object);
foreach ($properties as $p) {
return $p;
}
return null;
} | [
"private",
"function",
"findPredicateForObject",
"(",
"\\",
"EasyRdf_Graph",
"$",
"graph",
",",
"$",
"object",
")",
"{",
"$",
"properties",
"=",
"$",
"graph",
"->",
"reversePropertyUris",
"(",
"$",
"object",
")",
";",
"foreach",
"(",
"$",
"properties",
"as",
"$",
"p",
")",
"{",
"return",
"$",
"p",
";",
"}",
"return",
"null",
";",
"}"
]
| Locate the predicate for an object in a graph.
@param \EasyRdf_Graph $graph
The graph to look in.
@param string $object
The object to look for.
@return mixed string|null
Return the predicate or null. | [
"Locate",
"the",
"predicate",
"for",
"an",
"object",
"in",
"a",
"graph",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Recast/src/Controller/RecastController.php#L221-L228 | train |
Islandora-CLAW/Crayfish | Gemini/src/Controller/GeminiController.php | GeminiController.getByUri | public function getByUri(Request $request)
{
if (!$request->headers->has('X-Islandora-URI')) {
return new Response('Require the X-Islandora-URI header', 400);
}
$uri = $request->headers->get('X-Islandora-URI');
if (is_array($uri)) {
// Can only return one Location header.
$uri = reset($uri);
}
$uri = $this->urlMapper->findUrls($uri);
$headers = [];
if ($uri) {
$headers['Location'] = $uri;
}
return new Response(null, ($uri ? 200 : 404), $headers);
} | php | public function getByUri(Request $request)
{
if (!$request->headers->has('X-Islandora-URI')) {
return new Response('Require the X-Islandora-URI header', 400);
}
$uri = $request->headers->get('X-Islandora-URI');
if (is_array($uri)) {
// Can only return one Location header.
$uri = reset($uri);
}
$uri = $this->urlMapper->findUrls($uri);
$headers = [];
if ($uri) {
$headers['Location'] = $uri;
}
return new Response(null, ($uri ? 200 : 404), $headers);
} | [
"public",
"function",
"getByUri",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'X-Islandora-URI'",
")",
")",
"{",
"return",
"new",
"Response",
"(",
"'Require the X-Islandora-URI header'",
",",
"400",
")",
";",
"}",
"$",
"uri",
"=",
"$",
"request",
"->",
"headers",
"->",
"get",
"(",
"'X-Islandora-URI'",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"uri",
")",
")",
"{",
"// Can only return one Location header.",
"$",
"uri",
"=",
"reset",
"(",
"$",
"uri",
")",
";",
"}",
"$",
"uri",
"=",
"$",
"this",
"->",
"urlMapper",
"->",
"findUrls",
"(",
"$",
"uri",
")",
";",
"$",
"headers",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"uri",
")",
"{",
"$",
"headers",
"[",
"'Location'",
"]",
"=",
"$",
"uri",
";",
"}",
"return",
"new",
"Response",
"(",
"null",
",",
"(",
"$",
"uri",
"?",
"200",
":",
"404",
")",
",",
"$",
"headers",
")",
";",
"}"
]
| Find the opposite URI for the on provided in X-Islandora-URI.
@param \Symfony\Component\HttpFoundation\Request $request
The incoming request.
@return \Symfony\Component\HttpFoundation\Response
A response 200 with Location or 404. | [
"Find",
"the",
"opposite",
"URI",
"for",
"the",
"on",
"provided",
"in",
"X",
"-",
"Islandora",
"-",
"URI",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Gemini/src/Controller/GeminiController.php#L155-L171 | train |
Islandora-CLAW/Crayfish | Homarus/src/Controller/HomarusController.php | HomarusController.getFfmpegFormat | private function getFfmpegFormat(array $content_types)
{
$content_type = null;
foreach ($content_types as $type) {
if (in_array($type, $this->mimetypes)) {
$content_type = $type;
break;
}
}
if ($content_type === null) {
$this->log->info('No matching content-type, falling back to default.');
return [$this->default_mimetype, $this->default_format];
}
foreach ($this->mime_to_format as $format) {
$format_info = explode("_", $format);
if ($format_info[0] == $content_type) {
return [$content_type, $format_info[1]];
}
}
$this->log->info('No matching content-type to format mapping, falling back to default.');
return [$this->default_mimetype, $this->default_format];
} | php | private function getFfmpegFormat(array $content_types)
{
$content_type = null;
foreach ($content_types as $type) {
if (in_array($type, $this->mimetypes)) {
$content_type = $type;
break;
}
}
if ($content_type === null) {
$this->log->info('No matching content-type, falling back to default.');
return [$this->default_mimetype, $this->default_format];
}
foreach ($this->mime_to_format as $format) {
$format_info = explode("_", $format);
if ($format_info[0] == $content_type) {
return [$content_type, $format_info[1]];
}
}
$this->log->info('No matching content-type to format mapping, falling back to default.');
return [$this->default_mimetype, $this->default_format];
} | [
"private",
"function",
"getFfmpegFormat",
"(",
"array",
"$",
"content_types",
")",
"{",
"$",
"content_type",
"=",
"null",
";",
"foreach",
"(",
"$",
"content_types",
"as",
"$",
"type",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"type",
",",
"$",
"this",
"->",
"mimetypes",
")",
")",
"{",
"$",
"content_type",
"=",
"$",
"type",
";",
"break",
";",
"}",
"}",
"if",
"(",
"$",
"content_type",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"log",
"->",
"info",
"(",
"'No matching content-type, falling back to default.'",
")",
";",
"return",
"[",
"$",
"this",
"->",
"default_mimetype",
",",
"$",
"this",
"->",
"default_format",
"]",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"mime_to_format",
"as",
"$",
"format",
")",
"{",
"$",
"format_info",
"=",
"explode",
"(",
"\"_\"",
",",
"$",
"format",
")",
";",
"if",
"(",
"$",
"format_info",
"[",
"0",
"]",
"==",
"$",
"content_type",
")",
"{",
"return",
"[",
"$",
"content_type",
",",
"$",
"format_info",
"[",
"1",
"]",
"]",
";",
"}",
"}",
"$",
"this",
"->",
"log",
"->",
"info",
"(",
"'No matching content-type to format mapping, falling back to default.'",
")",
";",
"return",
"[",
"$",
"this",
"->",
"default_mimetype",
",",
"$",
"this",
"->",
"default_format",
"]",
";",
"}"
]
| Filters through an array of acceptable content-types and returns a FFmpeg format.
@param array $content_types
The Accept content-types.
@return array
Array with [ $content-type, $format ], falls back to defaults. | [
"Filters",
"through",
"an",
"array",
"of",
"acceptable",
"content",
"-",
"types",
"and",
"returns",
"a",
"FFmpeg",
"format",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Homarus/src/Controller/HomarusController.php#L153-L176 | train |
Islandora-CLAW/Crayfish | Milliner/src/Service/MillinerService.php | MillinerService.createNode | protected function createNode(
$uuid,
$jsonld_url,
$token = null
) {
// Mint a new Fedora URL.
$fedora_url = $this->gemini->mintFedoraUrl($uuid, $token);
// Get the jsonld from Drupal.
$headers = empty($token) ? [] : ['Authorization' => $token];
$drupal_response = $this->drupal->get(
$jsonld_url,
['headers' => $headers]
);
$jsonld = json_decode(
$drupal_response->getBody(),
true
);
// Mash it into the shape Fedora accepts.
$jsonld = $this->processJsonld(
$jsonld,
$jsonld_url,
$fedora_url
);
// Save it in Fedora.
$headers['Content-Type'] = 'application/ld+json';
$headers['Prefer'] = 'return=minimal; handling=lenient';
$response = $this->fedora->saveResource(
$fedora_url,
json_encode($jsonld),
$headers
);
$status = $response->getStatusCode();
if (!in_array($status, [201, 204])) {
$reason = $response->getReasonPhrase();
throw new \RuntimeException(
"Client error: `PUT $fedora_url` resulted in a `$status $reason` response: " . $response->getBody(),
$status
);
}
// Map the URLS.
$this->gemini->saveUrls(
$uuid,
$jsonld_url,
$fedora_url,
$token
);
// Return the response from Fedora.
return $response;
} | php | protected function createNode(
$uuid,
$jsonld_url,
$token = null
) {
// Mint a new Fedora URL.
$fedora_url = $this->gemini->mintFedoraUrl($uuid, $token);
// Get the jsonld from Drupal.
$headers = empty($token) ? [] : ['Authorization' => $token];
$drupal_response = $this->drupal->get(
$jsonld_url,
['headers' => $headers]
);
$jsonld = json_decode(
$drupal_response->getBody(),
true
);
// Mash it into the shape Fedora accepts.
$jsonld = $this->processJsonld(
$jsonld,
$jsonld_url,
$fedora_url
);
// Save it in Fedora.
$headers['Content-Type'] = 'application/ld+json';
$headers['Prefer'] = 'return=minimal; handling=lenient';
$response = $this->fedora->saveResource(
$fedora_url,
json_encode($jsonld),
$headers
);
$status = $response->getStatusCode();
if (!in_array($status, [201, 204])) {
$reason = $response->getReasonPhrase();
throw new \RuntimeException(
"Client error: `PUT $fedora_url` resulted in a `$status $reason` response: " . $response->getBody(),
$status
);
}
// Map the URLS.
$this->gemini->saveUrls(
$uuid,
$jsonld_url,
$fedora_url,
$token
);
// Return the response from Fedora.
return $response;
} | [
"protected",
"function",
"createNode",
"(",
"$",
"uuid",
",",
"$",
"jsonld_url",
",",
"$",
"token",
"=",
"null",
")",
"{",
"// Mint a new Fedora URL.",
"$",
"fedora_url",
"=",
"$",
"this",
"->",
"gemini",
"->",
"mintFedoraUrl",
"(",
"$",
"uuid",
",",
"$",
"token",
")",
";",
"// Get the jsonld from Drupal.",
"$",
"headers",
"=",
"empty",
"(",
"$",
"token",
")",
"?",
"[",
"]",
":",
"[",
"'Authorization'",
"=>",
"$",
"token",
"]",
";",
"$",
"drupal_response",
"=",
"$",
"this",
"->",
"drupal",
"->",
"get",
"(",
"$",
"jsonld_url",
",",
"[",
"'headers'",
"=>",
"$",
"headers",
"]",
")",
";",
"$",
"jsonld",
"=",
"json_decode",
"(",
"$",
"drupal_response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"// Mash it into the shape Fedora accepts.",
"$",
"jsonld",
"=",
"$",
"this",
"->",
"processJsonld",
"(",
"$",
"jsonld",
",",
"$",
"jsonld_url",
",",
"$",
"fedora_url",
")",
";",
"// Save it in Fedora.",
"$",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/ld+json'",
";",
"$",
"headers",
"[",
"'Prefer'",
"]",
"=",
"'return=minimal; handling=lenient'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"fedora",
"->",
"saveResource",
"(",
"$",
"fedora_url",
",",
"json_encode",
"(",
"$",
"jsonld",
")",
",",
"$",
"headers",
")",
";",
"$",
"status",
"=",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"status",
",",
"[",
"201",
",",
"204",
"]",
")",
")",
"{",
"$",
"reason",
"=",
"$",
"response",
"->",
"getReasonPhrase",
"(",
")",
";",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Client error: `PUT $fedora_url` resulted in a `$status $reason` response: \"",
".",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"$",
"status",
")",
";",
"}",
"// Map the URLS.",
"$",
"this",
"->",
"gemini",
"->",
"saveUrls",
"(",
"$",
"uuid",
",",
"$",
"jsonld_url",
",",
"$",
"fedora_url",
",",
"$",
"token",
")",
";",
"// Return the response from Fedora.",
"return",
"$",
"response",
";",
"}"
]
| Creates a new LDP-RS in Fedora from a Node.
@param string $uuid
@param string $jsonld_url
@param string $token
@return \GuzzleHttp\Psr7\Response
@throws \RuntimeException
@throws \GuzzleHttp\Exception\RequestException | [
"Creates",
"a",
"new",
"LDP",
"-",
"RS",
"in",
"Fedora",
"from",
"a",
"Node",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Milliner/src/Service/MillinerService.php#L102-L157 | train |
Islandora-CLAW/Crayfish | Milliner/src/Service/MillinerService.php | MillinerService.updateNode | protected function updateNode(
$jsonld_url,
$fedora_url,
$token = null
) {
// Get the RDF from Fedora.
$headers = empty($token) ? [] : ['Authorization' => $token];
$headers['Accept'] = 'application/ld+json';
$fedora_response = $this->fedora->getResource(
$fedora_url,
$headers
);
$status = $fedora_response->getStatusCode();
if ($status != 200) {
$reason = $fedora_response->getReasonPhrase();
throw new \RuntimeException(
"Client error: `GET $fedora_url` resulted in a `$status $reason` response: " .
$fedora_response->getBody(),
$status
);
}
// Strip off the W/ prefix to make the ETag strong.
$etags = $fedora_response->getHeader("ETag");
$etag = ltrim(reset($etags), "W/");
// Get the modified date from the RDF.
$fedora_jsonld = json_decode(
$fedora_response->getBody(),
true
);
// Account for the fact that new media haven't got a modified date
// pushed to it from Drupal yet.
try {
$fedora_modified = $this->getModifiedTimestamp(
$fedora_jsonld
);
} catch (\RuntimeException $e) {
$fedora_modified = 0;
}
// Get the jsonld from Drupal.
$headers = empty($token) ? [] : ['Authorization' => $token];
$drupal_response = $this->drupal->get(
$jsonld_url,
['headers' => $headers]
);
$drupal_jsonld = json_decode(
$drupal_response->getBody(),
true
);
// Mash it into the shape Fedora accepts.
$drupal_jsonld = $this->processJsonld(
$drupal_jsonld,
$jsonld_url,
$fedora_url
);
// Get the modified date from the RDF.
$drupal_modified = $this->getModifiedTimestamp(
$drupal_jsonld
);
// Abort with 412 if the Drupal RDF is stale.
if ($drupal_modified <= $fedora_modified) {
throw new \RuntimeException(
"Not updating $fedora_url because RDF at $jsonld_url is not newer",
412
);
}
// Conditionally save it in Fedora.
$headers['Content-Type'] = 'application/ld+json';
$headers['Prefer'] = 'return=minimal; handling=lenient';
$headers['If-Match'] = $etag;
$response = $this->fedora->saveResource(
$fedora_url,
json_encode($drupal_jsonld),
$headers
);
$status = $response->getStatusCode();
if (!in_array($status, [201, 204])) {
$reason = $response->getReasonPhrase();
throw new \RuntimeException(
"Client error: `PUT $fedora_url` resulted in a `$status $reason` response: " . $response->getBody(),
$status
);
}
// Return the response from Fedora.
return $response;
} | php | protected function updateNode(
$jsonld_url,
$fedora_url,
$token = null
) {
// Get the RDF from Fedora.
$headers = empty($token) ? [] : ['Authorization' => $token];
$headers['Accept'] = 'application/ld+json';
$fedora_response = $this->fedora->getResource(
$fedora_url,
$headers
);
$status = $fedora_response->getStatusCode();
if ($status != 200) {
$reason = $fedora_response->getReasonPhrase();
throw new \RuntimeException(
"Client error: `GET $fedora_url` resulted in a `$status $reason` response: " .
$fedora_response->getBody(),
$status
);
}
// Strip off the W/ prefix to make the ETag strong.
$etags = $fedora_response->getHeader("ETag");
$etag = ltrim(reset($etags), "W/");
// Get the modified date from the RDF.
$fedora_jsonld = json_decode(
$fedora_response->getBody(),
true
);
// Account for the fact that new media haven't got a modified date
// pushed to it from Drupal yet.
try {
$fedora_modified = $this->getModifiedTimestamp(
$fedora_jsonld
);
} catch (\RuntimeException $e) {
$fedora_modified = 0;
}
// Get the jsonld from Drupal.
$headers = empty($token) ? [] : ['Authorization' => $token];
$drupal_response = $this->drupal->get(
$jsonld_url,
['headers' => $headers]
);
$drupal_jsonld = json_decode(
$drupal_response->getBody(),
true
);
// Mash it into the shape Fedora accepts.
$drupal_jsonld = $this->processJsonld(
$drupal_jsonld,
$jsonld_url,
$fedora_url
);
// Get the modified date from the RDF.
$drupal_modified = $this->getModifiedTimestamp(
$drupal_jsonld
);
// Abort with 412 if the Drupal RDF is stale.
if ($drupal_modified <= $fedora_modified) {
throw new \RuntimeException(
"Not updating $fedora_url because RDF at $jsonld_url is not newer",
412
);
}
// Conditionally save it in Fedora.
$headers['Content-Type'] = 'application/ld+json';
$headers['Prefer'] = 'return=minimal; handling=lenient';
$headers['If-Match'] = $etag;
$response = $this->fedora->saveResource(
$fedora_url,
json_encode($drupal_jsonld),
$headers
);
$status = $response->getStatusCode();
if (!in_array($status, [201, 204])) {
$reason = $response->getReasonPhrase();
throw new \RuntimeException(
"Client error: `PUT $fedora_url` resulted in a `$status $reason` response: " . $response->getBody(),
$status
);
}
// Return the response from Fedora.
return $response;
} | [
"protected",
"function",
"updateNode",
"(",
"$",
"jsonld_url",
",",
"$",
"fedora_url",
",",
"$",
"token",
"=",
"null",
")",
"{",
"// Get the RDF from Fedora.",
"$",
"headers",
"=",
"empty",
"(",
"$",
"token",
")",
"?",
"[",
"]",
":",
"[",
"'Authorization'",
"=>",
"$",
"token",
"]",
";",
"$",
"headers",
"[",
"'Accept'",
"]",
"=",
"'application/ld+json'",
";",
"$",
"fedora_response",
"=",
"$",
"this",
"->",
"fedora",
"->",
"getResource",
"(",
"$",
"fedora_url",
",",
"$",
"headers",
")",
";",
"$",
"status",
"=",
"$",
"fedora_response",
"->",
"getStatusCode",
"(",
")",
";",
"if",
"(",
"$",
"status",
"!=",
"200",
")",
"{",
"$",
"reason",
"=",
"$",
"fedora_response",
"->",
"getReasonPhrase",
"(",
")",
";",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Client error: `GET $fedora_url` resulted in a `$status $reason` response: \"",
".",
"$",
"fedora_response",
"->",
"getBody",
"(",
")",
",",
"$",
"status",
")",
";",
"}",
"// Strip off the W/ prefix to make the ETag strong.",
"$",
"etags",
"=",
"$",
"fedora_response",
"->",
"getHeader",
"(",
"\"ETag\"",
")",
";",
"$",
"etag",
"=",
"ltrim",
"(",
"reset",
"(",
"$",
"etags",
")",
",",
"\"W/\"",
")",
";",
"// Get the modified date from the RDF.",
"$",
"fedora_jsonld",
"=",
"json_decode",
"(",
"$",
"fedora_response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"// Account for the fact that new media haven't got a modified date",
"// pushed to it from Drupal yet.",
"try",
"{",
"$",
"fedora_modified",
"=",
"$",
"this",
"->",
"getModifiedTimestamp",
"(",
"$",
"fedora_jsonld",
")",
";",
"}",
"catch",
"(",
"\\",
"RuntimeException",
"$",
"e",
")",
"{",
"$",
"fedora_modified",
"=",
"0",
";",
"}",
"// Get the jsonld from Drupal.",
"$",
"headers",
"=",
"empty",
"(",
"$",
"token",
")",
"?",
"[",
"]",
":",
"[",
"'Authorization'",
"=>",
"$",
"token",
"]",
";",
"$",
"drupal_response",
"=",
"$",
"this",
"->",
"drupal",
"->",
"get",
"(",
"$",
"jsonld_url",
",",
"[",
"'headers'",
"=>",
"$",
"headers",
"]",
")",
";",
"$",
"drupal_jsonld",
"=",
"json_decode",
"(",
"$",
"drupal_response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"// Mash it into the shape Fedora accepts.",
"$",
"drupal_jsonld",
"=",
"$",
"this",
"->",
"processJsonld",
"(",
"$",
"drupal_jsonld",
",",
"$",
"jsonld_url",
",",
"$",
"fedora_url",
")",
";",
"// Get the modified date from the RDF.",
"$",
"drupal_modified",
"=",
"$",
"this",
"->",
"getModifiedTimestamp",
"(",
"$",
"drupal_jsonld",
")",
";",
"// Abort with 412 if the Drupal RDF is stale.",
"if",
"(",
"$",
"drupal_modified",
"<=",
"$",
"fedora_modified",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Not updating $fedora_url because RDF at $jsonld_url is not newer\"",
",",
"412",
")",
";",
"}",
"// Conditionally save it in Fedora.",
"$",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/ld+json'",
";",
"$",
"headers",
"[",
"'Prefer'",
"]",
"=",
"'return=minimal; handling=lenient'",
";",
"$",
"headers",
"[",
"'If-Match'",
"]",
"=",
"$",
"etag",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"fedora",
"->",
"saveResource",
"(",
"$",
"fedora_url",
",",
"json_encode",
"(",
"$",
"drupal_jsonld",
")",
",",
"$",
"headers",
")",
";",
"$",
"status",
"=",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"status",
",",
"[",
"201",
",",
"204",
"]",
")",
")",
"{",
"$",
"reason",
"=",
"$",
"response",
"->",
"getReasonPhrase",
"(",
")",
";",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Client error: `PUT $fedora_url` resulted in a `$status $reason` response: \"",
".",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"$",
"status",
")",
";",
"}",
"// Return the response from Fedora.",
"return",
"$",
"response",
";",
"}"
]
| Updates an existing LDP-RS in Fedora from a Node.
@param string $uuid
@param string $jsonld_url
@param string $fedora_url
@param string $token
@return \GuzzleHttp\Psr7\Response
@throws \RuntimeException
@throws \GuzzleHttp\Exception\RequestException | [
"Updates",
"an",
"existing",
"LDP",
"-",
"RS",
"in",
"Fedora",
"from",
"a",
"Node",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Milliner/src/Service/MillinerService.php#L172-L267 | train |
Islandora-CLAW/Crayfish | Milliner/src/Service/MillinerService.php | MillinerService.processJsonld | protected function processJsonld(array $jsonld, $drupal_url, $fedora_url)
{
// Strip out everything other than the resource in question.
$resource = array_filter(
$jsonld['@graph'],
function (array $elem) use ($drupal_url) {
return $elem['@id'] == $drupal_url;
}
);
// Put in an fedora url for the resource.
$resource[0]['@id'] = $fedora_url;
return $resource;
} | php | protected function processJsonld(array $jsonld, $drupal_url, $fedora_url)
{
// Strip out everything other than the resource in question.
$resource = array_filter(
$jsonld['@graph'],
function (array $elem) use ($drupal_url) {
return $elem['@id'] == $drupal_url;
}
);
// Put in an fedora url for the resource.
$resource[0]['@id'] = $fedora_url;
return $resource;
} | [
"protected",
"function",
"processJsonld",
"(",
"array",
"$",
"jsonld",
",",
"$",
"drupal_url",
",",
"$",
"fedora_url",
")",
"{",
"// Strip out everything other than the resource in question.",
"$",
"resource",
"=",
"array_filter",
"(",
"$",
"jsonld",
"[",
"'@graph'",
"]",
",",
"function",
"(",
"array",
"$",
"elem",
")",
"use",
"(",
"$",
"drupal_url",
")",
"{",
"return",
"$",
"elem",
"[",
"'@id'",
"]",
"==",
"$",
"drupal_url",
";",
"}",
")",
";",
"// Put in an fedora url for the resource.",
"$",
"resource",
"[",
"0",
"]",
"[",
"'@id'",
"]",
"=",
"$",
"fedora_url",
";",
"return",
"$",
"resource",
";",
"}"
]
| Normalizes Drupal jsonld into a shape Fedora understands.
@param array $jsonld
@param string $drupal_url
@param string $fedora_url
@return array | [
"Normalizes",
"Drupal",
"jsonld",
"into",
"a",
"shape",
"Fedora",
"understands",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Milliner/src/Service/MillinerService.php#L278-L292 | train |
Islandora-CLAW/Crayfish | Milliner/src/Service/MillinerService.php | MillinerService.getFirstPredicate | protected function getFirstPredicate(array $jsonld, $predicate, $value = true)
{
$key = $value ? '@value' : '@id';
$malformed = empty($jsonld) ||
!isset($jsonld[0][$predicate]) ||
empty($jsonld[0][$predicate]) ||
!isset($jsonld[0][$predicate][0][$key]);
if ($malformed) {
return null;
}
return $jsonld[0][$predicate][0][$key];
} | php | protected function getFirstPredicate(array $jsonld, $predicate, $value = true)
{
$key = $value ? '@value' : '@id';
$malformed = empty($jsonld) ||
!isset($jsonld[0][$predicate]) ||
empty($jsonld[0][$predicate]) ||
!isset($jsonld[0][$predicate][0][$key]);
if ($malformed) {
return null;
}
return $jsonld[0][$predicate][0][$key];
} | [
"protected",
"function",
"getFirstPredicate",
"(",
"array",
"$",
"jsonld",
",",
"$",
"predicate",
",",
"$",
"value",
"=",
"true",
")",
"{",
"$",
"key",
"=",
"$",
"value",
"?",
"'@value'",
":",
"'@id'",
";",
"$",
"malformed",
"=",
"empty",
"(",
"$",
"jsonld",
")",
"||",
"!",
"isset",
"(",
"$",
"jsonld",
"[",
"0",
"]",
"[",
"$",
"predicate",
"]",
")",
"||",
"empty",
"(",
"$",
"jsonld",
"[",
"0",
"]",
"[",
"$",
"predicate",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"jsonld",
"[",
"0",
"]",
"[",
"$",
"predicate",
"]",
"[",
"0",
"]",
"[",
"$",
"key",
"]",
")",
";",
"if",
"(",
"$",
"malformed",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"jsonld",
"[",
"0",
"]",
"[",
"$",
"predicate",
"]",
"[",
"0",
"]",
"[",
"$",
"key",
"]",
";",
"}"
]
| Gets the first value for a predicate in a JSONLD array.
@param $jsonld
@param $predicate
@param $value
@return mixed string|null | [
"Gets",
"the",
"first",
"value",
"for",
"a",
"predicate",
"in",
"a",
"JSONLD",
"array",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Milliner/src/Service/MillinerService.php#L303-L316 | train |
Islandora-CLAW/Crayfish | Milliner/src/Service/MillinerService.php | MillinerService.getModifiedTimestamp | protected function getModifiedTimestamp(array $jsonld)
{
$modified = $this->getFirstPredicate(
$jsonld,
$this->modifiedDatePredicate
);
if (empty($modified)) {
throw new \RuntimeException(
"Could not parse {$this->modifiedDatePredicate} from " . json_encode($jsonld),
500
);
}
$date = \DateTime::createFromFormat(
\DateTime::W3C,
$modified
);
return $date->getTimestamp();
} | php | protected function getModifiedTimestamp(array $jsonld)
{
$modified = $this->getFirstPredicate(
$jsonld,
$this->modifiedDatePredicate
);
if (empty($modified)) {
throw new \RuntimeException(
"Could not parse {$this->modifiedDatePredicate} from " . json_encode($jsonld),
500
);
}
$date = \DateTime::createFromFormat(
\DateTime::W3C,
$modified
);
return $date->getTimestamp();
} | [
"protected",
"function",
"getModifiedTimestamp",
"(",
"array",
"$",
"jsonld",
")",
"{",
"$",
"modified",
"=",
"$",
"this",
"->",
"getFirstPredicate",
"(",
"$",
"jsonld",
",",
"$",
"this",
"->",
"modifiedDatePredicate",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"modified",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Could not parse {$this->modifiedDatePredicate} from \"",
".",
"json_encode",
"(",
"$",
"jsonld",
")",
",",
"500",
")",
";",
"}",
"$",
"date",
"=",
"\\",
"DateTime",
"::",
"createFromFormat",
"(",
"\\",
"DateTime",
"::",
"W3C",
",",
"$",
"modified",
")",
";",
"return",
"$",
"date",
"->",
"getTimestamp",
"(",
")",
";",
"}"
]
| Extracts a modified date from jsonld and returns it as a timestamp.
@param array $jsonld
@return int
@throws \RuntimeException | [
"Extracts",
"a",
"modified",
"date",
"from",
"jsonld",
"and",
"returns",
"it",
"as",
"a",
"timestamp",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Milliner/src/Service/MillinerService.php#L327-L347 | train |
Islandora-CLAW/Crayfish | Milliner/src/Service/MillinerService.php | MillinerService.getLinkHeader | protected function getLinkHeader($response, $rel_name, $type = null)
{
$parsed = Psr7\parse_header($response->getHeader("Link"));
foreach ($parsed as $header) {
$has_relation = isset($header['rel']) && $header['rel'] == $rel_name;
$has_type = $type ? isset($header['type']) && $header['type'] == $type : true;
if ($has_type && $has_relation) {
return trim($header[0], '<>');
}
}
return null;
} | php | protected function getLinkHeader($response, $rel_name, $type = null)
{
$parsed = Psr7\parse_header($response->getHeader("Link"));
foreach ($parsed as $header) {
$has_relation = isset($header['rel']) && $header['rel'] == $rel_name;
$has_type = $type ? isset($header['type']) && $header['type'] == $type : true;
if ($has_type && $has_relation) {
return trim($header[0], '<>');
}
}
return null;
} | [
"protected",
"function",
"getLinkHeader",
"(",
"$",
"response",
",",
"$",
"rel_name",
",",
"$",
"type",
"=",
"null",
")",
"{",
"$",
"parsed",
"=",
"Psr7",
"\\",
"parse_header",
"(",
"$",
"response",
"->",
"getHeader",
"(",
"\"Link\"",
")",
")",
";",
"foreach",
"(",
"$",
"parsed",
"as",
"$",
"header",
")",
"{",
"$",
"has_relation",
"=",
"isset",
"(",
"$",
"header",
"[",
"'rel'",
"]",
")",
"&&",
"$",
"header",
"[",
"'rel'",
"]",
"==",
"$",
"rel_name",
";",
"$",
"has_type",
"=",
"$",
"type",
"?",
"isset",
"(",
"$",
"header",
"[",
"'type'",
"]",
")",
"&&",
"$",
"header",
"[",
"'type'",
"]",
"==",
"$",
"type",
":",
"true",
";",
"if",
"(",
"$",
"has_type",
"&&",
"$",
"has_relation",
")",
"{",
"return",
"trim",
"(",
"$",
"header",
"[",
"0",
"]",
",",
"'<>'",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Gets a Link header with the supplied rel name.
@param $response
@param $rel_name
@return null|string | [
"Gets",
"a",
"Link",
"header",
"with",
"the",
"supplied",
"rel",
"name",
"."
]
| 0663c54a43b3c97dbf1aa1492bbe184025de6cdc | https://github.com/Islandora-CLAW/Crayfish/blob/0663c54a43b3c97dbf1aa1492bbe184025de6cdc/Milliner/src/Service/MillinerService.php#L430-L441 | train |
zachleigh/laravel-property-bag | src/Commands/PbagCommand.php | PbagCommand.makeDir | protected function makeDir($dir)
{
$dirPath = base_path('app/'.ltrim($dir, '/'));
if (!File::exists($dirPath)) {
File::makeDirectory($dirPath);
}
} | php | protected function makeDir($dir)
{
$dirPath = base_path('app/'.ltrim($dir, '/'));
if (!File::exists($dirPath)) {
File::makeDirectory($dirPath);
}
} | [
"protected",
"function",
"makeDir",
"(",
"$",
"dir",
")",
"{",
"$",
"dirPath",
"=",
"base_path",
"(",
"'app/'",
".",
"ltrim",
"(",
"$",
"dir",
",",
"'/'",
")",
")",
";",
"if",
"(",
"!",
"File",
"::",
"exists",
"(",
"$",
"dirPath",
")",
")",
"{",
"File",
"::",
"makeDirectory",
"(",
"$",
"dirPath",
")",
";",
"}",
"}"
]
| Make directory if it doesn't already exist.
@param string $dir | [
"Make",
"directory",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Commands/PbagCommand.php#L15-L22 | train |
pattern-lab/plugin-php-faker | src/PatternLab/Faker/PatternLabListener.php | PatternLabListener.fakeContent | public function fakeContent() {
if ((bool)Config::getOption("plugins.faker.enabled")) {
$fakedContent = $this->recursiveWalk(Data::get());
Data::replaceStore($fakedContent);
}
} | php | public function fakeContent() {
if ((bool)Config::getOption("plugins.faker.enabled")) {
$fakedContent = $this->recursiveWalk(Data::get());
Data::replaceStore($fakedContent);
}
} | [
"public",
"function",
"fakeContent",
"(",
")",
"{",
"if",
"(",
"(",
"bool",
")",
"Config",
"::",
"getOption",
"(",
"\"plugins.faker.enabled\"",
")",
")",
"{",
"$",
"fakedContent",
"=",
"$",
"this",
"->",
"recursiveWalk",
"(",
"Data",
"::",
"get",
"(",
")",
")",
";",
"Data",
"::",
"replaceStore",
"(",
"$",
"fakedContent",
")",
";",
"}",
"}"
]
| Fake some content. Replace the entire store. | [
"Fake",
"some",
"content",
".",
"Replace",
"the",
"entire",
"store",
"."
]
| c7552df29b050791df3941eca1e7d9bbc861e94e | https://github.com/pattern-lab/plugin-php-faker/blob/c7552df29b050791df3941eca1e7d9bbc861e94e/src/PatternLab/Faker/PatternLabListener.php#L94-L101 | train |
zachleigh/laravel-property-bag | src/Settings/HasSettings.php | HasSettings.settings | public function settings($passed = null)
{
if (is_array($passed)) {
return $this->setSettings($passed);
} elseif (!is_null($passed)) {
$settings = $this->getSettingsInstance();
return $settings->get($passed);
}
return $this->getSettingsInstance();
} | php | public function settings($passed = null)
{
if (is_array($passed)) {
return $this->setSettings($passed);
} elseif (!is_null($passed)) {
$settings = $this->getSettingsInstance();
return $settings->get($passed);
}
return $this->getSettingsInstance();
} | [
"public",
"function",
"settings",
"(",
"$",
"passed",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"passed",
")",
")",
"{",
"return",
"$",
"this",
"->",
"setSettings",
"(",
"$",
"passed",
")",
";",
"}",
"elseif",
"(",
"!",
"is_null",
"(",
"$",
"passed",
")",
")",
"{",
"$",
"settings",
"=",
"$",
"this",
"->",
"getSettingsInstance",
"(",
")",
";",
"return",
"$",
"settings",
"->",
"get",
"(",
"$",
"passed",
")",
";",
"}",
"return",
"$",
"this",
"->",
"getSettingsInstance",
"(",
")",
";",
"}"
]
| If passed is string, get settings class for the resource or return value
for given key. If passed is array, set the key value pair.
@param string|array $passed
@return \LaravelPropertyBag\Settings\Settings|mixed | [
"If",
"passed",
"is",
"string",
"get",
"settings",
"class",
"for",
"the",
"resource",
"or",
"return",
"value",
"for",
"given",
"key",
".",
"If",
"passed",
"is",
"array",
"set",
"the",
"key",
"value",
"pair",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/HasSettings.php#L35-L46 | train |
zachleigh/laravel-property-bag | src/Settings/HasSettings.php | HasSettings.getSettingsInstance | protected function getSettingsInstance()
{
if (isset($this->settings)) {
return $this->settings;
}
$settingsConfig = $this->getSettingsConfig();
return $this->settings = new Settings($settingsConfig, $this);
} | php | protected function getSettingsInstance()
{
if (isset($this->settings)) {
return $this->settings;
}
$settingsConfig = $this->getSettingsConfig();
return $this->settings = new Settings($settingsConfig, $this);
} | [
"protected",
"function",
"getSettingsInstance",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"settings",
")",
")",
"{",
"return",
"$",
"this",
"->",
"settings",
";",
"}",
"$",
"settingsConfig",
"=",
"$",
"this",
"->",
"getSettingsConfig",
"(",
")",
";",
"return",
"$",
"this",
"->",
"settings",
"=",
"new",
"Settings",
"(",
"$",
"settingsConfig",
",",
"$",
"this",
")",
";",
"}"
]
| Get settings off this or create new instance.
@return \LaravelPropertyBag\Settings\Settings | [
"Get",
"settings",
"off",
"this",
"or",
"create",
"new",
"instance",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/HasSettings.php#L53-L62 | train |
zachleigh/laravel-property-bag | src/Settings/HasSettings.php | HasSettings.getSettingsConfig | protected function getSettingsConfig()
{
if (isset($this->settingsConfig)) {
$fullNamespace = $this->settingsConfig;
} else {
$className = $this->getShortClassName();
$fullNamespace = NameResolver::makeConfigFileName($className);
}
if (class_exists($fullNamespace)) {
return new $fullNamespace($this);
}
throw ResourceNotFound::resourceConfigNotFound($fullNamespace);
} | php | protected function getSettingsConfig()
{
if (isset($this->settingsConfig)) {
$fullNamespace = $this->settingsConfig;
} else {
$className = $this->getShortClassName();
$fullNamespace = NameResolver::makeConfigFileName($className);
}
if (class_exists($fullNamespace)) {
return new $fullNamespace($this);
}
throw ResourceNotFound::resourceConfigNotFound($fullNamespace);
} | [
"protected",
"function",
"getSettingsConfig",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"settingsConfig",
")",
")",
"{",
"$",
"fullNamespace",
"=",
"$",
"this",
"->",
"settingsConfig",
";",
"}",
"else",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"getShortClassName",
"(",
")",
";",
"$",
"fullNamespace",
"=",
"NameResolver",
"::",
"makeConfigFileName",
"(",
"$",
"className",
")",
";",
"}",
"if",
"(",
"class_exists",
"(",
"$",
"fullNamespace",
")",
")",
"{",
"return",
"new",
"$",
"fullNamespace",
"(",
"$",
"this",
")",
";",
"}",
"throw",
"ResourceNotFound",
"::",
"resourceConfigNotFound",
"(",
"$",
"fullNamespace",
")",
";",
"}"
]
| Get the settings class name.
@throws ResourceNotFound
@return \LaravelPropertyBag\Settings\ResourceConfig | [
"Get",
"the",
"settings",
"class",
"name",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/HasSettings.php#L71-L86 | train |
zachleigh/laravel-property-bag | src/Settings/HasSettings.php | HasSettings.setSettingsByRequest | public function setSettingsByRequest()
{
$allAllowedSettings = array_keys($this->allSettings()->toArray());
return $this->settings()->set(request()->only($allAllowedSettings));
} | php | public function setSettingsByRequest()
{
$allAllowedSettings = array_keys($this->allSettings()->toArray());
return $this->settings()->set(request()->only($allAllowedSettings));
} | [
"public",
"function",
"setSettingsByRequest",
"(",
")",
"{",
"$",
"allAllowedSettings",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"allSettings",
"(",
")",
"->",
"toArray",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"settings",
"(",
")",
"->",
"set",
"(",
"request",
"(",
")",
"->",
"only",
"(",
"$",
"allAllowedSettings",
")",
")",
";",
"}"
]
| Set all allowed settings by Request.
@return \LaravelPropertyBag\Settings\Settings | [
"Set",
"all",
"allowed",
"settings",
"by",
"Request",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/HasSettings.php#L117-L122 | train |
zachleigh/laravel-property-bag | src/Settings/HasSettings.php | HasSettings.defaultSetting | public function defaultSetting($key = null)
{
if (!is_null($key)) {
return $this->settings()->getDefault($key);
}
return $this->settings()->allDefaults();
} | php | public function defaultSetting($key = null)
{
if (!is_null($key)) {
return $this->settings()->getDefault($key);
}
return $this->settings()->allDefaults();
} | [
"public",
"function",
"defaultSetting",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"settings",
"(",
")",
"->",
"getDefault",
"(",
"$",
"key",
")",
";",
"}",
"return",
"$",
"this",
"->",
"settings",
"(",
")",
"->",
"allDefaults",
"(",
")",
";",
"}"
]
| Get all default settings or default setting for single key if given.
@param string $key
@return \Illuminate\Support\Collection|mixed | [
"Get",
"all",
"default",
"settings",
"or",
"default",
"setting",
"for",
"single",
"key",
"if",
"given",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/HasSettings.php#L141-L148 | train |
zachleigh/laravel-property-bag | src/Settings/HasSettings.php | HasSettings.allowedSetting | public function allowedSetting($key = null)
{
if (!is_null($key)) {
return $this->settings()->getAllowed($key);
}
return $this->settings()->allAllowed();
} | php | public function allowedSetting($key = null)
{
if (!is_null($key)) {
return $this->settings()->getAllowed($key);
}
return $this->settings()->allAllowed();
} | [
"public",
"function",
"allowedSetting",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"settings",
"(",
")",
"->",
"getAllowed",
"(",
"$",
"key",
")",
";",
"}",
"return",
"$",
"this",
"->",
"settings",
"(",
")",
"->",
"allAllowed",
"(",
")",
";",
"}"
]
| Get all allowed settings or allowed settings for single ke if given.
@param string $key
@return \Illuminate\Support\Collection | [
"Get",
"all",
"allowed",
"settings",
"or",
"allowed",
"settings",
"for",
"single",
"ke",
"if",
"given",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/HasSettings.php#L157-L164 | train |
middlewares/error-handler | src/ErrorFormatter/AbstractImageFormatter.php | AbstractImageFormatter.createImage | protected function createImage(Throwable $error)
{
$type = get_class($error);
$code = $error->getCode();
$message = $error->getMessage();
$size = 200;
$image = imagecreatetruecolor($size, $size);
$textColor = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 5, 10, 10, "$type $code", $textColor);
foreach (str_split($message, intval($size / 10)) as $line => $text) {
imagestring($image, 5, 10, ($line * 18) + 28, $text, $textColor);
}
return $image;
} | php | protected function createImage(Throwable $error)
{
$type = get_class($error);
$code = $error->getCode();
$message = $error->getMessage();
$size = 200;
$image = imagecreatetruecolor($size, $size);
$textColor = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 5, 10, 10, "$type $code", $textColor);
foreach (str_split($message, intval($size / 10)) as $line => $text) {
imagestring($image, 5, 10, ($line * 18) + 28, $text, $textColor);
}
return $image;
} | [
"protected",
"function",
"createImage",
"(",
"Throwable",
"$",
"error",
")",
"{",
"$",
"type",
"=",
"get_class",
"(",
"$",
"error",
")",
";",
"$",
"code",
"=",
"$",
"error",
"->",
"getCode",
"(",
")",
";",
"$",
"message",
"=",
"$",
"error",
"->",
"getMessage",
"(",
")",
";",
"$",
"size",
"=",
"200",
";",
"$",
"image",
"=",
"imagecreatetruecolor",
"(",
"$",
"size",
",",
"$",
"size",
")",
";",
"$",
"textColor",
"=",
"imagecolorallocate",
"(",
"$",
"image",
",",
"255",
",",
"255",
",",
"255",
")",
";",
"imagestring",
"(",
"$",
"image",
",",
"5",
",",
"10",
",",
"10",
",",
"\"$type $code\"",
",",
"$",
"textColor",
")",
";",
"foreach",
"(",
"str_split",
"(",
"$",
"message",
",",
"intval",
"(",
"$",
"size",
"/",
"10",
")",
")",
"as",
"$",
"line",
"=>",
"$",
"text",
")",
"{",
"imagestring",
"(",
"$",
"image",
",",
"5",
",",
"10",
",",
"(",
"$",
"line",
"*",
"18",
")",
"+",
"28",
",",
"$",
"text",
",",
"$",
"textColor",
")",
";",
"}",
"return",
"$",
"image",
";",
"}"
]
| Create an image resource from an error
@return resource | [
"Create",
"an",
"image",
"resource",
"from",
"an",
"error"
]
| ec80134b92f3feb1998078489bb0fff6a9bd13f0 | https://github.com/middlewares/error-handler/blob/ec80134b92f3feb1998078489bb0fff6a9bd13f0/src/ErrorFormatter/AbstractImageFormatter.php#L15-L31 | train |
zachleigh/laravel-property-bag | src/Settings/Rules/RuleValidator.php | RuleValidator.validate | public function validate($rule, $value)
{
$arguments = $this->buildArgumentArray($rule, $value);
$method = $this->makeRuleMethod($rule);
if ($this->userDefinedExists($method)) {
$class = NameResolver::makeRulesFileName();
return call_user_func_array([$class, $method], $arguments);
} elseif (method_exists(Rules::class, $method)) {
return call_user_func_array([Rules::class, $method], $arguments);
}
throw InvalidSettingsRule::ruleNotFound($rule, $method);
} | php | public function validate($rule, $value)
{
$arguments = $this->buildArgumentArray($rule, $value);
$method = $this->makeRuleMethod($rule);
if ($this->userDefinedExists($method)) {
$class = NameResolver::makeRulesFileName();
return call_user_func_array([$class, $method], $arguments);
} elseif (method_exists(Rules::class, $method)) {
return call_user_func_array([Rules::class, $method], $arguments);
}
throw InvalidSettingsRule::ruleNotFound($rule, $method);
} | [
"public",
"function",
"validate",
"(",
"$",
"rule",
",",
"$",
"value",
")",
"{",
"$",
"arguments",
"=",
"$",
"this",
"->",
"buildArgumentArray",
"(",
"$",
"rule",
",",
"$",
"value",
")",
";",
"$",
"method",
"=",
"$",
"this",
"->",
"makeRuleMethod",
"(",
"$",
"rule",
")",
";",
"if",
"(",
"$",
"this",
"->",
"userDefinedExists",
"(",
"$",
"method",
")",
")",
"{",
"$",
"class",
"=",
"NameResolver",
"::",
"makeRulesFileName",
"(",
")",
";",
"return",
"call_user_func_array",
"(",
"[",
"$",
"class",
",",
"$",
"method",
"]",
",",
"$",
"arguments",
")",
";",
"}",
"elseif",
"(",
"method_exists",
"(",
"Rules",
"::",
"class",
",",
"$",
"method",
")",
")",
"{",
"return",
"call_user_func_array",
"(",
"[",
"Rules",
"::",
"class",
",",
"$",
"method",
"]",
",",
"$",
"arguments",
")",
";",
"}",
"throw",
"InvalidSettingsRule",
"::",
"ruleNotFound",
"(",
"$",
"rule",
",",
"$",
"method",
")",
";",
"}"
]
| Validate the value given for the rule.
@param string $rule
@param mixed $value
@throws InvalidSettingsRule
@return bool | [
"Validate",
"the",
"value",
"given",
"for",
"the",
"rule",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Rules/RuleValidator.php#L20-L35 | train |
zachleigh/laravel-property-bag | src/Settings/Rules/RuleValidator.php | RuleValidator.makeRuleMethod | protected function makeRuleMethod($rule)
{
if (strpos($rule, '=') !== false) {
$rule = explode('=', $rule)[0];
}
return 'rule'.ucfirst($rule);
} | php | protected function makeRuleMethod($rule)
{
if (strpos($rule, '=') !== false) {
$rule = explode('=', $rule)[0];
}
return 'rule'.ucfirst($rule);
} | [
"protected",
"function",
"makeRuleMethod",
"(",
"$",
"rule",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"rule",
",",
"'='",
")",
"!==",
"false",
")",
"{",
"$",
"rule",
"=",
"explode",
"(",
"'='",
",",
"$",
"rule",
")",
"[",
"0",
"]",
";",
"}",
"return",
"'rule'",
".",
"ucfirst",
"(",
"$",
"rule",
")",
";",
"}"
]
| Make method name used to validate rule.
@param string $rule
@return string | [
"Make",
"method",
"name",
"used",
"to",
"validate",
"rule",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Rules/RuleValidator.php#L60-L67 | train |
zachleigh/laravel-property-bag | src/Settings/Rules/RuleValidator.php | RuleValidator.userDefinedExists | protected function userDefinedExists($method)
{
$userDefined = NameResolver::makeRulesFileName();
return class_exists($userDefined) &&
method_exists($userDefined, $method);
} | php | protected function userDefinedExists($method)
{
$userDefined = NameResolver::makeRulesFileName();
return class_exists($userDefined) &&
method_exists($userDefined, $method);
} | [
"protected",
"function",
"userDefinedExists",
"(",
"$",
"method",
")",
"{",
"$",
"userDefined",
"=",
"NameResolver",
"::",
"makeRulesFileName",
"(",
")",
";",
"return",
"class_exists",
"(",
"$",
"userDefined",
")",
"&&",
"method_exists",
"(",
"$",
"userDefined",
",",
"$",
"method",
")",
";",
"}"
]
| User defined rule method exists.
@param string $method
@return bool | [
"User",
"defined",
"rule",
"method",
"exists",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Rules/RuleValidator.php#L76-L82 | train |
zachleigh/laravel-property-bag | src/Settings/Rules/RuleValidator.php | RuleValidator.buildArgumentArray | protected function buildArgumentArray($rule, $value)
{
$argumentString = explode('=', $rule);
$arguments = [$value];
if (isset($argumentString[1])) {
return array_merge($arguments, explode(',', $argumentString[1]));
}
return $arguments;
} | php | protected function buildArgumentArray($rule, $value)
{
$argumentString = explode('=', $rule);
$arguments = [$value];
if (isset($argumentString[1])) {
return array_merge($arguments, explode(',', $argumentString[1]));
}
return $arguments;
} | [
"protected",
"function",
"buildArgumentArray",
"(",
"$",
"rule",
",",
"$",
"value",
")",
"{",
"$",
"argumentString",
"=",
"explode",
"(",
"'='",
",",
"$",
"rule",
")",
";",
"$",
"arguments",
"=",
"[",
"$",
"value",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"argumentString",
"[",
"1",
"]",
")",
")",
"{",
"return",
"array_merge",
"(",
"$",
"arguments",
",",
"explode",
"(",
"','",
",",
"$",
"argumentString",
"[",
"1",
"]",
")",
")",
";",
"}",
"return",
"$",
"arguments",
";",
"}"
]
| Build argument array from rule and value.
@param string $rule
@param mixed $value
@return array | [
"Build",
"argument",
"array",
"from",
"rule",
"and",
"value",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Rules/RuleValidator.php#L92-L103 | train |
middlewares/error-handler | src/ErrorHandler.php | ErrorHandler.addFormatters | public function addFormatters(FormatterInterface ...$formatters): self
{
foreach ($formatters as $formatter) {
foreach ($formatter->contentTypes() as $contentType) {
$this->formatters[$contentType] = $formatter;
}
}
return $this;
} | php | public function addFormatters(FormatterInterface ...$formatters): self
{
foreach ($formatters as $formatter) {
foreach ($formatter->contentTypes() as $contentType) {
$this->formatters[$contentType] = $formatter;
}
}
return $this;
} | [
"public",
"function",
"addFormatters",
"(",
"FormatterInterface",
"...",
"$",
"formatters",
")",
":",
"self",
"{",
"foreach",
"(",
"$",
"formatters",
"as",
"$",
"formatter",
")",
"{",
"foreach",
"(",
"$",
"formatter",
"->",
"contentTypes",
"(",
")",
"as",
"$",
"contentType",
")",
"{",
"$",
"this",
"->",
"formatters",
"[",
"$",
"contentType",
"]",
"=",
"$",
"formatter",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
]
| Add additional error formatters | [
"Add",
"additional",
"error",
"formatters"
]
| ec80134b92f3feb1998078489bb0fff6a9bd13f0 | https://github.com/middlewares/error-handler/blob/ec80134b92f3feb1998078489bb0fff6a9bd13f0/src/ErrorHandler.php#L39-L48 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.isValid | public function isValid($key, $value)
{
$settings = collect(
$this->getRegistered()->get($key, ['allowed' => []])
);
$allowed = $settings->get('allowed');
if (!is_array($allowed) &&
$rule = $this->ruleValidator->isRule($allowed)) {
return $this->ruleValidator->validate($rule, $value);
}
return in_array($value, $allowed, true);
} | php | public function isValid($key, $value)
{
$settings = collect(
$this->getRegistered()->get($key, ['allowed' => []])
);
$allowed = $settings->get('allowed');
if (!is_array($allowed) &&
$rule = $this->ruleValidator->isRule($allowed)) {
return $this->ruleValidator->validate($rule, $value);
}
return in_array($value, $allowed, true);
} | [
"public",
"function",
"isValid",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"settings",
"=",
"collect",
"(",
"$",
"this",
"->",
"getRegistered",
"(",
")",
"->",
"get",
"(",
"$",
"key",
",",
"[",
"'allowed'",
"=>",
"[",
"]",
"]",
")",
")",
";",
"$",
"allowed",
"=",
"$",
"settings",
"->",
"get",
"(",
"'allowed'",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"allowed",
")",
"&&",
"$",
"rule",
"=",
"$",
"this",
"->",
"ruleValidator",
"->",
"isRule",
"(",
"$",
"allowed",
")",
")",
"{",
"return",
"$",
"this",
"->",
"ruleValidator",
"->",
"validate",
"(",
"$",
"rule",
",",
"$",
"value",
")",
";",
"}",
"return",
"in_array",
"(",
"$",
"value",
",",
"$",
"allowed",
",",
"true",
")",
";",
"}"
]
| Return true if key and value are registered values.
@param string $key
@param mixed $value
@return bool | [
"Return",
"true",
"if",
"key",
"and",
"value",
"are",
"registered",
"values",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L114-L128 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.all | public function all()
{
$saved = $this->allSaved();
return $this->allDefaults()->map(function ($value, $key) use ($saved) {
if ($saved->has($key)) {
return $saved->get($key);
}
return $value;
});
} | php | public function all()
{
$saved = $this->allSaved();
return $this->allDefaults()->map(function ($value, $key) use ($saved) {
if ($saved->has($key)) {
return $saved->get($key);
}
return $value;
});
} | [
"public",
"function",
"all",
"(",
")",
"{",
"$",
"saved",
"=",
"$",
"this",
"->",
"allSaved",
"(",
")",
";",
"return",
"$",
"this",
"->",
"allDefaults",
"(",
")",
"->",
"map",
"(",
"function",
"(",
"$",
"value",
",",
"$",
"key",
")",
"use",
"(",
"$",
"saved",
")",
"{",
"if",
"(",
"$",
"saved",
"->",
"has",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"saved",
"->",
"get",
"(",
"$",
"key",
")",
";",
"}",
"return",
"$",
"value",
";",
"}",
")",
";",
"}"
]
| Return all settings used by resource, including defaults.
@return \Illuminate\Support\Collection | [
"Return",
"all",
"settings",
"used",
"by",
"resource",
"including",
"defaults",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L162-L173 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.set | public function set(array $attributes)
{
collect($attributes)->each(function ($value, $key) {
$this->setKeyValue($key, $value);
});
// If we were working with eagerly-loaded relation,
// we need to reload its data to be sure that we
// are working only with the actual settings.
if ($this->resource->relationLoaded('propertyBag')) {
$this->resource->load('propertyBag');
}
return $this->sync();
} | php | public function set(array $attributes)
{
collect($attributes)->each(function ($value, $key) {
$this->setKeyValue($key, $value);
});
// If we were working with eagerly-loaded relation,
// we need to reload its data to be sure that we
// are working only with the actual settings.
if ($this->resource->relationLoaded('propertyBag')) {
$this->resource->load('propertyBag');
}
return $this->sync();
} | [
"public",
"function",
"set",
"(",
"array",
"$",
"attributes",
")",
"{",
"collect",
"(",
"$",
"attributes",
")",
"->",
"each",
"(",
"function",
"(",
"$",
"value",
",",
"$",
"key",
")",
"{",
"$",
"this",
"->",
"setKeyValue",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
")",
";",
"// If we were working with eagerly-loaded relation,",
"// we need to reload its data to be sure that we",
"// are working only with the actual settings.",
"if",
"(",
"$",
"this",
"->",
"resource",
"->",
"relationLoaded",
"(",
"'propertyBag'",
")",
")",
"{",
"$",
"this",
"->",
"resource",
"->",
"load",
"(",
"'propertyBag'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"sync",
"(",
")",
";",
"}"
]
| Update or add multiple values to the settings table.
@param array $attributes
@return static | [
"Update",
"or",
"add",
"multiple",
"values",
"to",
"the",
"settings",
"table",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L230-L245 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.setKeyValue | protected function setKeyValue($key, $value)
{
$this->validateKeyValue($key, $value);
if ($this->isDefault($key, $value) && $this->isSaved($key)) {
return $this->deleteRecord($key);
} elseif ($this->isDefault($key, $value)) {
return;
} elseif ($this->isSaved($key)) {
return $this->updateRecord($key, $value);
}
return $this->createRecord($key, $value);
} | php | protected function setKeyValue($key, $value)
{
$this->validateKeyValue($key, $value);
if ($this->isDefault($key, $value) && $this->isSaved($key)) {
return $this->deleteRecord($key);
} elseif ($this->isDefault($key, $value)) {
return;
} elseif ($this->isSaved($key)) {
return $this->updateRecord($key, $value);
}
return $this->createRecord($key, $value);
} | [
"protected",
"function",
"setKeyValue",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"validateKeyValue",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isDefault",
"(",
"$",
"key",
",",
"$",
"value",
")",
"&&",
"$",
"this",
"->",
"isSaved",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"deleteRecord",
"(",
"$",
"key",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"isDefault",
"(",
"$",
"key",
",",
"$",
"value",
")",
")",
"{",
"return",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"isSaved",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"updateRecord",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"this",
"->",
"createRecord",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}"
]
| Set a value to a key in local and database settings.
@param string $key
@param mixed $value
@return mixed | [
"Set",
"a",
"value",
"to",
"a",
"key",
"in",
"local",
"and",
"database",
"settings",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L284-L297 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.createRecord | protected function createRecord($key, $value)
{
return $this->propertyBag()->save(
new PropertyBag([
'key' => $key,
'value' => $this->valueToJson($value),
])
);
} | php | protected function createRecord($key, $value)
{
return $this->propertyBag()->save(
new PropertyBag([
'key' => $key,
'value' => $this->valueToJson($value),
])
);
} | [
"protected",
"function",
"createRecord",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"propertyBag",
"(",
")",
"->",
"save",
"(",
"new",
"PropertyBag",
"(",
"[",
"'key'",
"=>",
"$",
"key",
",",
"'value'",
"=>",
"$",
"this",
"->",
"valueToJson",
"(",
"$",
"value",
")",
",",
"]",
")",
")",
";",
"}"
]
| Create a new PropertyBag record.
@param string $key
@param mixed $value
@return \LaravelPropertyBag\Settings\PropertyBag | [
"Create",
"a",
"new",
"PropertyBag",
"record",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L334-L342 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.updateRecord | protected function updateRecord($key, $value)
{
$record = $this->getByKey($key);
$record->value = $this->valueToJson($value);
$record->save();
return $record;
} | php | protected function updateRecord($key, $value)
{
$record = $this->getByKey($key);
$record->value = $this->valueToJson($value);
$record->save();
return $record;
} | [
"protected",
"function",
"updateRecord",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"record",
"=",
"$",
"this",
"->",
"getByKey",
"(",
"$",
"key",
")",
";",
"$",
"record",
"->",
"value",
"=",
"$",
"this",
"->",
"valueToJson",
"(",
"$",
"value",
")",
";",
"$",
"record",
"->",
"save",
"(",
")",
";",
"return",
"$",
"record",
";",
"}"
]
| Update a PropertyBag record.
@param string $key
@param mixed $value
@return \LaravelPropertyBag\Settings\PropertyBag | [
"Update",
"a",
"PropertyBag",
"record",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L352-L361 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.getByKey | protected function getByKey($key)
{
return $this->propertyBag()
->where('resource_id', $this->resource->getKey())
->where('key', $key)
->first();
} | php | protected function getByKey($key)
{
return $this->propertyBag()
->where('resource_id', $this->resource->getKey())
->where('key', $key)
->first();
} | [
"protected",
"function",
"getByKey",
"(",
"$",
"key",
")",
"{",
"return",
"$",
"this",
"->",
"propertyBag",
"(",
")",
"->",
"where",
"(",
"'resource_id'",
",",
"$",
"this",
"->",
"resource",
"->",
"getKey",
"(",
")",
")",
"->",
"where",
"(",
"'key'",
",",
"$",
"key",
")",
"->",
"first",
"(",
")",
";",
"}"
]
| Get a property bag record by key.
@param string $key
@return \LaravelPropertyBag\Settings\PropertyBag | [
"Get",
"a",
"property",
"bag",
"record",
"by",
"key",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L394-L400 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.getAllSettingsFlat | protected function getAllSettingsFlat()
{
return $this->getAllSettings()->flatMap(function (Model $model) {
return [$model->key => json_decode($model->value)[0]];
});
} | php | protected function getAllSettingsFlat()
{
return $this->getAllSettings()->flatMap(function (Model $model) {
return [$model->key => json_decode($model->value)[0]];
});
} | [
"protected",
"function",
"getAllSettingsFlat",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"getAllSettings",
"(",
")",
"->",
"flatMap",
"(",
"function",
"(",
"Model",
"$",
"model",
")",
"{",
"return",
"[",
"$",
"model",
"->",
"key",
"=>",
"json_decode",
"(",
"$",
"model",
"->",
"value",
")",
"[",
"0",
"]",
"]",
";",
"}",
")",
";",
"}"
]
| Get all settings as a flat collection.
@return \Illuminate\Support\Collection | [
"Get",
"all",
"settings",
"as",
"a",
"flat",
"collection",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L415-L420 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.getAllSettings | protected function getAllSettings()
{
if ($this->resource->relationLoaded('propertyBag')) {
return $this->resource->propertyBag;
}
return $this->propertyBag()
->where('resource_id', $this->resource->getKey())
->get();
} | php | protected function getAllSettings()
{
if ($this->resource->relationLoaded('propertyBag')) {
return $this->resource->propertyBag;
}
return $this->propertyBag()
->where('resource_id', $this->resource->getKey())
->get();
} | [
"protected",
"function",
"getAllSettings",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"resource",
"->",
"relationLoaded",
"(",
"'propertyBag'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"resource",
"->",
"propertyBag",
";",
"}",
"return",
"$",
"this",
"->",
"propertyBag",
"(",
")",
"->",
"where",
"(",
"'resource_id'",
",",
"$",
"this",
"->",
"resource",
"->",
"getKey",
"(",
")",
")",
"->",
"get",
"(",
")",
";",
"}"
]
| Retrieve all settings from database.
@return \Illuminate\Support\Collection | [
"Retrieve",
"all",
"settings",
"from",
"database",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L427-L436 | train |
zachleigh/laravel-property-bag | src/Settings/Settings.php | Settings.get | public function get($key)
{
return $this->allSaved()->get($key, function () use ($key) {
return $this->getDefault($key);
});
} | php | public function get($key)
{
return $this->allSaved()->get($key, function () use ($key) {
return $this->getDefault($key);
});
} | [
"public",
"function",
"get",
"(",
"$",
"key",
")",
"{",
"return",
"$",
"this",
"->",
"allSaved",
"(",
")",
"->",
"get",
"(",
"$",
"key",
",",
"function",
"(",
")",
"use",
"(",
"$",
"key",
")",
"{",
"return",
"$",
"this",
"->",
"getDefault",
"(",
"$",
"key",
")",
";",
"}",
")",
";",
"}"
]
| Get value from settings by key. Get registered default if not set.
@param string $key
@return mixed | [
"Get",
"value",
"from",
"settings",
"by",
"key",
".",
"Get",
"registered",
"default",
"if",
"not",
"set",
"."
]
| 773d6e421694ebf9642c3baebe4720f3965038b4 | https://github.com/zachleigh/laravel-property-bag/blob/773d6e421694ebf9642c3baebe4720f3965038b4/src/Settings/Settings.php#L445-L450 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Request/HttpRequest.php | HttpRequest.getQuery | public function getQuery($param, $defaultValue = null, $filters = array())
{
return $this->fetchInputValue(
$this->input[self::INPUT_METHOD_QUERY],
$param,
$defaultValue,
$filters
);
} | php | public function getQuery($param, $defaultValue = null, $filters = array())
{
return $this->fetchInputValue(
$this->input[self::INPUT_METHOD_QUERY],
$param,
$defaultValue,
$filters
);
} | [
"public",
"function",
"getQuery",
"(",
"$",
"param",
",",
"$",
"defaultValue",
"=",
"null",
",",
"$",
"filters",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"fetchInputValue",
"(",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_QUERY",
"]",
",",
"$",
"param",
",",
"$",
"defaultValue",
",",
"$",
"filters",
")",
";",
"}"
]
| Returns the GET data parameter associated with the specified key.
@param string $param The GET data parameter.
@param mixed $defaultValue The default value to use when the key is not present.
@param mixed $filters The array of filters (or single filter) to apply to the data.
@return mixed Returns the data from the GET parameter after being filtered (or
the default value if the parameter is not present) | [
"Returns",
"the",
"GET",
"data",
"parameter",
"associated",
"with",
"the",
"specified",
"key",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/HttpRequest.php#L119-L127 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Request/HttpRequest.php | HttpRequest.getPost | public function getPost($param, $defaultValue = null, $filters = array())
{
return $this->fetchInputValue(
$this->input[self::INPUT_METHOD_POST],
$param,
$defaultValue,
$filters
);
} | php | public function getPost($param, $defaultValue = null, $filters = array())
{
return $this->fetchInputValue(
$this->input[self::INPUT_METHOD_POST],
$param,
$defaultValue,
$filters
);
} | [
"public",
"function",
"getPost",
"(",
"$",
"param",
",",
"$",
"defaultValue",
"=",
"null",
",",
"$",
"filters",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"fetchInputValue",
"(",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_POST",
"]",
",",
"$",
"param",
",",
"$",
"defaultValue",
",",
"$",
"filters",
")",
";",
"}"
]
| Returns the POST data parameter associated with the specified key.
@param string $param The POST data parameter.
@param mixed $defaultValue The default value to use when the key is not present.
@param mixed $filters The array of filters (or single filter) to apply to the data.
@return mixed Returns the data from the POST parameter after being filtered (or
the default value if the parameter is not present) | [
"Returns",
"the",
"POST",
"data",
"parameter",
"associated",
"with",
"the",
"specified",
"key",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/HttpRequest.php#L148-L156 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Request/HttpRequest.php | HttpRequest.getBody | public function getBody()
{
// If this value has been read from the stream, retrieve it from storage
if (null !== $this->input[self::INPUT_METHOD_BODY]) {
return $this->input[self::INPUT_METHOD_BODY];
}
if (is_resource($this->stream) && 'stream' === get_resource_type($this->stream)) {
$streamData = stream_get_contents($this->stream);
} elseif (is_string($this->stream)) {
$stream = @fopen($this->stream, "r");
if (false === $stream) {
throw new InternalErrorException('Unable to open request input stream.');
}
$streamData = stream_get_contents($stream);
fclose($stream);
} else {
$streamData = false;
}
if (false === $streamData) {
throw new InternalErrorException('Unable to open request input stream.');
}
$this->input[self::INPUT_METHOD_BODY] = $streamData;
return $this->input[self::INPUT_METHOD_BODY];
} | php | public function getBody()
{
// If this value has been read from the stream, retrieve it from storage
if (null !== $this->input[self::INPUT_METHOD_BODY]) {
return $this->input[self::INPUT_METHOD_BODY];
}
if (is_resource($this->stream) && 'stream' === get_resource_type($this->stream)) {
$streamData = stream_get_contents($this->stream);
} elseif (is_string($this->stream)) {
$stream = @fopen($this->stream, "r");
if (false === $stream) {
throw new InternalErrorException('Unable to open request input stream.');
}
$streamData = stream_get_contents($stream);
fclose($stream);
} else {
$streamData = false;
}
if (false === $streamData) {
throw new InternalErrorException('Unable to open request input stream.');
}
$this->input[self::INPUT_METHOD_BODY] = $streamData;
return $this->input[self::INPUT_METHOD_BODY];
} | [
"public",
"function",
"getBody",
"(",
")",
"{",
"// If this value has been read from the stream, retrieve it from storage",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_BODY",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_BODY",
"]",
";",
"}",
"if",
"(",
"is_resource",
"(",
"$",
"this",
"->",
"stream",
")",
"&&",
"'stream'",
"===",
"get_resource_type",
"(",
"$",
"this",
"->",
"stream",
")",
")",
"{",
"$",
"streamData",
"=",
"stream_get_contents",
"(",
"$",
"this",
"->",
"stream",
")",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"this",
"->",
"stream",
")",
")",
"{",
"$",
"stream",
"=",
"@",
"fopen",
"(",
"$",
"this",
"->",
"stream",
",",
"\"r\"",
")",
";",
"if",
"(",
"false",
"===",
"$",
"stream",
")",
"{",
"throw",
"new",
"InternalErrorException",
"(",
"'Unable to open request input stream.'",
")",
";",
"}",
"$",
"streamData",
"=",
"stream_get_contents",
"(",
"$",
"stream",
")",
";",
"fclose",
"(",
"$",
"stream",
")",
";",
"}",
"else",
"{",
"$",
"streamData",
"=",
"false",
";",
"}",
"if",
"(",
"false",
"===",
"$",
"streamData",
")",
"{",
"throw",
"new",
"InternalErrorException",
"(",
"'Unable to open request input stream.'",
")",
";",
"}",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_BODY",
"]",
"=",
"$",
"streamData",
";",
"return",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_BODY",
"]",
";",
"}"
]
| Returns the input stream data for the current request
@return string The input stream data | [
"Returns",
"the",
"input",
"stream",
"data",
"for",
"the",
"current",
"request"
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/HttpRequest.php#L173-L203 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Request/HttpRequest.php | HttpRequest.getAllInput | public function getAllInput()
{
return array_merge(
$this->input[self::INPUT_METHOD_QUERY],
$this->input[self::INPUT_METHOD_POST]
);
} | php | public function getAllInput()
{
return array_merge(
$this->input[self::INPUT_METHOD_QUERY],
$this->input[self::INPUT_METHOD_POST]
);
} | [
"public",
"function",
"getAllInput",
"(",
")",
"{",
"return",
"array_merge",
"(",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_QUERY",
"]",
",",
"$",
"this",
"->",
"input",
"[",
"self",
"::",
"INPUT_METHOD_POST",
"]",
")",
";",
"}"
]
| Returns an array of all the input parameters from the query and post data.
@return array An array of all input. | [
"Returns",
"an",
"array",
"of",
"all",
"the",
"input",
"parameters",
"from",
"the",
"query",
"and",
"post",
"data",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/HttpRequest.php#L209-L215 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Request/HttpRequest.php | HttpRequest.fetchInputValue | private function fetchInputValue($array, $param, $defaultValue, $filters)
{
$value = isset($array[$param]) ? $array[$param] : $defaultValue;
return $this->applyInputFilters($value, is_array($filters) ? $filters : array($filters));
} | php | private function fetchInputValue($array, $param, $defaultValue, $filters)
{
$value = isset($array[$param]) ? $array[$param] : $defaultValue;
return $this->applyInputFilters($value, is_array($filters) ? $filters : array($filters));
} | [
"private",
"function",
"fetchInputValue",
"(",
"$",
"array",
",",
"$",
"param",
",",
"$",
"defaultValue",
",",
"$",
"filters",
")",
"{",
"$",
"value",
"=",
"isset",
"(",
"$",
"array",
"[",
"$",
"param",
"]",
")",
"?",
"$",
"array",
"[",
"$",
"param",
"]",
":",
"$",
"defaultValue",
";",
"return",
"$",
"this",
"->",
"applyInputFilters",
"(",
"$",
"value",
",",
"is_array",
"(",
"$",
"filters",
")",
"?",
"$",
"filters",
":",
"array",
"(",
"$",
"filters",
")",
")",
";",
"}"
]
| Fetches the input value from the given array, or the default value. Also
applies any requested filters.
@param array $array The array ($_POST, $_GET, $params, etc).
@param string $param The array key to lookup.
@param mixed $defaultValue The default value to use if the key is not
found in the array.
@param mixed $filters The array of input filters to apply (or single filter).
@return mixed Returns the value filtered (or the default value filtered). | [
"Fetches",
"the",
"input",
"value",
"from",
"the",
"given",
"array",
"or",
"the",
"default",
"value",
".",
"Also",
"applies",
"any",
"requested",
"filters",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/HttpRequest.php#L227-L231 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Request/HttpRequest.php | HttpRequest.applyInputFilters | private function applyInputFilters($value, $filters)
{
foreach ($filters as $filter) {
if (is_string($filter) && isset(self::$filterCallbacks[$filter])) {
$value = call_user_func(self::$filterCallbacks[$filter], $value);
}
}
return $value;
} | php | private function applyInputFilters($value, $filters)
{
foreach ($filters as $filter) {
if (is_string($filter) && isset(self::$filterCallbacks[$filter])) {
$value = call_user_func(self::$filterCallbacks[$filter], $value);
}
}
return $value;
} | [
"private",
"function",
"applyInputFilters",
"(",
"$",
"value",
",",
"$",
"filters",
")",
"{",
"foreach",
"(",
"$",
"filters",
"as",
"$",
"filter",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"filter",
")",
"&&",
"isset",
"(",
"self",
"::",
"$",
"filterCallbacks",
"[",
"$",
"filter",
"]",
")",
")",
"{",
"$",
"value",
"=",
"call_user_func",
"(",
"self",
"::",
"$",
"filterCallbacks",
"[",
"$",
"filter",
"]",
",",
"$",
"value",
")",
";",
"}",
"}",
"return",
"$",
"value",
";",
"}"
]
| Applies the array of filters against the input value.
@param string $value The input value.
@param array $filters The array of filters.
@return string Returns the value after the filters have been applied. | [
"Applies",
"the",
"array",
"of",
"filters",
"against",
"the",
"input",
"value",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Request/HttpRequest.php#L239-L247 | train |
bigcommerce/net-http | src/Net/Http/Client.php | Net_Http_Client.setProxy | public function setProxy($host, $port=false)
{
$this->options[CURLOPT_PROXY] = $host;
if ($port) {
$this->options[CURLOPT_PROXYPORT] = $port;
}
} | php | public function setProxy($host, $port=false)
{
$this->options[CURLOPT_PROXY] = $host;
if ($port) {
$this->options[CURLOPT_PROXYPORT] = $port;
}
} | [
"public",
"function",
"setProxy",
"(",
"$",
"host",
",",
"$",
"port",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"CURLOPT_PROXY",
"]",
"=",
"$",
"host",
";",
"if",
"(",
"$",
"port",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"CURLOPT_PROXYPORT",
"]",
"=",
"$",
"port",
";",
"}",
"}"
]
| Push outgoing requests through the specified proxy server.
@param string $host
@param int $port | [
"Push",
"outgoing",
"requests",
"through",
"the",
"specified",
"proxy",
"server",
"."
]
| aba27bdaa13e478bcf31b2ec1686577994efbd96 | https://github.com/bigcommerce/net-http/blob/aba27bdaa13e478bcf31b2ec1686577994efbd96/src/Net/Http/Client.php#L180-L187 | train |
bigcommerce/net-http | src/Net/Http/Client.php | Net_Http_Client.checkResponse | private function checkResponse($ch)
{
$this->responseInfo = curl_getinfo($ch);
if (curl_errno($ch)) {
throw new Net_Http_NetworkError(curl_error($ch), curl_errno($ch));
}
if ($this->failOnError) {
$status = $this->getStatus();
if ($status >= 400 && $status <= 499) {
throw new Net_Http_ClientError($this->getStatusMessage(), $status, $this->getResponse());
} elseif ($status >= 500 && $status <= 599) {
throw new Net_Http_ServerError($this->getStatusMessage(), $status, $this->getResponse());
}
}
if ($this->followLocation) {
$this->followRedirectPath();
}
} | php | private function checkResponse($ch)
{
$this->responseInfo = curl_getinfo($ch);
if (curl_errno($ch)) {
throw new Net_Http_NetworkError(curl_error($ch), curl_errno($ch));
}
if ($this->failOnError) {
$status = $this->getStatus();
if ($status >= 400 && $status <= 499) {
throw new Net_Http_ClientError($this->getStatusMessage(), $status, $this->getResponse());
} elseif ($status >= 500 && $status <= 599) {
throw new Net_Http_ServerError($this->getStatusMessage(), $status, $this->getResponse());
}
}
if ($this->followLocation) {
$this->followRedirectPath();
}
} | [
"private",
"function",
"checkResponse",
"(",
"$",
"ch",
")",
"{",
"$",
"this",
"->",
"responseInfo",
"=",
"curl_getinfo",
"(",
"$",
"ch",
")",
";",
"if",
"(",
"curl_errno",
"(",
"$",
"ch",
")",
")",
"{",
"throw",
"new",
"Net_Http_NetworkError",
"(",
"curl_error",
"(",
"$",
"ch",
")",
",",
"curl_errno",
"(",
"$",
"ch",
")",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"failOnError",
")",
"{",
"$",
"status",
"=",
"$",
"this",
"->",
"getStatus",
"(",
")",
";",
"if",
"(",
"$",
"status",
">=",
"400",
"&&",
"$",
"status",
"<=",
"499",
")",
"{",
"throw",
"new",
"Net_Http_ClientError",
"(",
"$",
"this",
"->",
"getStatusMessage",
"(",
")",
",",
"$",
"status",
",",
"$",
"this",
"->",
"getResponse",
"(",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"status",
">=",
"500",
"&&",
"$",
"status",
"<=",
"599",
")",
"{",
"throw",
"new",
"Net_Http_ServerError",
"(",
"$",
"this",
"->",
"getStatusMessage",
"(",
")",
",",
"$",
"status",
",",
"$",
"this",
"->",
"getResponse",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"followLocation",
")",
"{",
"$",
"this",
"->",
"followRedirectPath",
"(",
")",
";",
"}",
"}"
]
| Check the response for possible errors. If failOnError is true
then throw a protocol level exception. Network errors are always
raised as exceptions.
@throws Net_Http_ClientError
@throws Net_Http_NetworkError
@throws Net_Http_ServerError | [
"Check",
"the",
"response",
"for",
"possible",
"errors",
".",
"If",
"failOnError",
"is",
"true",
"then",
"throw",
"a",
"protocol",
"level",
"exception",
".",
"Network",
"errors",
"are",
"always",
"raised",
"as",
"exceptions",
"."
]
| aba27bdaa13e478bcf31b2ec1686577994efbd96 | https://github.com/bigcommerce/net-http/blob/aba27bdaa13e478bcf31b2ec1686577994efbd96/src/Net/Http/Client.php#L285-L303 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Plugin/AccessControl/CrossOriginRequestPlugin.php | CrossOriginRequestPlugin.processRequestsForAccessDenial | private function processRequestsForAccessDenial(array $requests)
{
foreach ($requests as $request) {
$controller = $request->getController();
$action = $request->getAction();
if (false === $this->isServiceEnabledForCrossOrigin($controller, $action)) {
// we have a cross origin request for a controller that's not enabled
// so throw an exception instead of processing the request
throw new AccessDeniedException(
'Cross origin access denied to '.$controller.' and action '.$action
);
}
}
} | php | private function processRequestsForAccessDenial(array $requests)
{
foreach ($requests as $request) {
$controller = $request->getController();
$action = $request->getAction();
if (false === $this->isServiceEnabledForCrossOrigin($controller, $action)) {
// we have a cross origin request for a controller that's not enabled
// so throw an exception instead of processing the request
throw new AccessDeniedException(
'Cross origin access denied to '.$controller.' and action '.$action
);
}
}
} | [
"private",
"function",
"processRequestsForAccessDenial",
"(",
"array",
"$",
"requests",
")",
"{",
"foreach",
"(",
"$",
"requests",
"as",
"$",
"request",
")",
"{",
"$",
"controller",
"=",
"$",
"request",
"->",
"getController",
"(",
")",
";",
"$",
"action",
"=",
"$",
"request",
"->",
"getAction",
"(",
")",
";",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"isServiceEnabledForCrossOrigin",
"(",
"$",
"controller",
",",
"$",
"action",
")",
")",
"{",
"// we have a cross origin request for a controller that's not enabled",
"// so throw an exception instead of processing the request",
"throw",
"new",
"AccessDeniedException",
"(",
"'Cross origin access denied to '",
".",
"$",
"controller",
".",
"' and action '",
".",
"$",
"action",
")",
";",
"}",
"}",
"}"
]
| Processes the list of requests to check if any should be blocked due
to CORS policy.
@param array $requests The array of requests. | [
"Processes",
"the",
"list",
"of",
"requests",
"to",
"check",
"if",
"any",
"should",
"be",
"blocked",
"due",
"to",
"CORS",
"policy",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Plugin/AccessControl/CrossOriginRequestPlugin.php#L93-L106 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Plugin/AccessControl/CrossOriginRequestPlugin.php | CrossOriginRequestPlugin.addHeadersForOptionsRequests | private function addHeadersForOptionsRequests()
{
// header for preflight cache expiry
$maxAge = self::MAX_AGE;
if (isset($this->options[self::HEADER_MAX_AGE])) {
$maxAge = intval($this->options[self::HEADER_MAX_AGE]);
}
@header(self::HEADER_MAX_AGE.': '.$maxAge);
// header for allowed request headers in cross origin requests
$allowedHeaders = self::$allowedHeaders;
if (isset($this->options[self::HEADER_ALLOW_HEADERS])) {
$allowedHeaders = (array)$this->options[self::HEADER_ALLOW_HEADERS];
}
@header(self::HEADER_ALLOW_HEADERS.':'.implode(',', $allowedHeaders));
// header for allowed HTTP methods in cross orgin requests
$allowedMethods = self::$allowedMethods;
if (isset($this->options[self::HEADER_ALLOW_METHODS])) {
$allowedMethods = (array)$this->options[self::HEADER_ALLOW_METHODS];
}
@header(self::HEADER_ALLOW_METHODS.':'.implode(',', $allowedMethods));
} | php | private function addHeadersForOptionsRequests()
{
// header for preflight cache expiry
$maxAge = self::MAX_AGE;
if (isset($this->options[self::HEADER_MAX_AGE])) {
$maxAge = intval($this->options[self::HEADER_MAX_AGE]);
}
@header(self::HEADER_MAX_AGE.': '.$maxAge);
// header for allowed request headers in cross origin requests
$allowedHeaders = self::$allowedHeaders;
if (isset($this->options[self::HEADER_ALLOW_HEADERS])) {
$allowedHeaders = (array)$this->options[self::HEADER_ALLOW_HEADERS];
}
@header(self::HEADER_ALLOW_HEADERS.':'.implode(',', $allowedHeaders));
// header for allowed HTTP methods in cross orgin requests
$allowedMethods = self::$allowedMethods;
if (isset($this->options[self::HEADER_ALLOW_METHODS])) {
$allowedMethods = (array)$this->options[self::HEADER_ALLOW_METHODS];
}
@header(self::HEADER_ALLOW_METHODS.':'.implode(',', $allowedMethods));
} | [
"private",
"function",
"addHeadersForOptionsRequests",
"(",
")",
"{",
"// header for preflight cache expiry",
"$",
"maxAge",
"=",
"self",
"::",
"MAX_AGE",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"self",
"::",
"HEADER_MAX_AGE",
"]",
")",
")",
"{",
"$",
"maxAge",
"=",
"intval",
"(",
"$",
"this",
"->",
"options",
"[",
"self",
"::",
"HEADER_MAX_AGE",
"]",
")",
";",
"}",
"@",
"header",
"(",
"self",
"::",
"HEADER_MAX_AGE",
".",
"': '",
".",
"$",
"maxAge",
")",
";",
"// header for allowed request headers in cross origin requests",
"$",
"allowedHeaders",
"=",
"self",
"::",
"$",
"allowedHeaders",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"self",
"::",
"HEADER_ALLOW_HEADERS",
"]",
")",
")",
"{",
"$",
"allowedHeaders",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"options",
"[",
"self",
"::",
"HEADER_ALLOW_HEADERS",
"]",
";",
"}",
"@",
"header",
"(",
"self",
"::",
"HEADER_ALLOW_HEADERS",
".",
"':'",
".",
"implode",
"(",
"','",
",",
"$",
"allowedHeaders",
")",
")",
";",
"// header for allowed HTTP methods in cross orgin requests",
"$",
"allowedMethods",
"=",
"self",
"::",
"$",
"allowedMethods",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"self",
"::",
"HEADER_ALLOW_METHODS",
"]",
")",
")",
"{",
"$",
"allowedMethods",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"options",
"[",
"self",
"::",
"HEADER_ALLOW_METHODS",
"]",
";",
"}",
"@",
"header",
"(",
"self",
"::",
"HEADER_ALLOW_METHODS",
".",
"':'",
".",
"implode",
"(",
"','",
",",
"$",
"allowedMethods",
")",
")",
";",
"}"
]
| Adds additional headers for the OPTIONS http verb. | [
"Adds",
"additional",
"headers",
"for",
"the",
"OPTIONS",
"http",
"verb",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Plugin/AccessControl/CrossOriginRequestPlugin.php#L111-L133 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Handler/CliTaskHandler.php | CliTaskHandler.isAppropriate | public function isAppropriate($components)
{
$components = array_values(array_filter(array_map('trim', $components), 'strlen'));
$this->options = array();
if (count($components) < 5) {
return false;
}
if ($components[1] !== '--task' || $components[3] !== '--action') {
return false;
}
$this->options['task'] = $components[2];
$this->options['action'] = $components[4];
try {
// ensure we have this task registered
$this->getServiceProvider()->get($this->options['task']);
} catch (Exception $e) {
return false;
}
return true;
} | php | public function isAppropriate($components)
{
$components = array_values(array_filter(array_map('trim', $components), 'strlen'));
$this->options = array();
if (count($components) < 5) {
return false;
}
if ($components[1] !== '--task' || $components[3] !== '--action') {
return false;
}
$this->options['task'] = $components[2];
$this->options['action'] = $components[4];
try {
// ensure we have this task registered
$this->getServiceProvider()->get($this->options['task']);
} catch (Exception $e) {
return false;
}
return true;
} | [
"public",
"function",
"isAppropriate",
"(",
"$",
"components",
")",
"{",
"$",
"components",
"=",
"array_values",
"(",
"array_filter",
"(",
"array_map",
"(",
"'trim'",
",",
"$",
"components",
")",
",",
"'strlen'",
")",
")",
";",
"$",
"this",
"->",
"options",
"=",
"array",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"components",
")",
"<",
"5",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"components",
"[",
"1",
"]",
"!==",
"'--task'",
"||",
"$",
"components",
"[",
"3",
"]",
"!==",
"'--action'",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"options",
"[",
"'task'",
"]",
"=",
"$",
"components",
"[",
"2",
"]",
";",
"$",
"this",
"->",
"options",
"[",
"'action'",
"]",
"=",
"$",
"components",
"[",
"4",
"]",
";",
"try",
"{",
"// ensure we have this task registered",
"$",
"this",
"->",
"getServiceProvider",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"options",
"[",
"'task'",
"]",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Determines whether the current handler is appropriate for the given
path components.
@param array $components The path components as an array.
@return boolean Returns true if the handler is appropriate and false
otherwise. | [
"Determines",
"whether",
"the",
"current",
"handler",
"is",
"appropriate",
"for",
"the",
"given",
"path",
"components",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/CliTaskHandler.php#L23-L45 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Handler/PatternMatchHandler.php | PatternMatchHandler.getRouteInfo | protected function getRouteInfo($verb, $path, $useCache = false)
{
if (!$useCache || !isset($this->routeInfo)) {
$dispatcher = $this->getDispatcher($this->getRoutes());
$this->routeInfo = $dispatcher->dispatch(strtoupper($verb), $path);
}
return $this->routeInfo;
} | php | protected function getRouteInfo($verb, $path, $useCache = false)
{
if (!$useCache || !isset($this->routeInfo)) {
$dispatcher = $this->getDispatcher($this->getRoutes());
$this->routeInfo = $dispatcher->dispatch(strtoupper($verb), $path);
}
return $this->routeInfo;
} | [
"protected",
"function",
"getRouteInfo",
"(",
"$",
"verb",
",",
"$",
"path",
",",
"$",
"useCache",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"useCache",
"||",
"!",
"isset",
"(",
"$",
"this",
"->",
"routeInfo",
")",
")",
"{",
"$",
"dispatcher",
"=",
"$",
"this",
"->",
"getDispatcher",
"(",
"$",
"this",
"->",
"getRoutes",
"(",
")",
")",
";",
"$",
"this",
"->",
"routeInfo",
"=",
"$",
"dispatcher",
"->",
"dispatch",
"(",
"strtoupper",
"(",
"$",
"verb",
")",
",",
"$",
"path",
")",
";",
"}",
"return",
"$",
"this",
"->",
"routeInfo",
";",
"}"
]
| Returns the array of route info from the routing library.
@param string $verb The HTTP verb used in the request.
@param string $path The path to match against the patterns.
@param boolean $useCache (optional) An optional flag whether to use the
cached route info or not. Defaults to false.
@return array Returns the route info as an array. | [
"Returns",
"the",
"array",
"of",
"route",
"info",
"from",
"the",
"routing",
"library",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/PatternMatchHandler.php#L66-L73 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Handler/PatternMatchHandler.php | PatternMatchHandler.getDispatcher | private function getDispatcher($routes)
{
$verbs = self::$allHttpVerbs;
$f = function (RouteCollector $collector) use ($routes, $verbs) {
foreach ($routes as $pattern => $route) {
if (is_array($route)) {
foreach ($route as $verb => $callback) {
$collector->addRoute(strtoupper($verb), $pattern, $callback);
}
} else {
foreach ($verbs as $verb) {
$collector->addRoute($verb, $pattern, $route);
}
}
}
};
$options = $this->getOptions();
$cacheData = array();
if (isset($options[self::KEY_CACHE])) {
$cacheData = (array)$options[self::KEY_CACHE];
}
if (empty($cacheData)) {
return \FastRoute\simpleDispatcher($f);
} else {
return \FastRoute\cachedDispatcher($f, $cacheData);
}
} | php | private function getDispatcher($routes)
{
$verbs = self::$allHttpVerbs;
$f = function (RouteCollector $collector) use ($routes, $verbs) {
foreach ($routes as $pattern => $route) {
if (is_array($route)) {
foreach ($route as $verb => $callback) {
$collector->addRoute(strtoupper($verb), $pattern, $callback);
}
} else {
foreach ($verbs as $verb) {
$collector->addRoute($verb, $pattern, $route);
}
}
}
};
$options = $this->getOptions();
$cacheData = array();
if (isset($options[self::KEY_CACHE])) {
$cacheData = (array)$options[self::KEY_CACHE];
}
if (empty($cacheData)) {
return \FastRoute\simpleDispatcher($f);
} else {
return \FastRoute\cachedDispatcher($f, $cacheData);
}
} | [
"private",
"function",
"getDispatcher",
"(",
"$",
"routes",
")",
"{",
"$",
"verbs",
"=",
"self",
"::",
"$",
"allHttpVerbs",
";",
"$",
"f",
"=",
"function",
"(",
"RouteCollector",
"$",
"collector",
")",
"use",
"(",
"$",
"routes",
",",
"$",
"verbs",
")",
"{",
"foreach",
"(",
"$",
"routes",
"as",
"$",
"pattern",
"=>",
"$",
"route",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"route",
")",
")",
"{",
"foreach",
"(",
"$",
"route",
"as",
"$",
"verb",
"=>",
"$",
"callback",
")",
"{",
"$",
"collector",
"->",
"addRoute",
"(",
"strtoupper",
"(",
"$",
"verb",
")",
",",
"$",
"pattern",
",",
"$",
"callback",
")",
";",
"}",
"}",
"else",
"{",
"foreach",
"(",
"$",
"verbs",
"as",
"$",
"verb",
")",
"{",
"$",
"collector",
"->",
"addRoute",
"(",
"$",
"verb",
",",
"$",
"pattern",
",",
"$",
"route",
")",
";",
"}",
"}",
"}",
"}",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"getOptions",
"(",
")",
";",
"$",
"cacheData",
"=",
"array",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"KEY_CACHE",
"]",
")",
")",
"{",
"$",
"cacheData",
"=",
"(",
"array",
")",
"$",
"options",
"[",
"self",
"::",
"KEY_CACHE",
"]",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"cacheData",
")",
")",
"{",
"return",
"\\",
"FastRoute",
"\\",
"simpleDispatcher",
"(",
"$",
"f",
")",
";",
"}",
"else",
"{",
"return",
"\\",
"FastRoute",
"\\",
"cachedDispatcher",
"(",
"$",
"f",
",",
"$",
"cacheData",
")",
";",
"}",
"}"
]
| Returns an instance of the FastRoute dispatcher.
@param array $routes The array of specified routes.
@return FastRoute\Dispatcher The dispatcher to use. | [
"Returns",
"an",
"instance",
"of",
"the",
"FastRoute",
"dispatcher",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/PatternMatchHandler.php#L110-L138 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Controller/AbstractController.php | AbstractController.renderView | public function renderView($viewVariables, $template)
{
$encoder = $this->handler->getEncoder();
if (method_exists($encoder, 'renderView')) {
return $encoder->renderView(
$template,
array_merge($this->viewContext, (array)$viewVariables)
);
} else {
throw new Exception('The current encoder does not support the render view method.');
}
} | php | public function renderView($viewVariables, $template)
{
$encoder = $this->handler->getEncoder();
if (method_exists($encoder, 'renderView')) {
return $encoder->renderView(
$template,
array_merge($this->viewContext, (array)$viewVariables)
);
} else {
throw new Exception('The current encoder does not support the render view method.');
}
} | [
"public",
"function",
"renderView",
"(",
"$",
"viewVariables",
",",
"$",
"template",
")",
"{",
"$",
"encoder",
"=",
"$",
"this",
"->",
"handler",
"->",
"getEncoder",
"(",
")",
";",
"if",
"(",
"method_exists",
"(",
"$",
"encoder",
",",
"'renderView'",
")",
")",
"{",
"return",
"$",
"encoder",
"->",
"renderView",
"(",
"$",
"template",
",",
"array_merge",
"(",
"$",
"this",
"->",
"viewContext",
",",
"(",
"array",
")",
"$",
"viewVariables",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"'The current encoder does not support the render view method.'",
")",
";",
"}",
"}"
]
| Renders the view for the given controller and action.
@param array $viewVariables An array of additional parameters to add
to the existing view context.
@param string $template The name of the view template.
@return Returns the rendered view as a string. | [
"Renders",
"the",
"view",
"for",
"the",
"given",
"controller",
"and",
"action",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Controller/AbstractController.php#L50-L61 | train |
Vectorface/SnappyRouter | src/Vectorface/SnappyRouter/Handler/ControllerHandler.php | ControllerHandler.extractPathFromBasePath | protected function extractPathFromBasePath($path, $options)
{
if (isset($options[self::KEY_BASE_PATH])) {
$pos = strpos($path, $options[self::KEY_BASE_PATH]);
if (false !== $pos) {
$path = substr($path, $pos + strlen($options[self::KEY_BASE_PATH]));
}
}
// ensure the path has a leading slash
if (empty($path) || $path[0] !== '/') {
$path = '/'.$path;
}
return $path;
} | php | protected function extractPathFromBasePath($path, $options)
{
if (isset($options[self::KEY_BASE_PATH])) {
$pos = strpos($path, $options[self::KEY_BASE_PATH]);
if (false !== $pos) {
$path = substr($path, $pos + strlen($options[self::KEY_BASE_PATH]));
}
}
// ensure the path has a leading slash
if (empty($path) || $path[0] !== '/') {
$path = '/'.$path;
}
return $path;
} | [
"protected",
"function",
"extractPathFromBasePath",
"(",
"$",
"path",
",",
"$",
"options",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"KEY_BASE_PATH",
"]",
")",
")",
"{",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"path",
",",
"$",
"options",
"[",
"self",
"::",
"KEY_BASE_PATH",
"]",
")",
";",
"if",
"(",
"false",
"!==",
"$",
"pos",
")",
"{",
"$",
"path",
"=",
"substr",
"(",
"$",
"path",
",",
"$",
"pos",
"+",
"strlen",
"(",
"$",
"options",
"[",
"self",
"::",
"KEY_BASE_PATH",
"]",
")",
")",
";",
"}",
"}",
"// ensure the path has a leading slash",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
"||",
"$",
"path",
"[",
"0",
"]",
"!==",
"'/'",
")",
"{",
"$",
"path",
"=",
"'/'",
".",
"$",
"path",
";",
"}",
"return",
"$",
"path",
";",
"}"
]
| Returns the new path with the base path extracted.
@param string $path The full path.
@param array $options The array of options.
@return string Returns the new path with the base path removed. | [
"Returns",
"the",
"new",
"path",
"with",
"the",
"base",
"path",
"extracted",
"."
]
| 795c8377e808933f228835c9aa4d2071136931fc | https://github.com/Vectorface/SnappyRouter/blob/795c8377e808933f228835c9aa4d2071136931fc/src/Vectorface/SnappyRouter/Handler/ControllerHandler.php#L159-L172 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.