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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
mzur/kirby-uniform | src/Guards/Guard.php | Guard.reject | protected function reject($message = null, $key = null)
{
$message = $message ?: static::class.' rejected the request.';
$key = $key ?: static::class;
throw new PerformerException($message, $key);
} | php | protected function reject($message = null, $key = null)
{
$message = $message ?: static::class.' rejected the request.';
$key = $key ?: static::class;
throw new PerformerException($message, $key);
} | [
"protected",
"function",
"reject",
"(",
"$",
"message",
"=",
"null",
",",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"message",
"=",
"$",
"message",
"?",
":",
"static",
"::",
"class",
".",
"' rejected the request.'",
";",
"$",
"key",
"=",
"$",
"key",
"?... | Make this guard reject the request by throwing a PerformerException
@param string $message Rejection message
@param string $key Key of the rejection (e.g. form field name)
@throws PerformerException | [
"Make",
"this",
"guard",
"reject",
"the",
"request",
"by",
"throwing",
"a",
"PerformerException"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Guards/Guard.php#L26-L32 | train |
mzur/kirby-uniform | src/Performer.php | Performer.option | protected function option($key, $default = null)
{
return array_key_exists($key, $this->options) ? $this->options[$key] : $default;
} | php | protected function option($key, $default = null)
{
return array_key_exists($key, $this->options) ? $this->options[$key] : $default;
} | [
"protected",
"function",
"option",
"(",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"options",
")",
"?",
"$",
"this",
"->",
"options",
"[",
"$",
"key",
"]",
":",
"$"... | Get an option from the options array
@param string $key Option key
@param mixed $default Default value if the option was not set
@return mixed | [
"Get",
"an",
"option",
"from",
"the",
"options",
"array"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Performer.php#L50-L53 | train |
mzur/kirby-uniform | src/Performer.php | Performer.requireOption | protected function requireOption($key)
{
$value = $this->option($key);
if ($value === null) {
throw new Exception("The '{$key}' option is required.");
}
return $value;
} | php | protected function requireOption($key)
{
$value = $this->option($key);
if ($value === null) {
throw new Exception("The '{$key}' option is required.");
}
return $value;
} | [
"protected",
"function",
"requireOption",
"(",
"$",
"key",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"option",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"The '{$key}' option i... | Get an option from the options array and throw an exception if it isn't set
@param string $key Option key
@return mixed
@throws Exception | [
"Get",
"an",
"option",
"from",
"the",
"options",
"array",
"and",
"throw",
"an",
"exception",
"if",
"it",
"isn",
"t",
"set"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Performer.php#L61-L69 | train |
mzur/kirby-uniform | src/Actions/WebhookAction.php | WebhookAction.perform | public function perform()
{
$url = $this->requireOption('url');
$only = $this->option('only');
$except = $this->option('except');
if (is_array($only)) {
$data = [];
foreach ($only as $key) {
$data[$key] = $this->form->data($key);
}
} else {
$data = $this->form->data();
}
if (is_array($except)) {
foreach ($except as $key) {
unset($data[$key]);
}
}
$params = $this->option('params', []);
// merge the optional 'static' data from the action array with the form data
$data = array_merge(A::get($params, 'data', []), $data);
$params['data'] = $this->transformData($data);
if ($this->option('json') === true) {
$headers = ['Content-Type: application/json'];
$params['data'] = json_encode($params['data'], JSON_UNESCAPED_SLASHES);
} else {
$headers = ['Content-Type: application/x-www-form-urlencoded'];
}
$params['headers'] = array_merge(A::get($params, 'headers', []), $headers);
$response = $this->request($url, $params);
if ($response->error !== 0) {
$this->fail(I18n::translate('uniform-webhook-error').$response->message);
}
} | php | public function perform()
{
$url = $this->requireOption('url');
$only = $this->option('only');
$except = $this->option('except');
if (is_array($only)) {
$data = [];
foreach ($only as $key) {
$data[$key] = $this->form->data($key);
}
} else {
$data = $this->form->data();
}
if (is_array($except)) {
foreach ($except as $key) {
unset($data[$key]);
}
}
$params = $this->option('params', []);
// merge the optional 'static' data from the action array with the form data
$data = array_merge(A::get($params, 'data', []), $data);
$params['data'] = $this->transformData($data);
if ($this->option('json') === true) {
$headers = ['Content-Type: application/json'];
$params['data'] = json_encode($params['data'], JSON_UNESCAPED_SLASHES);
} else {
$headers = ['Content-Type: application/x-www-form-urlencoded'];
}
$params['headers'] = array_merge(A::get($params, 'headers', []), $headers);
$response = $this->request($url, $params);
if ($response->error !== 0) {
$this->fail(I18n::translate('uniform-webhook-error').$response->message);
}
} | [
"public",
"function",
"perform",
"(",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"requireOption",
"(",
"'url'",
")",
";",
"$",
"only",
"=",
"$",
"this",
"->",
"option",
"(",
"'only'",
")",
";",
"$",
"except",
"=",
"$",
"this",
"->",
"option",
... | Call a webhook | [
"Call",
"a",
"webhook"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/WebhookAction.php#L17-L57 | train |
mzur/kirby-uniform | src/Actions/EmailAction.php | EmailAction.perform | public function perform()
{
$params = array_merge($this->options, [
'to' => $this->requireOption('to'),
'from' => $this->requireOption('from'),
'replyTo' => $this->option('replyTo', $this->form->data(self::EMAIL_KEY)),
'subject' => $this->getSubject(),
]);
if (empty($params['replyTo'])) {
unset($params['replyTo']);
}
if (array_key_exists('data', $params)) {
$params['data'] = array_merge($params['data'], $this->form->data());
} else {
$params['data'] = $this->form->data();
}
if (isset($params['template'])) {
$params['data'] = array_merge($params['data'], [
'_data' => $params['data'],
'_options' => $this->options,
]);
} else {
$params['body'] = $this->getBody();
}
try {
$this->sendEmail($params);
if ($this->shouldReceiveCopy()) {
$params['subject'] = I18n::translate('uniform-email-copy').' '.$params['subject'];
$to = $params['to'];
$params['to'] = $params['replyTo'];
$params['replyTo'] = $to;
$this->sendEmail($params);
}
} catch (Exception $e) {
$this->handleException($e);
}
} | php | public function perform()
{
$params = array_merge($this->options, [
'to' => $this->requireOption('to'),
'from' => $this->requireOption('from'),
'replyTo' => $this->option('replyTo', $this->form->data(self::EMAIL_KEY)),
'subject' => $this->getSubject(),
]);
if (empty($params['replyTo'])) {
unset($params['replyTo']);
}
if (array_key_exists('data', $params)) {
$params['data'] = array_merge($params['data'], $this->form->data());
} else {
$params['data'] = $this->form->data();
}
if (isset($params['template'])) {
$params['data'] = array_merge($params['data'], [
'_data' => $params['data'],
'_options' => $this->options,
]);
} else {
$params['body'] = $this->getBody();
}
try {
$this->sendEmail($params);
if ($this->shouldReceiveCopy()) {
$params['subject'] = I18n::translate('uniform-email-copy').' '.$params['subject'];
$to = $params['to'];
$params['to'] = $params['replyTo'];
$params['replyTo'] = $to;
$this->sendEmail($params);
}
} catch (Exception $e) {
$this->handleException($e);
}
} | [
"public",
"function",
"perform",
"(",
")",
"{",
"$",
"params",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"options",
",",
"[",
"'to'",
"=>",
"$",
"this",
"->",
"requireOption",
"(",
"'to'",
")",
",",
"'from'",
"=>",
"$",
"this",
"->",
"requireOption",... | Send the form data via email. | [
"Send",
"the",
"form",
"data",
"via",
"email",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/EmailAction.php#L33-L74 | train |
mzur/kirby-uniform | src/Actions/EmailAction.php | EmailAction.handleException | protected function handleException($e)
{
if (App::instance()->option('debug') === true) {
$this->fail(I18n::translate('uniform-email-error').': '.$e->getMessage());
}
$this->fail(I18n::translate('uniform-email-error').'.');
} | php | protected function handleException($e)
{
if (App::instance()->option('debug') === true) {
$this->fail(I18n::translate('uniform-email-error').': '.$e->getMessage());
}
$this->fail(I18n::translate('uniform-email-error').'.');
} | [
"protected",
"function",
"handleException",
"(",
"$",
"e",
")",
"{",
"if",
"(",
"App",
"::",
"instance",
"(",
")",
"->",
"option",
"(",
"'debug'",
")",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"fail",
"(",
"I18n",
"::",
"translate",
"(",
"'uniform... | Handle an exception when the email should be sent.
@param Exception|Error $e | [
"Handle",
"an",
"exception",
"when",
"the",
"email",
"should",
"be",
"sent",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/EmailAction.php#L81-L88 | train |
mzur/kirby-uniform | src/Actions/EmailAction.php | EmailAction.getSubject | protected function getSubject()
{
// the form could contain arrays which are incompatible with the template function
$templatableItems = array_filter($this->form->data(), function ($item) {
return is_scalar($item);
});
$subject = Str::template($this->option('subject', I18n::translate('uniform-email-subject')), $templatableItems);
// Remove newlines to prevent malicious modifications of the email header.
return str_replace("\n", '', $subject);
} | php | protected function getSubject()
{
// the form could contain arrays which are incompatible with the template function
$templatableItems = array_filter($this->form->data(), function ($item) {
return is_scalar($item);
});
$subject = Str::template($this->option('subject', I18n::translate('uniform-email-subject')), $templatableItems);
// Remove newlines to prevent malicious modifications of the email header.
return str_replace("\n", '', $subject);
} | [
"protected",
"function",
"getSubject",
"(",
")",
"{",
"// the form could contain arrays which are incompatible with the template function",
"$",
"templatableItems",
"=",
"array_filter",
"(",
"$",
"this",
"->",
"form",
"->",
"data",
"(",
")",
",",
"function",
"(",
"$",
... | Get the email subject and resolve possible template strings
@return string | [
"Get",
"the",
"email",
"subject",
"and",
"resolve",
"possible",
"template",
"strings"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/EmailAction.php#L105-L116 | train |
mzur/kirby-uniform | src/Actions/EmailAction.php | EmailAction.getBody | protected function getBody()
{
$data = $this->form->data();
unset($data[self::EMAIL_KEY]);
unset($data[self::RECEIVE_COPY_KEY]);
$body = '';
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = implode(', ', array_filter($value, function ($i) {
return $i !== '';
}));
}
$body .= ucfirst($key).': '.$value."\n\n";
}
return $body;
} | php | protected function getBody()
{
$data = $this->form->data();
unset($data[self::EMAIL_KEY]);
unset($data[self::RECEIVE_COPY_KEY]);
$body = '';
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = implode(', ', array_filter($value, function ($i) {
return $i !== '';
}));
}
$body .= ucfirst($key).': '.$value."\n\n";
}
return $body;
} | [
"protected",
"function",
"getBody",
"(",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"form",
"->",
"data",
"(",
")",
";",
"unset",
"(",
"$",
"data",
"[",
"self",
"::",
"EMAIL_KEY",
"]",
")",
";",
"unset",
"(",
"$",
"data",
"[",
"self",
"::",
... | Get the email body
@return string | [
"Get",
"the",
"email",
"body"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/EmailAction.php#L123-L141 | train |
mzur/kirby-uniform | src/Actions/Action.php | Action.fail | protected function fail($message = null, $key = null)
{
$message = $message ?: static::class.' failed.';
$key = $key ?: static::class;
throw new PerformerException($message, $key);
} | php | protected function fail($message = null, $key = null)
{
$message = $message ?: static::class.' failed.';
$key = $key ?: static::class;
throw new PerformerException($message, $key);
} | [
"protected",
"function",
"fail",
"(",
"$",
"message",
"=",
"null",
",",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"message",
"=",
"$",
"message",
"?",
":",
"static",
"::",
"class",
".",
"' failed.'",
";",
"$",
"key",
"=",
"$",
"key",
"?",
":",
"sta... | Make this action fail by throwing an PerformerException.
@param string $message Error message
@param string $key Key of the error (e.g. form field name)
@throws PerformerException | [
"Make",
"this",
"action",
"fail",
"by",
"throwing",
"an",
"PerformerException",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/Action.php#L25-L31 | train |
mzur/kirby-uniform | src/Actions/UploadAction.php | UploadAction.perform | public function perform()
{
$fields = $this->requireOption('fields');
foreach ($fields as $field => $options) {
$this->handleFile($field, $options);
}
} | php | public function perform()
{
$fields = $this->requireOption('fields');
foreach ($fields as $field => $options) {
$this->handleFile($field, $options);
}
} | [
"public",
"function",
"perform",
"(",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"requireOption",
"(",
"'fields'",
")",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
"=>",
"$",
"options",
")",
"{",
"$",
"this",
"->",
"handleFile",
"("... | Move uploaded files to their target directory. | [
"Move",
"uploaded",
"files",
"to",
"their",
"target",
"directory",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/UploadAction.php#L31-L38 | train |
mzur/kirby-uniform | src/Actions/UploadAction.php | UploadAction.handleFile | protected function handleFile($field, $options)
{
$file = $this->form->data($field);
if (!is_array($file) || !isset($file['error']) || intval($file['error']) !== UPLOAD_ERR_OK) {
// If this is an array, kirby-form already recognized and validated the
// uploaded file. If the file is required, this should have been checked
// during validation.
return;
}
if (!array_key_exists('target', $options)) {
// No translation because this is a developer error.
$this->fail("The target directory is missing for field {$field}.");
}
$target = $options['target'];
if (!is_dir($target)) {
if (@mkdir($target, 0755)) {
$this->createdDirectories[] = $target;
} else {
$this->fail(I18n::translate('uniform-upload-mkdir-fail'), $field);
}
}
$name = $file['name'];
$prefix = A::get($options, 'prefix');
if (is_null($prefix)) {
$name = $this->getRandomPrefix($name);
} elseif ($prefix !== false) {
$name = $prefix.$name;
}
$path = $target.DIRECTORY_SEPARATOR.$name;
if (is_file($path)) {
$this->fail(I18n::translate('uniform-upload-exists'), $field);
}
$success = $this->moveFile($file['tmp_name'], $path);
if ($success) {
$this->createdFiles[] = $path;
} else {
$this->fail(I18n::translate('uniform-upload-failed'), $field);
}
} | php | protected function handleFile($field, $options)
{
$file = $this->form->data($field);
if (!is_array($file) || !isset($file['error']) || intval($file['error']) !== UPLOAD_ERR_OK) {
// If this is an array, kirby-form already recognized and validated the
// uploaded file. If the file is required, this should have been checked
// during validation.
return;
}
if (!array_key_exists('target', $options)) {
// No translation because this is a developer error.
$this->fail("The target directory is missing for field {$field}.");
}
$target = $options['target'];
if (!is_dir($target)) {
if (@mkdir($target, 0755)) {
$this->createdDirectories[] = $target;
} else {
$this->fail(I18n::translate('uniform-upload-mkdir-fail'), $field);
}
}
$name = $file['name'];
$prefix = A::get($options, 'prefix');
if (is_null($prefix)) {
$name = $this->getRandomPrefix($name);
} elseif ($prefix !== false) {
$name = $prefix.$name;
}
$path = $target.DIRECTORY_SEPARATOR.$name;
if (is_file($path)) {
$this->fail(I18n::translate('uniform-upload-exists'), $field);
}
$success = $this->moveFile($file['tmp_name'], $path);
if ($success) {
$this->createdFiles[] = $path;
} else {
$this->fail(I18n::translate('uniform-upload-failed'), $field);
}
} | [
"protected",
"function",
"handleFile",
"(",
"$",
"field",
",",
"$",
"options",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"form",
"->",
"data",
"(",
"$",
"field",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"file",
")",
"||",
"!",
"isset"... | Move a single uploaded file.
@param string $field Form field name.
@param array $options | [
"Move",
"a",
"single",
"uploaded",
"file",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/UploadAction.php#L46-L93 | train |
mzur/kirby-uniform | src/Actions/LogAction.php | LogAction.perform | public function perform()
{
$file = $this->requireOption('file');
$content = $this->getContent();
if ($this->write($file, $content) === false) {
$this->fail(I18n::translate('uniform-log-error'));
}
} | php | public function perform()
{
$file = $this->requireOption('file');
$content = $this->getContent();
if ($this->write($file, $content) === false) {
$this->fail(I18n::translate('uniform-log-error'));
}
} | [
"public",
"function",
"perform",
"(",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"requireOption",
"(",
"'file'",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"getContent",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"write",
"(",
"$",
"... | Append the form data to the log file. | [
"Append",
"the",
"form",
"data",
"to",
"the",
"log",
"file",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/LogAction.php#L16-L24 | train |
mzur/kirby-uniform | src/Actions/LogAction.php | LogAction.getContent | protected function getContent()
{
$template = $this->option('template');
$data = $this->form->data();
if ($template) {
$content = $this->getTemplate($template, [
'data' => $data,
'options' => $this->options
]);
} else {
$visitor = App::instance()->visitor();
$content = '['.date('c').'] '.$visitor->ip().' '.$visitor->userAgent();
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = implode(', ', array_filter($value, function ($i) {
return $i !== '';
}));
}
$content .= "\n{$key}: {$value}";
}
$content .= "\n\n";
}
return $content;
} | php | protected function getContent()
{
$template = $this->option('template');
$data = $this->form->data();
if ($template) {
$content = $this->getTemplate($template, [
'data' => $data,
'options' => $this->options
]);
} else {
$visitor = App::instance()->visitor();
$content = '['.date('c').'] '.$visitor->ip().' '.$visitor->userAgent();
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = implode(', ', array_filter($value, function ($i) {
return $i !== '';
}));
}
$content .= "\n{$key}: {$value}";
}
$content .= "\n\n";
}
return $content;
} | [
"protected",
"function",
"getContent",
"(",
")",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"option",
"(",
"'template'",
")",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"form",
"->",
"data",
"(",
")",
";",
"if",
"(",
"$",
"template",
")",
"{",
... | Get the content of the log entry
@return string | [
"Get",
"the",
"content",
"of",
"the",
"log",
"entry"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/LogAction.php#L43-L69 | train |
mzur/kirby-uniform | src/Actions/LogAction.php | LogAction.getTemplate | protected function getTemplate($name, array $data)
{
$template = App::instance()->template($name);
if (!$template->exists()) {
throw new Exception("The template '{$name}' does not exist.");
}
return $template->render($data);
} | php | protected function getTemplate($name, array $data)
{
$template = App::instance()->template($name);
if (!$template->exists()) {
throw new Exception("The template '{$name}' does not exist.");
}
return $template->render($data);
} | [
"protected",
"function",
"getTemplate",
"(",
"$",
"name",
",",
"array",
"$",
"data",
")",
"{",
"$",
"template",
"=",
"App",
"::",
"instance",
"(",
")",
"->",
"template",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"$",
"template",
"->",
"exists",
"... | Returns the a rendered template as string.
@param string $name
@param array $data
@return string | [
"Returns",
"the",
"a",
"rendered",
"template",
"as",
"string",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/LogAction.php#L78-L87 | train |
mzur/kirby-uniform | src/Actions/LoginAction.php | LoginAction.perform | public function perform()
{
$userField = $this->option('user-field', 'username');
$passwordField = $this->option('password-field', 'password');
$user = $this->getUser($this->form->data($userField));
if (!$user || !$user->login($this->form->data($passwordField))) {
$this->fail(I18n::translate('uniform-login-error'), $userField);
}
} | php | public function perform()
{
$userField = $this->option('user-field', 'username');
$passwordField = $this->option('password-field', 'password');
$user = $this->getUser($this->form->data($userField));
if (!$user || !$user->login($this->form->data($passwordField))) {
$this->fail(I18n::translate('uniform-login-error'), $userField);
}
} | [
"public",
"function",
"perform",
"(",
")",
"{",
"$",
"userField",
"=",
"$",
"this",
"->",
"option",
"(",
"'user-field'",
",",
"'username'",
")",
";",
"$",
"passwordField",
"=",
"$",
"this",
"->",
"option",
"(",
"'password-field'",
",",
"'password'",
")",
... | Log in a user. | [
"Log",
"in",
"a",
"user",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/LoginAction.php#L16-L26 | train |
mzur/kirby-uniform | src/Actions/EmailSelectAction.php | EmailSelectAction.perform | public function perform()
{
$this->options['to'] = $this->getRecipient();
unset($this->data[self::RECIPIENT_FIELD]);
unset($this->options['allowed-recipients']);
return parent::perform();
} | php | public function perform()
{
$this->options['to'] = $this->getRecipient();
unset($this->data[self::RECIPIENT_FIELD]);
unset($this->options['allowed-recipients']);
return parent::perform();
} | [
"public",
"function",
"perform",
"(",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"'to'",
"]",
"=",
"$",
"this",
"->",
"getRecipient",
"(",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"data",
"[",
"self",
"::",
"RECIPIENT_FIELD",
"]",
")",
";",
"un... | Set the chosen recipient email address and send the form data via email. | [
"Set",
"the",
"chosen",
"recipient",
"email",
"address",
"and",
"send",
"the",
"form",
"data",
"via",
"email",
"."
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/EmailSelectAction.php#L22-L29 | train |
mzur/kirby-uniform | src/Actions/EmailSelectAction.php | EmailSelectAction.getRecipient | protected function getRecipient()
{
$recipient = $this->form->data(self::RECIPIENT_FIELD);
$allowed = $this->requireOption('allowed-recipients');
if (!array_key_exists($recipient, $allowed)) {
$this->fail(I18n::translate('uniform-email-error').' '.I18n::translate('uniform-email-select-error'), self::RECIPIENT_FIELD);
}
return $allowed[$recipient];
} | php | protected function getRecipient()
{
$recipient = $this->form->data(self::RECIPIENT_FIELD);
$allowed = $this->requireOption('allowed-recipients');
if (!array_key_exists($recipient, $allowed)) {
$this->fail(I18n::translate('uniform-email-error').' '.I18n::translate('uniform-email-select-error'), self::RECIPIENT_FIELD);
}
return $allowed[$recipient];
} | [
"protected",
"function",
"getRecipient",
"(",
")",
"{",
"$",
"recipient",
"=",
"$",
"this",
"->",
"form",
"->",
"data",
"(",
"self",
"::",
"RECIPIENT_FIELD",
")",
";",
"$",
"allowed",
"=",
"$",
"this",
"->",
"requireOption",
"(",
"'allowed-recipients'",
")... | Get the chosen recipient or fail if it is invalid
@return string | [
"Get",
"the",
"chosen",
"recipient",
"or",
"fail",
"if",
"it",
"is",
"invalid"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Actions/EmailSelectAction.php#L36-L46 | train |
mzur/kirby-uniform | src/Form.php | Form.guard | public function guard($guard = HoneypotGuard::class, $options = [])
{
if ($this->shouldValidate) $this->validate();
$this->shouldCallGuard = false;
if ($this->shouldFallThrough) return $this;
if (is_string($guard) && !class_exists($guard)) {
throw new Exception("{$guard} does not exist.");
}
if (!is_subclass_of($guard, Guard::class)) {
throw new Exception('Guards must extend '.Guard::class.'.');
}
if (is_string($guard)) {
$guard = new $guard($this, $options);
}
$this->perform($guard);
return $this;
} | php | public function guard($guard = HoneypotGuard::class, $options = [])
{
if ($this->shouldValidate) $this->validate();
$this->shouldCallGuard = false;
if ($this->shouldFallThrough) return $this;
if (is_string($guard) && !class_exists($guard)) {
throw new Exception("{$guard} does not exist.");
}
if (!is_subclass_of($guard, Guard::class)) {
throw new Exception('Guards must extend '.Guard::class.'.');
}
if (is_string($guard)) {
$guard = new $guard($this, $options);
}
$this->perform($guard);
return $this;
} | [
"public",
"function",
"guard",
"(",
"$",
"guard",
"=",
"HoneypotGuard",
"::",
"class",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"shouldValidate",
")",
"$",
"this",
"->",
"validate",
"(",
")",
";",
"$",
"this",
"->... | Call a guard
@param string|Guard $guard Guard classname or object
@param array $options Guard options | [
"Call",
"a",
"guard"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Form.php#L152-L173 | train |
mzur/kirby-uniform | src/Form.php | Form.fail | protected function fail()
{
$this->success = false;
if ($this->shouldRedirect) {
die(Response::redirect(Url::last()));
} else {
$this->shouldFallThrough = true;
}
} | php | protected function fail()
{
$this->success = false;
if ($this->shouldRedirect) {
die(Response::redirect(Url::last()));
} else {
$this->shouldFallThrough = true;
}
} | [
"protected",
"function",
"fail",
"(",
")",
"{",
"$",
"this",
"->",
"success",
"=",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"shouldRedirect",
")",
"{",
"die",
"(",
"Response",
"::",
"redirect",
"(",
"Url",
"::",
"last",
"(",
")",
")",
")",
";",
... | Redirect back to the page of the form | [
"Redirect",
"back",
"to",
"the",
"page",
"of",
"the",
"form"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Form.php#L249-L258 | train |
mzur/kirby-uniform | src/Form.php | Form.perform | protected function perform(Performer $performer)
{
try {
$performer->perform();
} catch (PerformerException $e) {
$this->addError($e->getKey(), $e->getMessage());
$this->saveData();
$this->fail();
}
} | php | protected function perform(Performer $performer)
{
try {
$performer->perform();
} catch (PerformerException $e) {
$this->addError($e->getKey(), $e->getMessage());
$this->saveData();
$this->fail();
}
} | [
"protected",
"function",
"perform",
"(",
"Performer",
"$",
"performer",
")",
"{",
"try",
"{",
"$",
"performer",
"->",
"perform",
"(",
")",
";",
"}",
"catch",
"(",
"PerformerException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"addError",
"(",
"$",
"e",
... | Perform a performer and handle a possible exception
@param Performer $performer | [
"Perform",
"a",
"performer",
"and",
"handle",
"a",
"possible",
"exception"
] | 28dcc531ddc9b91e79dc5416bb20182f5eec3709 | https://github.com/mzur/kirby-uniform/blob/28dcc531ddc9b91e79dc5416bb20182f5eec3709/src/Form.php#L265-L274 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Auth/SharePointOnlineAuth.php | SharePointOnlineAuth.__doRequest | public function __doRequest($request, $location, $action, $version, $one_way = false) {
// Authenticate with SP online in order to get required authentication cookies
if (!$this->authCookies) $this->configureAuthCookies($location);
// Set base headers
$headers = array();
$headers[] = "Content-Type: text/xml;";
$headers[] = "SOAPAction: \"{$action}\"";
$curl = curl_init($location);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
// Send request and auth cookies.
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_COOKIE, $this->authCookies);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// Useful for debugging
curl_setopt($curl, CURLOPT_VERBOSE,FALSE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
// Add headers
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// Init the cURL
$response = curl_exec($curl);
// Throw exceptions if there are any issues
if (curl_errno($curl)) throw new \SoapFault('Receiver', curl_error($curl));
if ($response == '') throw new \SoapFault('Receiver', "No XML returned");
// Close CURL
curl_close($curl);
// Return?
if (!$one_way) return ($response);
} | php | public function __doRequest($request, $location, $action, $version, $one_way = false) {
// Authenticate with SP online in order to get required authentication cookies
if (!$this->authCookies) $this->configureAuthCookies($location);
// Set base headers
$headers = array();
$headers[] = "Content-Type: text/xml;";
$headers[] = "SOAPAction: \"{$action}\"";
$curl = curl_init($location);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
// Send request and auth cookies.
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_COOKIE, $this->authCookies);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// Useful for debugging
curl_setopt($curl, CURLOPT_VERBOSE,FALSE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
// Add headers
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// Init the cURL
$response = curl_exec($curl);
// Throw exceptions if there are any issues
if (curl_errno($curl)) throw new \SoapFault('Receiver', curl_error($curl));
if ($response == '') throw new \SoapFault('Receiver', "No XML returned");
// Close CURL
curl_close($curl);
// Return?
if (!$one_way) return ($response);
} | [
"public",
"function",
"__doRequest",
"(",
"$",
"request",
",",
"$",
"location",
",",
"$",
"action",
",",
"$",
"version",
",",
"$",
"one_way",
"=",
"false",
")",
"{",
"// Authenticate with SP online in order to get required authentication cookies",
"if",
"(",
"!",
... | Override do request method | [
"Override",
"do",
"request",
"method"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Auth/SharePointOnlineAuth.php#L17-L58 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Auth/SharePointOnlineAuth.php | SharePointOnlineAuth.configureAuthCookies | protected function configureAuthCookies($location) {
// Get endpoint "https://somthing.sharepoint.com"
$location = parse_url($location);
$endpoint = 'https://'.$location['host'];
// get username & password
$login = $this->{'_login'};
$password = $this->{'_password'};
// Create XML security token request
$xml = $this->generateSecurityToken($login, $password, $endpoint);
// Send request and grab returned xml
$result = $this->authCurl("https://login.microsoftonline.com/extSTS.srf", $xml);
// Extract security token from XML
$xml = new \DOMDocument();
$xml->loadXML($result);
$xpath = new \DOMXPath($xml);
// Register SOAPFault namespace for error checking
$xpath->registerNamespace('psf', "http://schemas.microsoft.com/Passport/SoapServices/SOAPFault");
// Try to detect authentication errors
$errors = $xpath->query("//psf:internalerror");
if($errors->length > 0){
$info = $errors->item(0)->childNodes;
throw new \Exception($info->item(1)->nodeValue, $info->item(0)->nodeValue);
}
$nodelist = $xpath->query("//wsse:BinarySecurityToken");
foreach ($nodelist as $n){
$token = $n->nodeValue;
break;
}
if(!isset($token)){
throw new \Exception("Unable to extract token from authentiction request");
}
// Send token to SharePoint online in order to gain authentication cookies
$result = $this->authCurl($endpoint."/_forms/default.aspx?wa=wsignin1.0", $token, true);
// Extract Authentication cookies from response & set them in to AuthCookies var
$this->authCookies = $this->extractAuthCookies($result);
} | php | protected function configureAuthCookies($location) {
// Get endpoint "https://somthing.sharepoint.com"
$location = parse_url($location);
$endpoint = 'https://'.$location['host'];
// get username & password
$login = $this->{'_login'};
$password = $this->{'_password'};
// Create XML security token request
$xml = $this->generateSecurityToken($login, $password, $endpoint);
// Send request and grab returned xml
$result = $this->authCurl("https://login.microsoftonline.com/extSTS.srf", $xml);
// Extract security token from XML
$xml = new \DOMDocument();
$xml->loadXML($result);
$xpath = new \DOMXPath($xml);
// Register SOAPFault namespace for error checking
$xpath->registerNamespace('psf', "http://schemas.microsoft.com/Passport/SoapServices/SOAPFault");
// Try to detect authentication errors
$errors = $xpath->query("//psf:internalerror");
if($errors->length > 0){
$info = $errors->item(0)->childNodes;
throw new \Exception($info->item(1)->nodeValue, $info->item(0)->nodeValue);
}
$nodelist = $xpath->query("//wsse:BinarySecurityToken");
foreach ($nodelist as $n){
$token = $n->nodeValue;
break;
}
if(!isset($token)){
throw new \Exception("Unable to extract token from authentiction request");
}
// Send token to SharePoint online in order to gain authentication cookies
$result = $this->authCurl($endpoint."/_forms/default.aspx?wa=wsignin1.0", $token, true);
// Extract Authentication cookies from response & set them in to AuthCookies var
$this->authCookies = $this->extractAuthCookies($result);
} | [
"protected",
"function",
"configureAuthCookies",
"(",
"$",
"location",
")",
"{",
"// Get endpoint \"https://somthing.sharepoint.com\"",
"$",
"location",
"=",
"parse_url",
"(",
"$",
"location",
")",
";",
"$",
"endpoint",
"=",
"'https://'",
".",
"$",
"location",
"[",
... | ConfigureAuthCookies
Authenticate with sharepoint online in order to get valid authentication cookies
@param $location - Url of sharepoint list
More info on method:
@see http://allthatjs.com/2012/03/28/remote-authentication-in-sharepoint-online/
@see http://macfoo.wordpress.com/2012/06/23/how-to-log-into-office365-or-sharepoint-online-using-php/ | [
"ConfigureAuthCookies",
"Authenticate",
"with",
"sharepoint",
"online",
"in",
"order",
"to",
"get",
"valid",
"authentication",
"cookies"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Auth/SharePointOnlineAuth.php#L70-L117 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Auth/SharePointOnlineAuth.php | SharePointOnlineAuth.extractAuthCookies | protected function extractAuthCookies($result){
$authCookies = array();
$cookie_payload = '';
$header_array = explode("\r\n", $result);
// Get the two auth cookies
foreach($header_array as $header) {
$loop = explode(":",$header);
if (strtolower($loop[0]) == 'set-cookie') {
$authCookies[] = $loop[1];
}
}
// Extract cookie name & payload and format in to cURL compatible string
foreach($authCookies as $payload){
$e = strpos($payload, "=");
// Get name
$name = substr($payload, 0, $e);
// Get token
$content = substr($payload, $e+1);
$content = substr($content, 0, strpos($content, ";"));
// If not first cookie, add cookie seperator
if($cookie_payload !== '') $cookie_payload .= '; ';
// Add cookie to string
$cookie_payload .= $name.'='.$content;
}
return $cookie_payload;
} | php | protected function extractAuthCookies($result){
$authCookies = array();
$cookie_payload = '';
$header_array = explode("\r\n", $result);
// Get the two auth cookies
foreach($header_array as $header) {
$loop = explode(":",$header);
if (strtolower($loop[0]) == 'set-cookie') {
$authCookies[] = $loop[1];
}
}
// Extract cookie name & payload and format in to cURL compatible string
foreach($authCookies as $payload){
$e = strpos($payload, "=");
// Get name
$name = substr($payload, 0, $e);
// Get token
$content = substr($payload, $e+1);
$content = substr($content, 0, strpos($content, ";"));
// If not first cookie, add cookie seperator
if($cookie_payload !== '') $cookie_payload .= '; ';
// Add cookie to string
$cookie_payload .= $name.'='.$content;
}
return $cookie_payload;
} | [
"protected",
"function",
"extractAuthCookies",
"(",
"$",
"result",
")",
"{",
"$",
"authCookies",
"=",
"array",
"(",
")",
";",
"$",
"cookie_payload",
"=",
"''",
";",
"$",
"header_array",
"=",
"explode",
"(",
"\"\\r\\n\"",
",",
"$",
"result",
")",
";",
"//... | extractAuthCookies
Extract Authentication cookies from SP response & format in to usable cookie string
@param $result cURL Response
@return $cookie_payload string containing cookie data. | [
"extractAuthCookies",
"Extract",
"Authentication",
"cookies",
"from",
"SP",
"response",
"&",
"format",
"in",
"to",
"usable",
"cookie",
"string"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Auth/SharePointOnlineAuth.php#L126-L158 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Auth/SharePointOnlineAuth.php | SharePointOnlineAuth.authCurl | protected function authCurl($url, $payload, $header = false){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
if($header) curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
// catch error
if($result === false) {
throw new \SoapFault('Sender', 'Curl error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
} | php | protected function authCurl($url, $payload, $header = false){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
if($header) curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
// catch error
if($result === false) {
throw new \SoapFault('Sender', 'Curl error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
} | [
"protected",
"function",
"authCurl",
"(",
"$",
"url",
",",
"$",
"payload",
",",
"$",
"header",
"=",
"false",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL",
",",
"$",
"url",
")",
";",
"curl_s... | authCurl
helper method used to cURL SharePoint Online authentiction webservices
@param $url URL to cURL
@param $payload value to post to URL
@param $header true|false - Include headers in response
@return $raw Data returned from cURL. | [
"authCurl",
"helper",
"method",
"used",
"to",
"cURL",
"SharePoint",
"Online",
"authentiction",
"webservices"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Auth/SharePointOnlineAuth.php#L169-L192 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.getLimitedLists | public function getLimitedLists (array $keys, array $params = array('hidden' => 'False'), $isSensetive = TRUE) {
// Get the full list back
$lists = $this->getLists();
// Init new list and look for all matching entries
$newLists = array();
foreach ($lists as $entry) {
// Default is found
$isFound = TRUE;
// Search for all criteria
foreach ($params as $key => $value) {
// Is it found?
if ((isset($entry[$key])) && ((($isSensetive === TRUE) && ($value != $entry[$key])) || (strtolower($value) != strtolower($entry[$key])))) {
// Is not found
$isFound = FALSE;
break;
}
}
// Add it?
if ($isFound === TRUE) {
// Generate new entry array
$newEntry = array();
foreach ($keys as $key) {
// Add this key
$newEntry[$key] = $entry[$key];
}
// Add this new array
$newLists[] = $newEntry;
unset($newEntry);
}
}
// Return finished array
return $newLists;
} | php | public function getLimitedLists (array $keys, array $params = array('hidden' => 'False'), $isSensetive = TRUE) {
// Get the full list back
$lists = $this->getLists();
// Init new list and look for all matching entries
$newLists = array();
foreach ($lists as $entry) {
// Default is found
$isFound = TRUE;
// Search for all criteria
foreach ($params as $key => $value) {
// Is it found?
if ((isset($entry[$key])) && ((($isSensetive === TRUE) && ($value != $entry[$key])) || (strtolower($value) != strtolower($entry[$key])))) {
// Is not found
$isFound = FALSE;
break;
}
}
// Add it?
if ($isFound === TRUE) {
// Generate new entry array
$newEntry = array();
foreach ($keys as $key) {
// Add this key
$newEntry[$key] = $entry[$key];
}
// Add this new array
$newLists[] = $newEntry;
unset($newEntry);
}
}
// Return finished array
return $newLists;
} | [
"public",
"function",
"getLimitedLists",
"(",
"array",
"$",
"keys",
",",
"array",
"$",
"params",
"=",
"array",
"(",
"'hidden'",
"=>",
"'False'",
")",
",",
"$",
"isSensetive",
"=",
"TRUE",
")",
"{",
"// Get the full list back",
"$",
"lists",
"=",
"$",
"this... | Returns an array of all lists
@param array $keys Keys which shall be included in final JSON output
@param array $params Only search for lists with given criteria (default: 'hidden' => 'False')
@param bool $isSensetive Whether to look case-sensetive (default: TRUE)
@return array $newLists An array with given keys from all lists | [
"Returns",
"an",
"array",
"of",
"all",
"lists"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L228-L265 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.getLists | public function getLists () {
// Query Sharepoint for full listing of it's lists.
$rawXml = '';
try {
$rawXml = $this->soapClient->GetListCollection()->GetListCollectionResult->any;
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Load XML in to DOM document and grab all list items.
$nodes = $this->getArrayFromElementsByTagName($rawXml, 'List');
// Format data in to array or object
foreach ($nodes as $counter => $node) {
foreach ($node->attributes as $attribute => $value) {
$idx = ($this->lower_case_indexs) ? strtolower($attribute) : $attribute;
$results[$counter][$idx] = $node->getAttribute($attribute);
}
// Make object if needed
if ($this->returnType === 1) {
settype($results[$counter], 'object');
}
}
// Add error array if stuff goes wrong.
if (!isset($results)) {
$results = array('warning' => 'No data returned.');
}
return $results;
} | php | public function getLists () {
// Query Sharepoint for full listing of it's lists.
$rawXml = '';
try {
$rawXml = $this->soapClient->GetListCollection()->GetListCollectionResult->any;
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Load XML in to DOM document and grab all list items.
$nodes = $this->getArrayFromElementsByTagName($rawXml, 'List');
// Format data in to array or object
foreach ($nodes as $counter => $node) {
foreach ($node->attributes as $attribute => $value) {
$idx = ($this->lower_case_indexs) ? strtolower($attribute) : $attribute;
$results[$counter][$idx] = $node->getAttribute($attribute);
}
// Make object if needed
if ($this->returnType === 1) {
settype($results[$counter], 'object');
}
}
// Add error array if stuff goes wrong.
if (!isset($results)) {
$results = array('warning' => 'No data returned.');
}
return $results;
} | [
"public",
"function",
"getLists",
"(",
")",
"{",
"// Query Sharepoint for full listing of it's lists.",
"$",
"rawXml",
"=",
"''",
";",
"try",
"{",
"$",
"rawXml",
"=",
"$",
"this",
"->",
"soapClient",
"->",
"GetListCollection",
"(",
")",
"->",
"GetListCollectionRes... | Get Lists
Return an array containing all avaiable lists within a given sharepoint subsite.
Use "set return type" if you wish for this data to be provided as an object.
@return array (array) | array (object) | [
"Get",
"Lists",
"Return",
"an",
"array",
"containing",
"all",
"avaiable",
"lists",
"within",
"a",
"given",
"sharepoint",
"subsite",
".",
"Use",
"set",
"return",
"type",
"if",
"you",
"wish",
"for",
"this",
"data",
"to",
"be",
"provided",
"as",
"an",
"object... | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L274-L305 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.read | public function read ($list_name, $limit = NULL, $query = NULL, $view = NULL, $sort = NULL, $options = NULL) {
// Check limit is set
if ($limit < 1 || is_null($limit)) {
$limit = $this->MAX_ROWS;
}
// Create Query XML is query is being used
$xml_options = '';
$xml_query = '';
$fields_xml = '';
// Setup Options
if ($query instanceof Service\QueryObjectService) {
$xml_query = $query->getCAML();
$xml_options = $query->getOptionCAML();
} else {
if (!is_null($query)) {
$xml_query .= $this->whereXML($query); // Build Query
}
if (!is_null($sort)) {
$xml_query .= $this->sortXML($sort);// add sort
}
// Add view or fields
if (!is_null($view)){
// array, fields have been specified
if(is_array($view)){
$xml_options .= $this->viewFieldsXML($view);
}else{
$xml_options .= '<viewName>' . $view . '</viewName>';
}
}
}
// If query is required
if (!empty($xml_query)) {
$xml_options .= '<query><Query>' . $xml_query . '</Query></query>';
}
/*
* Setup basic XML for querying a SharePoint list.
* If rowLimit is not provided SharePoint will default to a limit of 100 items.
*/
$CAML = '
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<rowLimit>' . $limit . '</rowLimit>
' . $xml_options . '
<queryOptions xmlns:SOAPSDK9="http://schemas.microsoft.com/sharepoint/soap/" >
<QueryOptions>
' . $options . '
</QueryOptions>
</queryOptions>
</GetListItems>';
// Ready XML
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
$result = NULL;
// Attempt to query SharePoint
try {
$result = $this->xmlHandler($this->soapClient->GetListItems($xmlvar)->GetListItemsResult->any);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return a XML as nice clean Array
return $result;
} | php | public function read ($list_name, $limit = NULL, $query = NULL, $view = NULL, $sort = NULL, $options = NULL) {
// Check limit is set
if ($limit < 1 || is_null($limit)) {
$limit = $this->MAX_ROWS;
}
// Create Query XML is query is being used
$xml_options = '';
$xml_query = '';
$fields_xml = '';
// Setup Options
if ($query instanceof Service\QueryObjectService) {
$xml_query = $query->getCAML();
$xml_options = $query->getOptionCAML();
} else {
if (!is_null($query)) {
$xml_query .= $this->whereXML($query); // Build Query
}
if (!is_null($sort)) {
$xml_query .= $this->sortXML($sort);// add sort
}
// Add view or fields
if (!is_null($view)){
// array, fields have been specified
if(is_array($view)){
$xml_options .= $this->viewFieldsXML($view);
}else{
$xml_options .= '<viewName>' . $view . '</viewName>';
}
}
}
// If query is required
if (!empty($xml_query)) {
$xml_options .= '<query><Query>' . $xml_query . '</Query></query>';
}
/*
* Setup basic XML for querying a SharePoint list.
* If rowLimit is not provided SharePoint will default to a limit of 100 items.
*/
$CAML = '
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<rowLimit>' . $limit . '</rowLimit>
' . $xml_options . '
<queryOptions xmlns:SOAPSDK9="http://schemas.microsoft.com/sharepoint/soap/" >
<QueryOptions>
' . $options . '
</QueryOptions>
</queryOptions>
</GetListItems>';
// Ready XML
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
$result = NULL;
// Attempt to query SharePoint
try {
$result = $this->xmlHandler($this->soapClient->GetListItems($xmlvar)->GetListItemsResult->any);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return a XML as nice clean Array
return $result;
} | [
"public",
"function",
"read",
"(",
"$",
"list_name",
",",
"$",
"limit",
"=",
"NULL",
",",
"$",
"query",
"=",
"NULL",
",",
"$",
"view",
"=",
"NULL",
",",
"$",
"sort",
"=",
"NULL",
",",
"$",
"options",
"=",
"NULL",
")",
"{",
"// Check limit is set",
... | Read
Use's raw CAML to query sharepoint data
@param String $list_name
@param int $limit
@param Array $query
@param String (GUID) $view "View to display results with."
@param Array $sort
@param String $options "XML string of query options."
@return Array | [
"Read",
"Use",
"s",
"raw",
"CAML",
"to",
"query",
"sharepoint",
"data"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L382-L451 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.readFromFolder | public function readFromFolder($listName, $folderName = '', $isLibrary = false, $limit = NULL, $query = NULL, $view = NULL, $sort = NULL) {
return $this->read($listName, $limit, $query, $view, $sort, "<Folder>" . ($isLibrary ? '' : 'Lists/') . $listName . '/' . $folderName . "</Folder>" );
} | php | public function readFromFolder($listName, $folderName = '', $isLibrary = false, $limit = NULL, $query = NULL, $view = NULL, $sort = NULL) {
return $this->read($listName, $limit, $query, $view, $sort, "<Folder>" . ($isLibrary ? '' : 'Lists/') . $listName . '/' . $folderName . "</Folder>" );
} | [
"public",
"function",
"readFromFolder",
"(",
"$",
"listName",
",",
"$",
"folderName",
"=",
"''",
",",
"$",
"isLibrary",
"=",
"false",
",",
"$",
"limit",
"=",
"NULL",
",",
"$",
"query",
"=",
"NULL",
",",
"$",
"view",
"=",
"NULL",
",",
"$",
"sort",
"... | ReadFromFolder
Uses raw CAML to query sharepoint data from a folder
@param String $listName
@param String $folderName
@param bool $isLibrary
@param String $limit
@param String $query
@param String $view
@param String $sort
@return Array | [
"ReadFromFolder",
"Uses",
"raw",
"CAML",
"to",
"query",
"sharepoint",
"data",
"from",
"a",
"folder"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L467-L469 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.deleteMultiple | public function deleteMultiple ($list_name, array $IDs, array $data = array()) {
/*
* change input "array(ID1, ID2, ID3)" to "array(array('id' => ID1),
* array('id' => ID2), array('id' => ID3))" in order to be compatible
* with modifyList.
*
* For each ID also check if we have any additional data. If so then
* add it to the delete data.
*/
$deletes = array();
foreach ($IDs as $ID) {
$delete = array('ID' => $ID);
// Add additional data if available
if (!empty($data[$ID])) {
foreach ($data[$ID] as $key => $value) {
$delete[$key] = $value;
}
}
$deletes[] = $delete;
}
// Return a XML as nice clean Array
return $this->modifyList($list_name, $deletes, 'Delete');
} | php | public function deleteMultiple ($list_name, array $IDs, array $data = array()) {
/*
* change input "array(ID1, ID2, ID3)" to "array(array('id' => ID1),
* array('id' => ID2), array('id' => ID3))" in order to be compatible
* with modifyList.
*
* For each ID also check if we have any additional data. If so then
* add it to the delete data.
*/
$deletes = array();
foreach ($IDs as $ID) {
$delete = array('ID' => $ID);
// Add additional data if available
if (!empty($data[$ID])) {
foreach ($data[$ID] as $key => $value) {
$delete[$key] = $value;
}
}
$deletes[] = $delete;
}
// Return a XML as nice clean Array
return $this->modifyList($list_name, $deletes, 'Delete');
} | [
"public",
"function",
"deleteMultiple",
"(",
"$",
"list_name",
",",
"array",
"$",
"IDs",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"/*\n\t\t * change input \"array(ID1, ID2, ID3)\" to \"array(array('id' => ID1),\n\t\t * array('id' => ID2), array('id' => ID3... | DeleteMultiple
Delete existing multiple list items.
@param String $list_name Name of list
@param array $IDs IDs of items to delete
@param array $data An array of arrays of additional required key/value pairs for each item to delete e.g. FileRef => URL to file.
@return Array | [
"DeleteMultiple",
"Delete",
"existing",
"multiple",
"list",
"items",
"."
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L584-L607 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.addAttachment | public function addAttachment ($list_name, $list_item_id, $file_name) {
// base64 encode file
$attachment = base64_encode(file_get_contents($file_name));
// Wrap in CAML
$CAML = '
<AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<listItemID>' . $list_item_id . '</listItemID>
<fileName>' . $file_name . '</fileName>
<attachment>' . $attachment . '</attachment>
</AddAttachment>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
// Attempt to run operation
try {
$this->soapClient->AddAttachment($xmlvar);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return true on success
return true;
} | php | public function addAttachment ($list_name, $list_item_id, $file_name) {
// base64 encode file
$attachment = base64_encode(file_get_contents($file_name));
// Wrap in CAML
$CAML = '
<AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<listItemID>' . $list_item_id . '</listItemID>
<fileName>' . $file_name . '</fileName>
<attachment>' . $attachment . '</attachment>
</AddAttachment>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
// Attempt to run operation
try {
$this->soapClient->AddAttachment($xmlvar);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return true on success
return true;
} | [
"public",
"function",
"addAttachment",
"(",
"$",
"list_name",
",",
"$",
"list_item_id",
",",
"$",
"file_name",
")",
"{",
"// base64 encode file",
"$",
"attachment",
"=",
"base64_encode",
"(",
"file_get_contents",
"(",
"$",
"file_name",
")",
")",
";",
"// Wrap in... | addAttachment
Add an attachment to a SharePoint List
@param $list_name Name of list
@param $list_item_id ID of record to attach attachment to
@param $file_name path of file to attach
@return Array | [
"addAttachment",
"Add",
"an",
"attachment",
"to",
"a",
"SharePoint",
"List"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L618-L642 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.deleteAttachment | public function deleteAttachment ($list_name, $list_item_id, $url) {
// Wrap in CAML
$CAML = '
<DeleteAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<listItemID>' . $list_item_id . '</listItemID>
<url>' . $url . '</url>
</DeleteAttachment>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
// Attempt to run operation
try {
$this->soapClient->DeleteAttachment($xmlvar);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return true on success
return true;
} | php | public function deleteAttachment ($list_name, $list_item_id, $url) {
// Wrap in CAML
$CAML = '
<DeleteAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<listItemID>' . $list_item_id . '</listItemID>
<url>' . $url . '</url>
</DeleteAttachment>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
// Attempt to run operation
try {
$this->soapClient->DeleteAttachment($xmlvar);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return true on success
return true;
} | [
"public",
"function",
"deleteAttachment",
"(",
"$",
"list_name",
",",
"$",
"list_item_id",
",",
"$",
"url",
")",
"{",
"// Wrap in CAML",
"$",
"CAML",
"=",
"'\n\t\t<DeleteAttachment xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">\n\t\t\t<listName>'",
".",
"$",
"list... | deleteAttachment
Remove an attachment from a SharePoint list item
@param $list_name Name of list
@param $list_item_id ID of record item is attached to
@param $url | [
"deleteAttachment",
"Remove",
"an",
"attachment",
"from",
"a",
"SharePoint",
"list",
"item"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L652-L672 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.getAttachments | public function getAttachments ($list_name, $list_item_id) {
// Wrap in CAML
$CAML = '
<GetAttachmentCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<listItemID>' . $list_item_id . '</listItemID>
</GetAttachmentCollection>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
// Attempt to run operation
try {
$rawXml = $this->soapClient->GetAttachmentCollection($xmlvar)->GetAttachmentCollectionResult->any;
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Load XML in to DOM document and grab all list items.
$nodes = $this->getArrayFromElementsByTagName($rawXml, 'Attachment');
$attachments = array();
// Format data in to array or object
foreach ($nodes as $counter => $node) {
$attachments[] = $node->textContent;
}
// Return Array of attachment URLs
return $attachments;
} | php | public function getAttachments ($list_name, $list_item_id) {
// Wrap in CAML
$CAML = '
<GetAttachmentCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<listItemID>' . $list_item_id . '</listItemID>
</GetAttachmentCollection>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
// Attempt to run operation
try {
$rawXml = $this->soapClient->GetAttachmentCollection($xmlvar)->GetAttachmentCollectionResult->any;
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Load XML in to DOM document and grab all list items.
$nodes = $this->getArrayFromElementsByTagName($rawXml, 'Attachment');
$attachments = array();
// Format data in to array or object
foreach ($nodes as $counter => $node) {
$attachments[] = $node->textContent;
}
// Return Array of attachment URLs
return $attachments;
} | [
"public",
"function",
"getAttachments",
"(",
"$",
"list_name",
",",
"$",
"list_item_id",
")",
"{",
"// Wrap in CAML",
"$",
"CAML",
"=",
"'\n\t\t<GetAttachmentCollection xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">\n\t\t\t<listName>'",
".",
"$",
"list_name",
".",
"... | getAttachment
Return an attachment from a SharePoint list item
@param $list_name Name of list
@param $list_item_id ID of record item is attached to
@return Array of attachment urls | [
"getAttachment",
"Return",
"an",
"attachment",
"from",
"a",
"SharePoint",
"list",
"item"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L682-L711 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.getArrayFromElementsByTagName | private function getArrayFromElementsByTagName ($rawXml, $tag, $namespace = NULL) {
// Get DOM instance and load XML
$dom = new \DOMDocument();
$dom->loadXML($rawXml, (LIBXML_VERSION >= 20900) ? LIBXML_PARSEHUGE : null);
// Is namespace set?
if (!is_null($namespace)) {
// Use it
$nodes = $dom->getElementsByTagNameNS($tag, $namespace);
} else {
// Get nodes
$nodes = $dom->getElementsByTagName($tag);
}
// Return nodes list
return $nodes;
} | php | private function getArrayFromElementsByTagName ($rawXml, $tag, $namespace = NULL) {
// Get DOM instance and load XML
$dom = new \DOMDocument();
$dom->loadXML($rawXml, (LIBXML_VERSION >= 20900) ? LIBXML_PARSEHUGE : null);
// Is namespace set?
if (!is_null($namespace)) {
// Use it
$nodes = $dom->getElementsByTagNameNS($tag, $namespace);
} else {
// Get nodes
$nodes = $dom->getElementsByTagName($tag);
}
// Return nodes list
return $nodes;
} | [
"private",
"function",
"getArrayFromElementsByTagName",
"(",
"$",
"rawXml",
",",
"$",
"tag",
",",
"$",
"namespace",
"=",
"NULL",
")",
"{",
"// Get DOM instance and load XML",
"$",
"dom",
"=",
"new",
"\\",
"DOMDocument",
"(",
")",
";",
"$",
"dom",
"->",
"load... | "Getter" for an array of nodes from given "raw XML" and tag name
@param string $rawXml "Raw XML" data
@param string $tag Name of tag
@param string $namespace Optional namespace
@return array $nodes An array of XML nodes | [
"Getter",
"for",
"an",
"array",
"of",
"nodes",
"from",
"given",
"raw",
"XML",
"and",
"tag",
"name"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L772-L789 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.whereXML | private function whereXML (array $q) {
$queryString = '';
$counter = 0;
foreach ($q as $col => $value) {
$counter++;
$queryString .= '<Eq><FieldRef Name="' . $col . '" /><Value Type="Text">' . htmlspecialchars($value) . '</Value></Eq>';
// Add additional "and"s if there are multiple query levels needed.
if ($counter >= 2) {
$queryString = '<And>' . $queryString . '</And>';
}
}
return '<Where>' . $queryString . '</Where>';
} | php | private function whereXML (array $q) {
$queryString = '';
$counter = 0;
foreach ($q as $col => $value) {
$counter++;
$queryString .= '<Eq><FieldRef Name="' . $col . '" /><Value Type="Text">' . htmlspecialchars($value) . '</Value></Eq>';
// Add additional "and"s if there are multiple query levels needed.
if ($counter >= 2) {
$queryString = '<And>' . $queryString . '</And>';
}
}
return '<Where>' . $queryString . '</Where>';
} | [
"private",
"function",
"whereXML",
"(",
"array",
"$",
"q",
")",
"{",
"$",
"queryString",
"=",
"''",
";",
"$",
"counter",
"=",
"0",
";",
"foreach",
"(",
"$",
"q",
"as",
"$",
"col",
"=>",
"$",
"value",
")",
"{",
"$",
"counter",
"++",
";",
"$",
"q... | Query XML
Generates XML for WHERE Query
@param Array $q array('<col>' => '<value_to_match_on>')
@return XML DATA | [
"Query",
"XML",
"Generates",
"XML",
"for",
"WHERE",
"Query"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L843-L858 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.sortXML | private function sortXML (array $sort) {
// On no count, no need to sort
if (count($sort) == 0) {
return '';
}
$queryString = '';
foreach ($sort as $col => $value) {
$queryString .= '<FieldRef Name="' . $col . '" Ascending="' . $this->getSortFromValue($value) . '" />';
}
return '<OrderBy>' . $queryString . '</OrderBy>';
} | php | private function sortXML (array $sort) {
// On no count, no need to sort
if (count($sort) == 0) {
return '';
}
$queryString = '';
foreach ($sort as $col => $value) {
$queryString .= '<FieldRef Name="' . $col . '" Ascending="' . $this->getSortFromValue($value) . '" />';
}
return '<OrderBy>' . $queryString . '</OrderBy>';
} | [
"private",
"function",
"sortXML",
"(",
"array",
"$",
"sort",
")",
"{",
"// On no count, no need to sort",
"if",
"(",
"count",
"(",
"$",
"sort",
")",
"==",
"0",
")",
"{",
"return",
"''",
";",
"}",
"$",
"queryString",
"=",
"''",
";",
"foreach",
"(",
"$",... | Sort XML
Generates XML for sort
@param Array $sort array('<col>' => 'asc | desc')
@return XML DATA | [
"Sort",
"XML",
"Generates",
"XML",
"for",
"sort"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L890-L901 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.modifyList | public function modifyList ($list_name, array $items, $method, $folderPath = null) {
// Get batch XML
$commands = $this->prepBatch($items, $method);
$rootFolderAttr = '';
if($folderPath != null && $folderPath != '/') {
$sitePath = substr($this->spWsdl, 0, strpos($this->spWsdl, '_vti_bin'));
$rootFolderAttr = ' RootFolder="'.$sitePath.$list_name.'/'.$folderPath.'"';
}
// Wrap in CAML
$CAML = '
<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<updates>
<Batch ListVersion="1" OnError="Continue"'.$rootFolderAttr.'>
' . $commands . '
</Batch>
</updates>
</UpdateListItems>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
$result = NULL;
// Attempt to run operation
try {
$result = $this->xmlHandler($this->soapClient->UpdateListItems($xmlvar)->UpdateListItemsResult->any);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return a XML as nice clean Array
return $result;
} | php | public function modifyList ($list_name, array $items, $method, $folderPath = null) {
// Get batch XML
$commands = $this->prepBatch($items, $method);
$rootFolderAttr = '';
if($folderPath != null && $folderPath != '/') {
$sitePath = substr($this->spWsdl, 0, strpos($this->spWsdl, '_vti_bin'));
$rootFolderAttr = ' RootFolder="'.$sitePath.$list_name.'/'.$folderPath.'"';
}
// Wrap in CAML
$CAML = '
<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>' . $list_name . '</listName>
<updates>
<Batch ListVersion="1" OnError="Continue"'.$rootFolderAttr.'>
' . $commands . '
</Batch>
</updates>
</UpdateListItems>';
$xmlvar = new \SoapVar($CAML, XSD_ANYXML);
$result = NULL;
// Attempt to run operation
try {
$result = $this->xmlHandler($this->soapClient->UpdateListItems($xmlvar)->UpdateListItemsResult->any);
} catch (\SoapFault $fault) {
$this->onError($fault);
}
// Return a XML as nice clean Array
return $result;
} | [
"public",
"function",
"modifyList",
"(",
"$",
"list_name",
",",
"array",
"$",
"items",
",",
"$",
"method",
",",
"$",
"folderPath",
"=",
"null",
")",
"{",
"// Get batch XML",
"$",
"commands",
"=",
"$",
"this",
"->",
"prepBatch",
"(",
"$",
"items",
",",
... | modifyList
Perform an action on a sharePoint list to either update or add content to it.
This method will use prepBatch to generate the batch xml, then call the SharePoint SOAP API with this data
to apply the changes.
@param $list_name SharePoint List to update
@param $items Array of new items or item changesets.
@param $method New/Update/Delete
@return Array|Object | [
"modifyList",
"Perform",
"an",
"action",
"on",
"a",
"sharePoint",
"list",
"to",
"either",
"update",
"or",
"add",
"content",
"to",
"it",
".",
"This",
"method",
"will",
"use",
"prepBatch",
"to",
"generate",
"the",
"batch",
"xml",
"then",
"call",
"the",
"Shar... | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L931-L964 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.prepBatch | public function prepBatch (array $items, $method) {
// Check if method is supported
assert(in_array($method, array('New', 'Update', 'Delete')));
// Get var's needed
$batch = '';
$counter = 1;
// Foreach item to be converted in to a SharePoint Soap Command
foreach ($items as $data) {
// Wrap item in command for given method
$batch .= '<Method Cmd="' . $method . '" ID="' . $counter . '">';
// Add required attributes
foreach ($data as $itm => $val) {
// Add entry
$batch .= '<Field Name="' . $itm . '">' . htmlspecialchars($val) . '</Field>' . PHP_EOL;
}
$batch .= '</Method>';
// Inc counter
$counter++;
}
// Return XML data.
return $batch;
} | php | public function prepBatch (array $items, $method) {
// Check if method is supported
assert(in_array($method, array('New', 'Update', 'Delete')));
// Get var's needed
$batch = '';
$counter = 1;
// Foreach item to be converted in to a SharePoint Soap Command
foreach ($items as $data) {
// Wrap item in command for given method
$batch .= '<Method Cmd="' . $method . '" ID="' . $counter . '">';
// Add required attributes
foreach ($data as $itm => $val) {
// Add entry
$batch .= '<Field Name="' . $itm . '">' . htmlspecialchars($val) . '</Field>' . PHP_EOL;
}
$batch .= '</Method>';
// Inc counter
$counter++;
}
// Return XML data.
return $batch;
} | [
"public",
"function",
"prepBatch",
"(",
"array",
"$",
"items",
",",
"$",
"method",
")",
"{",
"// Check if method is supported",
"assert",
"(",
"in_array",
"(",
"$",
"method",
",",
"array",
"(",
"'New'",
",",
"'Update'",
",",
"'Delete'",
")",
")",
")",
";",... | prepBatch
Convert an array of new items or change sets in to XML commands to be run on
the sharepoint SOAP API.
@param $items array of new items/change sets
@param $method New/Update/Delete
@return XML | [
"prepBatch",
"Convert",
"an",
"array",
"of",
"new",
"items",
"or",
"change",
"sets",
"in",
"to",
"XML",
"commands",
"to",
"be",
"run",
"on",
"the",
"sharepoint",
"SOAP",
"API",
"."
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L975-L1002 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.onError | private function onError (\SoapFault $fault) {
$more = '';
if (isset($fault->detail->errorstring)) {
$more = 'Detailed: ' . $fault->detail->errorstring;
}
throw new \Exception('Error (' . $fault->faultcode . ') ' . $fault->faultstring . ',more=' . $more);
} | php | private function onError (\SoapFault $fault) {
$more = '';
if (isset($fault->detail->errorstring)) {
$more = 'Detailed: ' . $fault->detail->errorstring;
}
throw new \Exception('Error (' . $fault->faultcode . ') ' . $fault->faultstring . ',more=' . $more);
} | [
"private",
"function",
"onError",
"(",
"\\",
"SoapFault",
"$",
"fault",
")",
"{",
"$",
"more",
"=",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"fault",
"->",
"detail",
"->",
"errorstring",
")",
")",
"{",
"$",
"more",
"=",
"'Detailed: '",
".",
"$",
"f... | onError
This is called when sharepoint throws an error and displays basic debug info.
@param $fault Error Information
@throws \Exception Puts data from $fault into an other exception | [
"onError",
"This",
"is",
"called",
"when",
"sharepoint",
"throws",
"an",
"error",
"and",
"displays",
"basic",
"debug",
"info",
"."
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L1011-L1017 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.getFieldVersions | public function getFieldVersions ($list, $id, $field) {
//Ready XML
$CAML = '
<GetVersionCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<strlistID>'.$list.'</strlistID>
<strlistItemID>'.$id.'</strlistItemID>
<strFieldName>'.$field.'</strFieldName>
</GetVersionCollection>
';
// Attempt to query SharePoint
try{
$rawxml = $this->soapClient->GetVersionCollection(new \SoapVar($CAML, XSD_ANYXML))->GetVersionCollectionResult->any;
}catch(\SoapFault $fault){
$this->onError($fault);
}
// Load XML in to DOM document and grab all Fields
$dom = new \DOMDocument();
$dom->loadXML($rawxml, (LIBXML_VERSION >= 20900) ? LIBXML_PARSEHUGE : null);
$nodes = $dom->getElementsByTagName("Version");
// Parse results
$results = array();
// Format data in to array or object
foreach ($nodes as $counter => $node) {
//Get Attributes
foreach ($node->attributes as $attribute => $value) {
$results[$counter][strtolower($attribute)] = $node->getAttribute($attribute);
}
//Make object if needed
if ($this->returnType === 1) settype($results[$counter], "object");
}
// Add error array if stuff goes wrong.
if (!isset($results)) $results = array('warning' => 'No data returned.');
return $results;
} | php | public function getFieldVersions ($list, $id, $field) {
//Ready XML
$CAML = '
<GetVersionCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<strlistID>'.$list.'</strlistID>
<strlistItemID>'.$id.'</strlistItemID>
<strFieldName>'.$field.'</strFieldName>
</GetVersionCollection>
';
// Attempt to query SharePoint
try{
$rawxml = $this->soapClient->GetVersionCollection(new \SoapVar($CAML, XSD_ANYXML))->GetVersionCollectionResult->any;
}catch(\SoapFault $fault){
$this->onError($fault);
}
// Load XML in to DOM document and grab all Fields
$dom = new \DOMDocument();
$dom->loadXML($rawxml, (LIBXML_VERSION >= 20900) ? LIBXML_PARSEHUGE : null);
$nodes = $dom->getElementsByTagName("Version");
// Parse results
$results = array();
// Format data in to array or object
foreach ($nodes as $counter => $node) {
//Get Attributes
foreach ($node->attributes as $attribute => $value) {
$results[$counter][strtolower($attribute)] = $node->getAttribute($attribute);
}
//Make object if needed
if ($this->returnType === 1) settype($results[$counter], "object");
}
// Add error array if stuff goes wrong.
if (!isset($results)) $results = array('warning' => 'No data returned.');
return $results;
} | [
"public",
"function",
"getFieldVersions",
"(",
"$",
"list",
",",
"$",
"id",
",",
"$",
"field",
")",
"{",
"//Ready XML",
"$",
"CAML",
"=",
"'\n\t <GetVersionCollection xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">\n\t <strlistID>'",
".",
"$",
"li... | getFieldVersions
Get previous versions of field contents
@see https://github.com/thybag/PHP-SharePoint-Lists-API/issues/6#issuecomment-13793688 by TimRainey
@param $list Name or GUID of list
@param $id ID of item to find versions for
@param $field name of column to get versions for
@return array | object | [
"getFieldVersions",
"Get",
"previous",
"versions",
"of",
"field",
"contents"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L1081-L1118 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/SharePointAPI.php | SharePointAPI.getVersions | public function getVersions ($list, $id, $field = null) {
return $this->getFieldVersions($list, $id, $field);
} | php | public function getVersions ($list, $id, $field = null) {
return $this->getFieldVersions($list, $id, $field);
} | [
"public",
"function",
"getVersions",
"(",
"$",
"list",
",",
"$",
"id",
",",
"$",
"field",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getFieldVersions",
"(",
"$",
"list",
",",
"$",
"id",
",",
"$",
"field",
")",
";",
"}"
] | getVersions
Get previous versions of a field
@param $list Name or GUID of list
@param $id ID of item to find versions for
@param $field optional name of column to get versions for
@return array | object | [
"getVersions",
"Get",
"previous",
"versions",
"of",
"a",
"field"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/SharePointAPI.php#L1130-L1132 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/ListService.php | ListService.read | public function read ($limit = 0, $query = NULL, $view = NULL, $sort = NULL, $options = NULL) {
return $this->api->read($this->list_name, $limit, $query, $view, $sort, $options);
} | php | public function read ($limit = 0, $query = NULL, $view = NULL, $sort = NULL, $options = NULL) {
return $this->api->read($this->list_name, $limit, $query, $view, $sort, $options);
} | [
"public",
"function",
"read",
"(",
"$",
"limit",
"=",
"0",
",",
"$",
"query",
"=",
"NULL",
",",
"$",
"view",
"=",
"NULL",
",",
"$",
"sort",
"=",
"NULL",
",",
"$",
"options",
"=",
"NULL",
")",
"{",
"return",
"$",
"this",
"->",
"api",
"->",
"read... | Read
Read items from List
@param int $limit
@param Array $query
@return Array | [
"Read",
"Read",
"items",
"from",
"List"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/ListService.php#L65-L67 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/QueryObjectService.php | QueryObjectService.sort | public function sort ($sort_on, $order = 'desc') {
$queryString = '<FieldRef Name="' .$sort_on . '" Ascending="' . $this->api->getSortFromValue($order) . '" />';
$this->sort_caml = '<OrderBy>' . $queryString . '</OrderBy>';
return $this;
} | php | public function sort ($sort_on, $order = 'desc') {
$queryString = '<FieldRef Name="' .$sort_on . '" Ascending="' . $this->api->getSortFromValue($order) . '" />';
$this->sort_caml = '<OrderBy>' . $queryString . '</OrderBy>';
return $this;
} | [
"public",
"function",
"sort",
"(",
"$",
"sort_on",
",",
"$",
"order",
"=",
"'desc'",
")",
"{",
"$",
"queryString",
"=",
"'<FieldRef Name=\"'",
".",
"$",
"sort_on",
".",
"'\" Ascending=\"'",
".",
"$",
"this",
"->",
"api",
"->",
"getSortFromValue",
"(",
"$",... | Sort
Specify order data should be returned in.
@param $sort_on column to sort on
@param $order Sort direction
@return Ref to self | [
"Sort",
"Specify",
"order",
"data",
"should",
"be",
"returned",
"in",
"."
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/QueryObjectService.php#L163-L168 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/QueryObjectService.php | QueryObjectService.all_fields | public function all_fields($exclude_hidden = true){
$fields = $this->api->readListMeta($this->list_name, $exclude_hidden);
foreach ($fields as $field) {
$this->fields[] = $field['name'];
}
return $this;
} | php | public function all_fields($exclude_hidden = true){
$fields = $this->api->readListMeta($this->list_name, $exclude_hidden);
foreach ($fields as $field) {
$this->fields[] = $field['name'];
}
return $this;
} | [
"public",
"function",
"all_fields",
"(",
"$",
"exclude_hidden",
"=",
"true",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"api",
"->",
"readListMeta",
"(",
"$",
"this",
"->",
"list_name",
",",
"$",
"exclude_hidden",
")",
";",
"foreach",
"(",
"$",
"... | all_fields
Attempt to include all fields row has within result
@param $exclude_hidden to to false to include hidden fields
@return Ref to self | [
"all_fields",
"Attempt",
"to",
"include",
"all",
"fields",
"row",
"has",
"within",
"result"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/QueryObjectService.php#L190-L196 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/QueryObjectService.php | QueryObjectService.get | public function get ($options = NULL) {
// String = view, array = specific fields
$view = (sizeof($this->fields) === 0) ? $this->view : $this->fields;
return $this->api->read($this->list_name, $this->limit, $this, $view, NULL, $this->options);
} | php | public function get ($options = NULL) {
// String = view, array = specific fields
$view = (sizeof($this->fields) === 0) ? $this->view : $this->fields;
return $this->api->read($this->list_name, $this->limit, $this, $view, NULL, $this->options);
} | [
"public",
"function",
"get",
"(",
"$",
"options",
"=",
"NULL",
")",
"{",
"// String = view, array = specific fields",
"$",
"view",
"=",
"(",
"sizeof",
"(",
"$",
"this",
"->",
"fields",
")",
"===",
"0",
")",
"?",
"$",
"this",
"->",
"view",
":",
"$",
"th... | get
Runs the specified query and returns a usable result.
@return Array: SharePoint List Data | [
"get",
"Runs",
"the",
"specified",
"query",
"and",
"returns",
"a",
"usable",
"result",
"."
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/QueryObjectService.php#L205-L211 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/QueryObjectService.php | QueryObjectService.addQueryLine | private function addQueryLine ($rel, $col, $test, $value) {
// Check tests are usable
if (!in_array($test, array('!=', '>=', '<=', '<', '>', '=', 'like'))) {
throw new \Exception('Unrecognized query parameter. Please use <,>,=,>=,<=, != or like');
}
// Make sure $rel is lower-case
$rel = strtolower($rel);
$test = str_replace(array('!=', '>=', '<=', '<', '>', '=', 'like'), array('Neq', 'Geq', 'Leq', 'Lt', 'Gt', 'Eq', 'Contains'), $test);
// Create caml
$caml = $this->where_caml;
$content = '<FieldRef Name="' . $col . '" /><Value Type="Text">' . htmlspecialchars($value) . '</Value>' . PHP_EOL;
$caml .= '<' . $test . '>' . $content . '</' . $test . '>';
// Attach relations
if ($rel == 'and') {
$this->where_caml = '<And>' . $caml . '</And>';
} elseif ($rel == 'or') {
$this->where_caml = '<Or>' . $caml . '</Or>';
} elseif ($rel == 'where') {
$this->where_caml = $caml;
}
// return self
return $this;
} | php | private function addQueryLine ($rel, $col, $test, $value) {
// Check tests are usable
if (!in_array($test, array('!=', '>=', '<=', '<', '>', '=', 'like'))) {
throw new \Exception('Unrecognized query parameter. Please use <,>,=,>=,<=, != or like');
}
// Make sure $rel is lower-case
$rel = strtolower($rel);
$test = str_replace(array('!=', '>=', '<=', '<', '>', '=', 'like'), array('Neq', 'Geq', 'Leq', 'Lt', 'Gt', 'Eq', 'Contains'), $test);
// Create caml
$caml = $this->where_caml;
$content = '<FieldRef Name="' . $col . '" /><Value Type="Text">' . htmlspecialchars($value) . '</Value>' . PHP_EOL;
$caml .= '<' . $test . '>' . $content . '</' . $test . '>';
// Attach relations
if ($rel == 'and') {
$this->where_caml = '<And>' . $caml . '</And>';
} elseif ($rel == 'or') {
$this->where_caml = '<Or>' . $caml . '</Or>';
} elseif ($rel == 'where') {
$this->where_caml = $caml;
}
// return self
return $this;
} | [
"private",
"function",
"addQueryLine",
"(",
"$",
"rel",
",",
"$",
"col",
",",
"$",
"test",
",",
"$",
"value",
")",
"{",
"// Check tests are usable",
"if",
"(",
"!",
"in_array",
"(",
"$",
"test",
",",
"array",
"(",
"'!='",
",",
"'>='",
",",
"'<='",
",... | addQueryLine
Generate CAML for where statements
@param $rel Relation AND/OR etc
@param $col column to test
@param $test comparison type (=,!+,<,>,like)
@param $value value to test with
@return Ref to self
@throws \Exception Thrown if $test is unrecognized | [
"addQueryLine",
"Generate",
"CAML",
"for",
"where",
"statements"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/QueryObjectService.php#L224-L251 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/QueryObjectService.php | QueryObjectService.getCAML | public function getCAML () {
// Start with empty string
$xml = '';
// Add where
if (!empty($this->where_caml)) {
$xml = '<Where>' . $this->where_caml . '</Where>';
}
// add sort
if (!empty($this->sort_caml)) {
$xml .= $this->sort_caml;
}
return $xml;
} | php | public function getCAML () {
// Start with empty string
$xml = '';
// Add where
if (!empty($this->where_caml)) {
$xml = '<Where>' . $this->where_caml . '</Where>';
}
// add sort
if (!empty($this->sort_caml)) {
$xml .= $this->sort_caml;
}
return $xml;
} | [
"public",
"function",
"getCAML",
"(",
")",
"{",
"// Start with empty string",
"$",
"xml",
"=",
"''",
";",
"// Add where",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"where_caml",
")",
")",
"{",
"$",
"xml",
"=",
"'<Where>'",
".",
"$",
"this",
"->"... | getCAML
Combine and return the raw CAML data for the query operation that has been specified.
@return CAML Code (XML) | [
"getCAML",
"Combine",
"and",
"return",
"the",
"raw",
"CAML",
"data",
"for",
"the",
"query",
"operation",
"that",
"has",
"been",
"specified",
"."
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/QueryObjectService.php#L258-L273 | train |
thybag/PHP-SharePoint-Lists-API | src/Thybag/Service/QueryObjectService.php | QueryObjectService.getOptionCAML | public function getOptionCAML () {
$xml = '';
// if fields are specified
if(sizeof($this->fields) > 0) {
$xml .= $this->api->viewFieldsXML($this->fields);
}
// If view, add to xml.
if($this->view !== NULL) $xml .= '<viewName>' . $this->view . '</viewName>';
return $xml;
} | php | public function getOptionCAML () {
$xml = '';
// if fields are specified
if(sizeof($this->fields) > 0) {
$xml .= $this->api->viewFieldsXML($this->fields);
}
// If view, add to xml.
if($this->view !== NULL) $xml .= '<viewName>' . $this->view . '</viewName>';
return $xml;
} | [
"public",
"function",
"getOptionCAML",
"(",
")",
"{",
"$",
"xml",
"=",
"''",
";",
"// if fields are specified",
"if",
"(",
"sizeof",
"(",
"$",
"this",
"->",
"fields",
")",
">",
"0",
")",
"{",
"$",
"xml",
".=",
"$",
"this",
"->",
"api",
"->",
"viewFie... | getOptionCAML
Combine and return the raw CAML data for the request options
@return CAML Code (XML) | [
"getOptionCAML",
"Combine",
"and",
"return",
"the",
"raw",
"CAML",
"data",
"for",
"the",
"request",
"options"
] | 56180751e246415fabcfaeb268d96b2aba6eb1f6 | https://github.com/thybag/PHP-SharePoint-Lists-API/blob/56180751e246415fabcfaeb268d96b2aba6eb1f6/src/Thybag/Service/QueryObjectService.php#L280-L293 | train |
spatie/laravel-paginateroute | src/SetPageMiddleware.php | SetPageMiddleware.handle | public function handle($request, Closure $next)
{
Paginator::currentPageResolver(function () {
return app('paginateroute')->currentPage();
});
return $next($request);
} | php | public function handle($request, Closure $next)
{
Paginator::currentPageResolver(function () {
return app('paginateroute')->currentPage();
});
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"Paginator",
"::",
"currentPageResolver",
"(",
"function",
"(",
")",
"{",
"return",
"app",
"(",
"'paginateroute'",
")",
"->",
"currentPage",
"(",
")",
";",
"}",
"... | Set the current page based on the page route parameter before the route's action is executed.
@return \Illuminate\Http\Request | [
"Set",
"the",
"current",
"page",
"based",
"on",
"the",
"page",
"route",
"parameter",
"before",
"the",
"route",
"s",
"action",
"is",
"executed",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/SetPageMiddleware.php#L16-L23 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.currentPage | public function currentPage()
{
$currentRoute = $this->router->getCurrentRoute();
if (! $currentRoute) {
return 1;
}
$query = $currentRoute->parameter('pageQuery');
return (int) str_replace($this->pageKeyword.'/', '', $query) ?: 1;
} | php | public function currentPage()
{
$currentRoute = $this->router->getCurrentRoute();
if (! $currentRoute) {
return 1;
}
$query = $currentRoute->parameter('pageQuery');
return (int) str_replace($this->pageKeyword.'/', '', $query) ?: 1;
} | [
"public",
"function",
"currentPage",
"(",
")",
"{",
"$",
"currentRoute",
"=",
"$",
"this",
"->",
"router",
"->",
"getCurrentRoute",
"(",
")",
";",
"if",
"(",
"!",
"$",
"currentRoute",
")",
"{",
"return",
"1",
";",
"}",
"$",
"query",
"=",
"$",
"curren... | Return the current page.
@return int | [
"Return",
"the",
"current",
"page",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L57-L68 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.nextPageUrl | public function nextPageUrl(Paginator $paginator)
{
$nextPage = $this->nextPage($paginator);
if ($nextPage === null) {
return;
}
return $this->pageUrl($nextPage);
} | php | public function nextPageUrl(Paginator $paginator)
{
$nextPage = $this->nextPage($paginator);
if ($nextPage === null) {
return;
}
return $this->pageUrl($nextPage);
} | [
"public",
"function",
"nextPageUrl",
"(",
"Paginator",
"$",
"paginator",
")",
"{",
"$",
"nextPage",
"=",
"$",
"this",
"->",
"nextPage",
"(",
"$",
"paginator",
")",
";",
"if",
"(",
"$",
"nextPage",
"===",
"null",
")",
"{",
"return",
";",
"}",
"return",
... | Get the next page URL.
@param \Illuminate\Contracts\Pagination\Paginator $paginator
@return string|null | [
"Get",
"the",
"next",
"page",
"URL",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L117-L126 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.previousPageUrl | public function previousPageUrl($full = false)
{
$previousPage = $this->previousPage();
if ($previousPage === null) {
return;
}
return $this->pageUrl($previousPage, $full);
} | php | public function previousPageUrl($full = false)
{
$previousPage = $this->previousPage();
if ($previousPage === null) {
return;
}
return $this->pageUrl($previousPage, $full);
} | [
"public",
"function",
"previousPageUrl",
"(",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"previousPage",
"=",
"$",
"this",
"->",
"previousPage",
"(",
")",
";",
"if",
"(",
"$",
"previousPage",
"===",
"null",
")",
"{",
"return",
";",
"}",
"return",
"$",
... | Get the previous page URL.
@param bool $full Return the full version of the URL in for the first page
Ex. /users/page/1 instead of /users
@return string|null | [
"Get",
"the",
"previous",
"page",
"URL",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L160-L169 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.allUrls | public function allUrls(LengthAwarePaginator $paginator, $full = false)
{
if (! $paginator->hasPages()) {
return [];
}
$urls = [];
$left = $this->getLeftPoint($paginator);
$right = $this->getRightPoint($paginator);
for ($page = $left; $page <= $right; $page++) {
$urls[$page] = $this->pageUrl($page, $full);
}
return $urls;
} | php | public function allUrls(LengthAwarePaginator $paginator, $full = false)
{
if (! $paginator->hasPages()) {
return [];
}
$urls = [];
$left = $this->getLeftPoint($paginator);
$right = $this->getRightPoint($paginator);
for ($page = $left; $page <= $right; $page++) {
$urls[$page] = $this->pageUrl($page, $full);
}
return $urls;
} | [
"public",
"function",
"allUrls",
"(",
"LengthAwarePaginator",
"$",
"paginator",
",",
"$",
"full",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"paginator",
"->",
"hasPages",
"(",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"urls",
"=",
"[",
"... | Get all urls in an array.
@param \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginator
@param bool $full Return the full version of the URL in for the first page
Ex. /users/page/1 instead of /users
@return array | [
"Get",
"all",
"urls",
"in",
"an",
"array",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L180-L194 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.getLeftPoint | public function getLeftPoint(LengthAwarePaginator $paginator)
{
$side = $paginator->onEachSide;
$current = $paginator->currentPage();
$last = $paginator->lastPage();
if (! empty($side)) {
$x = $current + $side;
$offset = $x >= $last ? $x - $last : 0;
$left = $current - $side - $offset;
}
return ! isset($left) || $left < 1 ? 1 : $left;
} | php | public function getLeftPoint(LengthAwarePaginator $paginator)
{
$side = $paginator->onEachSide;
$current = $paginator->currentPage();
$last = $paginator->lastPage();
if (! empty($side)) {
$x = $current + $side;
$offset = $x >= $last ? $x - $last : 0;
$left = $current - $side - $offset;
}
return ! isset($left) || $left < 1 ? 1 : $left;
} | [
"public",
"function",
"getLeftPoint",
"(",
"LengthAwarePaginator",
"$",
"paginator",
")",
"{",
"$",
"side",
"=",
"$",
"paginator",
"->",
"onEachSide",
";",
"$",
"current",
"=",
"$",
"paginator",
"->",
"currentPage",
"(",
")",
";",
"$",
"last",
"=",
"$",
... | Get the left most point in the pagination element.
@param LengthAwarePaginator $paginator
@return int | [
"Get",
"the",
"left",
"most",
"point",
"in",
"the",
"pagination",
"element",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L202-L215 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.getRightPoint | public function getRightPoint(LengthAwarePaginator $paginator)
{
$side = $paginator->onEachSide;
$current = $paginator->currentPage();
$last = $paginator->lastPage();
if (! empty($side)) {
$offset = $current <= $side ? $side - $current + 1 : 0;
$right = $current + $side + $offset;
}
return ! isset($right) || $right > $last ? $last : $right;
} | php | public function getRightPoint(LengthAwarePaginator $paginator)
{
$side = $paginator->onEachSide;
$current = $paginator->currentPage();
$last = $paginator->lastPage();
if (! empty($side)) {
$offset = $current <= $side ? $side - $current + 1 : 0;
$right = $current + $side + $offset;
}
return ! isset($right) || $right > $last ? $last : $right;
} | [
"public",
"function",
"getRightPoint",
"(",
"LengthAwarePaginator",
"$",
"paginator",
")",
"{",
"$",
"side",
"=",
"$",
"paginator",
"->",
"onEachSide",
";",
"$",
"current",
"=",
"$",
"paginator",
"->",
"currentPage",
"(",
")",
";",
"$",
"last",
"=",
"$",
... | Get the right or last point of the pagination element.
@param LengthAwarePaginator $paginator
@return int | [
"Get",
"the",
"right",
"or",
"last",
"point",
"of",
"the",
"pagination",
"element",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L223-L235 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.renderPageList | public function renderPageList(LengthAwarePaginator $paginator, $full = false, $class = null, $additionalLinks = false)
{
$urls = $this->allUrls($paginator, $full);
if ($class) {
$class = " class=\"$class\"";
}
$listItems = "<ul{$class}>";
if ($this->hasPreviousPage() && $additionalLinks) {
$listItems .= "<li><a href=\"{$this->previousPageUrl()}\">«</a></li>";
}
foreach ($urls as $i => $url) {
$pageNum = $i;
$css = '';
$link = "<a href=\"{$url}\">{$pageNum}</a>";
if ($pageNum == $this->currentPage()) {
$css = ' class="active"';
$link = $pageNum;
}
$listItems .= "<li{$css}>$link</li>";
}
if ($this->hasNextPage($paginator) && $additionalLinks) {
$listItems .= "<li><a href=\"{$this->nextPageUrl($paginator)}\">»</a></li>";
}
$listItems .= '</ul>';
return $listItems;
} | php | public function renderPageList(LengthAwarePaginator $paginator, $full = false, $class = null, $additionalLinks = false)
{
$urls = $this->allUrls($paginator, $full);
if ($class) {
$class = " class=\"$class\"";
}
$listItems = "<ul{$class}>";
if ($this->hasPreviousPage() && $additionalLinks) {
$listItems .= "<li><a href=\"{$this->previousPageUrl()}\">«</a></li>";
}
foreach ($urls as $i => $url) {
$pageNum = $i;
$css = '';
$link = "<a href=\"{$url}\">{$pageNum}</a>";
if ($pageNum == $this->currentPage()) {
$css = ' class="active"';
$link = $pageNum;
}
$listItems .= "<li{$css}>$link</li>";
}
if ($this->hasNextPage($paginator) && $additionalLinks) {
$listItems .= "<li><a href=\"{$this->nextPageUrl($paginator)}\">»</a></li>";
}
$listItems .= '</ul>';
return $listItems;
} | [
"public",
"function",
"renderPageList",
"(",
"LengthAwarePaginator",
"$",
"paginator",
",",
"$",
"full",
"=",
"false",
",",
"$",
"class",
"=",
"null",
",",
"$",
"additionalLinks",
"=",
"false",
")",
"{",
"$",
"urls",
"=",
"$",
"this",
"->",
"allUrls",
"(... | Render a plain html list with previous, next and all urls. The current page gets a current class on the list item.
@param \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginator
@param bool $full Return the full version of the URL in for the first page
Ex. /users/page/1 instead of /users
@param string $class Include class on pagination list
Ex. <ul class="pagination">
@param bool $additionalLinks Include prev and next links on pagination list
@return string | [
"Render",
"a",
"plain",
"html",
"list",
"with",
"previous",
"next",
"and",
"all",
"urls",
".",
"The",
"current",
"page",
"gets",
"a",
"current",
"class",
"on",
"the",
"list",
"item",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L249-L283 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.renderRelLinks | public function renderRelLinks(LengthAwarePaginator $paginator, $full = false)
{
$urls = $this->allUrls($paginator, $full);
$linkItems = '';
foreach ($urls as $i => $url) {
$pageNum = $i + 1;
switch ($pageNum - $this->currentPage()) {
case -1:
$linkItems .= "<link rel=\"prev\" href=\"{$url}\" />";
break;
case 1:
$linkItems .= "<link rel=\"next\" href=\"{$url}\" />";
break;
}
}
return $linkItems;
} | php | public function renderRelLinks(LengthAwarePaginator $paginator, $full = false)
{
$urls = $this->allUrls($paginator, $full);
$linkItems = '';
foreach ($urls as $i => $url) {
$pageNum = $i + 1;
switch ($pageNum - $this->currentPage()) {
case -1:
$linkItems .= "<link rel=\"prev\" href=\"{$url}\" />";
break;
case 1:
$linkItems .= "<link rel=\"next\" href=\"{$url}\" />";
break;
}
}
return $linkItems;
} | [
"public",
"function",
"renderRelLinks",
"(",
"LengthAwarePaginator",
"$",
"paginator",
",",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"urls",
"=",
"$",
"this",
"->",
"allUrls",
"(",
"$",
"paginator",
",",
"$",
"full",
")",
";",
"$",
"linkItems",
"=",
"... | Render html link tags for SEO indication of previous and next page.
@param \Illuminate\Contracts\Pagination\LengthAwarePaginator $paginator
@param bool $full Return the full version of the URL in for the first page
Ex. /users/page/1 instead of /users
@return string | [
"Render",
"html",
"link",
"tags",
"for",
"SEO",
"indication",
"of",
"previous",
"and",
"next",
"page",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L294-L314 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.pageUrl | public function pageUrl($page, $full = false)
{
$currentPageUrl = $this->router->getCurrentRoute()->uri();
$url = $this->addPageQuery(str_replace('{pageQuery?}', '', $currentPageUrl), $page, $full);
foreach ((new RouteParameterBinder($this->router->getCurrentRoute()))->parameters(app('request')) as $parameterName => $parameterValue) {
$url = str_replace(['{'.$parameterName.'}', '{'.$parameterName.'?}'], $parameterValue, $url);
}
$query = Request::getQueryString();
$query = $query
? '?'.$query
: '';
return $this->urlGenerator->to($url).$query;
} | php | public function pageUrl($page, $full = false)
{
$currentPageUrl = $this->router->getCurrentRoute()->uri();
$url = $this->addPageQuery(str_replace('{pageQuery?}', '', $currentPageUrl), $page, $full);
foreach ((new RouteParameterBinder($this->router->getCurrentRoute()))->parameters(app('request')) as $parameterName => $parameterValue) {
$url = str_replace(['{'.$parameterName.'}', '{'.$parameterName.'?}'], $parameterValue, $url);
}
$query = Request::getQueryString();
$query = $query
? '?'.$query
: '';
return $this->urlGenerator->to($url).$query;
} | [
"public",
"function",
"pageUrl",
"(",
"$",
"page",
",",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"currentPageUrl",
"=",
"$",
"this",
"->",
"router",
"->",
"getCurrentRoute",
"(",
")",
"->",
"uri",
"(",
")",
";",
"$",
"url",
"=",
"$",
"this",
"->",... | Generate a page URL, based on the request's current URL.
@param int $page
@param bool $full Return the full version of the URL in for the first page
Ex. /users/page/1 instead of /users
@return string | [
"Generate",
"a",
"page",
"URL",
"based",
"on",
"the",
"request",
"s",
"current",
"URL",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L339-L356 | train |
spatie/laravel-paginateroute | src/PaginateRoute.php | PaginateRoute.addPageQuery | public function addPageQuery($url, $page, $full = false)
{
// If the first page's URL is requested and $full is set to false, there's nothing to be added.
if ($page === 1 && ! $full) {
return $url;
}
return trim($url, '/')."/{$this->pageKeyword}/{$page}";
} | php | public function addPageQuery($url, $page, $full = false)
{
// If the first page's URL is requested and $full is set to false, there's nothing to be added.
if ($page === 1 && ! $full) {
return $url;
}
return trim($url, '/')."/{$this->pageKeyword}/{$page}";
} | [
"public",
"function",
"addPageQuery",
"(",
"$",
"url",
",",
"$",
"page",
",",
"$",
"full",
"=",
"false",
")",
"{",
"// If the first page's URL is requested and $full is set to false, there's nothing to be added.",
"if",
"(",
"$",
"page",
"===",
"1",
"&&",
"!",
"$",
... | Append the page query to a URL.
@param string $url
@param int $page
@param bool $full Return the full version of the URL in for the first page
Ex. /users/page/1 instead of /users
@return string | [
"Append",
"the",
"page",
"query",
"to",
"a",
"URL",
"."
] | 1e12dd26337bd4dffd3ca1b2b82f22068d999752 | https://github.com/spatie/laravel-paginateroute/blob/1e12dd26337bd4dffd3ca1b2b82f22068d999752/src/PaginateRoute.php#L368-L376 | train |
oscarotero/form-manager | src/Node.php | Node.setVariable | public function setVariable(string $name, $value = null): self
{
$this->variables[$name] = $value;
return $this;
} | php | public function setVariable(string $name, $value = null): self
{
$this->variables[$name] = $value;
return $this;
} | [
"public",
"function",
"setVariable",
"(",
"string",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
":",
"self",
"{",
"$",
"this",
"->",
"variables",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] | Set an arbitrary variable. | [
"Set",
"an",
"arbitrary",
"variable",
"."
] | 3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a | https://github.com/oscarotero/form-manager/blob/3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a/src/Node.php#L149-L154 | train |
oscarotero/form-manager | src/Node.php | Node.getOpeningTag | public function getOpeningTag(): string
{
$attributes = [];
foreach ($this->attributes as $name => $value) {
$attributes[] = self::getHtmlAttribute($name, $value);
}
$attributes = implode(' ', array_filter($attributes));
return sprintf('<%s%s>', $this->nodeName, $attributes === '' ? '' : " {$attributes}");
} | php | public function getOpeningTag(): string
{
$attributes = [];
foreach ($this->attributes as $name => $value) {
$attributes[] = self::getHtmlAttribute($name, $value);
}
$attributes = implode(' ', array_filter($attributes));
return sprintf('<%s%s>', $this->nodeName, $attributes === '' ? '' : " {$attributes}");
} | [
"public",
"function",
"getOpeningTag",
"(",
")",
":",
"string",
"{",
"$",
"attributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"attributes",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"attributes",
"[",
"]",
"=",
"self",
... | Returns the html code of the opening tag. | [
"Returns",
"the",
"html",
"code",
"of",
"the",
"opening",
"tag",
"."
] | 3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a | https://github.com/oscarotero/form-manager/blob/3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a/src/Node.php#L167-L178 | train |
oscarotero/form-manager | src/Node.php | Node.getClosingTag | public function getClosingTag(): ?string
{
if (!in_array($this->nodeName, self::SELF_CLOSING_TAGS)) {
return sprintf('</%s>', $this->nodeName);
}
return null;
} | php | public function getClosingTag(): ?string
{
if (!in_array($this->nodeName, self::SELF_CLOSING_TAGS)) {
return sprintf('</%s>', $this->nodeName);
}
return null;
} | [
"public",
"function",
"getClosingTag",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"this",
"->",
"nodeName",
",",
"self",
"::",
"SELF_CLOSING_TAGS",
")",
")",
"{",
"return",
"sprintf",
"(",
"'</%s>'",
",",
"$",
"this",
"->"... | Returns the html code of the closing tag. | [
"Returns",
"the",
"html",
"code",
"of",
"the",
"closing",
"tag",
"."
] | 3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a | https://github.com/oscarotero/form-manager/blob/3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a/src/Node.php#L183-L190 | train |
oscarotero/form-manager | src/Node.php | Node.getHtmlAttribute | private static function getHtmlAttribute(string $name, $value): string
{
if (!self::isset($value)) {
return '';
}
if ($value === true) {
return $name;
}
if (is_array($value)) {
$value = self::convertAttributeArrayValue($name, $value);
}
return sprintf('%s="%s"', $name, static::escape((string) $value));
} | php | private static function getHtmlAttribute(string $name, $value): string
{
if (!self::isset($value)) {
return '';
}
if ($value === true) {
return $name;
}
if (is_array($value)) {
$value = self::convertAttributeArrayValue($name, $value);
}
return sprintf('%s="%s"', $name, static::escape((string) $value));
} | [
"private",
"static",
"function",
"getHtmlAttribute",
"(",
"string",
"$",
"name",
",",
"$",
"value",
")",
":",
"string",
"{",
"if",
"(",
"!",
"self",
"::",
"isset",
"(",
"$",
"value",
")",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"$",
"value",... | Creates a html attribute. | [
"Creates",
"a",
"html",
"attribute",
"."
] | 3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a | https://github.com/oscarotero/form-manager/blob/3c5ed57d1469ca703ae8fb58e09f5ce276cf5e0a/src/Node.php#L203-L218 | train |
ostark/upper | src/drivers/AbstractPurger.php | AbstractPurger.getTaggedUrls | public function getTaggedUrls($tag)
{
// Use fulltext for mysql or array field for pgsql
$sql = \Craft::$app->getDb()->getIsMysql()
? "SELECT uid, url FROM %s WHERE MATCH(tags) AGAINST (%s IN BOOLEAN MODE)"
: "SELECT uid, url FROM %s WHERE tags @> (ARRAY[%s]::varchar[])";
// Replace table name and tag
$sql = sprintf(
$sql,
\Craft::$app->getDb()->quoteTableName(Plugin::CACHE_TABLE),
\Craft::$app->getDb()->quoteValue($tag)
);
// Execute the sql
$results = \Craft::$app->getDb()
->createCommand($sql)
->queryAll();
if (count($results) === 0) {
return [];
}
return ArrayHelper::map($results, 'uid', 'url');
} | php | public function getTaggedUrls($tag)
{
// Use fulltext for mysql or array field for pgsql
$sql = \Craft::$app->getDb()->getIsMysql()
? "SELECT uid, url FROM %s WHERE MATCH(tags) AGAINST (%s IN BOOLEAN MODE)"
: "SELECT uid, url FROM %s WHERE tags @> (ARRAY[%s]::varchar[])";
// Replace table name and tag
$sql = sprintf(
$sql,
\Craft::$app->getDb()->quoteTableName(Plugin::CACHE_TABLE),
\Craft::$app->getDb()->quoteValue($tag)
);
// Execute the sql
$results = \Craft::$app->getDb()
->createCommand($sql)
->queryAll();
if (count($results) === 0) {
return [];
}
return ArrayHelper::map($results, 'uid', 'url');
} | [
"public",
"function",
"getTaggedUrls",
"(",
"$",
"tag",
")",
"{",
"// Use fulltext for mysql or array field for pgsql",
"$",
"sql",
"=",
"\\",
"Craft",
"::",
"$",
"app",
"->",
"getDb",
"(",
")",
"->",
"getIsMysql",
"(",
")",
"?",
"\"SELECT uid, url FROM %s WHERE M... | Get cached urls by given tag
Example result
[
'2481f019-27a4-4338-8784-10d1781b' => '/services/development'
'a139aa60-9b56-43b0-a9f5-bfaa7c68' => '/services/app-development'
]
@param string $tag
@return array
@throws \yii\db\Exception | [
"Get",
"cached",
"urls",
"by",
"given",
"tag"
] | 674d8807677fb7ace655575fb5e23e0be805ee45 | https://github.com/ostark/upper/blob/674d8807677fb7ace655575fb5e23e0be805ee45/src/drivers/AbstractPurger.php#L63-L88 | train |
ostark/upper | src/Plugin.php | Plugin.afterInstall | protected function afterInstall()
{
$configSourceFile = __DIR__ . DIRECTORY_SEPARATOR . 'config.example.php';
$configTargetFile = \Craft::$app->getConfig()->configDir . DIRECTORY_SEPARATOR . $this->handle . '.php';
if (!file_exists($configTargetFile)) {
copy($configSourceFile, $configTargetFile);
}
} | php | protected function afterInstall()
{
$configSourceFile = __DIR__ . DIRECTORY_SEPARATOR . 'config.example.php';
$configTargetFile = \Craft::$app->getConfig()->configDir . DIRECTORY_SEPARATOR . $this->handle . '.php';
if (!file_exists($configTargetFile)) {
copy($configSourceFile, $configTargetFile);
}
} | [
"protected",
"function",
"afterInstall",
"(",
")",
"{",
"$",
"configSourceFile",
"=",
"__DIR__",
".",
"DIRECTORY_SEPARATOR",
".",
"'config.example.php'",
";",
"$",
"configTargetFile",
"=",
"\\",
"Craft",
"::",
"$",
"app",
"->",
"getConfig",
"(",
")",
"->",
"co... | Is called after the plugin is installed.
Copies example config to project's config folder | [
"Is",
"called",
"after",
"the",
"plugin",
"is",
"installed",
".",
"Copies",
"example",
"config",
"to",
"project",
"s",
"config",
"folder"
] | 674d8807677fb7ace655575fb5e23e0be805ee45 | https://github.com/ostark/upper/blob/674d8807677fb7ace655575fb5e23e0be805ee45/src/Plugin.php#L121-L129 | train |
ostark/upper | src/drivers/Fastly.php | Fastly.purgeUrls | public function purgeUrls(array $urls)
{
if (strpos($this->domain, 'http') === false) {
throw new \InvalidArgumentException("'domain' is not configured for fastly driver");
}
if (strpos($this->domain, 'http') !== 0) {
throw new \InvalidArgumentException("'domain' must include the protocol, e.g. http://www.foo.com");
}
foreach ($urls as $url) {
if (!$this->sendRequest('PURGE', $this->domain . $url)) {
return false;
}
}
return true;
} | php | public function purgeUrls(array $urls)
{
if (strpos($this->domain, 'http') === false) {
throw new \InvalidArgumentException("'domain' is not configured for fastly driver");
}
if (strpos($this->domain, 'http') !== 0) {
throw new \InvalidArgumentException("'domain' must include the protocol, e.g. http://www.foo.com");
}
foreach ($urls as $url) {
if (!$this->sendRequest('PURGE', $this->domain . $url)) {
return false;
}
}
return true;
} | [
"public",
"function",
"purgeUrls",
"(",
"array",
"$",
"urls",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"this",
"->",
"domain",
",",
"'http'",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"'domain' is not configured ... | Purge cache by urls
@param array $urls
@return bool | [
"Purge",
"cache",
"by",
"urls"
] | 674d8807677fb7ace655575fb5e23e0be805ee45 | https://github.com/ostark/upper/blob/674d8807677fb7ace655575fb5e23e0be805ee45/src/drivers/Fastly.php#L70-L87 | train |
ostark/upper | src/drivers/Fastly.php | Fastly.sendRequest | protected function sendRequest(string $method = 'PURGE', string $uri, array $headers = [])
{
$client = new Client([
'base_uri' => self::API_ENDPOINT,
'headers' => array_merge($headers, [
'Content-Type' => 'application/json',
'Fastly-Key' => $this->apiToken
])
]);
// Prepend the service endpoint
if (in_array($method, ['POST','GET'])) {
$uri = "service/{$this->serviceId}/{$uri}";
}
try {
$client->request($method, $uri);
} catch (BadResponseException $e) {
throw FastlyApiException::create(
$e->getRequest(),
$e->getResponse()
);
}
return true;
} | php | protected function sendRequest(string $method = 'PURGE', string $uri, array $headers = [])
{
$client = new Client([
'base_uri' => self::API_ENDPOINT,
'headers' => array_merge($headers, [
'Content-Type' => 'application/json',
'Fastly-Key' => $this->apiToken
])
]);
// Prepend the service endpoint
if (in_array($method, ['POST','GET'])) {
$uri = "service/{$this->serviceId}/{$uri}";
}
try {
$client->request($method, $uri);
} catch (BadResponseException $e) {
throw FastlyApiException::create(
$e->getRequest(),
$e->getResponse()
);
}
return true;
} | [
"protected",
"function",
"sendRequest",
"(",
"string",
"$",
"method",
"=",
"'PURGE'",
",",
"string",
"$",
"uri",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"client",
"=",
"new",
"Client",
"(",
"[",
"'base_uri'",
"=>",
"self",
"::",
"... | Send API call
@param string $method HTTP verb
@param string $uri
@param array $headers
@return bool
@throws \ostark\upper\exceptions\FastlyApiException | [
"Send",
"API",
"call"
] | 674d8807677fb7ace655575fb5e23e0be805ee45 | https://github.com/ostark/upper/blob/674d8807677fb7ace655575fb5e23e0be805ee45/src/drivers/Fastly.php#L110-L138 | train |
ostark/upper | src/models/Settings.php | Settings.getKeyPrefix | public function getKeyPrefix()
{
if (!$this->keyPrefix) {
return '';
}
$clean = Inflector::slug($this->keyPrefix);
return substr($clean, 0, 8);
} | php | public function getKeyPrefix()
{
if (!$this->keyPrefix) {
return '';
}
$clean = Inflector::slug($this->keyPrefix);
return substr($clean, 0, 8);
} | [
"public",
"function",
"getKeyPrefix",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"keyPrefix",
")",
"{",
"return",
"''",
";",
"}",
"$",
"clean",
"=",
"Inflector",
"::",
"slug",
"(",
"$",
"this",
"->",
"keyPrefix",
")",
";",
"return",
"substr",
... | Get key prefix.
To prevent key collision if you use the same
cache server for several Craft installations.
@return string | [
"Get",
"key",
"prefix",
".",
"To",
"prevent",
"key",
"collision",
"if",
"you",
"use",
"the",
"same",
"cache",
"server",
"for",
"several",
"Craft",
"installations",
"."
] | 674d8807677fb7ace655575fb5e23e0be805ee45 | https://github.com/ostark/upper/blob/674d8807677fb7ace655575fb5e23e0be805ee45/src/models/Settings.php#L103-L111 | train |
ostark/upper | src/behaviors/CacheControlBehavior.php | CacheControlBehavior.removeCacheControlDirective | public function removeCacheControlDirective(string $key)
{
unset($this->cacheControl[$key]);
$this->owner->getHeaders()->set('Cache-Control', $this->getCacheControlHeader());
} | php | public function removeCacheControlDirective(string $key)
{
unset($this->cacheControl[$key]);
$this->owner->getHeaders()->set('Cache-Control', $this->getCacheControlHeader());
} | [
"public",
"function",
"removeCacheControlDirective",
"(",
"string",
"$",
"key",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"cacheControl",
"[",
"$",
"key",
"]",
")",
";",
"$",
"this",
"->",
"owner",
"->",
"getHeaders",
"(",
")",
"->",
"set",
"(",
"'Cac... | Removes a Cache-Control directive.
@param string $key The Cache-Control directive | [
"Removes",
"a",
"Cache",
"-",
"Control",
"directive",
"."
] | 674d8807677fb7ace655575fb5e23e0be805ee45 | https://github.com/ostark/upper/blob/674d8807677fb7ace655575fb5e23e0be805ee45/src/behaviors/CacheControlBehavior.php#L37-L41 | train |
Crell/ApiProblem | src/JsonException.php | JsonException.fromJsonError | public static function fromJsonError(int $jsonError, $failedValue): self
{
return new static(static::getExceptionMessage($jsonError), $jsonError, null, $failedValue);
} | php | public static function fromJsonError(int $jsonError, $failedValue): self
{
return new static(static::getExceptionMessage($jsonError), $jsonError, null, $failedValue);
} | [
"public",
"static",
"function",
"fromJsonError",
"(",
"int",
"$",
"jsonError",
",",
"$",
"failedValue",
")",
":",
"self",
"{",
"return",
"new",
"static",
"(",
"static",
"::",
"getExceptionMessage",
"(",
"$",
"jsonError",
")",
",",
"$",
"jsonError",
",",
"n... | Creates a new exception object based on the JSON error code.
@param int $jsonError
the JSON error code.
@param $failedValue
The value that failed to parse or encode.
@return JsonException
A new exception object. | [
"Creates",
"a",
"new",
"exception",
"object",
"based",
"on",
"the",
"JSON",
"error",
"code",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/JsonException.php#L54-L57 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.fromJson | public static function fromJson(string $json) : self
{
if (empty($json)) {
throw new JsonParseException('An empty string is not a valid JSON value', JSON_ERROR_SYNTAX, null, $json);
}
$parsed = json_decode($json, true);
$lastError = json_last_error();
if (\JSON_ERROR_NONE !== $lastError) {
throw JsonParseException::fromJsonError($lastError, $json);
}
return static::decompile($parsed);
} | php | public static function fromJson(string $json) : self
{
if (empty($json)) {
throw new JsonParseException('An empty string is not a valid JSON value', JSON_ERROR_SYNTAX, null, $json);
}
$parsed = json_decode($json, true);
$lastError = json_last_error();
if (\JSON_ERROR_NONE !== $lastError) {
throw JsonParseException::fromJsonError($lastError, $json);
}
return static::decompile($parsed);
} | [
"public",
"static",
"function",
"fromJson",
"(",
"string",
"$",
"json",
")",
":",
"self",
"{",
"if",
"(",
"empty",
"(",
"$",
"json",
")",
")",
"{",
"throw",
"new",
"JsonParseException",
"(",
"'An empty string is not a valid JSON value'",
",",
"JSON_ERROR_SYNTAX"... | Parses a JSON string into a Problem object.
@param string $json
The JSON string to parse.
@return ApiProblem
A newly constructed problem object.
@throws JsonParseException
Invalid JSON strings will result in a thrown exception. | [
"Parses",
"a",
"JSON",
"string",
"into",
"a",
"Problem",
"object",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L136-L150 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.xmlToArray | protected static function xmlToArray(\SimpleXMLElement $element) : array
{
$data = (array)$element;
foreach ($data as $key => $value) {
if ($value instanceof \SimpleXMLElement) {
$data[$key] = static::xmlToArray($value);
}
}
return $data;
} | php | protected static function xmlToArray(\SimpleXMLElement $element) : array
{
$data = (array)$element;
foreach ($data as $key => $value) {
if ($value instanceof \SimpleXMLElement) {
$data[$key] = static::xmlToArray($value);
}
}
return $data;
} | [
"protected",
"static",
"function",
"xmlToArray",
"(",
"\\",
"SimpleXMLElement",
"$",
"element",
")",
":",
"array",
"{",
"$",
"data",
"=",
"(",
"array",
")",
"$",
"element",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
... | Converts a SimpleXMLElement to a nested array.
@param \SimpleXMLElement $element
The XML
@return array
A nested array corresponding to the XML element provided. | [
"Converts",
"a",
"SimpleXMLElement",
"to",
"a",
"nested",
"array",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L160-L170 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.fromXml | public static function fromXml(string $string) : self
{
$xml = new \SimpleXMLElement($string);
$data = static::xmlToArray($xml);
return static::decompile($data);
} | php | public static function fromXml(string $string) : self
{
$xml = new \SimpleXMLElement($string);
$data = static::xmlToArray($xml);
return static::decompile($data);
} | [
"public",
"static",
"function",
"fromXml",
"(",
"string",
"$",
"string",
")",
":",
"self",
"{",
"$",
"xml",
"=",
"new",
"\\",
"SimpleXMLElement",
"(",
"$",
"string",
")",
";",
"$",
"data",
"=",
"static",
"::",
"xmlToArray",
"(",
"$",
"xml",
")",
";",... | Parses an XML string into a Problem object.
@param string $string
The XML string to parse.
@return ApiProblem
A newly constructed problem object. | [
"Parses",
"an",
"XML",
"string",
"into",
"a",
"Problem",
"object",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L180-L187 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.decompile | protected static function decompile(array $parsed) : self
{
$problem = new static();
if (!empty($parsed['title'])) {
$problem->setTitle($parsed['title']);
}
if (!empty($parsed['type'])) {
$problem->setType($parsed['type']);
}
if (!empty($parsed['status'])) {
$problem->setStatus((int) $parsed['status']);
}
if (!empty($parsed['detail'])) {
$problem->setDetail($parsed['detail']);
}
if (!empty($parsed['instance'])) {
$problem->setInstance($parsed['instance']);
}
// Remove the defined keys. That means whatever is left must be a custom
// extension property.
unset($parsed['title'], $parsed['type'], $parsed['status'], $parsed['detail'], $parsed['instance']);
foreach ($parsed as $key => $value) {
$problem[$key] = $value;
}
return $problem;
} | php | protected static function decompile(array $parsed) : self
{
$problem = new static();
if (!empty($parsed['title'])) {
$problem->setTitle($parsed['title']);
}
if (!empty($parsed['type'])) {
$problem->setType($parsed['type']);
}
if (!empty($parsed['status'])) {
$problem->setStatus((int) $parsed['status']);
}
if (!empty($parsed['detail'])) {
$problem->setDetail($parsed['detail']);
}
if (!empty($parsed['instance'])) {
$problem->setInstance($parsed['instance']);
}
// Remove the defined keys. That means whatever is left must be a custom
// extension property.
unset($parsed['title'], $parsed['type'], $parsed['status'], $parsed['detail'], $parsed['instance']);
foreach ($parsed as $key => $value) {
$problem[$key] = $value;
}
return $problem;
} | [
"protected",
"static",
"function",
"decompile",
"(",
"array",
"$",
"parsed",
")",
":",
"self",
"{",
"$",
"problem",
"=",
"new",
"static",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"parsed",
"[",
"'title'",
"]",
")",
")",
"{",
"$",
"problem"... | Decompiles an array into an ApiProblem object.
@param array $parsed
An array parsed from JSON or XML to turn into an ApiProblem object.
@return ApiProblem
A new ApiProblem object. | [
"Decompiles",
"an",
"array",
"into",
"an",
"ApiProblem",
"object",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L197-L227 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.asJson | public function asJson(bool $pretty = false): string
{
$response = $this->compile();
$options = 0;
if ($pretty) {
$options = \JSON_UNESCAPED_SLASHES | \JSON_PRETTY_PRINT;
}
$json = json_encode($response, $options);
if (false === $json) {
throw JsonEncodeException::fromJsonError(\json_last_error(), $response);
}
return $json;
} | php | public function asJson(bool $pretty = false): string
{
$response = $this->compile();
$options = 0;
if ($pretty) {
$options = \JSON_UNESCAPED_SLASHES | \JSON_PRETTY_PRINT;
}
$json = json_encode($response, $options);
if (false === $json) {
throw JsonEncodeException::fromJsonError(\json_last_error(), $response);
}
return $json;
} | [
"public",
"function",
"asJson",
"(",
"bool",
"$",
"pretty",
"=",
"false",
")",
":",
"string",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"compile",
"(",
")",
";",
"$",
"options",
"=",
"0",
";",
"if",
"(",
"$",
"pretty",
")",
"{",
"$",
"options... | Renders this problem as JSON.
@param bool $pretty
Whether or not to pretty-print the JSON string for easier debugging.
@return string
A JSON string representing this problem. | [
"Renders",
"this",
"problem",
"as",
"JSON",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L385-L401 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.asXml | public function asXml(bool $pretty = false)
{
$doc = new \SimpleXMLElement('<problem></problem>');
$this->arrayToXml($this->compile(), $doc);
$dom = dom_import_simplexml($doc);
if ($pretty) {
$dom->ownerDocument->preserveWhiteSpace = false;
$dom->ownerDocument->formatOutput = true;
}
return $dom->ownerDocument->saveXML();
} | php | public function asXml(bool $pretty = false)
{
$doc = new \SimpleXMLElement('<problem></problem>');
$this->arrayToXml($this->compile(), $doc);
$dom = dom_import_simplexml($doc);
if ($pretty) {
$dom->ownerDocument->preserveWhiteSpace = false;
$dom->ownerDocument->formatOutput = true;
}
return $dom->ownerDocument->saveXML();
} | [
"public",
"function",
"asXml",
"(",
"bool",
"$",
"pretty",
"=",
"false",
")",
"{",
"$",
"doc",
"=",
"new",
"\\",
"SimpleXMLElement",
"(",
"'<problem></problem>'",
")",
";",
"$",
"this",
"->",
"arrayToXml",
"(",
"$",
"this",
"->",
"compile",
"(",
")",
"... | Renders this problem as XML.
@param bool $pretty
Whether or not to pretty-print the XML string for easier debugging.
@return string
An XML string representing this problem. | [
"Renders",
"this",
"problem",
"as",
"XML",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L411-L423 | train |
Crell/ApiProblem | src/ApiProblem.php | ApiProblem.compile | protected function compile() : array
{
// Start with any extensions, since that's already an array.
$response = $this->extensions;
// These properties are optional.
foreach (['title', 'type', 'status', 'detail', 'instance'] as $key) {
if (!empty($this->$key)) {
$response[$key] = $this->$key;
}
}
return $response;
} | php | protected function compile() : array
{
// Start with any extensions, since that's already an array.
$response = $this->extensions;
// These properties are optional.
foreach (['title', 'type', 'status', 'detail', 'instance'] as $key) {
if (!empty($this->$key)) {
$response[$key] = $this->$key;
}
}
return $response;
} | [
"protected",
"function",
"compile",
"(",
")",
":",
"array",
"{",
"// Start with any extensions, since that's already an array.",
"$",
"response",
"=",
"$",
"this",
"->",
"extensions",
";",
"// These properties are optional.",
"foreach",
"(",
"[",
"'title'",
",",
"'type'... | Compiles the object down to an array format, suitable for serializing.
@return array
This object, rendered to an array. | [
"Compiles",
"the",
"object",
"down",
"to",
"an",
"array",
"format",
"suitable",
"for",
"serializing",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/ApiProblem.php#L445-L458 | train |
Crell/ApiProblem | src/HttpConverter.php | HttpConverter.toJsonResponse | public function toJsonResponse(ApiProblem $problem) : ResponseInterface
{
$response = $this->toResponse($problem);
$body = $response->getBody();
$body->write($problem->asJson($this->pretty));
$body->rewind();
return $response
->withHeader('Content-Type', ApiProblem::CONTENT_TYPE_JSON)
->withBody($body);
} | php | public function toJsonResponse(ApiProblem $problem) : ResponseInterface
{
$response = $this->toResponse($problem);
$body = $response->getBody();
$body->write($problem->asJson($this->pretty));
$body->rewind();
return $response
->withHeader('Content-Type', ApiProblem::CONTENT_TYPE_JSON)
->withBody($body);
} | [
"public",
"function",
"toJsonResponse",
"(",
"ApiProblem",
"$",
"problem",
")",
":",
"ResponseInterface",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"toResponse",
"(",
"$",
"problem",
")",
";",
"$",
"body",
"=",
"$",
"response",
"->",
"getBody",
"(",
... | Converts a problem to a JSON HTTP Response object, provided.
@param ApiProblem $problem
The problem to convert.
@return ResponseInterface
The appropriate response object. | [
"Converts",
"a",
"problem",
"to",
"a",
"JSON",
"HTTP",
"Response",
"object",
"provided",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/HttpConverter.php#L50-L61 | train |
Crell/ApiProblem | src/HttpConverter.php | HttpConverter.toXmlResponse | public function toXmlResponse(ApiProblem $problem) : ResponseInterface
{
$response = $this->toResponse($problem);
$body = $response->getBody();
$body->write($problem->asXml($this->pretty));
$body->rewind();
return $this->toResponse($problem)
->withHeader('Content-Type', ApiProblem::CONTENT_TYPE_XML)
->withBody($body);
} | php | public function toXmlResponse(ApiProblem $problem) : ResponseInterface
{
$response = $this->toResponse($problem);
$body = $response->getBody();
$body->write($problem->asXml($this->pretty));
$body->rewind();
return $this->toResponse($problem)
->withHeader('Content-Type', ApiProblem::CONTENT_TYPE_XML)
->withBody($body);
} | [
"public",
"function",
"toXmlResponse",
"(",
"ApiProblem",
"$",
"problem",
")",
":",
"ResponseInterface",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"toResponse",
"(",
"$",
"problem",
")",
";",
"$",
"body",
"=",
"$",
"response",
"->",
"getBody",
"(",
"... | Converts a problem to an XML HTTP Response object, provided.
@param ApiProblem $problem
The problem to convert.
@return ResponseInterface
The appropriate response object. | [
"Converts",
"a",
"problem",
"to",
"an",
"XML",
"HTTP",
"Response",
"object",
"provided",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/HttpConverter.php#L72-L83 | train |
Crell/ApiProblem | src/HttpConverter.php | HttpConverter.toResponse | protected function toResponse(ApiProblem $problem) : ResponseInterface
{
$status = $problem->getStatus() ?: 500;
$response = $this->responseFactory->createResponse($status);
return $response;
} | php | protected function toResponse(ApiProblem $problem) : ResponseInterface
{
$status = $problem->getStatus() ?: 500;
$response = $this->responseFactory->createResponse($status);
return $response;
} | [
"protected",
"function",
"toResponse",
"(",
"ApiProblem",
"$",
"problem",
")",
":",
"ResponseInterface",
"{",
"$",
"status",
"=",
"$",
"problem",
"->",
"getStatus",
"(",
")",
"?",
":",
"500",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"responseFactory",... | Converts a problem to a provided Response, without the format-sensitive bits.
@param ApiProblem $problem
The problem to convert.
@return ResponseInterface
The appropriate response object. | [
"Converts",
"a",
"problem",
"to",
"a",
"provided",
"Response",
"without",
"the",
"format",
"-",
"sensitive",
"bits",
"."
] | e77bd0933add33907e02f9cb603a3ca54b9c3b71 | https://github.com/Crell/ApiProblem/blob/e77bd0933add33907e02f9cb603a3ca54b9c3b71/src/HttpConverter.php#L94-L101 | train |
Silentscripter/laravel-prestashop-webservice | src/PrestashopWebServiceLibrary.php | PrestashopWebServiceLibrary.isPrestashopVersionSupported | public function isPrestashopVersionSupported($version)
{
if (version_compare($version, self::PS_COMPATIBLE_VERSION_MIN, '>=') === false ||
version_compare($version, self::PS_COMPATIBLE_VERSION_MAX, '<=') === false
) {
$exception = 'This library is not compatible with this version of PrestaShop. ';
$exception.= 'Please upgrade/downgrade this library';
throw new PrestashopWebServiceException($exception);
}
} | php | public function isPrestashopVersionSupported($version)
{
if (version_compare($version, self::PS_COMPATIBLE_VERSION_MIN, '>=') === false ||
version_compare($version, self::PS_COMPATIBLE_VERSION_MAX, '<=') === false
) {
$exception = 'This library is not compatible with this version of PrestaShop. ';
$exception.= 'Please upgrade/downgrade this library';
throw new PrestashopWebServiceException($exception);
}
} | [
"public",
"function",
"isPrestashopVersionSupported",
"(",
"$",
"version",
")",
"{",
"if",
"(",
"version_compare",
"(",
"$",
"version",
",",
"self",
"::",
"PS_COMPATIBLE_VERSION_MIN",
",",
"'>='",
")",
"===",
"false",
"||",
"version_compare",
"(",
"$",
"version"... | Throws exception if prestashop version is not supported
@param int $version The prestashop version
@throws PrestashopWebServiceException | [
"Throws",
"exception",
"if",
"prestashop",
"version",
"is",
"not",
"supported"
] | d23cd41b014fa4cafada0869b0c631fb75e80def | https://github.com/Silentscripter/laravel-prestashop-webservice/blob/d23cd41b014fa4cafada0869b0c631fb75e80def/src/PrestashopWebServiceLibrary.php#L110-L119 | train |
Silentscripter/laravel-prestashop-webservice | src/PrestashopWebServiceLibrary.php | PrestashopWebServiceLibrary.executeCurl | protected function executeCurl($url, array $options = array())
{
$session = curl_init($url);
if (count($options)) {
curl_setopt_array($session, $options);
}
$response = curl_exec($session);
$error = false;
$info = curl_getinfo($session);
if ($response === false) {
$error = curl_error($session);
}
curl_close($session);
return array($response, $info, $error);
} | php | protected function executeCurl($url, array $options = array())
{
$session = curl_init($url);
if (count($options)) {
curl_setopt_array($session, $options);
}
$response = curl_exec($session);
$error = false;
$info = curl_getinfo($session);
if ($response === false) {
$error = curl_error($session);
}
curl_close($session);
return array($response, $info, $error);
} | [
"protected",
"function",
"executeCurl",
"(",
"$",
"url",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"session",
"=",
"curl_init",
"(",
"$",
"url",
")",
";",
"if",
"(",
"count",
"(",
"$",
"options",
")",
")",
"{",
"curl_seto... | Executes the CURL request to PrestaShop WebService.
@param string $url Resource name
@param mixed $options CURL parameters (sent to curl_setopt_array)
@return array response, info | [
"Executes",
"the",
"CURL",
"request",
"to",
"PrestaShop",
"WebService",
"."
] | d23cd41b014fa4cafada0869b0c631fb75e80def | https://github.com/Silentscripter/laravel-prestashop-webservice/blob/d23cd41b014fa4cafada0869b0c631fb75e80def/src/PrestashopWebServiceLibrary.php#L208-L227 | train |
Silentscripter/laravel-prestashop-webservice | src/PrestashopWebService.php | PrestashopWebService.fillSchema | public function fillSchema(
SimpleXMLElement $xmlSchema,
$data,
$removeUselessNodes = true,
$removeSpecificNodes = array()
) {
$resource = $xmlSchema->children()->children();
foreach ($data as $key => $value) {
$this->processNode($resource, $key, $value);
}
if ($removeUselessNodes) {
$this->checkForUselessNodes($resource, $data);
} else {
$this->removeSpecificNodes($resource, $removeSpecificNodes);
}
return $xmlSchema;
} | php | public function fillSchema(
SimpleXMLElement $xmlSchema,
$data,
$removeUselessNodes = true,
$removeSpecificNodes = array()
) {
$resource = $xmlSchema->children()->children();
foreach ($data as $key => $value) {
$this->processNode($resource, $key, $value);
}
if ($removeUselessNodes) {
$this->checkForUselessNodes($resource, $data);
} else {
$this->removeSpecificNodes($resource, $removeSpecificNodes);
}
return $xmlSchema;
} | [
"public",
"function",
"fillSchema",
"(",
"SimpleXMLElement",
"$",
"xmlSchema",
",",
"$",
"data",
",",
"$",
"removeUselessNodes",
"=",
"true",
",",
"$",
"removeSpecificNodes",
"=",
"array",
"(",
")",
")",
"{",
"$",
"resource",
"=",
"$",
"xmlSchema",
"->",
"... | Fill the provided schema with an associative array data, also remove the useless XML nodes if
the corresponding flag is true
@param SimpleXMLElement $xmlSchema
@param array $data
@param bool $removeUselessNodes set true if you want to remove nodes that are not present in the data array
@param array $removeSpecificNodes If $removeUselessNodes is false you may add here the first level nodes that
you want to remove
@return SimpleXMLElement | [
"Fill",
"the",
"provided",
"schema",
"with",
"an",
"associative",
"array",
"data",
"also",
"remove",
"the",
"useless",
"XML",
"nodes",
"if",
"the",
"corresponding",
"flag",
"is",
"true"
] | d23cd41b014fa4cafada0869b0c631fb75e80def | https://github.com/Silentscripter/laravel-prestashop-webservice/blob/d23cd41b014fa4cafada0869b0c631fb75e80def/src/PrestashopWebService.php#L34-L50 | train |
Silentscripter/laravel-prestashop-webservice | src/PrestashopWebService.php | PrestashopWebService.checkForUselessNodes | private function checkForUselessNodes(SimpleXMLElement $resource, $data)
{
$uselessNodes = [];
foreach ($resource as $key => $value) {
if (!array_key_exists($key, $data)) {
$uselessNodes[] = $key;
}
}
foreach ($uselessNodes as $key) {
unset($resource->$key);
}
} | php | private function checkForUselessNodes(SimpleXMLElement $resource, $data)
{
$uselessNodes = [];
foreach ($resource as $key => $value) {
if (!array_key_exists($key, $data)) {
$uselessNodes[] = $key;
}
}
foreach ($uselessNodes as $key) {
unset($resource->$key);
}
} | [
"private",
"function",
"checkForUselessNodes",
"(",
"SimpleXMLElement",
"$",
"resource",
",",
"$",
"data",
")",
"{",
"$",
"uselessNodes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"resource",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!... | Remove XML first level nodes that are not present int the data array
@param SimpleXMLElement $resource
@param $data | [
"Remove",
"XML",
"first",
"level",
"nodes",
"that",
"are",
"not",
"present",
"int",
"the",
"data",
"array"
] | d23cd41b014fa4cafada0869b0c631fb75e80def | https://github.com/Silentscripter/laravel-prestashop-webservice/blob/d23cd41b014fa4cafada0869b0c631fb75e80def/src/PrestashopWebService.php#L109-L120 | train |
swarrot/SwarrotBundle | Broker/AmqpLibFactory.php | AmqpLibFactory.getChannel | public function getChannel($connection)
{
if (isset($this->channels[$connection])) {
return $this->channels[$connection];
}
if (!isset($this->connections[$connection])) {
throw new \InvalidArgumentException(sprintf(
'Unknown connection "%s". Available: [%s]',
$connection,
implode(', ', array_keys($this->connections))
));
}
if (!isset($this->channels[$connection])) {
$this->channels[$connection] = array();
}
if (isset($this->connections[$connection]['ssl']) && $this->connections[$connection]['ssl']) {
if (empty($this->connections[$connection]['ssl_options'])) {
$ssl_opts = array(
'verify_peer' => true,
);
} else {
$ssl_opts = array();
foreach ($this->connections[$connection]['ssl_options'] as $key => $value) {
if (!empty($value)) {
$ssl_opts[$key] = $value;
}
}
}
$conn = new AMQPSSLConnection(
$this->connections[$connection]['host'],
$this->connections[$connection]['port'],
$this->connections[$connection]['login'],
$this->connections[$connection]['password'],
$this->connections[$connection]['vhost'],
$ssl_opts
);
} else {
$conn = new AMQPConnection(
$this->connections[$connection]['host'],
$this->connections[$connection]['port'],
$this->connections[$connection]['login'],
$this->connections[$connection]['password'],
$this->connections[$connection]['vhost']
);
}
$this->channels[$connection] = $conn->channel();
return $this->channels[$connection];
} | php | public function getChannel($connection)
{
if (isset($this->channels[$connection])) {
return $this->channels[$connection];
}
if (!isset($this->connections[$connection])) {
throw new \InvalidArgumentException(sprintf(
'Unknown connection "%s". Available: [%s]',
$connection,
implode(', ', array_keys($this->connections))
));
}
if (!isset($this->channels[$connection])) {
$this->channels[$connection] = array();
}
if (isset($this->connections[$connection]['ssl']) && $this->connections[$connection]['ssl']) {
if (empty($this->connections[$connection]['ssl_options'])) {
$ssl_opts = array(
'verify_peer' => true,
);
} else {
$ssl_opts = array();
foreach ($this->connections[$connection]['ssl_options'] as $key => $value) {
if (!empty($value)) {
$ssl_opts[$key] = $value;
}
}
}
$conn = new AMQPSSLConnection(
$this->connections[$connection]['host'],
$this->connections[$connection]['port'],
$this->connections[$connection]['login'],
$this->connections[$connection]['password'],
$this->connections[$connection]['vhost'],
$ssl_opts
);
} else {
$conn = new AMQPConnection(
$this->connections[$connection]['host'],
$this->connections[$connection]['port'],
$this->connections[$connection]['login'],
$this->connections[$connection]['password'],
$this->connections[$connection]['vhost']
);
}
$this->channels[$connection] = $conn->channel();
return $this->channels[$connection];
} | [
"public",
"function",
"getChannel",
"(",
"$",
"connection",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"channels",
"[",
"$",
"connection",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"channels",
"[",
"$",
"connection",
"]",
";",
"}",
... | Return the AMQPChannel of the given connection.
@param string $connection
@return AMQPChannel | [
"Return",
"the",
"AMQPChannel",
"of",
"the",
"given",
"connection",
"."
] | a85a710ee6e95c46d83b6797d5fcd5f3ae17d6b6 | https://github.com/swarrot/SwarrotBundle/blob/a85a710ee6e95c46d83b6797d5fcd5f3ae17d6b6/Broker/AmqpLibFactory.php#L76-L129 | train |
swarrot/SwarrotBundle | Broker/UrlParserTrait.php | UrlParserTrait.parseUrl | private function parseUrl(string $url): array
{
$parts = parse_url($url);
if ($parts === false || !isset($parts['host'])) {
throw new \InvalidArgumentException(sprintf('Invalid connection URL given: "%s"', $url));
}
$params = [
'login' => $parts['user'] ?? '',
'password' => $parts['pass'] ?? '',
'host' => $parts['host'],
'port' => (int) ($parts['port'] ?? 5672),
'vhost' => empty($parts['path']) || $parts['path'] === '/' ? '/' : substr($parts['path'], 1),
];
parse_str($parts['query'] ?? '', $queryParams);
return $params + $queryParams;
} | php | private function parseUrl(string $url): array
{
$parts = parse_url($url);
if ($parts === false || !isset($parts['host'])) {
throw new \InvalidArgumentException(sprintf('Invalid connection URL given: "%s"', $url));
}
$params = [
'login' => $parts['user'] ?? '',
'password' => $parts['pass'] ?? '',
'host' => $parts['host'],
'port' => (int) ($parts['port'] ?? 5672),
'vhost' => empty($parts['path']) || $parts['path'] === '/' ? '/' : substr($parts['path'], 1),
];
parse_str($parts['query'] ?? '', $queryParams);
return $params + $queryParams;
} | [
"private",
"function",
"parseUrl",
"(",
"string",
"$",
"url",
")",
":",
"array",
"{",
"$",
"parts",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"if",
"(",
"$",
"parts",
"===",
"false",
"||",
"!",
"isset",
"(",
"$",
"parts",
"[",
"'host'",
"]",
"... | Parse a RabbitMQ URI into its components.
@throws \InvalidArgumentException if the URL can not be parsed. | [
"Parse",
"a",
"RabbitMQ",
"URI",
"into",
"its",
"components",
"."
] | a85a710ee6e95c46d83b6797d5fcd5f3ae17d6b6 | https://github.com/swarrot/SwarrotBundle/blob/a85a710ee6e95c46d83b6797d5fcd5f3ae17d6b6/Broker/UrlParserTrait.php#L12-L31 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.set_line_style | public function set_line_style($style1, $style2 = '', $preserve_defaults = false) {
//Check if we got 2 or three parameters
if (is_bool($style2)) {
$preserve_defaults = $style2;
$style2 = '';
}
//Actually set the new styles
if (!$preserve_defaults) {
$this->line_style1 = $style1;
$this->line_style2 = $style2;
} else {
$this->line_style1 .= $style1;
$this->line_style2 .= $style2;
}
} | php | public function set_line_style($style1, $style2 = '', $preserve_defaults = false) {
//Check if we got 2 or three parameters
if (is_bool($style2)) {
$preserve_defaults = $style2;
$style2 = '';
}
//Actually set the new styles
if (!$preserve_defaults) {
$this->line_style1 = $style1;
$this->line_style2 = $style2;
} else {
$this->line_style1 .= $style1;
$this->line_style2 .= $style2;
}
} | [
"public",
"function",
"set_line_style",
"(",
"$",
"style1",
",",
"$",
"style2",
"=",
"''",
",",
"$",
"preserve_defaults",
"=",
"false",
")",
"{",
"//Check if we got 2 or three parameters",
"if",
"(",
"is_bool",
"(",
"$",
"style2",
")",
")",
"{",
"$",
"preser... | Sets the styles for the line numbers.
@param string $style1 The style for the line numbers that are "normal"
@param string|boolean $style2 If a string, this is the style of the line
numbers that are "fancy", otherwise if boolean then this
defines whether the normal styles should be merged with the
new normal styles or not
@param boolean $preserve_defaults If set, is the flag for whether to merge the "fancy"
styles with the current styles or not
@since 1.0.2 | [
"Sets",
"the",
"styles",
"for",
"the",
"line",
"numbers",
"."
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L918-L933 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.set_tab_width | public function set_tab_width($width) {
$this->tab_width = intval($width);
//Check if it fit's the constraints:
if ($this->tab_width < 1) {
//Return it to the default
$this->tab_width = 8;
}
} | php | public function set_tab_width($width) {
$this->tab_width = intval($width);
//Check if it fit's the constraints:
if ($this->tab_width < 1) {
//Return it to the default
$this->tab_width = 8;
}
} | [
"public",
"function",
"set_tab_width",
"(",
"$",
"width",
")",
"{",
"$",
"this",
"->",
"tab_width",
"=",
"intval",
"(",
"$",
"width",
")",
";",
"//Check if it fit's the constraints:",
"if",
"(",
"$",
"this",
"->",
"tab_width",
"<",
"1",
")",
"{",
"//Return... | Sets how many spaces a tab is substituted for
Widths below zero are ignored
@param int $width The tab width
@since 1.0.0 | [
"Sets",
"how",
"many",
"spaces",
"a",
"tab",
"is",
"substituted",
"for"
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L1350-L1358 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.get_real_tab_width | public function get_real_tab_width() {
if (!$this->use_language_tab_width ||
!isset($this->language_data['TAB_WIDTH'])) {
return $this->tab_width;
} else {
return $this->language_data['TAB_WIDTH'];
}
} | php | public function get_real_tab_width() {
if (!$this->use_language_tab_width ||
!isset($this->language_data['TAB_WIDTH'])) {
return $this->tab_width;
} else {
return $this->language_data['TAB_WIDTH'];
}
} | [
"public",
"function",
"get_real_tab_width",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"use_language_tab_width",
"||",
"!",
"isset",
"(",
"$",
"this",
"->",
"language_data",
"[",
"'TAB_WIDTH'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"tab... | Returns the tab width to use, based on the current language and user
preference
@return int Tab width
@since 1.0.7.20 | [
"Returns",
"the",
"tab",
"width",
"to",
"use",
"based",
"on",
"the",
"current",
"language",
"and",
"user",
"preference"
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L1377-L1384 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.add_keyword | public function add_keyword($key, $word) {
if (!is_array($this->language_data['KEYWORDS'][$key])) {
$this->language_data['KEYWORDS'][$key] = array();
}
if (!in_array($word, $this->language_data['KEYWORDS'][$key])) {
$this->language_data['KEYWORDS'][$key][] = $word;
//NEW in 1.0.8 don't recompile the whole optimized regexp, simply append it
if ($this->parse_cache_built) {
$subkey = count($this->language_data['CACHED_KEYWORD_LISTS'][$key]) - 1;
$this->language_data['CACHED_KEYWORD_LISTS'][$key][$subkey] .= '|' . preg_quote($word, '/');
}
}
} | php | public function add_keyword($key, $word) {
if (!is_array($this->language_data['KEYWORDS'][$key])) {
$this->language_data['KEYWORDS'][$key] = array();
}
if (!in_array($word, $this->language_data['KEYWORDS'][$key])) {
$this->language_data['KEYWORDS'][$key][] = $word;
//NEW in 1.0.8 don't recompile the whole optimized regexp, simply append it
if ($this->parse_cache_built) {
$subkey = count($this->language_data['CACHED_KEYWORD_LISTS'][$key]) - 1;
$this->language_data['CACHED_KEYWORD_LISTS'][$key][$subkey] .= '|' . preg_quote($word, '/');
}
}
} | [
"public",
"function",
"add_keyword",
"(",
"$",
"key",
",",
"$",
"word",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"language_data",
"[",
"'KEYWORDS'",
"]",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"this",
"->",
"language_data",
... | Adds a keyword to a keyword group for highlighting
@param int $key The key of the keyword group to add the keyword to
@param string $word The word to add to the keyword group
@since 1.0.0 | [
"Adds",
"a",
"keyword",
"to",
"a",
"keyword",
"group",
"for",
"highlighting"
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L1571-L1584 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.remove_keyword_group | public function remove_keyword_group ($key) {
//Remove the keyword group internally
unset($this->language_data['KEYWORDS'][$key]);
unset($this->lexic_permissions['KEYWORDS'][$key]);
unset($this->language_data['CASE_SENSITIVE'][$key]);
unset($this->language_data['STYLES']['KEYWORDS'][$key]);
//NEW in 1.0.8
unset($this->language_data['CACHED_KEYWORD_LISTS'][$key]);
} | php | public function remove_keyword_group ($key) {
//Remove the keyword group internally
unset($this->language_data['KEYWORDS'][$key]);
unset($this->lexic_permissions['KEYWORDS'][$key]);
unset($this->language_data['CASE_SENSITIVE'][$key]);
unset($this->language_data['STYLES']['KEYWORDS'][$key]);
//NEW in 1.0.8
unset($this->language_data['CACHED_KEYWORD_LISTS'][$key]);
} | [
"public",
"function",
"remove_keyword_group",
"(",
"$",
"key",
")",
"{",
"//Remove the keyword group internally",
"unset",
"(",
"$",
"this",
"->",
"language_data",
"[",
"'KEYWORDS'",
"]",
"[",
"$",
"key",
"]",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"lexi... | Removes a keyword group
@param int $key The key of the keyword group to remove
@since 1.0.0 | [
"Removes",
"a",
"keyword",
"group"
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L1647-L1656 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.set_time | protected function set_time($start_time, $end_time) {
$start = explode(' ', $start_time);
$end = explode(' ', $end_time);
$this->time = $end[0] + $end[1] - $start[0] - $start[1];
} | php | protected function set_time($start_time, $end_time) {
$start = explode(' ', $start_time);
$end = explode(' ', $end_time);
$this->time = $end[0] + $end[1] - $start[0] - $start[1];
} | [
"protected",
"function",
"set_time",
"(",
"$",
"start_time",
",",
"$",
"end_time",
")",
"{",
"$",
"start",
"=",
"explode",
"(",
"' '",
",",
"$",
"start_time",
")",
";",
"$",
"end",
"=",
"explode",
"(",
"' '",
",",
"$",
"end_time",
")",
";",
"$",
"t... | Sets the time taken to parse the code
@param string $start_time The time when parsing started as returned by @see microtime()
@param string $end_time The time when parsing ended as returned by @see microtime()
@since 1.0.2 | [
"Sets",
"the",
"time",
"taken",
"to",
"parse",
"the",
"code"
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L3668-L3672 | train |
GeSHi/geshi-1.0 | src/geshi.php | GeSHi.merge_arrays | protected function merge_arrays() {
$arrays = func_get_args();
$narrays = count($arrays);
// check arguments
// comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
for ($i = 0; $i < $narrays; $i ++) {
if (!is_array($arrays[$i])) {
// also array_merge_recursive returns nothing in this case
trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning false!', E_USER_WARNING);
return false;
}
}
// the first array is in the output set in every case
$ret = $arrays[0];
// merege $ret with the remaining arrays
for ($i = 1; $i < $narrays; $i ++) {
foreach ($arrays[$i] as $key => $value) {
if (is_array($value) && isset($ret[$key])) {
// if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
// in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be false.
$ret[$key] = $this->merge_arrays($ret[$key], $value);
} else {
$ret[$key] = $value;
}
}
}
return $ret;
} | php | protected function merge_arrays() {
$arrays = func_get_args();
$narrays = count($arrays);
// check arguments
// comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
for ($i = 0; $i < $narrays; $i ++) {
if (!is_array($arrays[$i])) {
// also array_merge_recursive returns nothing in this case
trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning false!', E_USER_WARNING);
return false;
}
}
// the first array is in the output set in every case
$ret = $arrays[0];
// merege $ret with the remaining arrays
for ($i = 1; $i < $narrays; $i ++) {
foreach ($arrays[$i] as $key => $value) {
if (is_array($value) && isset($ret[$key])) {
// if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
// in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be false.
$ret[$key] = $this->merge_arrays($ret[$key], $value);
} else {
$ret[$key] = $value;
}
}
}
return $ret;
} | [
"protected",
"function",
"merge_arrays",
"(",
")",
"{",
"$",
"arrays",
"=",
"func_get_args",
"(",
")",
";",
"$",
"narrays",
"=",
"count",
"(",
"$",
"arrays",
")",
";",
"// check arguments",
"// comment out if more performance is necessary (in this case the foreach loop ... | Merges arrays recursively, overwriting values of the first array with values of later arrays
@since 1.0.8 | [
"Merges",
"arrays",
"recursively",
"overwriting",
"values",
"of",
"the",
"first",
"array",
"with",
"values",
"of",
"later",
"arrays"
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/src/geshi.php#L3689-L3720 | train |
GeSHi/geshi-1.0 | contrib/geshi-cli.php | GeSHi_Cli.run | public function run()
{
$parser = $this->createParser();
try {
$result = $parser->parse();
$file = $result->args['infile'];
$format = $result->options['format'];
$css = $result->options['css'];
if ($format == '') {
$format = $this->detectFormat($file);
}
$geshi = new GeSHi(file_get_contents($file), $format);
if ($css) {
$geshi->enable_classes();
echo '<style type="text/css">' . "\n"
. $geshi->get_stylesheet(true)
. "</style>\n";
}
echo $geshi->parse_code() . "\n";
} catch (Exception $e) {
$parser->displayError($e->getMessage());
exit(1);
}
} | php | public function run()
{
$parser = $this->createParser();
try {
$result = $parser->parse();
$file = $result->args['infile'];
$format = $result->options['format'];
$css = $result->options['css'];
if ($format == '') {
$format = $this->detectFormat($file);
}
$geshi = new GeSHi(file_get_contents($file), $format);
if ($css) {
$geshi->enable_classes();
echo '<style type="text/css">' . "\n"
. $geshi->get_stylesheet(true)
. "</style>\n";
}
echo $geshi->parse_code() . "\n";
} catch (Exception $e) {
$parser->displayError($e->getMessage());
exit(1);
}
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"parser",
"=",
"$",
"this",
"->",
"createParser",
"(",
")",
";",
"try",
"{",
"$",
"result",
"=",
"$",
"parser",
"->",
"parse",
"(",
")",
";",
"$",
"file",
"=",
"$",
"result",
"->",
"args",
"[",
"... | Runs the script and outputs highlighted code.
@return void | [
"Runs",
"the",
"script",
"and",
"outputs",
"highlighted",
"code",
"."
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/contrib/geshi-cli.php#L34-L59 | train |
GeSHi/geshi-1.0 | contrib/geshi-cli.php | GeSHi_Cli.createParser | protected function createParser()
{
$geshi = new GeSHi();
$parser = new Console_CommandLine();
$parser->description = 'CLI interface to GeSHi, the generic syntax highlighter';
$parser->version = '0.1.0';
$parser->addOption('css', array(
'long_name' => '--css',
'description' => 'Use CSS classes',
'action' => 'StoreTrue',
'default' => false,
));
$langs = $geshi->get_supported_languages();
sort($langs);
$parser->addOption('format', array(
'short_name' => '-f',
'long_name' => '--format',
'description' => 'Format of file to highlight (e.g. php).',
'help_name' => 'FORMAT',
'action' => 'StoreString',
'default' => false,
'choices' => $langs,
));
$parser->addArgument('infile', array('help_name' => 'source file'));
return $parser;
} | php | protected function createParser()
{
$geshi = new GeSHi();
$parser = new Console_CommandLine();
$parser->description = 'CLI interface to GeSHi, the generic syntax highlighter';
$parser->version = '0.1.0';
$parser->addOption('css', array(
'long_name' => '--css',
'description' => 'Use CSS classes',
'action' => 'StoreTrue',
'default' => false,
));
$langs = $geshi->get_supported_languages();
sort($langs);
$parser->addOption('format', array(
'short_name' => '-f',
'long_name' => '--format',
'description' => 'Format of file to highlight (e.g. php).',
'help_name' => 'FORMAT',
'action' => 'StoreString',
'default' => false,
'choices' => $langs,
));
$parser->addArgument('infile', array('help_name' => 'source file'));
return $parser;
} | [
"protected",
"function",
"createParser",
"(",
")",
"{",
"$",
"geshi",
"=",
"new",
"GeSHi",
"(",
")",
";",
"$",
"parser",
"=",
"new",
"Console_CommandLine",
"(",
")",
";",
"$",
"parser",
"->",
"description",
"=",
"'CLI interface to GeSHi, the generic syntax highl... | Creates the command line parser and populates it with all allowed
options and parameters.
@return Console_CommandLine CommandLine object | [
"Creates",
"the",
"command",
"line",
"parser",
"and",
"populates",
"it",
"with",
"all",
"allowed",
"options",
"and",
"parameters",
"."
] | 5861c58981244ab6ee0dd337f096ff14bf15b1eb | https://github.com/GeSHi/geshi-1.0/blob/5861c58981244ab6ee0dd337f096ff14bf15b1eb/contrib/geshi-cli.php#L69-L97 | train |
laravel-admin-extensions/log-viewer | src/LogViewer.php | LogViewer.getFilePath | public function getFilePath()
{
if (!$this->filePath) {
$path = sprintf(storage_path('logs/%s'), $this->file);
if (!file_exists($path)) {
throw new \Exception('log not exists!');
}
$this->filePath = $path;
}
return $this->filePath;
} | php | public function getFilePath()
{
if (!$this->filePath) {
$path = sprintf(storage_path('logs/%s'), $this->file);
if (!file_exists($path)) {
throw new \Exception('log not exists!');
}
$this->filePath = $path;
}
return $this->filePath;
} | [
"public",
"function",
"getFilePath",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"filePath",
")",
"{",
"$",
"path",
"=",
"sprintf",
"(",
"storage_path",
"(",
"'logs/%s'",
")",
",",
"$",
"this",
"->",
"file",
")",
";",
"if",
"(",
"!",
"file_ex... | Get file path by giving log file name.
@throws \Exception
@return string | [
"Get",
"file",
"path",
"by",
"giving",
"log",
"file",
"name",
"."
] | 742a2550746c9346d463249ba16b8fba9ac9cf97 | https://github.com/laravel-admin-extensions/log-viewer/blob/742a2550746c9346d463249ba16b8fba9ac9cf97/src/LogViewer.php#L72-L85 | train |
laravel-admin-extensions/log-viewer | src/LogViewer.php | LogViewer.fetch | public function fetch($seek = 0, $lines = 20, $buffer = 4096)
{
$f = fopen($this->filePath, 'rb');
if ($seek) {
fseek($f, abs($seek));
} else {
fseek($f, 0, SEEK_END);
}
if (fread($f, 1) != "\n") {
$lines -= 1;
}
fseek($f, -1, SEEK_CUR);
// 从前往后读,上一页
// Start reading
if ($seek > 0) {
$output = '';
$this->pageOffset['start'] = ftell($f);
while (!feof($f) && $lines >= 0) {
$output = $output.($chunk = fread($f, $buffer));
$lines -= substr_count($chunk, "\n[20");
}
$this->pageOffset['end'] = ftell($f);
while ($lines++ < 0) {
$strpos = strrpos($output, "\n[20") + 1;
$_ = mb_strlen($output, '8bit') - $strpos;
$output = substr($output, 0, $strpos);
$this->pageOffset['end'] -= $_;
}
// 从后往前读,下一页
} else {
$output = '';
$this->pageOffset['end'] = ftell($f);
while (ftell($f) > 0 && $lines >= 0) {
$offset = min(ftell($f), $buffer);
fseek($f, -$offset, SEEK_CUR);
$output = ($chunk = fread($f, $offset)).$output;
fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
$lines -= substr_count($chunk, "\n[20");
}
$this->pageOffset['start'] = ftell($f);
while ($lines++ < 0) {
$strpos = strpos($output, "\n[20") + 1;
$output = substr($output, $strpos);
$this->pageOffset['start'] += $strpos;
}
}
fclose($f);
return $this->parseLog($output);
} | php | public function fetch($seek = 0, $lines = 20, $buffer = 4096)
{
$f = fopen($this->filePath, 'rb');
if ($seek) {
fseek($f, abs($seek));
} else {
fseek($f, 0, SEEK_END);
}
if (fread($f, 1) != "\n") {
$lines -= 1;
}
fseek($f, -1, SEEK_CUR);
// 从前往后读,上一页
// Start reading
if ($seek > 0) {
$output = '';
$this->pageOffset['start'] = ftell($f);
while (!feof($f) && $lines >= 0) {
$output = $output.($chunk = fread($f, $buffer));
$lines -= substr_count($chunk, "\n[20");
}
$this->pageOffset['end'] = ftell($f);
while ($lines++ < 0) {
$strpos = strrpos($output, "\n[20") + 1;
$_ = mb_strlen($output, '8bit') - $strpos;
$output = substr($output, 0, $strpos);
$this->pageOffset['end'] -= $_;
}
// 从后往前读,下一页
} else {
$output = '';
$this->pageOffset['end'] = ftell($f);
while (ftell($f) > 0 && $lines >= 0) {
$offset = min(ftell($f), $buffer);
fseek($f, -$offset, SEEK_CUR);
$output = ($chunk = fread($f, $offset)).$output;
fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
$lines -= substr_count($chunk, "\n[20");
}
$this->pageOffset['start'] = ftell($f);
while ($lines++ < 0) {
$strpos = strpos($output, "\n[20") + 1;
$output = substr($output, $strpos);
$this->pageOffset['start'] += $strpos;
}
}
fclose($f);
return $this->parseLog($output);
} | [
"public",
"function",
"fetch",
"(",
"$",
"seek",
"=",
"0",
",",
"$",
"lines",
"=",
"20",
",",
"$",
"buffer",
"=",
"4096",
")",
"{",
"$",
"f",
"=",
"fopen",
"(",
"$",
"this",
"->",
"filePath",
",",
"'rb'",
")",
";",
"if",
"(",
"$",
"seek",
")"... | Fetch logs by giving offset.
@param int $seek
@param int $lines
@param int $buffer
@return array
@see http://www.geekality.net/2011/05/28/php-tail-tackling-large-files/ | [
"Fetch",
"logs",
"by",
"giving",
"offset",
"."
] | 742a2550746c9346d463249ba16b8fba9ac9cf97 | https://github.com/laravel-admin-extensions/log-viewer/blob/742a2550746c9346d463249ba16b8fba9ac9cf97/src/LogViewer.php#L170-L232 | train |
laravel-admin-extensions/log-viewer | src/LogViewer.php | LogViewer.parseLog | protected function parseLog($raw)
{
$logs = preg_split('/\[(\d{4}(?:-\d{2}){2} \d{2}(?::\d{2}){2})\] (\w+)\.(\w+):((?:(?!{"exception").)*)?/', trim($raw), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach ($logs as $index => $log) {
if (preg_match('/^\d{4}/', $log)) {
break;
} else {
unset($logs[$index]);
}
}
if (empty($logs)) {
return [];
}
$parsed = [];
foreach (array_chunk($logs, 5) as $log) {
$parsed[] = [
'time' => $log[0] ?? '',
'env' => $log[1] ?? '',
'level' => $log[2] ?? '',
'info' => $log[3] ?? '',
'trace' => trim($log[4] ?? ''),
];
}
unset($logs);
rsort($parsed);
return $parsed;
} | php | protected function parseLog($raw)
{
$logs = preg_split('/\[(\d{4}(?:-\d{2}){2} \d{2}(?::\d{2}){2})\] (\w+)\.(\w+):((?:(?!{"exception").)*)?/', trim($raw), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach ($logs as $index => $log) {
if (preg_match('/^\d{4}/', $log)) {
break;
} else {
unset($logs[$index]);
}
}
if (empty($logs)) {
return [];
}
$parsed = [];
foreach (array_chunk($logs, 5) as $log) {
$parsed[] = [
'time' => $log[0] ?? '',
'env' => $log[1] ?? '',
'level' => $log[2] ?? '',
'info' => $log[3] ?? '',
'trace' => trim($log[4] ?? ''),
];
}
unset($logs);
rsort($parsed);
return $parsed;
} | [
"protected",
"function",
"parseLog",
"(",
"$",
"raw",
")",
"{",
"$",
"logs",
"=",
"preg_split",
"(",
"'/\\[(\\d{4}(?:-\\d{2}){2} \\d{2}(?::\\d{2}){2})\\] (\\w+)\\.(\\w+):((?:(?!{\"exception\").)*)?/'",
",",
"trim",
"(",
"$",
"raw",
")",
",",
"-",
"1",
",",
"PREG_SPLIT... | Parse raw log text to array.
@param $raw
@return array | [
"Parse",
"raw",
"log",
"text",
"to",
"array",
"."
] | 742a2550746c9346d463249ba16b8fba9ac9cf97 | https://github.com/laravel-admin-extensions/log-viewer/blob/742a2550746c9346d463249ba16b8fba9ac9cf97/src/LogViewer.php#L318-L351 | train |
MUlt1mate/cron-manager | examples/file_storage/models/TaskFile.php | TaskFile.taskFileLoad | public static function taskFileLoad()
{
if (file_exists(self::$data_file)) {
$data = file_get_contents(self::$data_file);
$data = unserialize($data);
}
if (empty($data)) {
$data = array();
}
return $data;
} | php | public static function taskFileLoad()
{
if (file_exists(self::$data_file)) {
$data = file_get_contents(self::$data_file);
$data = unserialize($data);
}
if (empty($data)) {
$data = array();
}
return $data;
} | [
"public",
"static",
"function",
"taskFileLoad",
"(",
")",
"{",
"if",
"(",
"file_exists",
"(",
"self",
"::",
"$",
"data_file",
")",
")",
"{",
"$",
"data",
"=",
"file_get_contents",
"(",
"self",
"::",
"$",
"data_file",
")",
";",
"$",
"data",
"=",
"unseri... | Reads file from disk and returns array of tasks
@return array | [
"Reads",
"file",
"from",
"disk",
"and",
"returns",
"array",
"of",
"tasks"
] | ccea814d338a0b5edf0e2008ebfe07038090ca5a | https://github.com/MUlt1mate/cron-manager/blob/ccea814d338a0b5edf0e2008ebfe07038090ca5a/examples/file_storage/models/TaskFile.php#L30-L41 | train |
MUlt1mate/cron-manager | examples/file_storage/models/TaskFile.php | TaskFile.taskGet | public static function taskGet($task_id)
{
$tasks = self::taskFileLoad();
if (isset($tasks[$task_id])) {
return $tasks[$task_id];
}
return false;
} | php | public static function taskGet($task_id)
{
$tasks = self::taskFileLoad();
if (isset($tasks[$task_id])) {
return $tasks[$task_id];
}
return false;
} | [
"public",
"static",
"function",
"taskGet",
"(",
"$",
"task_id",
")",
"{",
"$",
"tasks",
"=",
"self",
"::",
"taskFileLoad",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"tasks",
"[",
"$",
"task_id",
"]",
")",
")",
"{",
"return",
"$",
"tasks",
"[",
... | Returns tasks with given id
@param int $task_id
@return TaskInterface | [
"Returns",
"tasks",
"with",
"given",
"id"
] | ccea814d338a0b5edf0e2008ebfe07038090ca5a | https://github.com/MUlt1mate/cron-manager/blob/ccea814d338a0b5edf0e2008ebfe07038090ca5a/examples/file_storage/models/TaskFile.php#L59-L66 | train |
MUlt1mate/cron-manager | examples/file_storage/models/TaskFile.php | TaskFile.find | public static function find($task_ids)
{
if (!is_array($task_ids)) {
$task_ids = array($task_ids);
}
$tasks = self::getAll();
foreach ($tasks as $key => $task) {
/**
* @var self $task
*/
if (!in_array($task->task_id, $task_ids)) {
unset($tasks[$key]);
}
}
return $tasks;
} | php | public static function find($task_ids)
{
if (!is_array($task_ids)) {
$task_ids = array($task_ids);
}
$tasks = self::getAll();
foreach ($tasks as $key => $task) {
/**
* @var self $task
*/
if (!in_array($task->task_id, $task_ids)) {
unset($tasks[$key]);
}
}
return $tasks;
} | [
"public",
"static",
"function",
"find",
"(",
"$",
"task_ids",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"task_ids",
")",
")",
"{",
"$",
"task_ids",
"=",
"array",
"(",
"$",
"task_ids",
")",
";",
"}",
"$",
"tasks",
"=",
"self",
"::",
"getAll",
... | Returns array of tasks with specified ids
@param array $task_ids array of task ids
@return array | [
"Returns",
"array",
"of",
"tasks",
"with",
"specified",
"ids"
] | ccea814d338a0b5edf0e2008ebfe07038090ca5a | https://github.com/MUlt1mate/cron-manager/blob/ccea814d338a0b5edf0e2008ebfe07038090ca5a/examples/file_storage/models/TaskFile.php#L82-L97 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.