repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
kiwiz/esquery | src/Result.php | Result.processResults | private function processResults($response_set, $meta) {
// If getting an aggregation, results appear on the first response.
if(count($meta['aggs']) > 0) {
return $this->processAggResults($response_set[0], $meta);
}
// If we're only returning hits, we can return the count here.
if($meta['count'] && !$meta['post_query']) {
return ['count' => array_sum(array_map(function($x) { return $x['hits']['total']; }, $response_set))];
}
$results = [];
$this->processHitResults($results, $response_set, $meta);
return $results;
} | php | private function processResults($response_set, $meta) {
// If getting an aggregation, results appear on the first response.
if(count($meta['aggs']) > 0) {
return $this->processAggResults($response_set[0], $meta);
}
// If we're only returning hits, we can return the count here.
if($meta['count'] && !$meta['post_query']) {
return ['count' => array_sum(array_map(function($x) { return $x['hits']['total']; }, $response_set))];
}
$results = [];
$this->processHitResults($results, $response_set, $meta);
return $results;
} | [
"private",
"function",
"processResults",
"(",
"$",
"response_set",
",",
"$",
"meta",
")",
"{",
"// If getting an aggregation, results appear on the first response.",
"if",
"(",
"count",
"(",
"$",
"meta",
"[",
"'aggs'",
"]",
")",
">",
"0",
")",
"{",
"return",
"$"... | Process raw results and return parsed results. | [
"Process",
"raw",
"results",
"and",
"return",
"parsed",
"results",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L511-L525 |
kiwiz/esquery | src/Result.php | Result.processAggResults | private function processAggResults($response, $meta) {
$aggs = $response['aggregations'];
if(!count($aggs)) {
throw new Exception('No keys in aggregation');
}
$ret = $this->processAggResultsRecurse(null, $aggs, $meta['aggs'], 0);
// If we don't have a post query, we can return the count here.
if($meta['count'] && !$meta['post_query']) {
$ret = ['count' => count($ret)];
}
return $ret;
} | php | private function processAggResults($response, $meta) {
$aggs = $response['aggregations'];
if(!count($aggs)) {
throw new Exception('No keys in aggregation');
}
$ret = $this->processAggResultsRecurse(null, $aggs, $meta['aggs'], 0);
// If we don't have a post query, we can return the count here.
if($meta['count'] && !$meta['post_query']) {
$ret = ['count' => count($ret)];
}
return $ret;
} | [
"private",
"function",
"processAggResults",
"(",
"$",
"response",
",",
"$",
"meta",
")",
"{",
"$",
"aggs",
"=",
"$",
"response",
"[",
"'aggregations'",
"]",
";",
"if",
"(",
"!",
"count",
"(",
"$",
"aggs",
")",
")",
"{",
"throw",
"new",
"Exception",
"... | Process any aggregation results recursively. | [
"Process",
"any",
"aggregation",
"results",
"recursively",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L530-L543 |
kiwiz/esquery | src/Result.php | Result.processHitResults | private function processHitResults(&$results, $response_set, $meta) {
// Determine what fields we want to rename.
$fields = null;
if(count($meta['map'])) {
$fields = $meta['map'];
}
foreach($response_set as $response) {
foreach($response['hits']['hits'] as $result) {
$data = $result['_source'];
if($fields) {
// Map fields.
foreach($fields as $old_field=>$new_field) {
if(array_key_exists($old_field, $data)) {
$data[$new_field] = $data[$old_field];
unset($data[$old_field]);
}
}
}
unset($result['_source']);
$result = array_merge($result, $data);
if($meta['flatten']) {
$result = $this->processHitResultsRecurse($result);
}
$results[] = $result;
}
}
} | php | private function processHitResults(&$results, $response_set, $meta) {
// Determine what fields we want to rename.
$fields = null;
if(count($meta['map'])) {
$fields = $meta['map'];
}
foreach($response_set as $response) {
foreach($response['hits']['hits'] as $result) {
$data = $result['_source'];
if($fields) {
// Map fields.
foreach($fields as $old_field=>$new_field) {
if(array_key_exists($old_field, $data)) {
$data[$new_field] = $data[$old_field];
unset($data[$old_field]);
}
}
}
unset($result['_source']);
$result = array_merge($result, $data);
if($meta['flatten']) {
$result = $this->processHitResultsRecurse($result);
}
$results[] = $result;
}
}
} | [
"private",
"function",
"processHitResults",
"(",
"&",
"$",
"results",
",",
"$",
"response_set",
",",
"$",
"meta",
")",
"{",
"// Determine what fields we want to rename.",
"$",
"fields",
"=",
"null",
";",
"if",
"(",
"count",
"(",
"$",
"meta",
"[",
"'map'",
"]... | Process any hit results. | [
"Process",
"any",
"hit",
"results",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L548-L577 |
kiwiz/esquery | src/Result.php | Result.processHitResultsRecurse | private function processHitResultsRecurse($results, $prefix=null) {
if(!is_array($results)) {
return [$prefix => $results];
}
$ret = [];
foreach($results as $key=>$result) {
// Flatten arrays.
$sub_prefix = is_null($prefix) ? $key:"$prefix.$key";
$ret = array_merge($ret, $this->processHitResultsRecurse($result, $sub_prefix));
}
return $ret;
} | php | private function processHitResultsRecurse($results, $prefix=null) {
if(!is_array($results)) {
return [$prefix => $results];
}
$ret = [];
foreach($results as $key=>$result) {
// Flatten arrays.
$sub_prefix = is_null($prefix) ? $key:"$prefix.$key";
$ret = array_merge($ret, $this->processHitResultsRecurse($result, $sub_prefix));
}
return $ret;
} | [
"private",
"function",
"processHitResultsRecurse",
"(",
"$",
"results",
",",
"$",
"prefix",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"results",
")",
")",
"{",
"return",
"[",
"$",
"prefix",
"=>",
"$",
"results",
"]",
";",
"}",
"$",... | Process any hit results recursively. | [
"Process",
"any",
"hit",
"results",
"recursively",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L582-L594 |
kiwiz/esquery | src/Result.php | Result.processAggResultsRecurse | private function processAggResultsRecurse($pkey, $node, $queries, $i) {
// If terminal node, return the actual value.
if($i >= count($queries)) {
return [[$pkey => $node['key'], 'count' => $node['doc_count']]];
}
$ret = [];
$pvalue = array_key_exists('key', $node) ? $node['key']:null;
$key = $queries[$i][2];
$node = $node['$$$_' . $key];
$head = [];
if(!is_null($pkey)) {
$head = [$pkey => $pvalue];
}
if(!array_key_exists('buckets', $node)) {
$ret[] = array_merge($head, $node);
} else {
$buckets = $node['buckets'];
foreach($buckets as $bucket) {
$data = $this->processAggResultsRecurse($key, $bucket, $queries, $i + 1);
foreach($data as $row) {
$ret[] = array_merge($row, $head);
}
}
}
return $ret;
} | php | private function processAggResultsRecurse($pkey, $node, $queries, $i) {
// If terminal node, return the actual value.
if($i >= count($queries)) {
return [[$pkey => $node['key'], 'count' => $node['doc_count']]];
}
$ret = [];
$pvalue = array_key_exists('key', $node) ? $node['key']:null;
$key = $queries[$i][2];
$node = $node['$$$_' . $key];
$head = [];
if(!is_null($pkey)) {
$head = [$pkey => $pvalue];
}
if(!array_key_exists('buckets', $node)) {
$ret[] = array_merge($head, $node);
} else {
$buckets = $node['buckets'];
foreach($buckets as $bucket) {
$data = $this->processAggResultsRecurse($key, $bucket, $queries, $i + 1);
foreach($data as $row) {
$ret[] = array_merge($row, $head);
}
}
}
return $ret;
} | [
"private",
"function",
"processAggResultsRecurse",
"(",
"$",
"pkey",
",",
"$",
"node",
",",
"$",
"queries",
",",
"$",
"i",
")",
"{",
"// If terminal node, return the actual value.",
"if",
"(",
"$",
"i",
">=",
"count",
"(",
"$",
"queries",
")",
")",
"{",
"r... | Process any aggregation results recursively. | [
"Process",
"any",
"aggregation",
"results",
"recursively",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L599-L626 |
kiwiz/esquery | src/Result.php | Result.postProcessResults | private function postProcessResults($post_query, $results, $meta) {
if(is_null($post_query)) {
return $results;
}
$ret = [];
switch($post_query[0]) {
// Join up all results with a given key:value.
case Token::C_TRANS:
$key = $post_query[1];
$ret_map = [];
foreach($results as $result) {
if(!array_key_exists($key, $result)) {
continue;
}
$value = $result[$key];
if(!array_key_exists($value, $ret_map)) {
$ret_map[$value] = [];
}
$ret_map[$value] = array_merge($ret_map[$value], $result);
}
$ret = array_values($ret_map);
break;
default:
throw new Exception('Unexpected command');
}
// If we wanted a count, generate it now.
if($meta['count']) {
$ret = ['count' => count($ret)];
}
return $ret;
} | php | private function postProcessResults($post_query, $results, $meta) {
if(is_null($post_query)) {
return $results;
}
$ret = [];
switch($post_query[0]) {
// Join up all results with a given key:value.
case Token::C_TRANS:
$key = $post_query[1];
$ret_map = [];
foreach($results as $result) {
if(!array_key_exists($key, $result)) {
continue;
}
$value = $result[$key];
if(!array_key_exists($value, $ret_map)) {
$ret_map[$value] = [];
}
$ret_map[$value] = array_merge($ret_map[$value], $result);
}
$ret = array_values($ret_map);
break;
default:
throw new Exception('Unexpected command');
}
// If we wanted a count, generate it now.
if($meta['count']) {
$ret = ['count' => count($ret)];
}
return $ret;
} | [
"private",
"function",
"postProcessResults",
"(",
"$",
"post_query",
",",
"$",
"results",
",",
"$",
"meta",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"post_query",
")",
")",
"{",
"return",
"$",
"results",
";",
"}",
"$",
"ret",
"=",
"[",
"]",
";",
"... | Run any post-processing steps on the results. | [
"Run",
"any",
"post",
"-",
"processing",
"steps",
"on",
"the",
"results",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L631-L667 |
Kaishiyoku/laravel-menu | src/Kaishiyoku/Menu/Data/MenuContainer.php | MenuContainer.render | public function render()
{
$output = '';
foreach ($this->entries as $entry) {
$entryAttributes = [];
if ($entry instanceof Dropdown) {
$entryAttributes['class'] = 'dropdown';
foreach ($entry->getEntries() as $dropdownEntry) {
if ($dropdownEntry instanceof LinkRoute) {
foreach ($dropdownEntry->getAdditionalRouteNames() as $additionalRouteName) {
if (MenuHelper::isCurrentRoute($additionalRouteName)) {
$entryAttributes['class'] .= ' active';
}
}
if (MenuHelper::isCurrentRoute($dropdownEntry->getName())) {
$entryAttributes['class'] .= ' active';
}
}
}
} elseif ($entry instanceof Content) {
$entryAttributes['class'] = 'navbar-text';
} else if ($entry instanceof Link) {
} else {
if (!array_key_exists('class', $entryAttributes)) {
$entryAttributes['class'] = '';
}
foreach ($entry->getAdditionalRouteNames() as $additionalRouteName) {
if (MenuHelper::isCurrentRoute($additionalRouteName)) {
$entryAttributes['class'] .= ' active';
}
}
if (MenuHelper::isCurrentRoute($entry->getName())) {
$entryAttributes['class'] .= ' active';
}
}
if ($entry->isVisible()) {
if (count(MenuHelper::getConfig()->getListElementClasses()) > 0) {
if (!array_key_exists('class', $entryAttributes)) {
$entryAttributes['class'] = '';
}
foreach (MenuHelper::getConfig()->getListElementClasses() as $listElementClass) {
$entryAttributes['class'] .= ' ' . $listElementClass;
}
}
$output .= '<li ' . Html::attributes($entryAttributes) . '>' . $entry->render() . '</li>';
}
}
return '<ul ' . Html::attributes($this->attributes) . '>' . $output . '</ul>';
} | php | public function render()
{
$output = '';
foreach ($this->entries as $entry) {
$entryAttributes = [];
if ($entry instanceof Dropdown) {
$entryAttributes['class'] = 'dropdown';
foreach ($entry->getEntries() as $dropdownEntry) {
if ($dropdownEntry instanceof LinkRoute) {
foreach ($dropdownEntry->getAdditionalRouteNames() as $additionalRouteName) {
if (MenuHelper::isCurrentRoute($additionalRouteName)) {
$entryAttributes['class'] .= ' active';
}
}
if (MenuHelper::isCurrentRoute($dropdownEntry->getName())) {
$entryAttributes['class'] .= ' active';
}
}
}
} elseif ($entry instanceof Content) {
$entryAttributes['class'] = 'navbar-text';
} else if ($entry instanceof Link) {
} else {
if (!array_key_exists('class', $entryAttributes)) {
$entryAttributes['class'] = '';
}
foreach ($entry->getAdditionalRouteNames() as $additionalRouteName) {
if (MenuHelper::isCurrentRoute($additionalRouteName)) {
$entryAttributes['class'] .= ' active';
}
}
if (MenuHelper::isCurrentRoute($entry->getName())) {
$entryAttributes['class'] .= ' active';
}
}
if ($entry->isVisible()) {
if (count(MenuHelper::getConfig()->getListElementClasses()) > 0) {
if (!array_key_exists('class', $entryAttributes)) {
$entryAttributes['class'] = '';
}
foreach (MenuHelper::getConfig()->getListElementClasses() as $listElementClass) {
$entryAttributes['class'] .= ' ' . $listElementClass;
}
}
$output .= '<li ' . Html::attributes($entryAttributes) . '>' . $entry->render() . '</li>';
}
}
return '<ul ' . Html::attributes($this->attributes) . '>' . $output . '</ul>';
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"output",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"entries",
"as",
"$",
"entry",
")",
"{",
"$",
"entryAttributes",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"entry",
"instanceof",
"Dropdown",
... | Get the evaluated contents of the object.
@return string | [
"Get",
"the",
"evaluated",
"contents",
"of",
"the",
"object",
"."
] | train | https://github.com/Kaishiyoku/laravel-menu/blob/0a1aa772f19002d354f0c338e603d98c49d10a7a/src/Kaishiyoku/Menu/Data/MenuContainer.php#L49-L108 |
schmunk42/p3extensions | validators/P3ArrayValidator.php | P3ArrayValidator.validateAttribute | protected function validateAttribute($object,$attribute) {
$value=$object->$attribute;
if($this->allowEmpty && $this->isEmpty($value))
return;
elseif(!is_array($value)) {
$message=$this->message!==null?$this->message:Yii::t('P2Module.p2','{attribute} is not valid.');
$this->addError($object,$attribute,$message);
}
$length=count($value);
if($this->min!==null && $length<$this->min) {
$message=$this->tooShort!==null?$this->tooShort:Yii::t('P2Module.p2','{attribute} is too short (minimum is {min} entries).');
$this->addError($object,$attribute,$message,array('{min}'=>$this->min));
}
if($this->max!==null && $length>$this->max) {
$message=$this->tooLong!==null?$this->tooLong:Yii::t('P2Module.p2','{attribute} is too long (maximum is {max} entries).');
$this->addError($object,$attribute,$message,array('{max}'=>$this->max));
}
if($this->is!==null && $length!==$this->is) {
$message=$this->message!==null?$this->message:Yii::t('P2Module.p2','{attribute} is of the wrong length (should be {length} entries).');
$this->addError($object,$attribute,$message,array('{length}'=>$this->is));
}
} | php | protected function validateAttribute($object,$attribute) {
$value=$object->$attribute;
if($this->allowEmpty && $this->isEmpty($value))
return;
elseif(!is_array($value)) {
$message=$this->message!==null?$this->message:Yii::t('P2Module.p2','{attribute} is not valid.');
$this->addError($object,$attribute,$message);
}
$length=count($value);
if($this->min!==null && $length<$this->min) {
$message=$this->tooShort!==null?$this->tooShort:Yii::t('P2Module.p2','{attribute} is too short (minimum is {min} entries).');
$this->addError($object,$attribute,$message,array('{min}'=>$this->min));
}
if($this->max!==null && $length>$this->max) {
$message=$this->tooLong!==null?$this->tooLong:Yii::t('P2Module.p2','{attribute} is too long (maximum is {max} entries).');
$this->addError($object,$attribute,$message,array('{max}'=>$this->max));
}
if($this->is!==null && $length!==$this->is) {
$message=$this->message!==null?$this->message:Yii::t('P2Module.p2','{attribute} is of the wrong length (should be {length} entries).');
$this->addError($object,$attribute,$message,array('{length}'=>$this->is));
}
} | [
"protected",
"function",
"validateAttribute",
"(",
"$",
"object",
",",
"$",
"attribute",
")",
"{",
"$",
"value",
"=",
"$",
"object",
"->",
"$",
"attribute",
";",
"if",
"(",
"$",
"this",
"->",
"allowEmpty",
"&&",
"$",
"this",
"->",
"isEmpty",
"(",
"$",
... | Validates the attribute of the object.
If there is any error, the error message is added to the object.
@param CModel the object being validated
@param Array the attribute being validated | [
"Validates",
"the",
"attribute",
"of",
"the",
"object",
".",
"If",
"there",
"is",
"any",
"error",
"the",
"error",
"message",
"is",
"added",
"to",
"the",
"object",
"."
] | train | https://github.com/schmunk42/p3extensions/blob/93999c06fc8e3eadd83983d001df231e46b06838/validators/P3ArrayValidator.php#L53-L75 |
awurth/SlimHelpers | Controller/RouterTrait.php | RouterTrait.path | protected function path($route, array $params = [], array $queryParams = [])
{
return $this->container['router']->pathFor($route, $params, $queryParams);
} | php | protected function path($route, array $params = [], array $queryParams = [])
{
return $this->container['router']->pathFor($route, $params, $queryParams);
} | [
"protected",
"function",
"path",
"(",
"$",
"route",
",",
"array",
"$",
"params",
"=",
"[",
"]",
",",
"array",
"$",
"queryParams",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"container",
"[",
"'router'",
"]",
"->",
"pathFor",
"(",
"$",
"r... | Generates a URL from a route.
@param string $route
@param array $params
@param array $queryParams
@return string | [
"Generates",
"a",
"URL",
"from",
"a",
"route",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/RouterTrait.php#L18-L21 |
awurth/SlimHelpers | Controller/RouterTrait.php | RouterTrait.relativePath | protected function relativePath($route, array $params = [], array $queryParams = [])
{
return $this->container['router']->relativePathFor($route, $params, $queryParams);
} | php | protected function relativePath($route, array $params = [], array $queryParams = [])
{
return $this->container['router']->relativePathFor($route, $params, $queryParams);
} | [
"protected",
"function",
"relativePath",
"(",
"$",
"route",
",",
"array",
"$",
"params",
"=",
"[",
"]",
",",
"array",
"$",
"queryParams",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"container",
"[",
"'router'",
"]",
"->",
"relativePathFor",
... | Generates a relative URL from a route.
@param string $route
@param array $params
@param array $queryParams
@return string | [
"Generates",
"a",
"relative",
"URL",
"from",
"a",
"route",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/RouterTrait.php#L32-L35 |
awurth/SlimHelpers | Controller/RouterTrait.php | RouterTrait.redirect | protected function redirect(Response $response, $route, array $params = [])
{
return $response->withRedirect($this->container['router']->pathFor($route, $params));
} | php | protected function redirect(Response $response, $route, array $params = [])
{
return $response->withRedirect($this->container['router']->pathFor($route, $params));
} | [
"protected",
"function",
"redirect",
"(",
"Response",
"$",
"response",
",",
"$",
"route",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"response",
"->",
"withRedirect",
"(",
"$",
"this",
"->",
"container",
"[",
"'router'",
"]",
... | Redirects to a route.
@param Response $response
@param string $route
@param array $params
@return Response | [
"Redirects",
"to",
"a",
"route",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/RouterTrait.php#L46-L49 |
txj123/zilf | src/Zilf/Curl/Client.php | Client.get_curlObj | public function get_curlObj()
{
//curl 请求的句柄
$curlObj = curl_init();
$this->_set_method();
if (empty($this->config['CURLOPT_URL'])) {
throw new CurlException('请设置请求的url');
}
//TRUE 将curl_exec()获取的信息以字符串返回,而不是直接输出。
$this->config['CURLOPT_RETURNTRANSFER'] = true;
//启用时会将头文件的信息作为数据流输出。
if (!isset($this->config['CURLOPT_HEADER'])) {
$this->config['CURLOPT_HEADER'] = true;
}
//发送请求的字符串
if (!isset($this->config['CURLINFO_HEADER_OUT'])) {
$this->config['CURLINFO_HEADER_OUT'] = true;
}
//判断是否是ssl请求
if (stripos($this->config['CURLOPT_URL'], 'http://') === 0) {
} elseif (stripos($this->config['CURLOPT_URL'], 'https://') === 0) {
$this->set_ssl();
} else {
throw new CurlException('请求的url必须以http或https开头');
}
foreach ($this->config as $key => $row) {
curl_setopt($curlObj, $this->curlOptions[$key], $row);
}
return $curlObj;
} | php | public function get_curlObj()
{
//curl 请求的句柄
$curlObj = curl_init();
$this->_set_method();
if (empty($this->config['CURLOPT_URL'])) {
throw new CurlException('请设置请求的url');
}
//TRUE 将curl_exec()获取的信息以字符串返回,而不是直接输出。
$this->config['CURLOPT_RETURNTRANSFER'] = true;
//启用时会将头文件的信息作为数据流输出。
if (!isset($this->config['CURLOPT_HEADER'])) {
$this->config['CURLOPT_HEADER'] = true;
}
//发送请求的字符串
if (!isset($this->config['CURLINFO_HEADER_OUT'])) {
$this->config['CURLINFO_HEADER_OUT'] = true;
}
//判断是否是ssl请求
if (stripos($this->config['CURLOPT_URL'], 'http://') === 0) {
} elseif (stripos($this->config['CURLOPT_URL'], 'https://') === 0) {
$this->set_ssl();
} else {
throw new CurlException('请求的url必须以http或https开头');
}
foreach ($this->config as $key => $row) {
curl_setopt($curlObj, $this->curlOptions[$key], $row);
}
return $curlObj;
} | [
"public",
"function",
"get_curlObj",
"(",
")",
"{",
"//curl 请求的句柄",
"$",
"curlObj",
"=",
"curl_init",
"(",
")",
";",
"$",
"this",
"->",
"_set_method",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"config",
"[",
"'CURLOPT_URL'",
"]",
")",
... | curl_init 对象 | [
"curl_init",
"对象"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/Client.php#L698-L735 |
txj123/zilf | src/Zilf/Curl/Client.php | Client.add_upload_file | public function add_upload_file(string $postname, string $filename, string $mimetype = '')
{
$this->parameters[$postname] = new \CURLFile($filename, $mimetype, $postname);
return $this;
} | php | public function add_upload_file(string $postname, string $filename, string $mimetype = '')
{
$this->parameters[$postname] = new \CURLFile($filename, $mimetype, $postname);
return $this;
} | [
"public",
"function",
"add_upload_file",
"(",
"string",
"$",
"postname",
",",
"string",
"$",
"filename",
",",
"string",
"$",
"mimetype",
"=",
"''",
")",
"{",
"$",
"this",
"->",
"parameters",
"[",
"$",
"postname",
"]",
"=",
"new",
"\\",
"CURLFile",
"(",
... | 添加需要上传的文件
@param string $postname 文件名称
@param string $filename 文件绝对路径
@param string $mimetype 文件的mimetype
@return $this | [
"添加需要上传的文件"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/Client.php#L835-L841 |
txj123/zilf | src/Zilf/Curl/Client.php | Client.set_ssl | public function set_ssl(string $cacert = '', string $sslcert = '', string $sslcertpasswd = '', $ssl_verifyhost = 2)
{
if ($sslcert) {
$this->config['CURLOPT_SSLCERT'] = $sslcert;
}
if ($sslcertpasswd) {
$this->config['CURLOPT_SSLCERTPASSWD'] = $sslcertpasswd;
}
if (!empty($cacert_path)) {
$this->config['CURLOPT_SSL_VERIFYPEER'] = true; // 只信任CA颁布的证书
$this->config['CURLOPT_CAINFO'] = $cacert; // CA根证书(用来验证的网站证书是否是CA颁布)
} else {
$this->config['CURLOPT_SSL_VERIFYPEER'] = false;
}
$this->config['CURLOPT_SSL_VERIFYHOST'] = $ssl_verifyhost;
return $this;
} | php | public function set_ssl(string $cacert = '', string $sslcert = '', string $sslcertpasswd = '', $ssl_verifyhost = 2)
{
if ($sslcert) {
$this->config['CURLOPT_SSLCERT'] = $sslcert;
}
if ($sslcertpasswd) {
$this->config['CURLOPT_SSLCERTPASSWD'] = $sslcertpasswd;
}
if (!empty($cacert_path)) {
$this->config['CURLOPT_SSL_VERIFYPEER'] = true; // 只信任CA颁布的证书
$this->config['CURLOPT_CAINFO'] = $cacert; // CA根证书(用来验证的网站证书是否是CA颁布)
} else {
$this->config['CURLOPT_SSL_VERIFYPEER'] = false;
}
$this->config['CURLOPT_SSL_VERIFYHOST'] = $ssl_verifyhost;
return $this;
} | [
"public",
"function",
"set_ssl",
"(",
"string",
"$",
"cacert",
"=",
"''",
",",
"string",
"$",
"sslcert",
"=",
"''",
",",
"string",
"$",
"sslcertpasswd",
"=",
"''",
",",
"$",
"ssl_verifyhost",
"=",
"2",
")",
"{",
"if",
"(",
"$",
"sslcert",
")",
"{",
... | 设置ssl请求
@param string $cacert //
CA根证书(用来验证的网站证书是否是CA颁布)
@param string $sslcert 一个包含 PEM
格式证书的文件名。
@param string $sslcertpasswd 使用CURLOPT_SSLCERT证书需要的密码。
@param int $ssl_verifyhost 设置为 1 是检查服务器SSL证书中是否存在一个公用名 设置成
2,会检查公用名是否存在,并且是否与提供的主机名匹配。 0
为不检查名称。 在生产环境中,这个值应该是 2(默认值)。
@return $this | [
"设置ssl请求"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/Client.php#L878-L900 |
txj123/zilf | src/Zilf/Curl/Client.php | Client._set_method | private function _set_method()
{
switch (strtoupper($this->method)) {
case 'HEAD':
//CURLOPT_NOBODY TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。
if (!isset($this->config['CURLOPT_NOBODY'])) {
$this->config['CURLOPT_NOBODY'] = true;
}
break;
case 'GET':
if (!empty($this->config['parameters'])) {
$url = (stripos($this->config['CURLOPT_URL'], '?') !== false) ? '&' : '?';
if (is_array($this->config['parameters'])) { //参数是数组
$url .= http_build_query($this->_parameters, '', '&');
} else { //参数是字符串
$url .= $this->config['parameters'];
}
$this->config['CURLOPT_URL'] = $url;
unset($url);
}
$this->config['CURLOPT_HTTPGET'] = true; //TRUE 时会设置 HTTP 的 method 为 GET
break;
case 'POST':
if (!empty($this->parameters) && is_array($this->parameters)) { //参数是数组
$data = http_build_query($this->parameters); //为了更好的兼容性
} else { //参数是字符串
$data = $this->parameters;
}
$this->config['CURLOPT_POSTFIELDS'] = $data; //post请求的数据
$this->config['CURLOPT_POST'] = true; //TRUE 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
unset($data);
break;
default:
throw new CurlException('该请求方式不支持!');
}
} | php | private function _set_method()
{
switch (strtoupper($this->method)) {
case 'HEAD':
//CURLOPT_NOBODY TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。
if (!isset($this->config['CURLOPT_NOBODY'])) {
$this->config['CURLOPT_NOBODY'] = true;
}
break;
case 'GET':
if (!empty($this->config['parameters'])) {
$url = (stripos($this->config['CURLOPT_URL'], '?') !== false) ? '&' : '?';
if (is_array($this->config['parameters'])) { //参数是数组
$url .= http_build_query($this->_parameters, '', '&');
} else { //参数是字符串
$url .= $this->config['parameters'];
}
$this->config['CURLOPT_URL'] = $url;
unset($url);
}
$this->config['CURLOPT_HTTPGET'] = true; //TRUE 时会设置 HTTP 的 method 为 GET
break;
case 'POST':
if (!empty($this->parameters) && is_array($this->parameters)) { //参数是数组
$data = http_build_query($this->parameters); //为了更好的兼容性
} else { //参数是字符串
$data = $this->parameters;
}
$this->config['CURLOPT_POSTFIELDS'] = $data; //post请求的数据
$this->config['CURLOPT_POST'] = true; //TRUE 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
unset($data);
break;
default:
throw new CurlException('该请求方式不支持!');
}
} | [
"private",
"function",
"_set_method",
"(",
")",
"{",
"switch",
"(",
"strtoupper",
"(",
"$",
"this",
"->",
"method",
")",
")",
"{",
"case",
"'HEAD'",
":",
"//CURLOPT_NOBODY TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。",
"if",
"(",
"!",
"isset",
"(",
"... | 设置请求的方法,以及请求参数的设置
@throws \Exception | [
"设置请求的方法,以及请求参数的设置"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/Client.php#L907-L955 |
txj123/zilf | src/Zilf/Curl/Client.php | Client.set_httpHeader | public function set_httpHeader($data = [])
{
//将二维数组转为一维数组
$result = [];
foreach ($data as $key => $row) {
if (is_array($row)) {
if (isset($row[0])) {
$result[] = $row[0];
}
} else {
$result[] = $row;
}
}
$this->config['CURLOPT_HTTPHEADER'] = $data;
return $this;
} | php | public function set_httpHeader($data = [])
{
//将二维数组转为一维数组
$result = [];
foreach ($data as $key => $row) {
if (is_array($row)) {
if (isset($row[0])) {
$result[] = $row[0];
}
} else {
$result[] = $row;
}
}
$this->config['CURLOPT_HTTPHEADER'] = $data;
return $this;
} | [
"public",
"function",
"set_httpHeader",
"(",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"//将二维数组转为一维数组",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"row",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"ro... | 设置文件的头信息
@param array $data
@return $this | [
"设置文件的头信息"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/Client.php#L993-L1010 |
txj123/zilf | src/Zilf/Curl/Client.php | Client.set_proxy | public function set_proxy($proxy,$userpwd='')
{
$this->config['CURLOPT_PROXY'] = $proxy;
if ($userpwd) {
$this->config['CURLOPT_PROXYUSERPWD'] = $userpwd;
}
return $this;
} | php | public function set_proxy($proxy,$userpwd='')
{
$this->config['CURLOPT_PROXY'] = $proxy;
if ($userpwd) {
$this->config['CURLOPT_PROXYUSERPWD'] = $userpwd;
}
return $this;
} | [
"public",
"function",
"set_proxy",
"(",
"$",
"proxy",
",",
"$",
"userpwd",
"=",
"''",
")",
"{",
"$",
"this",
"->",
"config",
"[",
"'CURLOPT_PROXY'",
"]",
"=",
"$",
"proxy",
";",
"if",
"(",
"$",
"userpwd",
")",
"{",
"$",
"this",
"->",
"config",
"[",... | 设置代理请求
@param $proxy 如: 192.168.2.2:220
@param string $userpwd 如:
admin:admin
@return $this | [
"设置代理请求"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Curl/Client.php#L1020-L1029 |
geocoder-php/maxmind-provider | MaxMind.php | MaxMind.executeQuery | private function executeQuery(string $url): AddressCollection
{
$fields = $this->fieldsForService($this->service);
$content = $this->getUrlContents($url);
$data = str_getcsv($content);
if (in_array(end($data), ['INVALID_LICENSE_KEY', 'LICENSE_REQUIRED'])) {
throw new InvalidCredentials('API Key provided is not valid.');
}
if ('IP_NOT_FOUND' === end($data)) {
return new AddressCollection([]);
}
if (count($fields) !== count($data)) {
throw InvalidServerResponse::create($url);
}
$data = array_combine($fields, $data);
$data = array_map(function ($value) {
return '' === $value ? null : $value;
}, $data);
if (empty($data['country']) && !empty($data['countryCode'])) {
$data['country'] = $this->countryCodeToCountryName($data['countryCode']);
}
$data = $this->replaceAdmins($data);
$data['providedBy'] = $this->getName();
return new AddressCollection([Address::createFromArray($data)]);
} | php | private function executeQuery(string $url): AddressCollection
{
$fields = $this->fieldsForService($this->service);
$content = $this->getUrlContents($url);
$data = str_getcsv($content);
if (in_array(end($data), ['INVALID_LICENSE_KEY', 'LICENSE_REQUIRED'])) {
throw new InvalidCredentials('API Key provided is not valid.');
}
if ('IP_NOT_FOUND' === end($data)) {
return new AddressCollection([]);
}
if (count($fields) !== count($data)) {
throw InvalidServerResponse::create($url);
}
$data = array_combine($fields, $data);
$data = array_map(function ($value) {
return '' === $value ? null : $value;
}, $data);
if (empty($data['country']) && !empty($data['countryCode'])) {
$data['country'] = $this->countryCodeToCountryName($data['countryCode']);
}
$data = $this->replaceAdmins($data);
$data['providedBy'] = $this->getName();
return new AddressCollection([Address::createFromArray($data)]);
} | [
"private",
"function",
"executeQuery",
"(",
"string",
"$",
"url",
")",
":",
"AddressCollection",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"fieldsForService",
"(",
"$",
"this",
"->",
"service",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"getUrlC... | @param string $url
@return Collection | [
"@param",
"string",
"$url"
] | train | https://github.com/geocoder-php/maxmind-provider/blob/eddb07f690036fc95dd411de42158a68fb114cd8/MaxMind.php#L114-L145 |
geocoder-php/maxmind-provider | MaxMind.php | MaxMind.fieldsForService | private function fieldsForService(string $service): array
{
switch ($service) {
case self::CITY_EXTENDED_SERVICE:
return [
'countryCode',
'regionCode',
'locality',
'postalCode',
'latitude',
'longitude',
'metroCode',
'areaCode',
'isp',
'organization',
];
case self::OMNI_SERVICE:
return [
'countryCode',
'countryName',
'regionCode',
'region',
'locality',
'latitude',
'longitude',
'metroCode',
'areaCode',
'timezone',
'continentCode',
'postalCode',
'isp',
'organization',
'domain',
'asNumber',
'netspeed',
'userType',
'accuracyRadius',
'countryConfidence',
'cityConfidence',
'regionConfidence',
'postalConfidence',
'error',
];
default:
throw new UnsupportedOperation(sprintf('Unknown MaxMind service %s', $service));
}
} | php | private function fieldsForService(string $service): array
{
switch ($service) {
case self::CITY_EXTENDED_SERVICE:
return [
'countryCode',
'regionCode',
'locality',
'postalCode',
'latitude',
'longitude',
'metroCode',
'areaCode',
'isp',
'organization',
];
case self::OMNI_SERVICE:
return [
'countryCode',
'countryName',
'regionCode',
'region',
'locality',
'latitude',
'longitude',
'metroCode',
'areaCode',
'timezone',
'continentCode',
'postalCode',
'isp',
'organization',
'domain',
'asNumber',
'netspeed',
'userType',
'accuracyRadius',
'countryConfidence',
'cityConfidence',
'regionConfidence',
'postalConfidence',
'error',
];
default:
throw new UnsupportedOperation(sprintf('Unknown MaxMind service %s', $service));
}
} | [
"private",
"function",
"fieldsForService",
"(",
"string",
"$",
"service",
")",
":",
"array",
"{",
"switch",
"(",
"$",
"service",
")",
"{",
"case",
"self",
"::",
"CITY_EXTENDED_SERVICE",
":",
"return",
"[",
"'countryCode'",
",",
"'regionCode'",
",",
"'locality'... | We do not support Country and City services because they do not return much fields.
@see http://dev.maxmind.com/geoip/web-services
@param string $service
@return string[] | [
"We",
"do",
"not",
"support",
"Country",
"and",
"City",
"services",
"because",
"they",
"do",
"not",
"return",
"much",
"fields",
"."
] | train | https://github.com/geocoder-php/maxmind-provider/blob/eddb07f690036fc95dd411de42158a68fb114cd8/MaxMind.php#L180-L226 |
phug-php/compiler | src/Phug/Compiler/NodeCompiler/ImportNodeCompiler.php | ImportNodeCompiler.compileNode | public function compileNode(NodeInterface $node, ElementInterface $parent = null)
{
$compiler = $this->getCompiler();
$compiler->assert(
$node instanceof ImportNode,
'Unexpected '.get_class($node).' given to import compiler.',
$node
);
/** @var ImportNode $node */
$path = $node->getPath();
$isAbsolutePath = mb_substr($path, 0, 1) === '/';
$compiler->assert(
!($isAbsolutePath && empty($compiler->getOption('paths'))),
'Either the "basedir" or "paths" option is required'.
' to use includes and extends with "absolute" paths'
);
$paths = $isAbsolutePath
? null
: [dirname($compiler->getPath()) ?: '.'];
$path = $compiler->resolve($node->getPath(), $paths);
$compiler->registerImportPath($path);
/** @var FilterNode $filter */
if ($filter = $node->getFilter()) {
$text = new TextNode();
$text->setValue($compiler->getFileContents($path));
$filter->appendChild($text);
$import = $filter->getImport();
$filter->setImport(null);
$element = $compiler->compileNode($filter, $parent);
$filter->setImport($import);
return $element;
}
if (!$this->isPugImport($path)) {
return new TextElement($compiler->getFileContents($path), $node);
}
$subCompiler = clone $compiler;
$subCompiler->setParentCompiler($compiler);
$subCompiler->setImportNode($compiler->getImportNode() ?: $node);
$element = $subCompiler->compileFileIntoElement($path);
$compiler->importBlocks($subCompiler->getBlocks());
$isIncludeImport = $node->getName() === 'include';
if ($layout = $subCompiler->getLayout()) {
$element = $layout->getDocument();
$layoutCompiler = $layout->getCompiler();
if ($isIncludeImport) {
$layoutCompiler->compileBlocks();
}
}
if (!$subCompiler->isImportNodeYielded()) {
$yield = $element;
while ($yield instanceof ElementInterface && $yield->hasChildren()) {
$yield = $yield->getChildAt($yield->getChildCount() - 1);
}
while ($yield instanceof CodeElement ||
$yield instanceof ExpressionElement ||
$yield instanceof TextElement
) {
if ($yield instanceof CodeElement &&
trim($yield->getValue(), '; ') === 'break' &&
$yield->getPreviousSibling()
) {
$yield = $yield->getPreviousSibling();
continue;
}
$yield = $yield->getParent();
}
if ($yield instanceof MarkupElement && in_array($yield->getName(), [
'script',
'link',
'img',
'input',
'meta',
'hr',
])) {
$yield = $yield->getParent();
}
if ($compiler->getImportNode()) {
$node->appendChild(new YieldNode());
}
// TODO: check answers on https://github.com/pugjs/pug/issues/2878
$this->compileNodeChildren($node, $yield);
}
if ($isIncludeImport) {
$parentLayout = $compiler->getLayout();
if ($parentLayout) {
$parentDocument = $parentLayout->getDocument();
foreach ($element->getChildren() as $child) {
if ($child instanceof MixinElement) {
$parentDocument->appendChild(clone $child);
}
}
}
return $element;
}
if ($node->getName() === 'extend') {
$layout = new Layout($element, $subCompiler);
$subDocument = $layout->getDocument();
foreach ($node->getParent()->getChildren() as $child) {
if ($child instanceof MixinNode) {
$mixinElement = $subCompiler->compileNode($child, $subDocument);
if ($mixinElement) {
$subDocument->appendChild($mixinElement);
}
}
}
$compiler->setLayout($layout);
}
return null;
} | php | public function compileNode(NodeInterface $node, ElementInterface $parent = null)
{
$compiler = $this->getCompiler();
$compiler->assert(
$node instanceof ImportNode,
'Unexpected '.get_class($node).' given to import compiler.',
$node
);
/** @var ImportNode $node */
$path = $node->getPath();
$isAbsolutePath = mb_substr($path, 0, 1) === '/';
$compiler->assert(
!($isAbsolutePath && empty($compiler->getOption('paths'))),
'Either the "basedir" or "paths" option is required'.
' to use includes and extends with "absolute" paths'
);
$paths = $isAbsolutePath
? null
: [dirname($compiler->getPath()) ?: '.'];
$path = $compiler->resolve($node->getPath(), $paths);
$compiler->registerImportPath($path);
/** @var FilterNode $filter */
if ($filter = $node->getFilter()) {
$text = new TextNode();
$text->setValue($compiler->getFileContents($path));
$filter->appendChild($text);
$import = $filter->getImport();
$filter->setImport(null);
$element = $compiler->compileNode($filter, $parent);
$filter->setImport($import);
return $element;
}
if (!$this->isPugImport($path)) {
return new TextElement($compiler->getFileContents($path), $node);
}
$subCompiler = clone $compiler;
$subCompiler->setParentCompiler($compiler);
$subCompiler->setImportNode($compiler->getImportNode() ?: $node);
$element = $subCompiler->compileFileIntoElement($path);
$compiler->importBlocks($subCompiler->getBlocks());
$isIncludeImport = $node->getName() === 'include';
if ($layout = $subCompiler->getLayout()) {
$element = $layout->getDocument();
$layoutCompiler = $layout->getCompiler();
if ($isIncludeImport) {
$layoutCompiler->compileBlocks();
}
}
if (!$subCompiler->isImportNodeYielded()) {
$yield = $element;
while ($yield instanceof ElementInterface && $yield->hasChildren()) {
$yield = $yield->getChildAt($yield->getChildCount() - 1);
}
while ($yield instanceof CodeElement ||
$yield instanceof ExpressionElement ||
$yield instanceof TextElement
) {
if ($yield instanceof CodeElement &&
trim($yield->getValue(), '; ') === 'break' &&
$yield->getPreviousSibling()
) {
$yield = $yield->getPreviousSibling();
continue;
}
$yield = $yield->getParent();
}
if ($yield instanceof MarkupElement && in_array($yield->getName(), [
'script',
'link',
'img',
'input',
'meta',
'hr',
])) {
$yield = $yield->getParent();
}
if ($compiler->getImportNode()) {
$node->appendChild(new YieldNode());
}
// TODO: check answers on https://github.com/pugjs/pug/issues/2878
$this->compileNodeChildren($node, $yield);
}
if ($isIncludeImport) {
$parentLayout = $compiler->getLayout();
if ($parentLayout) {
$parentDocument = $parentLayout->getDocument();
foreach ($element->getChildren() as $child) {
if ($child instanceof MixinElement) {
$parentDocument->appendChild(clone $child);
}
}
}
return $element;
}
if ($node->getName() === 'extend') {
$layout = new Layout($element, $subCompiler);
$subDocument = $layout->getDocument();
foreach ($node->getParent()->getChildren() as $child) {
if ($child instanceof MixinNode) {
$mixinElement = $subCompiler->compileNode($child, $subDocument);
if ($mixinElement) {
$subDocument->appendChild($mixinElement);
}
}
}
$compiler->setLayout($layout);
}
return null;
} | [
"public",
"function",
"compileNode",
"(",
"NodeInterface",
"$",
"node",
",",
"ElementInterface",
"$",
"parent",
"=",
"null",
")",
"{",
"$",
"compiler",
"=",
"$",
"this",
"->",
"getCompiler",
"(",
")",
";",
"$",
"compiler",
"->",
"assert",
"(",
"$",
"node... | @param NodeInterface $node
@param ElementInterface $parent
@throws CompilerException
@return null|ElementInterface | [
"@param",
"NodeInterface",
"$node",
"@param",
"ElementInterface",
"$parent"
] | train | https://github.com/phug-php/compiler/blob/13fc3f44ef783fbdb4f052e3982eda33e1291a76/src/Phug/Compiler/NodeCompiler/ImportNodeCompiler.php#L54-L177 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Cookie.php | Zend_Http_Cookie.isExpired | public function isExpired($now = null)
{
if ($now === null) { $now = time();
}
if (is_int($this->expires) && $this->expires < $now) {
return true;
} else {
return false;
}
} | php | public function isExpired($now = null)
{
if ($now === null) { $now = time();
}
if (is_int($this->expires) && $this->expires < $now) {
return true;
} else {
return false;
}
} | [
"public",
"function",
"isExpired",
"(",
"$",
"now",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"now",
"===",
"null",
")",
"{",
"$",
"now",
"=",
"time",
"(",
")",
";",
"}",
"if",
"(",
"is_int",
"(",
"$",
"this",
"->",
"expires",
")",
"&&",
"$",
"t... | Check whether the cookie has expired
Always returns false if the cookie is a session cookie (has no expiry time)
@param int $now Timestamp to consider as "now"
@return boolean | [
"Check",
"whether",
"the",
"cookie",
"has",
"expired"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Cookie.php#L189-L198 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Cookie.php | Zend_Http_Cookie.match | public function match($uri, $matchSessionCookies = true, $now = null)
{
if (is_string($uri)) {
$uri = Zend_Uri_Http::factory($uri);
}
// Make sure we have a valid Zend_Uri_Http object
if (! ($uri->valid() && ($uri->getScheme() == 'http' || $uri->getScheme() =='https'))) {
include_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Passed URI is not a valid HTTP or HTTPS URI');
}
// Check that the cookie is secure (if required) and not expired
if ($this->secure && $uri->getScheme() != 'https') { return false;
}
if ($this->isExpired($now)) { return false;
}
if ($this->isSessionCookie() && ! $matchSessionCookies) { return false;
}
// Validate domain and path
// Domain is validated using tail match, while path is validated using head match
$domain_preg = preg_quote($this->getDomain(), "/");
if (! preg_match("/{$domain_preg}$/", $uri->getHost())) { return false;
}
$path_preg = preg_quote($this->getPath(), "/");
if (! preg_match("/^{$path_preg}/", $uri->getPath())) { return false;
}
// If we didn't die until now, return true.
return true;
} | php | public function match($uri, $matchSessionCookies = true, $now = null)
{
if (is_string($uri)) {
$uri = Zend_Uri_Http::factory($uri);
}
// Make sure we have a valid Zend_Uri_Http object
if (! ($uri->valid() && ($uri->getScheme() == 'http' || $uri->getScheme() =='https'))) {
include_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Passed URI is not a valid HTTP or HTTPS URI');
}
// Check that the cookie is secure (if required) and not expired
if ($this->secure && $uri->getScheme() != 'https') { return false;
}
if ($this->isExpired($now)) { return false;
}
if ($this->isSessionCookie() && ! $matchSessionCookies) { return false;
}
// Validate domain and path
// Domain is validated using tail match, while path is validated using head match
$domain_preg = preg_quote($this->getDomain(), "/");
if (! preg_match("/{$domain_preg}$/", $uri->getHost())) { return false;
}
$path_preg = preg_quote($this->getPath(), "/");
if (! preg_match("/^{$path_preg}/", $uri->getPath())) { return false;
}
// If we didn't die until now, return true.
return true;
} | [
"public",
"function",
"match",
"(",
"$",
"uri",
",",
"$",
"matchSessionCookies",
"=",
"true",
",",
"$",
"now",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"uri",
")",
")",
"{",
"$",
"uri",
"=",
"Zend_Uri_Http",
"::",
"factory",
"(",
"$... | Checks whether the cookie should be sent or not in a specific scenario
@param string|Zend_Uri_Http $uri URI to check against (secure, domain, path)
@param boolean $matchSessionCookies Whether to send session cookies
@param int $now Override the current time when checking for expiry time
@return boolean | [
"Checks",
"whether",
"the",
"cookie",
"should",
"be",
"sent",
"or",
"not",
"in",
"a",
"specific",
"scenario"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Cookie.php#L218-L249 |
mcustiel/php-simple-di | src/Dependency.php | Dependency.get | public function get()
{
if (! $this->singleton) {
return call_user_func($this->loader);
}
if ($this->object === null) {
$this->object = call_user_func($this->loader);
}
return $this->object;
} | php | public function get()
{
if (! $this->singleton) {
return call_user_func($this->loader);
}
if ($this->object === null) {
$this->object = call_user_func($this->loader);
}
return $this->object;
} | [
"public",
"function",
"get",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"singleton",
")",
"{",
"return",
"call_user_func",
"(",
"$",
"this",
"->",
"loader",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"object",
"===",
"null",
")",
"{",
"$... | Returns the specific dependency instance.
@return mixed | [
"Returns",
"the",
"specific",
"dependency",
"instance",
"."
] | train | https://github.com/mcustiel/php-simple-di/blob/da0116625d9704185c4a9f01210469266970b265/src/Dependency.php#L47-L57 |
txj123/zilf | src/Zilf/HttpFoundation/RequestMatcher.php | RequestMatcher.matches | public function matches(Request $request)
{
if ($this->schemes && !in_array($request->getScheme(), $this->schemes, true)) {
return false;
}
if ($this->methods && !in_array($request->getMethod(), $this->methods, true)) {
return false;
}
foreach ($this->attributes as $key => $pattern) {
if (!preg_match('{'.$pattern.'}', $request->attributes->get($key))) {
return false;
}
}
if (null !== $this->path && !preg_match('{'.$this->path.'}', rawurldecode($request->getPathInfo()))) {
return false;
}
if (null !== $this->host && !preg_match('{'.$this->host.'}i', $request->getHost())) {
return false;
}
if (IpUtils::checkIp($request->getClientIp(), $this->ips)) {
return true;
}
// Note to future implementors: add additional checks above the
// foreach above or else your check might not be run!
return count($this->ips) === 0;
} | php | public function matches(Request $request)
{
if ($this->schemes && !in_array($request->getScheme(), $this->schemes, true)) {
return false;
}
if ($this->methods && !in_array($request->getMethod(), $this->methods, true)) {
return false;
}
foreach ($this->attributes as $key => $pattern) {
if (!preg_match('{'.$pattern.'}', $request->attributes->get($key))) {
return false;
}
}
if (null !== $this->path && !preg_match('{'.$this->path.'}', rawurldecode($request->getPathInfo()))) {
return false;
}
if (null !== $this->host && !preg_match('{'.$this->host.'}i', $request->getHost())) {
return false;
}
if (IpUtils::checkIp($request->getClientIp(), $this->ips)) {
return true;
}
// Note to future implementors: add additional checks above the
// foreach above or else your check might not be run!
return count($this->ips) === 0;
} | [
"public",
"function",
"matches",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"schemes",
"&&",
"!",
"in_array",
"(",
"$",
"request",
"->",
"getScheme",
"(",
")",
",",
"$",
"this",
"->",
"schemes",
",",
"true",
")",
")",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/RequestMatcher.php#L146-L177 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Identical.php | Zend_Validate_Identical.isValid | public function isValid($value)
{
$this->_setValue($value);
$token = $this->getToken();
if (empty($token)) {
$this->_error(self::MISSING_TOKEN);
return false;
}
if ($value !== $token) {
$this->_error(self::NOT_SAME);
return false;
}
return true;
} | php | public function isValid($value)
{
$this->_setValue($value);
$token = $this->getToken();
if (empty($token)) {
$this->_error(self::MISSING_TOKEN);
return false;
}
if ($value !== $token) {
$this->_error(self::NOT_SAME);
return false;
}
return true;
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"_setValue",
"(",
"$",
"value",
")",
";",
"$",
"token",
"=",
"$",
"this",
"->",
"getToken",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"token",
")",
")",
"{",
"$... | Defined by Zend_Validate_Interface
Returns true if and only if a token has been set and the provided value
matches that token.
@param string $value
@return boolean | [
"Defined",
"by",
"Zend_Validate_Interface"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Identical.php#L108-L124 |
txj123/zilf | src/Zilf/Queue/RedisQueue.php | RedisQueue.retrieveNextJob | protected function retrieveNextJob($queue)
{
if (! is_null($this->blockFor)) {
return $this->blockingPop($queue);
}
return $this->getConnection()->eval(
LuaScripts::pop(), 2, $queue, $queue.':reserved',
$this->availableAt($this->retryAfter)
);
} | php | protected function retrieveNextJob($queue)
{
if (! is_null($this->blockFor)) {
return $this->blockingPop($queue);
}
return $this->getConnection()->eval(
LuaScripts::pop(), 2, $queue, $queue.':reserved',
$this->availableAt($this->retryAfter)
);
} | [
"protected",
"function",
"retrieveNextJob",
"(",
"$",
"queue",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"blockFor",
")",
")",
"{",
"return",
"$",
"this",
"->",
"blockingPop",
"(",
"$",
"queue",
")",
";",
"}",
"return",
"$",
"this"... | Retrieve the next job from the queue.
@param string $queue
@return array | [
"Retrieve",
"the",
"next",
"job",
"from",
"the",
"queue",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/RedisQueue.php#L216-L226 |
txj123/zilf | src/Zilf/Queue/RedisQueue.php | RedisQueue.blockingPop | protected function blockingPop($queue)
{
$rawBody = $this->getConnection()->blpop($queue, $this->blockFor);
if (! empty($rawBody)) {
$payload = json_decode($rawBody[1], true);
$payload['attempts']++;
$reserved = json_encode($payload);
$this->getConnection()->zadd(
$queue.':reserved', [
$reserved => $this->availableAt($this->retryAfter),
]
);
return [$rawBody[1], $reserved];
}
return [null, null];
} | php | protected function blockingPop($queue)
{
$rawBody = $this->getConnection()->blpop($queue, $this->blockFor);
if (! empty($rawBody)) {
$payload = json_decode($rawBody[1], true);
$payload['attempts']++;
$reserved = json_encode($payload);
$this->getConnection()->zadd(
$queue.':reserved', [
$reserved => $this->availableAt($this->retryAfter),
]
);
return [$rawBody[1], $reserved];
}
return [null, null];
} | [
"protected",
"function",
"blockingPop",
"(",
"$",
"queue",
")",
"{",
"$",
"rawBody",
"=",
"$",
"this",
"->",
"getConnection",
"(",
")",
"->",
"blpop",
"(",
"$",
"queue",
",",
"$",
"this",
"->",
"blockFor",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$... | Retrieve the next job by blocking-pop.
@param string $queue
@return array | [
"Retrieve",
"the",
"next",
"job",
"by",
"blocking",
"-",
"pop",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/RedisQueue.php#L234-L255 |
Kaishiyoku/laravel-menu | src/Kaishiyoku/Menu/Data/Dropdown.php | Dropdown.render | public function render($customAttributes = null)
{
$output = '';
foreach ($this->entries as $entry) {
$isActive = false;
$entryAttributes = [];
if ($entry instanceof DropdownDivider) {
$entryAttributes['role'] = 'seperator';
$entryAttributes['class'] = 'divider';
} else {
if ($entry instanceof DropdownHeader) {
$entryAttributes['class'] = 'dropdown-header';
} else if ($entry instanceof Content) {
$entryAttributes['class'] = 'content';
} else if ($entry instanceof Link) {
} else {
if (MenuHelper::isCurrentRouteWithParameters($entry->getName(), $entry->getParameters())) {
$entryAttributes['class'] = 'active';
$isActive = true;
} else {
foreach ($entry->getAdditionalRouteNames() as $additionalRouteName) {
if (MenuHelper::isCurrentRoute($additionalRouteName)) {
$entryAttributes['class'] = ' active';
$isActive = true;
}
}
}
}
}
if (MenuHelper::getConfig()->getCustomDropdownItemRenderFunction() != null) {
$output .= MenuHelper::getConfig()->getCustomDropdownItemRenderFunction()($entry, $isActive);
} else {
$output .= '<li ' . Html::attributes($entryAttributes) . '>' . $entry->render() . '</li>';
}
}
$classes = 'dropdown-toggle';
if (count(MenuHelper::getConfig()->getAnchorElementClasses()) > 0) {
foreach (MenuHelper::getConfig()->getAnchorElementClasses() as $anchorElementClass) {
$classes .= ' ' . $anchorElementClass;
}
}
if (empty($this->name)) {
$link = Html::link('#', $this->title . '<span class="caret"></span>',
['class' => $classes, 'data-toggle' => 'dropdown']);
} else {
$link = Html::linkRoute($this->name, $this->title . '<span class="caret"></span>', $this->parameters,
['class' => $classes, 'data-toggle' => 'dropdown']);
}
if (MenuHelper::getConfig()->getCustomDropdownContainerRenderFunction() != null) {
$additionalClasses = array_key_exists('class', $this->attributes) ? $this->attributes['class'] : null;
return MenuHelper::getConfig()->getCustomDropdownContainerRenderFunction()($link, $output, $additionalClasses);
}
$dropdownClasses = 'dropdown-menu';
if (array_key_exists('class', $this->attributes)) {
$dropdownClasses = $this->attributes['class'];
}
return $link . '<ul class="' . $dropdownClasses . '">' . $output . '</ul>';
} | php | public function render($customAttributes = null)
{
$output = '';
foreach ($this->entries as $entry) {
$isActive = false;
$entryAttributes = [];
if ($entry instanceof DropdownDivider) {
$entryAttributes['role'] = 'seperator';
$entryAttributes['class'] = 'divider';
} else {
if ($entry instanceof DropdownHeader) {
$entryAttributes['class'] = 'dropdown-header';
} else if ($entry instanceof Content) {
$entryAttributes['class'] = 'content';
} else if ($entry instanceof Link) {
} else {
if (MenuHelper::isCurrentRouteWithParameters($entry->getName(), $entry->getParameters())) {
$entryAttributes['class'] = 'active';
$isActive = true;
} else {
foreach ($entry->getAdditionalRouteNames() as $additionalRouteName) {
if (MenuHelper::isCurrentRoute($additionalRouteName)) {
$entryAttributes['class'] = ' active';
$isActive = true;
}
}
}
}
}
if (MenuHelper::getConfig()->getCustomDropdownItemRenderFunction() != null) {
$output .= MenuHelper::getConfig()->getCustomDropdownItemRenderFunction()($entry, $isActive);
} else {
$output .= '<li ' . Html::attributes($entryAttributes) . '>' . $entry->render() . '</li>';
}
}
$classes = 'dropdown-toggle';
if (count(MenuHelper::getConfig()->getAnchorElementClasses()) > 0) {
foreach (MenuHelper::getConfig()->getAnchorElementClasses() as $anchorElementClass) {
$classes .= ' ' . $anchorElementClass;
}
}
if (empty($this->name)) {
$link = Html::link('#', $this->title . '<span class="caret"></span>',
['class' => $classes, 'data-toggle' => 'dropdown']);
} else {
$link = Html::linkRoute($this->name, $this->title . '<span class="caret"></span>', $this->parameters,
['class' => $classes, 'data-toggle' => 'dropdown']);
}
if (MenuHelper::getConfig()->getCustomDropdownContainerRenderFunction() != null) {
$additionalClasses = array_key_exists('class', $this->attributes) ? $this->attributes['class'] : null;
return MenuHelper::getConfig()->getCustomDropdownContainerRenderFunction()($link, $output, $additionalClasses);
}
$dropdownClasses = 'dropdown-menu';
if (array_key_exists('class', $this->attributes)) {
$dropdownClasses = $this->attributes['class'];
}
return $link . '<ul class="' . $dropdownClasses . '">' . $output . '</ul>';
} | [
"public",
"function",
"render",
"(",
"$",
"customAttributes",
"=",
"null",
")",
"{",
"$",
"output",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"entries",
"as",
"$",
"entry",
")",
"{",
"$",
"isActive",
"=",
"false",
";",
"$",
"entryAttributes",
... | Get the evaluated contents of the object.
@param null|array $customAttributes
@return string | [
"Get",
"the",
"evaluated",
"contents",
"of",
"the",
"object",
"."
] | train | https://github.com/Kaishiyoku/laravel-menu/blob/0a1aa772f19002d354f0c338e603d98c49d10a7a/src/Kaishiyoku/Menu/Data/Dropdown.php#L66-L135 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php | MongoDbSessionHandler.destroy | public function destroy($sessionId)
{
$methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
$this->getCollection()->$methodName(
array(
$this->options['id_field'] => $sessionId,
)
);
return true;
} | php | public function destroy($sessionId)
{
$methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
$this->getCollection()->$methodName(
array(
$this->options['id_field'] => $sessionId,
)
);
return true;
} | [
"public",
"function",
"destroy",
"(",
"$",
"sessionId",
")",
"{",
"$",
"methodName",
"=",
"$",
"this",
"->",
"mongo",
"instanceof",
"\\",
"MongoDB",
"\\",
"Client",
"?",
"'deleteOne'",
":",
"'remove'",
";",
"$",
"this",
"->",
"getCollection",
"(",
")",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php#L111-L122 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php | MongoDbSessionHandler.gc | public function gc($maxlifetime)
{
$methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
$this->getCollection()->$methodName(
array(
$this->options['expiry_field'] => array('$lt' => $this->createDateTime()),
)
);
return true;
} | php | public function gc($maxlifetime)
{
$methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
$this->getCollection()->$methodName(
array(
$this->options['expiry_field'] => array('$lt' => $this->createDateTime()),
)
);
return true;
} | [
"public",
"function",
"gc",
"(",
"$",
"maxlifetime",
")",
"{",
"$",
"methodName",
"=",
"$",
"this",
"->",
"mongo",
"instanceof",
"\\",
"MongoDB",
"\\",
"Client",
"?",
"'deleteOne'",
":",
"'remove'",
";",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->"... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php#L127-L138 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php | MongoDbSessionHandler.write | public function write($sessionId, $data)
{
$expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime'));
$fields = array(
$this->options['time_field'] => $this->createDateTime(),
$this->options['expiry_field'] => $expiry,
);
$options = array('upsert' => true);
if ($this->mongo instanceof \MongoDB\Client) {
$fields[$this->options['data_field']] = new \MongoDB\BSON\Binary($data, \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
} else {
$fields[$this->options['data_field']] = new \MongoBinData($data, \MongoBinData::BYTE_ARRAY);
$options['multiple'] = false;
}
$methodName = $this->mongo instanceof \MongoDB\Client ? 'updateOne' : 'update';
$this->getCollection()->$methodName(
array($this->options['id_field'] => $sessionId),
array('$set' => $fields),
$options
);
return true;
} | php | public function write($sessionId, $data)
{
$expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime'));
$fields = array(
$this->options['time_field'] => $this->createDateTime(),
$this->options['expiry_field'] => $expiry,
);
$options = array('upsert' => true);
if ($this->mongo instanceof \MongoDB\Client) {
$fields[$this->options['data_field']] = new \MongoDB\BSON\Binary($data, \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
} else {
$fields[$this->options['data_field']] = new \MongoBinData($data, \MongoBinData::BYTE_ARRAY);
$options['multiple'] = false;
}
$methodName = $this->mongo instanceof \MongoDB\Client ? 'updateOne' : 'update';
$this->getCollection()->$methodName(
array($this->options['id_field'] => $sessionId),
array('$set' => $fields),
$options
);
return true;
} | [
"public",
"function",
"write",
"(",
"$",
"sessionId",
",",
"$",
"data",
")",
"{",
"$",
"expiry",
"=",
"$",
"this",
"->",
"createDateTime",
"(",
"time",
"(",
")",
"+",
"(",
"int",
")",
"ini_get",
"(",
"'session.gc_maxlifetime'",
")",
")",
";",
"$",
"f... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php#L143-L170 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php | MongoDbSessionHandler.read | public function read($sessionId)
{
$dbData = $this->getCollection()->findOne(
array(
$this->options['id_field'] => $sessionId,
$this->options['expiry_field'] => array('$gte' => $this->createDateTime()),
)
);
if (null === $dbData) {
return '';
}
if ($dbData[$this->options['data_field']] instanceof \MongoDB\BSON\Binary) {
return $dbData[$this->options['data_field']]->getData();
}
return $dbData[$this->options['data_field']]->bin;
} | php | public function read($sessionId)
{
$dbData = $this->getCollection()->findOne(
array(
$this->options['id_field'] => $sessionId,
$this->options['expiry_field'] => array('$gte' => $this->createDateTime()),
)
);
if (null === $dbData) {
return '';
}
if ($dbData[$this->options['data_field']] instanceof \MongoDB\BSON\Binary) {
return $dbData[$this->options['data_field']]->getData();
}
return $dbData[$this->options['data_field']]->bin;
} | [
"public",
"function",
"read",
"(",
"$",
"sessionId",
")",
"{",
"$",
"dbData",
"=",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"findOne",
"(",
"array",
"(",
"$",
"this",
"->",
"options",
"[",
"'id_field'",
"]",
"=>",
"$",
"sessionId",
",",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php#L175-L193 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php | MongoDbSessionHandler.createDateTime | private function createDateTime($seconds = null)
{
if (null === $seconds) {
$seconds = time();
}
if ($this->mongo instanceof \MongoDB\Client) {
return new \MongoDB\BSON\UTCDateTime($seconds * 1000);
}
return new \MongoDate($seconds);
} | php | private function createDateTime($seconds = null)
{
if (null === $seconds) {
$seconds = time();
}
if ($this->mongo instanceof \MongoDB\Client) {
return new \MongoDB\BSON\UTCDateTime($seconds * 1000);
}
return new \MongoDate($seconds);
} | [
"private",
"function",
"createDateTime",
"(",
"$",
"seconds",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"seconds",
")",
"{",
"$",
"seconds",
"=",
"time",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"mongo",
"instanceof",
"\\",
"Mo... | Create a date object using the class appropriate for the current mongo connection.
Return an instance of a MongoDate or \MongoDB\BSON\UTCDateTime
@param int $seconds An integer representing UTC seconds since Jan 1 1970. Defaults to now. | [
"Create",
"a",
"date",
"object",
"using",
"the",
"class",
"appropriate",
"for",
"the",
"current",
"mongo",
"connection",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php#L226-L237 |
oxygen-cms/core | src/Console/Formatter.php | Formatter.associativeArray | public static function associativeArray(array $array) {
$string = '[ ';
foreach($array as $key => $item) {
$string .= $key . ' => ' . $item;
if($item !== last($array)) {
$string .= ', ';
}
}
$string .= ' ]';
return $string;
} | php | public static function associativeArray(array $array) {
$string = '[ ';
foreach($array as $key => $item) {
$string .= $key . ' => ' . $item;
if($item !== last($array)) {
$string .= ', ';
}
}
$string .= ' ]';
return $string;
} | [
"public",
"static",
"function",
"associativeArray",
"(",
"array",
"$",
"array",
")",
"{",
"$",
"string",
"=",
"'[ '",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"item",
")",
"{",
"$",
"string",
".=",
"$",
"key",
".",
"' => '",
... | Formats an array for console output.
@param array $array
@return string | [
"Formats",
"an",
"array",
"for",
"console",
"output",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/Formatter.php#L47-L58 |
oxygen-cms/core | src/Console/Formatter.php | Formatter.keyedArray | public static function keyedArray($array) {
if(is_array($array)) {
$string = '[ ';
foreach($array as $key => $item) {
if(!is_string($item)) {
$item = self::keyedArray($item);
}
$string .= $key . ' => ' . $item;
if($item !== last($array)) {
$string .= ', ';
}
}
$string .= ' ]';
return $string;
} else {
if(is_object($array)) {
return get_class($array);
} else {
if(is_null($array)) {
return 'Null';
} else {
return 'Unknown';
}
}
}
} | php | public static function keyedArray($array) {
if(is_array($array)) {
$string = '[ ';
foreach($array as $key => $item) {
if(!is_string($item)) {
$item = self::keyedArray($item);
}
$string .= $key . ' => ' . $item;
if($item !== last($array)) {
$string .= ', ';
}
}
$string .= ' ]';
return $string;
} else {
if(is_object($array)) {
return get_class($array);
} else {
if(is_null($array)) {
return 'Null';
} else {
return 'Unknown';
}
}
}
} | [
"public",
"static",
"function",
"keyedArray",
"(",
"$",
"array",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"array",
")",
")",
"{",
"$",
"string",
"=",
"'[ '",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"item",
")",
"{",
"if"... | Formats an array for console output.
@param array $array
@return string | [
"Formats",
"an",
"array",
"for",
"console",
"output",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/Formatter.php#L80-L106 |
txj123/zilf | src/Zilf/Db/Command.php | Command.bindValues | public function bindValues($values)
{
if (empty($values)) {
return $this;
}
$schema = $this->db->getSchema();
foreach ($values as $name => $value) {
if (is_array($value)) { // TODO: Drop in Zilf 2.1
$this->_pendingParams[$name] = $value;
$this->params[$name] = $value[0];
} elseif ($value instanceof PdoValue) {
$this->_pendingParams[$name] = [$value->getValue(), $value->getType()];
$this->params[$name] = $value->getValue();
} else {
$type = $schema->getPdoType($value);
$this->_pendingParams[$name] = [$value, $type];
$this->params[$name] = $value;
}
}
return $this;
} | php | public function bindValues($values)
{
if (empty($values)) {
return $this;
}
$schema = $this->db->getSchema();
foreach ($values as $name => $value) {
if (is_array($value)) { // TODO: Drop in Zilf 2.1
$this->_pendingParams[$name] = $value;
$this->params[$name] = $value[0];
} elseif ($value instanceof PdoValue) {
$this->_pendingParams[$name] = [$value->getValue(), $value->getType()];
$this->params[$name] = $value->getValue();
} else {
$type = $schema->getPdoType($value);
$this->_pendingParams[$name] = [$value, $type];
$this->params[$name] = $value;
}
}
return $this;
} | [
"public",
"function",
"bindValues",
"(",
"$",
"values",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"values",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"schema",
"=",
"$",
"this",
"->",
"db",
"->",
"getSchema",
"(",
")",
";",
"foreach",
"(... | Binds a list of values to the corresponding parameters.
This is similar to [[bindValue()]] except that it binds multiple values at a time.
Note that the SQL data type of each value is determined by its PHP type.
@param array $values the values to be bound. This must be given in terms of an associative
array with array keys being the parameter names, and array values the corresponding parameter values,
e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined
by its PHP type. You may explicitly specify the PDO type by using a [[Zilf\Db\PdoValue]] class: `new PdoValue(value, type)`,
e.g. `[':name' => 'John', ':profile' => new PdoValue($profile, \PDO::PARAM_LOB)]`.
@return $this the current command being executed | [
"Binds",
"a",
"list",
"of",
"values",
"to",
"the",
"corresponding",
"parameters",
".",
"This",
"is",
"similar",
"to",
"[[",
"bindValue",
"()",
"]]",
"except",
"that",
"it",
"binds",
"multiple",
"values",
"at",
"a",
"time",
".",
"Note",
"that",
"the",
"SQ... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Command.php#L367-L389 |
txj123/zilf | src/Zilf/Db/Command.php | Command.execute | public function execute()
{
$sql = $this->getSql();
list($profile, $rawSql) = $this->logQuery(__METHOD__);
if ($sql == '') {
return 0;
}
$this->prepare(false);
try {
//$profile and Zilf::beginProfile($rawSql, __METHOD__);
$this->internalExecute($rawSql);
$n = $this->pdoStatement->rowCount();
//$profile and Zilf::endProfile($rawSql, __METHOD__);
$this->refreshTableSchema();
return $n;
} catch (Exception $e) {
//$profile and Zilf::endProfile($rawSql, __METHOD__);
throw $e;
}
} | php | public function execute()
{
$sql = $this->getSql();
list($profile, $rawSql) = $this->logQuery(__METHOD__);
if ($sql == '') {
return 0;
}
$this->prepare(false);
try {
//$profile and Zilf::beginProfile($rawSql, __METHOD__);
$this->internalExecute($rawSql);
$n = $this->pdoStatement->rowCount();
//$profile and Zilf::endProfile($rawSql, __METHOD__);
$this->refreshTableSchema();
return $n;
} catch (Exception $e) {
//$profile and Zilf::endProfile($rawSql, __METHOD__);
throw $e;
}
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"$",
"sql",
"=",
"$",
"this",
"->",
"getSql",
"(",
")",
";",
"list",
"(",
"$",
"profile",
",",
"$",
"rawSql",
")",
"=",
"$",
"this",
"->",
"logQuery",
"(",
"__METHOD__",
")",
";",
"if",
"(",
"$",
... | Executes the SQL statement.
This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
No result set will be returned.
@return int number of rows affected by the execution.
@throws Exception execution failed | [
"Executes",
"the",
"SQL",
"statement",
".",
"This",
"method",
"should",
"only",
"be",
"used",
"for",
"executing",
"non",
"-",
"query",
"SQL",
"statement",
"such",
"as",
"INSERT",
"DELETE",
"UPDATE",
"SQLs",
".",
"No",
"result",
"set",
"will",
"be",
"return... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Command.php#L1126-L1152 |
txj123/zilf | src/Zilf/Db/Command.php | Command.logQuery | protected function logQuery($category)
{
if ($this->db->enableLogging) {
$rawSql = $this->getRawSql();
//Zilf::info($rawSql, $category);
}
if (!$this->db->enableProfiling) {
return [false, isset($rawSql) ? $rawSql : null];
}
return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
} | php | protected function logQuery($category)
{
if ($this->db->enableLogging) {
$rawSql = $this->getRawSql();
//Zilf::info($rawSql, $category);
}
if (!$this->db->enableProfiling) {
return [false, isset($rawSql) ? $rawSql : null];
}
return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
} | [
"protected",
"function",
"logQuery",
"(",
"$",
"category",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"db",
"->",
"enableLogging",
")",
"{",
"$",
"rawSql",
"=",
"$",
"this",
"->",
"getRawSql",
"(",
")",
";",
"//Zilf::info($rawSql, $category);",
"}",
"if",
"... | Logs the current database query if query logging is enabled and returns
the profiling token if profiling is enabled.
@param string $category the log category.
@return array array of two elements, the first is boolean of whether profiling is enabled or not.
The second is the rawSql if it has been created. | [
"Logs",
"the",
"current",
"database",
"query",
"if",
"query",
"logging",
"is",
"enabled",
"and",
"returns",
"the",
"profiling",
"token",
"if",
"profiling",
"is",
"enabled",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Command.php#L1162-L1173 |
txj123/zilf | src/Zilf/Db/Command.php | Command.queryInternal | protected function queryInternal($method, $fetchMode = null)
{
list($profile, $rawSql) = $this->logQuery('Zilf\Db\Command::query');
if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) {
/* @var $cache \Zilf\caching\CacheInterface */
$cache = $info[0];
$cacheKey = [
__CLASS__,
$method,
$fetchMode,
$this->db->dsn,
$this->db->username,
$rawSql ?: $rawSql = $this->getRawSql(),
];
$result = $cache->get($cacheKey);
if (is_array($result) && isset($result[0])) {
Log::debug('Query result served from cache', 'Zilf\Db\Command::query');
return $result[0];
}
}
}
$this->prepare(true);
try {
//$profile and Zilf::beginProfile($rawSql, 'Zilf\Db\Command::query');
$this->internalExecute($rawSql);
if ($method === '') {
$result = new DataReader($this);
} else {
if ($fetchMode === null) {
$fetchMode = $this->fetchMode;
}
$result = call_user_func_array([$this->pdoStatement, $method], (array)$fetchMode);
$this->pdoStatement->closeCursor();
}
//$profile and Zilf::endProfile($rawSql, 'Zilf\Db\Command::query');
} catch (Exception $e) {
//$profile and Zilf::endProfile($rawSql, 'Zilf\Db\Command::query');
throw $e;
}
if (isset($cache, $cacheKey, $info)) {
$cache->set($cacheKey, [$result], $info[1], $info[2]);
Log::debug('Saved query result in cache' . 'Zilf\Db\Command::query');
}
return $result;
} | php | protected function queryInternal($method, $fetchMode = null)
{
list($profile, $rawSql) = $this->logQuery('Zilf\Db\Command::query');
if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) {
/* @var $cache \Zilf\caching\CacheInterface */
$cache = $info[0];
$cacheKey = [
__CLASS__,
$method,
$fetchMode,
$this->db->dsn,
$this->db->username,
$rawSql ?: $rawSql = $this->getRawSql(),
];
$result = $cache->get($cacheKey);
if (is_array($result) && isset($result[0])) {
Log::debug('Query result served from cache', 'Zilf\Db\Command::query');
return $result[0];
}
}
}
$this->prepare(true);
try {
//$profile and Zilf::beginProfile($rawSql, 'Zilf\Db\Command::query');
$this->internalExecute($rawSql);
if ($method === '') {
$result = new DataReader($this);
} else {
if ($fetchMode === null) {
$fetchMode = $this->fetchMode;
}
$result = call_user_func_array([$this->pdoStatement, $method], (array)$fetchMode);
$this->pdoStatement->closeCursor();
}
//$profile and Zilf::endProfile($rawSql, 'Zilf\Db\Command::query');
} catch (Exception $e) {
//$profile and Zilf::endProfile($rawSql, 'Zilf\Db\Command::query');
throw $e;
}
if (isset($cache, $cacheKey, $info)) {
$cache->set($cacheKey, [$result], $info[1], $info[2]);
Log::debug('Saved query result in cache' . 'Zilf\Db\Command::query');
}
return $result;
} | [
"protected",
"function",
"queryInternal",
"(",
"$",
"method",
",",
"$",
"fetchMode",
"=",
"null",
")",
"{",
"list",
"(",
"$",
"profile",
",",
"$",
"rawSql",
")",
"=",
"$",
"this",
"->",
"logQuery",
"(",
"'Zilf\\Db\\Command::query'",
")",
";",
"if",
"(",
... | Performs the actual DB query of a SQL statement.
@param string $method method of PDOStatement to be called
@param int $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
@return mixed the method execution result
@throws Exception if the query causes any problem
@since 2.0.1 this method is protected (was private before). | [
"Performs",
"the",
"actual",
"DB",
"query",
"of",
"a",
"SQL",
"statement",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Command.php#L1185-L1239 |
oxygen-cms/core | src/Html/Toolbar/Toolbar.php | Toolbar.fillFromBlueprint | public function fillFromBlueprint(Blueprint $blueprint, $set) {
$this->addItemsFromBlueprint($blueprint);
$this->setOrder($blueprint->getToolbarOrder($set));
} | php | public function fillFromBlueprint(Blueprint $blueprint, $set) {
$this->addItemsFromBlueprint($blueprint);
$this->setOrder($blueprint->getToolbarOrder($set));
} | [
"public",
"function",
"fillFromBlueprint",
"(",
"Blueprint",
"$",
"blueprint",
",",
"$",
"set",
")",
"{",
"$",
"this",
"->",
"addItemsFromBlueprint",
"(",
"$",
"blueprint",
")",
";",
"$",
"this",
"->",
"setOrder",
"(",
"$",
"blueprint",
"->",
"getToolbarOrde... | Adds toolbar items from a Blueprint.
@param Blueprint $blueprint
@param string $set Set of items to use
@return void | [
"Adds",
"toolbar",
"items",
"from",
"a",
"Blueprint",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/Toolbar.php#L89-L92 |
oxygen-cms/core | src/Html/Toolbar/Toolbar.php | Toolbar.addItemsFromBlueprint | public function addItemsFromBlueprint(Blueprint $blueprint) {
foreach($blueprint->getToolbarItems() as $item) {
$this->addItem($item);
}
} | php | public function addItemsFromBlueprint(Blueprint $blueprint) {
foreach($blueprint->getToolbarItems() as $item) {
$this->addItem($item);
}
} | [
"public",
"function",
"addItemsFromBlueprint",
"(",
"Blueprint",
"$",
"blueprint",
")",
"{",
"foreach",
"(",
"$",
"blueprint",
"->",
"getToolbarItems",
"(",
")",
"as",
"$",
"item",
")",
"{",
"$",
"this",
"->",
"addItem",
"(",
"$",
"item",
")",
";",
"}",
... | Adds toolbar items from a Blueprint.
@param Blueprint $blueprint
@return void | [
"Adds",
"toolbar",
"items",
"from",
"a",
"Blueprint",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/Toolbar.php#L100-L104 |
oxygen-cms/core | src/Html/Toolbar/Toolbar.php | Toolbar.setOrder | public function setOrder(array $keys) {
$this->itemsOrdered = [];
foreach($keys as $label => $value) {
if($value === 'spacer' || $value === '|') {
$this->itemsOrdered[] = $this->spacer;
} elseif(is_array($value)) {
$parts = explode(',', $label);
if($this->hasItem($parts[0])) {
$dropdown = new DropdownToolbarItem($parts[1]);
$dropdown->button = $this->getItem($parts[0]);
} else {
$dropdown = new DropdownToolbarItem($parts[0]);
}
foreach($value as $dropdownItem) {
$dropdown->addItem($this->getItem($dropdownItem));
}
$this->itemsOrdered[] = $dropdown;
} else {
$this->itemsOrdered[] = $this->getItem($value);
}
}
} | php | public function setOrder(array $keys) {
$this->itemsOrdered = [];
foreach($keys as $label => $value) {
if($value === 'spacer' || $value === '|') {
$this->itemsOrdered[] = $this->spacer;
} elseif(is_array($value)) {
$parts = explode(',', $label);
if($this->hasItem($parts[0])) {
$dropdown = new DropdownToolbarItem($parts[1]);
$dropdown->button = $this->getItem($parts[0]);
} else {
$dropdown = new DropdownToolbarItem($parts[0]);
}
foreach($value as $dropdownItem) {
$dropdown->addItem($this->getItem($dropdownItem));
}
$this->itemsOrdered[] = $dropdown;
} else {
$this->itemsOrdered[] = $this->getItem($value);
}
}
} | [
"public",
"function",
"setOrder",
"(",
"array",
"$",
"keys",
")",
"{",
"$",
"this",
"->",
"itemsOrdered",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"label",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"'spacer'",... | Sets the order of items on the toolbar.
@param array $keys
@return void | [
"Sets",
"the",
"order",
"of",
"items",
"on",
"the",
"toolbar",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/Toolbar.php#L122-L145 |
oxygen-cms/core | src/Html/Toolbar/Toolbar.php | Toolbar.hasItem | public function hasItem($identifier) {
return isset($this->itemsPool[$this->prefix . '.' . $identifier]) || isset($this->itemsPool[$identifier]);
} | php | public function hasItem($identifier) {
return isset($this->itemsPool[$this->prefix . '.' . $identifier]) || isset($this->itemsPool[$identifier]);
} | [
"public",
"function",
"hasItem",
"(",
"$",
"identifier",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"itemsPool",
"[",
"$",
"this",
"->",
"prefix",
".",
"'.'",
".",
"$",
"identifier",
"]",
")",
"||",
"isset",
"(",
"$",
"this",
"->",
"itemsPo... | Determines a ToolbarItem exists.
@param string $identifier
@return boolean | [
"Determines",
"a",
"ToolbarItem",
"exists",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/Toolbar.php#L153-L155 |
oxygen-cms/core | src/Html/Toolbar/Toolbar.php | Toolbar.getItem | public function getItem($identifier) {
if(!isset($this->itemsPool[$identifier]) && $this->prefix !== null) {
return $this->itemsPool[$this->prefix . '.' . $identifier];
}
return $this->itemsPool[$identifier];
} | php | public function getItem($identifier) {
if(!isset($this->itemsPool[$identifier]) && $this->prefix !== null) {
return $this->itemsPool[$this->prefix . '.' . $identifier];
}
return $this->itemsPool[$identifier];
} | [
"public",
"function",
"getItem",
"(",
"$",
"identifier",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"itemsPool",
"[",
"$",
"identifier",
"]",
")",
"&&",
"$",
"this",
"->",
"prefix",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"-... | Get a ToolbarItem.
@param string $identifier
@return ToolbarItem | [
"Get",
"a",
"ToolbarItem",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/Toolbar.php#L163-L169 |
oxygen-cms/core | src/View/CompilerEngine.php | CompilerEngine.getMessage | protected function getMessage($e) {
$last = last($this->lastCompiled);
$path = is_object($last) ? $last->path : realpath($last);
return $e->getMessage() . ' (View: ' . $path . ')';
} | php | protected function getMessage($e) {
$last = last($this->lastCompiled);
$path = is_object($last) ? $last->path : realpath($last);
return $e->getMessage() . ' (View: ' . $path . ')';
} | [
"protected",
"function",
"getMessage",
"(",
"$",
"e",
")",
"{",
"$",
"last",
"=",
"last",
"(",
"$",
"this",
"->",
"lastCompiled",
")",
";",
"$",
"path",
"=",
"is_object",
"(",
"$",
"last",
")",
"?",
"$",
"last",
"->",
"path",
":",
"realpath",
"(",
... | Get the exception message for an exception.
@param \Exception $e
@return string | [
"Get",
"the",
"exception",
"message",
"for",
"an",
"exception",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/View/CompilerEngine.php#L15-L20 |
txj123/zilf | src/Zilf/Helpers/BaseArrayHelper.php | BaseArrayHelper.keyExists | public static function keyExists($key, $array, $caseSensitive = true)
{
if ($caseSensitive) {
// Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
// http://php.net/manual/en/function.array-key-exists.php#107786
return isset($array[$key]) || array_key_exists($key, $array);
}
foreach (array_keys($array) as $k) {
if (strcasecmp($key, $k) === 0) {
return true;
}
}
return false;
} | php | public static function keyExists($key, $array, $caseSensitive = true)
{
if ($caseSensitive) {
// Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
// http://php.net/manual/en/function.array-key-exists.php#107786
return isset($array[$key]) || array_key_exists($key, $array);
}
foreach (array_keys($array) as $k) {
if (strcasecmp($key, $k) === 0) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"keyExists",
"(",
"$",
"key",
",",
"$",
"array",
",",
"$",
"caseSensitive",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"caseSensitive",
")",
"{",
"// Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case",
... | Checks if the given array contains the specified key.
This method enhances the `array_key_exists()` function by supporting case-insensitive
key comparison.
@param string $key the key to check
@param array $array the array with keys to check
@param bool $caseSensitive whether the key comparison should be case-sensitive
@return bool whether the array contains the specified key | [
"Checks",
"if",
"the",
"given",
"array",
"contains",
"the",
"specified",
"key",
".",
"This",
"method",
"enhances",
"the",
"array_key_exists",
"()",
"function",
"by",
"supporting",
"case",
"-",
"insensitive",
"key",
"comparison",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Helpers/BaseArrayHelper.php#L582-L597 |
txj123/zilf | src/Zilf/Support/AggregateServiceProvider.php | AggregateServiceProvider.register | public function register()
{
$this->instances = [];
foreach ($this->providers as $provider) {
Zilf::$container->register($provider, $provider);
$this->instances[] = Zilf::$container->get($provider)->register();
}
} | php | public function register()
{
$this->instances = [];
foreach ($this->providers as $provider) {
Zilf::$container->register($provider, $provider);
$this->instances[] = Zilf::$container->get($provider)->register();
}
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"instances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"providers",
"as",
"$",
"provider",
")",
"{",
"Zilf",
"::",
"$",
"container",
"->",
"register",
"(",
"$",
"provide... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Support/AggregateServiceProvider.php#L28-L36 |
jcchavezs/dd-trace-php | src/DdTrace/Tracer.php | Tracer.flushTraces | public function flushTraces()
{
$spans = $this->buffer->pop();
$spansCount = $spans->count();
if ($this->debugLoggingEnabled) {
$this->logger->debug(sprintf("Sending %d spans", $spansCount));
foreach($spans as $span) {
$this->logger->debug(sprintf("SPAN:\n%s", $span->__toString()));
}
}
if (!$this->isEnabled() || !$this->hasTransport() || $spansCount == 0) {
return;
}
$traceBuffer = TracesBuffer::fromSpanCollection($spans);
$this->transport->sendTraces($traceBuffer);
} | php | public function flushTraces()
{
$spans = $this->buffer->pop();
$spansCount = $spans->count();
if ($this->debugLoggingEnabled) {
$this->logger->debug(sprintf("Sending %d spans", $spansCount));
foreach($spans as $span) {
$this->logger->debug(sprintf("SPAN:\n%s", $span->__toString()));
}
}
if (!$this->isEnabled() || !$this->hasTransport() || $spansCount == 0) {
return;
}
$traceBuffer = TracesBuffer::fromSpanCollection($spans);
$this->transport->sendTraces($traceBuffer);
} | [
"public",
"function",
"flushTraces",
"(",
")",
"{",
"$",
"spans",
"=",
"$",
"this",
"->",
"buffer",
"->",
"pop",
"(",
")",
";",
"$",
"spansCount",
"=",
"$",
"spans",
"->",
"count",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"debugLoggingEnabled",
... | FlushTraces will push any currently buffered traces to the server.
XXX Note that it is currently exported because some tests use it. They
really should not. | [
"FlushTraces",
"will",
"push",
"any",
"currently",
"buffered",
"traces",
"to",
"the",
"server",
".",
"XXX",
"Note",
"that",
"it",
"is",
"currently",
"exported",
"because",
"some",
"tests",
"use",
"it",
".",
"They",
"really",
"should",
"not",
"."
] | train | https://github.com/jcchavezs/dd-trace-php/blob/d10be51fc63cb5bfc4de19c1880fe7b5397a8b0d/src/DdTrace/Tracer.php#L74-L94 |
txj123/zilf | src/Zilf/Log/LogManager.php | LogManager.get | protected function get($name)
{
try {
return $this->channels[$name] ?? with(
$this->resolve($name), function ($logger) use ($name) {
return $this->channels[$name] = $this->tap($name, new Logger($logger));
}
);
} catch (Throwable $e) {
return tap(
$this->createEmergencyLogger(), function ($logger) use ($e) {
$logger->emergency(
'Unable to create configured logger. Using emergency logger.', [
'exception' => $e,
]
);
}
);
}
} | php | protected function get($name)
{
try {
return $this->channels[$name] ?? with(
$this->resolve($name), function ($logger) use ($name) {
return $this->channels[$name] = $this->tap($name, new Logger($logger));
}
);
} catch (Throwable $e) {
return tap(
$this->createEmergencyLogger(), function ($logger) use ($e) {
$logger->emergency(
'Unable to create configured logger. Using emergency logger.', [
'exception' => $e,
]
);
}
);
}
} | [
"protected",
"function",
"get",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"channels",
"[",
"$",
"name",
"]",
"??",
"with",
"(",
"$",
"this",
"->",
"resolve",
"(",
"$",
"name",
")",
",",
"function",
"(",
"$",
"logger",
"... | Attempt to get the log from the local cache.
@param string $name
@return \Psr\Log\LoggerInterface | [
"Attempt",
"to",
"get",
"the",
"log",
"from",
"the",
"local",
"cache",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Log/LogManager.php#L112-L131 |
txj123/zilf | src/Zilf/Log/LogManager.php | LogManager.createEmergencyLogger | protected function createEmergencyLogger()
{
return new Logger(
new Monolog(
'zilf', $this->prepareHandlers(
[new StreamHandler(
Zilf::$app->runtimePath() . '/logs/zilf.log', $this->level(['level' => 'debug'])
)]
)
)
);
} | php | protected function createEmergencyLogger()
{
return new Logger(
new Monolog(
'zilf', $this->prepareHandlers(
[new StreamHandler(
Zilf::$app->runtimePath() . '/logs/zilf.log', $this->level(['level' => 'debug'])
)]
)
)
);
} | [
"protected",
"function",
"createEmergencyLogger",
"(",
")",
"{",
"return",
"new",
"Logger",
"(",
"new",
"Monolog",
"(",
"'zilf'",
",",
"$",
"this",
"->",
"prepareHandlers",
"(",
"[",
"new",
"StreamHandler",
"(",
"Zilf",
"::",
"$",
"app",
"->",
"runtimePath",... | Create an emergency log handler to avoid white screens of death.
@return \Psr\Log\LoggerInterface | [
"Create",
"an",
"emergency",
"log",
"handler",
"to",
"avoid",
"white",
"screens",
"of",
"death",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Log/LogManager.php#L167-L178 |
txj123/zilf | src/Zilf/Log/LogManager.php | LogManager.createSlackDriver | protected function createSlackDriver(array $config)
{
return new Monolog(
$this->parseChannel($config), [
$this->prepareHandler(
new SlackWebhookHandler(
$config['url'],
$config['channel'] ?? null,
$config['username'] ?? 'zilf',
$config['attachment'] ?? true,
$config['emoji'] ?? ':boom:',
$config['short'] ?? false,
$config['context'] ?? true,
$this->level($config)
)
),
]
);
} | php | protected function createSlackDriver(array $config)
{
return new Monolog(
$this->parseChannel($config), [
$this->prepareHandler(
new SlackWebhookHandler(
$config['url'],
$config['channel'] ?? null,
$config['username'] ?? 'zilf',
$config['attachment'] ?? true,
$config['emoji'] ?? ':boom:',
$config['short'] ?? false,
$config['context'] ?? true,
$this->level($config)
)
),
]
);
} | [
"protected",
"function",
"createSlackDriver",
"(",
"array",
"$",
"config",
")",
"{",
"return",
"new",
"Monolog",
"(",
"$",
"this",
"->",
"parseChannel",
"(",
"$",
"config",
")",
",",
"[",
"$",
"this",
"->",
"prepareHandler",
"(",
"new",
"SlackWebhookHandler"... | Create an instance of the Slack log driver.
@param array $config
@return \Psr\Log\LoggerInterface | [
"Create",
"an",
"instance",
"of",
"the",
"Slack",
"log",
"driver",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Log/LogManager.php#L296-L314 |
txj123/zilf | src/Zilf/Log/LogManager.php | LogManager.createSyslogDriver | protected function createSyslogDriver(array $config)
{
return new Monolog(
$this->parseChannel($config), [
$this->prepareHandler(
new SyslogHandler(
$this->app['config']['app.name'], $config['facility'] ?? LOG_USER, $this->level($config)
)
),
]
);
} | php | protected function createSyslogDriver(array $config)
{
return new Monolog(
$this->parseChannel($config), [
$this->prepareHandler(
new SyslogHandler(
$this->app['config']['app.name'], $config['facility'] ?? LOG_USER, $this->level($config)
)
),
]
);
} | [
"protected",
"function",
"createSyslogDriver",
"(",
"array",
"$",
"config",
")",
"{",
"return",
"new",
"Monolog",
"(",
"$",
"this",
"->",
"parseChannel",
"(",
"$",
"config",
")",
",",
"[",
"$",
"this",
"->",
"prepareHandler",
"(",
"new",
"SyslogHandler",
"... | Create an instance of the syslog log driver.
@param array $config
@return \Psr\Log\LoggerInterface | [
"Create",
"an",
"instance",
"of",
"the",
"syslog",
"log",
"driver",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Log/LogManager.php#L322-L333 |
txj123/zilf | src/Zilf/Log/LogManager.php | LogManager.createMonologDriver | protected function createMonologDriver(array $config)
{
if (!is_a($config['handler'], HandlerInterface::class, true)) {
throw new InvalidArgumentException(
$config['handler'] . ' must be an instance of ' . HandlerInterface::class
);
}
return new Monolog(
$this->parseChannel($config), [$this->prepareHandler(
$this->app->make($config['handler'], $config['with'] ?? []), $config
)]
);
} | php | protected function createMonologDriver(array $config)
{
if (!is_a($config['handler'], HandlerInterface::class, true)) {
throw new InvalidArgumentException(
$config['handler'] . ' must be an instance of ' . HandlerInterface::class
);
}
return new Monolog(
$this->parseChannel($config), [$this->prepareHandler(
$this->app->make($config['handler'], $config['with'] ?? []), $config
)]
);
} | [
"protected",
"function",
"createMonologDriver",
"(",
"array",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"is_a",
"(",
"$",
"config",
"[",
"'handler'",
"]",
",",
"HandlerInterface",
"::",
"class",
",",
"true",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentEx... | Create an instance of any handler available in Monolog.
@param array $config
@return \Psr\Log\LoggerInterface
@throws \InvalidArgumentException
@throws \Illuminate\Contracts\Container\BindingResolutionException | [
"Create",
"an",
"instance",
"of",
"any",
"handler",
"available",
"in",
"Monolog",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Log/LogManager.php#L363-L376 |
txj123/zilf | src/Zilf/Redis/Connectors/PhpRedisConnector.php | PhpRedisConnector.establishConnection | protected function establishConnection($client, array $config)
{
$client->{Arr::get($config, 'persistent', false) === true ? 'pconnect' : 'connect'}(
$config['host'], $config['port'], Arr::get($config, 'timeout', 0)
);
} | php | protected function establishConnection($client, array $config)
{
$client->{Arr::get($config, 'persistent', false) === true ? 'pconnect' : 'connect'}(
$config['host'], $config['port'], Arr::get($config, 'timeout', 0)
);
} | [
"protected",
"function",
"establishConnection",
"(",
"$",
"client",
",",
"array",
"$",
"config",
")",
"{",
"$",
"client",
"->",
"{",
"Arr",
"::",
"get",
"(",
"$",
"config",
",",
"'persistent'",
",",
"false",
")",
"===",
"true",
"?",
"'pconnect'",
":",
... | Establish a connection with the Redis host.
@param \Redis $client
@param array $config
@return void | [
"Establish",
"a",
"connection",
"with",
"the",
"Redis",
"host",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Redis/Connectors/PhpRedisConnector.php#L105-L110 |
txj123/zilf | src/Zilf/Redis/Connectors/PhpRedisConnector.php | PhpRedisConnector.createRedisClusterInstance | protected function createRedisClusterInstance(array $servers, array $options)
{
return new RedisCluster(
null,
array_values($servers),
Arr::get($options, 'timeout', 0),
Arr::get($options, 'read_timeout', 0),
isset($options['persistent']) && $options['persistent']
);
} | php | protected function createRedisClusterInstance(array $servers, array $options)
{
return new RedisCluster(
null,
array_values($servers),
Arr::get($options, 'timeout', 0),
Arr::get($options, 'read_timeout', 0),
isset($options['persistent']) && $options['persistent']
);
} | [
"protected",
"function",
"createRedisClusterInstance",
"(",
"array",
"$",
"servers",
",",
"array",
"$",
"options",
")",
"{",
"return",
"new",
"RedisCluster",
"(",
"null",
",",
"array_values",
"(",
"$",
"servers",
")",
",",
"Arr",
"::",
"get",
"(",
"$",
"op... | Create a new redis cluster instance.
@param array $servers
@param array $options
@return \RedisCluster | [
"Create",
"a",
"new",
"redis",
"cluster",
"instance",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Redis/Connectors/PhpRedisConnector.php#L119-L128 |
oxygen-cms/core | src/View/StringView.php | StringView.render | public function render(Closure $callback = null) {
$contents = $this->renderContents();
$response = isset($callback) ? $callback($this, $contents) : null;
// Once we have the contents of the view, we will flush the sections if we are
// done rendering all views so that there is nothing left hanging over when
// another view is rendered in the future by the application developers.
$this->factory->flushSectionsIfDoneRendering();
return $response ?: $contents;
} | php | public function render(Closure $callback = null) {
$contents = $this->renderContents();
$response = isset($callback) ? $callback($this, $contents) : null;
// Once we have the contents of the view, we will flush the sections if we are
// done rendering all views so that there is nothing left hanging over when
// another view is rendered in the future by the application developers.
$this->factory->flushSectionsIfDoneRendering();
return $response ?: $contents;
} | [
"public",
"function",
"render",
"(",
"Closure",
"$",
"callback",
"=",
"null",
")",
"{",
"$",
"contents",
"=",
"$",
"this",
"->",
"renderContents",
"(",
")",
";",
"$",
"response",
"=",
"isset",
"(",
"$",
"callback",
")",
"?",
"$",
"callback",
"(",
"$"... | Get the string contents of the view.
@param \Closure $callback
@return string | [
"Get",
"the",
"string",
"contents",
"of",
"the",
"view",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/View/StringView.php#L62-L73 |
oxygen-cms/core | src/View/StringView.php | StringView.renderContents | protected function renderContents() {
// We will keep track of the amount of views being rendered so we can flush
// the section after the complete rendering operation is done. This will
// clear out the sections for any separate views that may be rendered.
$this->factory->incrementRender();
$contents = $this->getContents();
// Once we've finished rendering the view, we'll decrement the render count
// so that each sections get flushed out next time a view is created and
// no old sections are staying around in the memory of an environment.
$this->factory->decrementRender();
return $contents;
} | php | protected function renderContents() {
// We will keep track of the amount of views being rendered so we can flush
// the section after the complete rendering operation is done. This will
// clear out the sections for any separate views that may be rendered.
$this->factory->incrementRender();
$contents = $this->getContents();
// Once we've finished rendering the view, we'll decrement the render count
// so that each sections get flushed out next time a view is created and
// no old sections are staying around in the memory of an environment.
$this->factory->decrementRender();
return $contents;
} | [
"protected",
"function",
"renderContents",
"(",
")",
"{",
"// We will keep track of the amount of views being rendered so we can flush",
"// the section after the complete rendering operation is done. This will",
"// clear out the sections for any separate views that may be rendered.",
"$",
"thi... | Get the contents of the view instance.
@return string | [
"Get",
"the",
"contents",
"of",
"the",
"view",
"instance",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/View/StringView.php#L80-L94 |
oxygen-cms/core | src/View/StringView.php | StringView.gatherInfo | protected function gatherInfo() {
$info = new stdClass();
$info->contents = $this->contents;
$info->path = $this->path;
$info->lastModified = $this->lastModified;
return $info;
} | php | protected function gatherInfo() {
$info = new stdClass();
$info->contents = $this->contents;
$info->path = $this->path;
$info->lastModified = $this->lastModified;
return $info;
} | [
"protected",
"function",
"gatherInfo",
"(",
")",
"{",
"$",
"info",
"=",
"new",
"stdClass",
"(",
")",
";",
"$",
"info",
"->",
"contents",
"=",
"$",
"this",
"->",
"contents",
";",
"$",
"info",
"->",
"path",
"=",
"$",
"this",
"->",
"path",
";",
"$",
... | Gathers the information about the view.
@return \stdClass | [
"Gathers",
"the",
"information",
"about",
"the",
"view",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/View/StringView.php#L110-L117 |
railken/search-query | src/Languages/BoomTree/Resolvers/ValueResolver.php | ValueResolver.parseValue | public function parseValue($value)
{
if (strlen($value) === 0) {
return $value;
}
if ($value[0] === '"' || $value[0] === "'") {
$value = substr($value, 1, -1);
}
$value = stripslashes($value);
return $value;
} | php | public function parseValue($value)
{
if (strlen($value) === 0) {
return $value;
}
if ($value[0] === '"' || $value[0] === "'") {
$value = substr($value, 1, -1);
}
$value = stripslashes($value);
return $value;
} | [
"public",
"function",
"parseValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
"===",
"0",
")",
"{",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"$",
"value",
"[",
"0",
"]",
"===",
"'\"'",
"||",
"$",
"value",
"["... | Parse the value before adding to the node.
@param mixed $value
@return mixed | [
"Parse",
"the",
"value",
"before",
"adding",
"to",
"the",
"node",
"."
] | train | https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/ValueResolver.php#L35-L48 |
phug-php/compiler | src/Phug/Compiler/Util/YieldHandlerTrait.php | YieldHandlerTrait.setImportNode | public function setImportNode(NodeInterface $importNode)
{
$this->importNode = $importNode;
$this->importNodeYielded = false;
return $this;
} | php | public function setImportNode(NodeInterface $importNode)
{
$this->importNode = $importNode;
$this->importNodeYielded = false;
return $this;
} | [
"public",
"function",
"setImportNode",
"(",
"NodeInterface",
"$",
"importNode",
")",
"{",
"$",
"this",
"->",
"importNode",
"=",
"$",
"importNode",
";",
"$",
"this",
"->",
"importNodeYielded",
"=",
"false",
";",
"return",
"$",
"this",
";",
"}"
] | @param NodeInterface $importNode
@return $this | [
"@param",
"NodeInterface",
"$importNode"
] | train | https://github.com/phug-php/compiler/blob/13fc3f44ef783fbdb4f052e3982eda33e1291a76/src/Phug/Compiler/Util/YieldHandlerTrait.php#L29-L35 |
damonjones/Vebra-PHP-API-Wrapper | lib/YDD/Vebra/Model/ChangedPropertySummary.php | ChangedPropertySummary.getClientId | public function getClientId()
{
preg_match('#branch\/(\d+)/#', $this->url, $matches);
return isset($matches[1]) ? (int) $matches[1] : null;
} | php | public function getClientId()
{
preg_match('#branch\/(\d+)/#', $this->url, $matches);
return isset($matches[1]) ? (int) $matches[1] : null;
} | [
"public",
"function",
"getClientId",
"(",
")",
"{",
"preg_match",
"(",
"'#branch\\/(\\d+)/#'",
",",
"$",
"this",
"->",
"url",
",",
"$",
"matches",
")",
";",
"return",
"isset",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
"?",
"(",
"int",
")",
"$",
"match... | get ClientId
@return int $clientId | [
"get",
"ClientId"
] | train | https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/Model/ChangedPropertySummary.php#L51-L56 |
oxygen-cms/core | src/Html/Form/EditableField.php | EditableField.getValue | public function getValue() {
if($this->input->old($this->getMeta()->name)) {
return $this->getMeta()->getType()->transformInput($this->getMeta(), $this->input->old($this->getMeta()->name));
} else {
if($this->value !== null) {
return parent::getValue();
} else {
return null;
}
}
} | php | public function getValue() {
if($this->input->old($this->getMeta()->name)) {
return $this->getMeta()->getType()->transformInput($this->getMeta(), $this->input->old($this->getMeta()->name));
} else {
if($this->value !== null) {
return parent::getValue();
} else {
return null;
}
}
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"input",
"->",
"old",
"(",
"$",
"this",
"->",
"getMeta",
"(",
")",
"->",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getMeta",
"(",
")",
"->",
"getType",
"(",... | Get the value of the field.
@return mixed | [
"Get",
"the",
"value",
"of",
"the",
"field",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Form/EditableField.php#L49-L59 |
oxygen-cms/core | src/Html/Form/EditableField.php | EditableField.render | public function render(array $arguments = [], $renderer = null) {
if(!$this->getMeta()->editable) {
throw new Exception('Field "' . $this->getMeta()->name . '" is not editable');
}
$type = $this->getMeta()->type;
if($renderer === null) {
if(!isset(static::$renderers[$type])) {
if(static::$fallbackRenderer === null) {
throw new Exception('No Default Renderer Exists for Class "' . get_class() . '"');
}
$renderer = static::$fallbackRenderer;
} else {
if(is_callable(static::$renderers[$type])) {
$callable = static::$renderers[$type];
static::$renderers[$type] = $callable();
}
$renderer = static::$renderers[$type];
}
} else {
if(is_callable($renderer)) {
$renderer = $renderer();
}
}
return $renderer->render($this, $arguments);
} | php | public function render(array $arguments = [], $renderer = null) {
if(!$this->getMeta()->editable) {
throw new Exception('Field "' . $this->getMeta()->name . '" is not editable');
}
$type = $this->getMeta()->type;
if($renderer === null) {
if(!isset(static::$renderers[$type])) {
if(static::$fallbackRenderer === null) {
throw new Exception('No Default Renderer Exists for Class "' . get_class() . '"');
}
$renderer = static::$fallbackRenderer;
} else {
if(is_callable(static::$renderers[$type])) {
$callable = static::$renderers[$type];
static::$renderers[$type] = $callable();
}
$renderer = static::$renderers[$type];
}
} else {
if(is_callable($renderer)) {
$renderer = $renderer();
}
}
return $renderer->render($this, $arguments);
} | [
"public",
"function",
"render",
"(",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"$",
"renderer",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getMeta",
"(",
")",
"->",
"editable",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Fiel... | Renders the object.
@param array $arguments
@param RendererInterface|callable $renderer
@throws Exception if no renderer has been set or if the field is not editable
@return string the rendered object | [
"Renders",
"the",
"object",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Form/EditableField.php#L97-L123 |
oxygen-cms/core | src/Html/Form/EditableField.php | EditableField.fromEntity | public static function fromEntity(FieldMetadata $meta, Request $input, $entity) {
$instance = new static($meta, $input, $entity->getAttribute($meta->name));
return $instance;
} | php | public static function fromEntity(FieldMetadata $meta, Request $input, $entity) {
$instance = new static($meta, $input, $entity->getAttribute($meta->name));
return $instance;
} | [
"public",
"static",
"function",
"fromEntity",
"(",
"FieldMetadata",
"$",
"meta",
",",
"Request",
"$",
"input",
",",
"$",
"entity",
")",
"{",
"$",
"instance",
"=",
"new",
"static",
"(",
"$",
"meta",
",",
"$",
"input",
",",
"$",
"entity",
"->",
"getAttri... | Create a field from meta and a model
@param FieldMetadata $meta
@param \Illuminate\Http\Request $input
@param object $entity
@return \Oxygen\Core\Form\FieldMetadata | [
"Create",
"a",
"field",
"from",
"meta",
"and",
"a",
"model"
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Form/EditableField.php#L133-L137 |
txj123/zilf | src/Zilf/Redis/RedisManager.php | RedisManager.resolve | protected function resolve($name)
{
$options = Arr::get($this->config, 'options', []);
if (isset($this->config[$name])) {
return $this->connector()->connect($this->config[$name], $options);
}
if (isset($this->config['clusters'][$name])) {
return $this->resolveCluster($name);
}
throw new \InvalidArgumentException(
"Redis connection [{$name}] not configured."
);
} | php | protected function resolve($name)
{
$options = Arr::get($this->config, 'options', []);
if (isset($this->config[$name])) {
return $this->connector()->connect($this->config[$name], $options);
}
if (isset($this->config['clusters'][$name])) {
return $this->resolveCluster($name);
}
throw new \InvalidArgumentException(
"Redis connection [{$name}] not configured."
);
} | [
"protected",
"function",
"resolve",
"(",
"$",
"name",
")",
"{",
"$",
"options",
"=",
"Arr",
"::",
"get",
"(",
"$",
"this",
"->",
"config",
",",
"'options'",
",",
"[",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"config",
"[",
"$",
... | Resolve the given connection by name.
@param string $name
@return \Zilf\Redis\Connections\Connection
@throws \InvalidArgumentException | [
"Resolve",
"the",
"given",
"connection",
"by",
"name",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Redis/RedisManager.php#L70-L85 |
txj123/zilf | src/Zilf/Redis/RedisManager.php | RedisManager.resolveCluster | protected function resolveCluster($name)
{
$clusterOptions = Arr::get($this->config, 'clusters.options', []);
return $this->connector()->connectToCluster(
$this->config['clusters'][$name], $clusterOptions, Arr::get($this->config, 'options', [])
);
} | php | protected function resolveCluster($name)
{
$clusterOptions = Arr::get($this->config, 'clusters.options', []);
return $this->connector()->connectToCluster(
$this->config['clusters'][$name], $clusterOptions, Arr::get($this->config, 'options', [])
);
} | [
"protected",
"function",
"resolveCluster",
"(",
"$",
"name",
")",
"{",
"$",
"clusterOptions",
"=",
"Arr",
"::",
"get",
"(",
"$",
"this",
"->",
"config",
",",
"'clusters.options'",
",",
"[",
"]",
")",
";",
"return",
"$",
"this",
"->",
"connector",
"(",
... | Resolve the given cluster connection by name.
@param string $name
@return \Zilf\Redis\Connections\Connection | [
"Resolve",
"the",
"given",
"cluster",
"connection",
"by",
"name",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Redis/RedisManager.php#L94-L101 |
txj123/zilf | src/Zilf/HttpFoundation/IpUtils.php | IpUtils.checkIp6 | public static function checkIp6($requestIp, $ip)
{
if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) {
throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
}
if (false !== strpos($ip, '/')) {
list($address, $netmask) = explode('/', $ip, 2);
if ($netmask < 1 || $netmask > 128) {
return false;
}
} else {
$address = $ip;
$netmask = 128;
}
$bytesAddr = unpack('n*', @inet_pton($address));
$bytesTest = unpack('n*', @inet_pton($requestIp));
if (!$bytesAddr || !$bytesTest) {
return false;
}
for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
$left = $netmask - 16 * ($i - 1);
$left = ($left <= 16) ? $left : 16;
$mask = ~(0xffff >> $left) & 0xffff;
if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
return false;
}
}
return true;
} | php | public static function checkIp6($requestIp, $ip)
{
if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) {
throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
}
if (false !== strpos($ip, '/')) {
list($address, $netmask) = explode('/', $ip, 2);
if ($netmask < 1 || $netmask > 128) {
return false;
}
} else {
$address = $ip;
$netmask = 128;
}
$bytesAddr = unpack('n*', @inet_pton($address));
$bytesTest = unpack('n*', @inet_pton($requestIp));
if (!$bytesAddr || !$bytesTest) {
return false;
}
for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
$left = $netmask - 16 * ($i - 1);
$left = ($left <= 16) ? $left : 16;
$mask = ~(0xffff >> $left) & 0xffff;
if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
return false;
}
}
return true;
} | [
"public",
"static",
"function",
"checkIp6",
"(",
"$",
"requestIp",
",",
"$",
"ip",
")",
"{",
"if",
"(",
"!",
"(",
"(",
"extension_loaded",
"(",
"'sockets'",
")",
"&&",
"defined",
"(",
"'AF_INET6'",
")",
")",
"||",
"@",
"inet_pton",
"(",
"'::1'",
")",
... | Compares two IPv6 addresses.
In case a subnet is given, it checks if it contains the request IP.
@author David Soria Parra <dsp at php dot net>
@see https://github.com/dsp/v6tools
@param string $requestIp IPv6 address to check
@param string $ip IPv6 address or subnet in CIDR notation
@return bool Whether the IP is valid
@throws \RuntimeException When IPV6 support is not enabled | [
"Compares",
"two",
"IPv6",
"addresses",
".",
"In",
"case",
"a",
"subnet",
"is",
"given",
"it",
"checks",
"if",
"it",
"contains",
"the",
"request",
"IP",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/IpUtils.php#L101-L135 |
txj123/zilf | src/Zilf/HttpFoundation/HeaderBag.php | HeaderBag.remove | public function remove($key)
{
$key = str_replace('_', '-', strtolower($key));
unset($this->headers[$key]);
if ('cache-control' === $key) {
$this->cacheControl = array();
}
} | php | public function remove($key)
{
$key = str_replace('_', '-', strtolower($key));
unset($this->headers[$key]);
if ('cache-control' === $key) {
$this->cacheControl = array();
}
} | [
"public",
"function",
"remove",
"(",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"str_replace",
"(",
"'_'",
",",
"'-'",
",",
"strtolower",
"(",
"$",
"key",
")",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"headers",
"[",
"$",
"key",
"]",
")",
";",
"i... | Removes a header.
@param string $key The HTTP header name | [
"Removes",
"a",
"header",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/HeaderBag.php#L186-L195 |
oxygen-cms/core | src/Console/ConsoleServiceProvider.php | ConsoleServiceProvider.boot | public function boot() {
$this->commands(BlueprintListCommand::class);
$this->commands(BlueprintDetailCommand::class);
$this->commands(FieldSetDetailCommand::class);
$this->commands(PackageMigrateCommand::class);
} | php | public function boot() {
$this->commands(BlueprintListCommand::class);
$this->commands(BlueprintDetailCommand::class);
$this->commands(FieldSetDetailCommand::class);
$this->commands(PackageMigrateCommand::class);
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"this",
"->",
"commands",
"(",
"BlueprintListCommand",
"::",
"class",
")",
";",
"$",
"this",
"->",
"commands",
"(",
"BlueprintDetailCommand",
"::",
"class",
")",
";",
"$",
"this",
"->",
"commands",
"(",
"... | Bootstrap the application events.
@return void | [
"Bootstrap",
"the",
"application",
"events",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/ConsoleServiceProvider.php#L23-L28 |
oxygen-cms/core | src/Console/ConsoleServiceProvider.php | ConsoleServiceProvider.register | public function register() {
$this->app->singleton(PackageMigrateCommand::class, function () {
return new PackageMigrateCommand($this->app['migrator'], $this->app[AutomaticMigrator::class]);
});
} | php | public function register() {
$this->app->singleton(PackageMigrateCommand::class, function () {
return new PackageMigrateCommand($this->app['migrator'], $this->app[AutomaticMigrator::class]);
});
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"singleton",
"(",
"PackageMigrateCommand",
"::",
"class",
",",
"function",
"(",
")",
"{",
"return",
"new",
"PackageMigrateCommand",
"(",
"$",
"this",
"->",
"app",
"[",
"'migra... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Console/ConsoleServiceProvider.php#L35-L39 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Mapper/ScopeMapper.php | ScopeMapper.scope | public function scope($scope)
{
$scope = (new Scope())->scope($scope);
$this->scopes[] = $scope;
return $scope;
} | php | public function scope($scope)
{
$scope = (new Scope())->scope($scope);
$this->scopes[] = $scope;
return $scope;
} | [
"public",
"function",
"scope",
"(",
"$",
"scope",
")",
"{",
"$",
"scope",
"=",
"(",
"new",
"Scope",
"(",
")",
")",
"->",
"scope",
"(",
"$",
"scope",
")",
";",
"$",
"this",
"->",
"scopes",
"[",
"]",
"=",
"$",
"scope",
";",
"return",
"$",
"scope"... | Add a scope.
@param string $scope
@access public
@return ScopeMapper | [
"Add",
"a",
"scope",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Mapper/ScopeMapper.php#L38-L44 |
xutl/qcloud-cmq | src/Queue.php | Queue.batchReceiveMessageAsync | public function batchReceiveMessageAsync($numOfMessages, AsyncCallback $callback = NULL)
{
$request = new BatchReceiveMessageRequest($this->queueName, $numOfMessages);
return $this->client->sendRequestAsync($request, $response, $callback);
} | php | public function batchReceiveMessageAsync($numOfMessages, AsyncCallback $callback = NULL)
{
$request = new BatchReceiveMessageRequest($this->queueName, $numOfMessages);
return $this->client->sendRequestAsync($request, $response, $callback);
} | [
"public",
"function",
"batchReceiveMessageAsync",
"(",
"$",
"numOfMessages",
",",
"AsyncCallback",
"$",
"callback",
"=",
"NULL",
")",
"{",
"$",
"request",
"=",
"new",
"BatchReceiveMessageRequest",
"(",
"$",
"this",
"->",
"queueName",
",",
"$",
"numOfMessages",
"... | 异步批量消费消息
@param int $numOfMessages
@param AsyncCallback|NULL $callback
@return Http\Promise | [
"异步批量消费消息"
] | train | https://github.com/xutl/qcloud-cmq/blob/f48b905c2d4001817126f0c25a0433acda79ea6a/src/Queue.php#L194-L198 |
txj123/zilf | src/Zilf/Cache/ApcStore.php | ApcStore.put | public function put($key, $value, $minutes)
{
$this->apc->put($this->prefix.$key, $value, (int) ($minutes * 60));
} | php | public function put($key, $value, $minutes)
{
$this->apc->put($this->prefix.$key, $value, (int) ($minutes * 60));
} | [
"public",
"function",
"put",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"minutes",
")",
"{",
"$",
"this",
"->",
"apc",
"->",
"put",
"(",
"$",
"this",
"->",
"prefix",
".",
"$",
"key",
",",
"$",
"value",
",",
"(",
"int",
")",
"(",
"$",
"minu... | Store an item in the cache for a given number of minutes.
@param string $key
@param mixed $value
@param float|int $minutes
@return void | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"for",
"a",
"given",
"number",
"of",
"minutes",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/ApcStore.php#L61-L64 |
txj123/zilf | src/Zilf/Bus/BusServiceProvider.php | BusServiceProvider.register | public function register()
{
Zilf::$container->register(
Dispatcher::class, function () {
return new Dispatcher(
function ($connection = null) {
return Zilf::$container['queue']->connection($connection);
}
);
}
);
} | php | public function register()
{
Zilf::$container->register(
Dispatcher::class, function () {
return new Dispatcher(
function ($connection = null) {
return Zilf::$container['queue']->connection($connection);
}
);
}
);
} | [
"public",
"function",
"register",
"(",
")",
"{",
"Zilf",
"::",
"$",
"container",
"->",
"register",
"(",
"Dispatcher",
"::",
"class",
",",
"function",
"(",
")",
"{",
"return",
"new",
"Dispatcher",
"(",
"function",
"(",
"$",
"connection",
"=",
"null",
")",... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Bus/BusServiceProvider.php#L25-L36 |
awurth/SlimHelpers | Controller/RestTrait.php | RestTrait.created | protected function created(Response $response, $route, array $params = [])
{
return $this->redirect($response, $route, $params)->withStatus(201);
} | php | protected function created(Response $response, $route, array $params = [])
{
return $this->redirect($response, $route, $params)->withStatus(201);
} | [
"protected",
"function",
"created",
"(",
"Response",
"$",
"response",
",",
"$",
"route",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"redirect",
"(",
"$",
"response",
",",
"$",
"route",
",",
"$",
"params",
")",
... | Returns a "201 Created" response with a location header.
@param Response $response
@param string $route
@param array $params
@return Response | [
"Returns",
"a",
"201",
"Created",
"response",
"with",
"a",
"location",
"header",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/RestTrait.php#L33-L36 |
txj123/zilf | src/Zilf/View/ViewServiceProvider.php | ViewServiceProvider.registerFactory | public function registerFactory()
{
Zilf::$container->register(
'view', function () {
// Next we need to grab the engine resolver instance that will be used by the
// environment. The resolver will be used by an environment to get each of
// the various engine implementations such as plain PHP or Blade engine.
$resolver = Zilf::$container->getShare('view.engine.resolver');
$finder = Zilf::$container->getShare('view.finder');
$factory = $this->createFactory($resolver, $finder);
// We will also set the container instance on this view environment since the
// view composers may be classes registered in the container, which allows
// for great testable, flexible composers for the application developer.
/* $factory->setContainer($app);
$factory->share('app', $app);*/
return $factory;
}
);
} | php | public function registerFactory()
{
Zilf::$container->register(
'view', function () {
// Next we need to grab the engine resolver instance that will be used by the
// environment. The resolver will be used by an environment to get each of
// the various engine implementations such as plain PHP or Blade engine.
$resolver = Zilf::$container->getShare('view.engine.resolver');
$finder = Zilf::$container->getShare('view.finder');
$factory = $this->createFactory($resolver, $finder);
// We will also set the container instance on this view environment since the
// view composers may be classes registered in the container, which allows
// for great testable, flexible composers for the application developer.
/* $factory->setContainer($app);
$factory->share('app', $app);*/
return $factory;
}
);
} | [
"public",
"function",
"registerFactory",
"(",
")",
"{",
"Zilf",
"::",
"$",
"container",
"->",
"register",
"(",
"'view'",
",",
"function",
"(",
")",
"{",
"// Next we need to grab the engine resolver instance that will be used by the",
"// environment. The resolver will be used... | Register the view environment.
@return void | [
"Register",
"the",
"view",
"environment",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/View/ViewServiceProvider.php#L34-L57 |
txj123/zilf | src/Zilf/View/ViewServiceProvider.php | ViewServiceProvider.registerViewFinder | public function registerViewFinder()
{
Zilf::$container->register(
'view.finder', function ($app) {
return new FileViewFinder(Zilf::$container['files'], [Zilf::$app->resourcePath()]);
}
);
} | php | public function registerViewFinder()
{
Zilf::$container->register(
'view.finder', function ($app) {
return new FileViewFinder(Zilf::$container['files'], [Zilf::$app->resourcePath()]);
}
);
} | [
"public",
"function",
"registerViewFinder",
"(",
")",
"{",
"Zilf",
"::",
"$",
"container",
"->",
"register",
"(",
"'view.finder'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"new",
"FileViewFinder",
"(",
"Zilf",
"::",
"$",
"container",
"[",
"'fi... | Register the view finder implementation.
@return void | [
"Register",
"the",
"view",
"finder",
"implementation",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/View/ViewServiceProvider.php#L76-L83 |
txj123/zilf | src/Zilf/View/ViewServiceProvider.php | ViewServiceProvider.registerBladeEngine | public function registerBladeEngine($resolver)
{
// The Compiler engine requires an instance of the CompilerInterface, which in
// this case will be the Blade compiler, so we'll first create the compiler
// instance to pass into the engine so it can compile the views properly.
Zilf::$container->register(
'blade.compiler', function () {
return new BladeCompiler(
Zilf::$container['files'], Zilf::$app->runtimePath().'/views'
);
}
);
$resolver->register(
'blade', function () {
return new CompilerEngine(Zilf::$container['blade.compiler']);
}
);
} | php | public function registerBladeEngine($resolver)
{
// The Compiler engine requires an instance of the CompilerInterface, which in
// this case will be the Blade compiler, so we'll first create the compiler
// instance to pass into the engine so it can compile the views properly.
Zilf::$container->register(
'blade.compiler', function () {
return new BladeCompiler(
Zilf::$container['files'], Zilf::$app->runtimePath().'/views'
);
}
);
$resolver->register(
'blade', function () {
return new CompilerEngine(Zilf::$container['blade.compiler']);
}
);
} | [
"public",
"function",
"registerBladeEngine",
"(",
"$",
"resolver",
")",
"{",
"// The Compiler engine requires an instance of the CompilerInterface, which in",
"// this case will be the Blade compiler, so we'll first create the compiler",
"// instance to pass into the engine so it can compile the... | Register the Blade engine implementation.
@param \Zilf\View\Engines\EngineResolver $resolver
@return void | [
"Register",
"the",
"Blade",
"engine",
"implementation",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/View/ViewServiceProvider.php#L144-L164 |
schmunk42/p3extensions | components/image/drivers/Image_ImageMagick_Driver.php | Image_ImageMagick_Driver.process | public function process($image, $actions, $dir, $file, $render = FALSE)
{
// We only need the filename
$image = $image['file'];
// Unique temporary filename
$this->tmp_image = $dir.'k2img--'.sha1(time().$dir.$file).substr($file, strrpos($file, '.'));
// Copy the image to the temporary file
copy($image, $this->tmp_image);
// Quality change is done last
if(isset ($actions['quality'])) {
$quality = $actions['quality'];
unset($actions['quality']);
}
// Use 95 for the default quality
empty($quality) and $quality = 95;
// All calls to these will need to be escaped, so do it now
$this->cmd_image = escapeshellarg($this->tmp_image);
$this->new_image = ($render)? $this->cmd_image : escapeshellarg($dir.$file);
if ($status = $this->execute($actions))
{
// Use convert to change the image into its final version. This is
// done to allow the file type to change correctly, and to handle
// the quality conversion in the most effective way possible.
if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -quality '.$quality.'% '.$this->cmd_image.' '.$this->new_image))
{
$this->errors[] = $error;
}
else
{
// Output the image directly to the browser
if ($render !== FALSE)
{
$contents = file_get_contents($this->tmp_image);
switch (substr($file, strrpos($file, '.') + 1))
{
case 'jpg':
case 'jpeg':
header('Content-Type: image/jpeg');
break;
case 'gif':
header('Content-Type: image/gif');
break;
case 'png':
header('Content-Type: image/png');
break;
}
echo $contents;
}
}
}
// Remove the temporary image
unlink($this->tmp_image);
$this->tmp_image = '';
return $status;
} | php | public function process($image, $actions, $dir, $file, $render = FALSE)
{
// We only need the filename
$image = $image['file'];
// Unique temporary filename
$this->tmp_image = $dir.'k2img--'.sha1(time().$dir.$file).substr($file, strrpos($file, '.'));
// Copy the image to the temporary file
copy($image, $this->tmp_image);
// Quality change is done last
if(isset ($actions['quality'])) {
$quality = $actions['quality'];
unset($actions['quality']);
}
// Use 95 for the default quality
empty($quality) and $quality = 95;
// All calls to these will need to be escaped, so do it now
$this->cmd_image = escapeshellarg($this->tmp_image);
$this->new_image = ($render)? $this->cmd_image : escapeshellarg($dir.$file);
if ($status = $this->execute($actions))
{
// Use convert to change the image into its final version. This is
// done to allow the file type to change correctly, and to handle
// the quality conversion in the most effective way possible.
if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -quality '.$quality.'% '.$this->cmd_image.' '.$this->new_image))
{
$this->errors[] = $error;
}
else
{
// Output the image directly to the browser
if ($render !== FALSE)
{
$contents = file_get_contents($this->tmp_image);
switch (substr($file, strrpos($file, '.') + 1))
{
case 'jpg':
case 'jpeg':
header('Content-Type: image/jpeg');
break;
case 'gif':
header('Content-Type: image/gif');
break;
case 'png':
header('Content-Type: image/png');
break;
}
echo $contents;
}
}
}
// Remove the temporary image
unlink($this->tmp_image);
$this->tmp_image = '';
return $status;
} | [
"public",
"function",
"process",
"(",
"$",
"image",
",",
"$",
"actions",
",",
"$",
"dir",
",",
"$",
"file",
",",
"$",
"render",
"=",
"FALSE",
")",
"{",
"// We only need the filename",
"$",
"image",
"=",
"$",
"image",
"[",
"'file'",
"]",
";",
"// Unique... | Creates a temporary image and executes the given actions. By creating a
temporary copy of the image before manipulating it, this process is atomic. | [
"Creates",
"a",
"temporary",
"image",
"and",
"executes",
"the",
"given",
"actions",
".",
"By",
"creating",
"a",
"temporary",
"copy",
"of",
"the",
"image",
"before",
"manipulating",
"it",
"this",
"process",
"is",
"atomic",
"."
] | train | https://github.com/schmunk42/p3extensions/blob/93999c06fc8e3eadd83983d001df231e46b06838/components/image/drivers/Image_ImageMagick_Driver.php#L57-L119 |
txj123/zilf | src/Zilf/System/Controller.php | Controller.render | public function render($viewFile, $parameters = [], Response $response = null)
{
if (null === $response) {
$response = new Response();
}
return $response->setContent($this->getContent($viewFile, $parameters));
} | php | public function render($viewFile, $parameters = [], Response $response = null)
{
if (null === $response) {
$response = new Response();
}
return $response->setContent($this->getContent($viewFile, $parameters));
} | [
"public",
"function",
"render",
"(",
"$",
"viewFile",
",",
"$",
"parameters",
"=",
"[",
"]",
",",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"response",
")",
"{",
"$",
"response",
"=",
"new",
"Response",
"(",
... | 渲染视图
@param string $viewFile
@param array $parameters
@param Response|null $response
@return Response
@throws \Exception | [
"渲染视图"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Controller.php#L64-L71 |
txj123/zilf | src/Zilf/System/Controller.php | Controller.stream | public function stream($view = '', array $parameters = array(), Response $response = null)
{
return $this->render($view, $parameters, $response);
} | php | public function stream($view = '', array $parameters = array(), Response $response = null)
{
return $this->render($view, $parameters, $response);
} | [
"public",
"function",
"stream",
"(",
"$",
"view",
"=",
"''",
",",
"array",
"$",
"parameters",
"=",
"array",
"(",
")",
",",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"render",
"(",
"$",
"view",
",",
"$",
"param... | 返回视图的流数据
@param string $view
@param array $parameters
@param Response|null $response
@return Response
@throws \Exception | [
"返回视图的流数据"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Controller.php#L129-L132 |
oxygen-cms/core | src/Routing/BlueprintRegistrar.php | BlueprintRegistrar.blueprint | public function blueprint(Blueprint $blueprint) {
foreach($blueprint->getActions() as $action) {
$this->action($action);
}
} | php | public function blueprint(Blueprint $blueprint) {
foreach($blueprint->getActions() as $action) {
$this->action($action);
}
} | [
"public",
"function",
"blueprint",
"(",
"Blueprint",
"$",
"blueprint",
")",
"{",
"foreach",
"(",
"$",
"blueprint",
"->",
"getActions",
"(",
")",
"as",
"$",
"action",
")",
"{",
"$",
"this",
"->",
"action",
"(",
"$",
"action",
")",
";",
"}",
"}"
] | Generates a Route from a \Oxygen\Core\Blueprint\Blueprint
@param \Oxygen\Core\Blueprint\Blueprint $blueprint | [
"Generates",
"a",
"Route",
"from",
"a",
"\\",
"Oxygen",
"\\",
"Core",
"\\",
"Blueprint",
"\\",
"Blueprint"
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Routing/BlueprintRegistrar.php#L36-L40 |
oxygen-cms/core | src/Routing/BlueprintRegistrar.php | BlueprintRegistrar.action | public function action(Action $action) {
if($action->register === Action::REGISTER_AT_END) {
$this->registerActionsLast[] = $action;
} else {
if($action->register) {
$this->registerAction($action);
}
}
} | php | public function action(Action $action) {
if($action->register === Action::REGISTER_AT_END) {
$this->registerActionsLast[] = $action;
} else {
if($action->register) {
$this->registerAction($action);
}
}
} | [
"public",
"function",
"action",
"(",
"Action",
"$",
"action",
")",
"{",
"if",
"(",
"$",
"action",
"->",
"register",
"===",
"Action",
"::",
"REGISTER_AT_END",
")",
"{",
"$",
"this",
"->",
"registerActionsLast",
"[",
"]",
"=",
"$",
"action",
";",
"}",
"e... | Generates a Route from a Oxygen\Core\Action\Action
@param \Oxygen\Core\Action\Action $action | [
"Generates",
"a",
"Route",
"from",
"a",
"Oxygen",
"\\",
"Core",
"\\",
"Action",
"\\",
"Action"
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Routing/BlueprintRegistrar.php#L47-L55 |
despark/image-purify | src/Commands/MozJpeg.php | MozJpeg.getArguments | public function getArguments(): array
{
// We will need to process the arguments and merge them.
$arguments = parent::getArguments();
// If we have outfile setup don't act!
foreach ($arguments as $argument) {
if (strstr($argument, '-outfile') !== false) {
return $arguments;
}
}
if ($this->isOutSourceEqual()) // Check if not already specified
{
$this->outFileTemp = tempnam(sys_get_temp_dir(), 'img-prfy-');
$arguments[] = '-outfile '.escapeshellarg($this->outFileTemp);
} else {
$arguments[] = '-outfile '.escapeshellarg($this->getOutFile());
}
return $arguments;
} | php | public function getArguments(): array
{
// We will need to process the arguments and merge them.
$arguments = parent::getArguments();
// If we have outfile setup don't act!
foreach ($arguments as $argument) {
if (strstr($argument, '-outfile') !== false) {
return $arguments;
}
}
if ($this->isOutSourceEqual()) // Check if not already specified
{
$this->outFileTemp = tempnam(sys_get_temp_dir(), 'img-prfy-');
$arguments[] = '-outfile '.escapeshellarg($this->outFileTemp);
} else {
$arguments[] = '-outfile '.escapeshellarg($this->getOutFile());
}
return $arguments;
} | [
"public",
"function",
"getArguments",
"(",
")",
":",
"array",
"{",
"// We will need to process the arguments and merge them.",
"$",
"arguments",
"=",
"parent",
"::",
"getArguments",
"(",
")",
";",
"// If we have outfile setup don't act!",
"foreach",
"(",
"$",
"arguments",... | Gets all the arguments
@return array | [
"Gets",
"all",
"the",
"arguments"
] | train | https://github.com/despark/image-purify/blob/63066df047145a32ed11579439d0a2b085ce0484/src/Commands/MozJpeg.php#L63-L84 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.setTrustedProxies | public static function setTrustedProxies(array $proxies/*, int $trustedHeaderSet*/)
{
self::$trustedProxies = $proxies;
if (2 > func_num_args()) {
// @deprecated code path in 3.3, to be replaced by mandatory argument in 4.0.
throw new \InvalidArgumentException(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument. Defining it is required since version 3.3. See http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html for more info.', __METHOD__));
}
$trustedHeaderSet = func_get_arg(1);
foreach (self::$trustedHeaderNames as $header => $name) {
self::$trustedHeaders[$header] = $header & $trustedHeaderSet ? $name : null;
}
self::$trustedHeaderSet = $trustedHeaderSet;
} | php | public static function setTrustedProxies(array $proxies/*, int $trustedHeaderSet*/)
{
self::$trustedProxies = $proxies;
if (2 > func_num_args()) {
// @deprecated code path in 3.3, to be replaced by mandatory argument in 4.0.
throw new \InvalidArgumentException(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument. Defining it is required since version 3.3. See http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html for more info.', __METHOD__));
}
$trustedHeaderSet = func_get_arg(1);
foreach (self::$trustedHeaderNames as $header => $name) {
self::$trustedHeaders[$header] = $header & $trustedHeaderSet ? $name : null;
}
self::$trustedHeaderSet = $trustedHeaderSet;
} | [
"public",
"static",
"function",
"setTrustedProxies",
"(",
"array",
"$",
"proxies",
"/*, int $trustedHeaderSet*/",
")",
"{",
"self",
"::",
"$",
"trustedProxies",
"=",
"$",
"proxies",
";",
"if",
"(",
"2",
">",
"func_num_args",
"(",
")",
")",
"{",
"// @deprecated... | Sets a list of trusted proxies.
You should only list the reverse proxies that you manage directly.
@param array $proxies A list of trusted proxies
@param int $trustedHeaderSet A bit field of Request::HEADER_*, usually either Request::HEADER_FORWARDED or Request::HEADER_X_FORWARDED_ALL, to set which headers to trust from your proxies
@throws \InvalidArgumentException When $trustedHeaderSet is invalid | [
"Sets",
"a",
"list",
"of",
"trusted",
"proxies",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L599-L613 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.setTrustedHeaderName | public static function setTrustedHeaderName($key, $value)
{
@trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use "X-Forwarded-*" headers or the "Forwarded" header defined in RFC7239, and the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED);
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
}
self::$trustedHeaders[$key] = $value;
if (null !== $value) {
self::$trustedHeaderNames[$key] = $value;
}
} | php | public static function setTrustedHeaderName($key, $value)
{
@trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use "X-Forwarded-*" headers or the "Forwarded" header defined in RFC7239, and the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED);
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
}
self::$trustedHeaders[$key] = $value;
if (null !== $value) {
self::$trustedHeaderNames[$key] = $value;
}
} | [
"public",
"static",
"function",
"setTrustedHeaderName",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'The \"%s()\" method is deprecated since version 3.3 and will be removed in 4.0. Use \"X-Forwarded-*\" headers or the \"Forwarded\" head... | Sets the name for trusted headers.
The following header keys are supported:
* Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp())
* Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost())
* Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort())
* Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure())
* Request::HEADER_FORWARDED: defaults to Forwarded (see RFC 7239)
Setting an empty value allows to disable the trusted header for the given key.
@param string $key The header key
@param string $value The header name
@throws \InvalidArgumentException
@deprecated since version 3.3, to be removed in 4.0. Use "X-Forwarded-*" headers or the "Forwarded" header defined in RFC7239, and the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. | [
"Sets",
"the",
"name",
"for",
"trusted",
"headers",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L683-L696 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.getTrustedHeaderName | public static function getTrustedHeaderName($key)
{
if (2 > func_num_args() || func_get_arg(1)) {
@trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED);
}
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key));
}
return self::$trustedHeaders[$key];
} | php | public static function getTrustedHeaderName($key)
{
if (2 > func_num_args() || func_get_arg(1)) {
@trigger_error(sprintf('The "%s()" method is deprecated since version 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED);
}
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key));
}
return self::$trustedHeaders[$key];
} | [
"public",
"static",
"function",
"getTrustedHeaderName",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"2",
">",
"func_num_args",
"(",
")",
"||",
"func_get_arg",
"(",
"1",
")",
")",
"{",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'The \"%s()\" method is deprecated sin... | Gets the trusted proxy header name.
@param string $key The header key
@return string The header name
@throws \InvalidArgumentException
@deprecated since version 3.3, to be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead. | [
"Gets",
"the",
"trusted",
"proxy",
"header",
"name",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L709-L720 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.normalizeQueryString | public static function normalizeQueryString($qs)
{
if ('' == $qs) {
return '';
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $param) {
if ('' === $param || '=' === $param[0]) {
// Ignore useless delimiters, e.g. "x=y&".
// Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
// PHP also does not include them when building _GET.
continue;
}
$keyValuePair = explode('=', $param, 2);
// GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
// PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
// RFC 3986 with rawurlencode.
$parts[] = isset($keyValuePair[1]) ?
rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
rawurlencode(urldecode($keyValuePair[0]));
$order[] = urldecode($keyValuePair[0]);
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
} | php | public static function normalizeQueryString($qs)
{
if ('' == $qs) {
return '';
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $param) {
if ('' === $param || '=' === $param[0]) {
// Ignore useless delimiters, e.g. "x=y&".
// Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
// PHP also does not include them when building _GET.
continue;
}
$keyValuePair = explode('=', $param, 2);
// GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
// PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
// RFC 3986 with rawurlencode.
$parts[] = isset($keyValuePair[1]) ?
rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
rawurlencode(urldecode($keyValuePair[0]));
$order[] = urldecode($keyValuePair[0]);
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
} | [
"public",
"static",
"function",
"normalizeQueryString",
"(",
"$",
"qs",
")",
"{",
"if",
"(",
"''",
"==",
"$",
"qs",
")",
"{",
"return",
"''",
";",
"}",
"$",
"parts",
"=",
"array",
"(",
")",
";",
"$",
"order",
"=",
"array",
"(",
")",
";",
"foreach... | Normalizes a query string.
It builds a normalized query string, where keys/value pairs are alphabetized,
have consistent escaping and unneeded delimiters are removed.
@param string $qs Query string
@return string A normalized query string for the Request | [
"Normalizes",
"a",
"query",
"string",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L732-L763 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.getClientIps | public function getClientIps()
{
$ip = $this->server->get('REMOTE_ADDR');
if (!$this->isFromTrustedProxy()) {
return array($ip);
}
return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: array($ip);
} | php | public function getClientIps()
{
$ip = $this->server->get('REMOTE_ADDR');
if (!$this->isFromTrustedProxy()) {
return array($ip);
}
return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: array($ip);
} | [
"public",
"function",
"getClientIps",
"(",
")",
"{",
"$",
"ip",
"=",
"$",
"this",
"->",
"server",
"->",
"get",
"(",
"'REMOTE_ADDR'",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isFromTrustedProxy",
"(",
")",
")",
"{",
"return",
"array",
"(",
"$",
... | Returns the client IP addresses.
In the returned array the most trusted IP address is first, and the
least trusted one last. The "real" client IP address is the last one,
but this is also the least trusted one. Trusted proxies are stripped.
Use this method carefully; you should use getClientIp() instead.
@return array The client IP addresses
@see getClientIp() | [
"Returns",
"the",
"client",
"IP",
"addresses",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L881-L890 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.getPort | public function getPort()
{
if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_PORT)) {
$host = $host[0];
} elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) {
$host = $host[0];
} elseif (!$host = $this->headers->get('HOST')) {
return $this->server->get('SERVER_PORT');
}
if ($host[0] === '[') {
$pos = strpos($host, ':', strrpos($host, ']'));
} else {
$pos = strrpos($host, ':');
}
if (false !== $pos) {
return (int) substr($host, $pos + 1);
}
return 'https' === $this->getScheme() ? 443 : 80;
} | php | public function getPort()
{
if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_PORT)) {
$host = $host[0];
} elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) {
$host = $host[0];
} elseif (!$host = $this->headers->get('HOST')) {
return $this->server->get('SERVER_PORT');
}
if ($host[0] === '[') {
$pos = strpos($host, ':', strrpos($host, ']'));
} else {
$pos = strrpos($host, ':');
}
if (false !== $pos) {
return (int) substr($host, $pos + 1);
}
return 'https' === $this->getScheme() ? 443 : 80;
} | [
"public",
"function",
"getPort",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isFromTrustedProxy",
"(",
")",
"&&",
"$",
"host",
"=",
"$",
"this",
"->",
"getTrustedValues",
"(",
"self",
"::",
"HEADER_CLIENT_PORT",
")",
")",
"{",
"$",
"host",
"=",
"$",
... | Returns the port on which the request is made.
This method can read the client port from the "X-Forwarded-Port" header
when trusted proxies were set via "setTrustedProxies()".
The "X-Forwarded-Port" header must contain the client port.
If your reverse proxy uses a different header name than "X-Forwarded-Port",
configure it via "setTrustedHeaderName()" with the "client-port" key.
@return int|string can be a string if fetched from the server bag | [
"Returns",
"the",
"port",
"on",
"which",
"the",
"request",
"is",
"made",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L1013-L1034 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.isMethodSafe | public function isMethodSafe(/* $andCacheable = true */)
{
if (!func_num_args() || func_get_arg(0)) {
// This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature)
// then setting $andCacheable to false should be deprecated in 4.1
@trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED);
return in_array($this->getMethod(), array('GET', 'HEAD'));
}
return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
} | php | public function isMethodSafe(/* $andCacheable = true */)
{
if (!func_num_args() || func_get_arg(0)) {
// This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature)
// then setting $andCacheable to false should be deprecated in 4.1
@trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED);
return in_array($this->getMethod(), array('GET', 'HEAD'));
}
return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
} | [
"public",
"function",
"isMethodSafe",
"(",
"/* $andCacheable = true */",
")",
"{",
"if",
"(",
"!",
"func_num_args",
"(",
")",
"||",
"func_get_arg",
"(",
"0",
")",
")",
"{",
"// This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument... | Checks whether or not the method is safe.
@see https://tools.ietf.org/html/rfc7231#section-4.2.1
@param bool $andCacheable Adds the additional condition that the method should be cacheable. True by default.
@return bool | [
"Checks",
"whether",
"or",
"not",
"the",
"method",
"is",
"safe",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L1546-L1557 |
txj123/zilf | src/Zilf/HttpFoundation/Request.php | Request.getContent | public function getContent($asResource = false)
{
$currentContentIsResource = is_resource($this->content);
if (PHP_VERSION_ID < 50600 && false === $this->content) {
throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
}
if (true === $asResource) {
if ($currentContentIsResource) {
rewind($this->content);
return $this->content;
}
// Content passed in parameter (test)
if (is_string($this->content)) {
$resource = fopen('php://temp', 'r+');
fwrite($resource, $this->content);
rewind($resource);
return $resource;
}
$this->content = false;
return fopen('php://input', 'rb');
}
if ($currentContentIsResource) {
rewind($this->content);
return stream_get_contents($this->content);
}
if (null === $this->content || false === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
} | php | public function getContent($asResource = false)
{
$currentContentIsResource = is_resource($this->content);
if (PHP_VERSION_ID < 50600 && false === $this->content) {
throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
}
if (true === $asResource) {
if ($currentContentIsResource) {
rewind($this->content);
return $this->content;
}
// Content passed in parameter (test)
if (is_string($this->content)) {
$resource = fopen('php://temp', 'r+');
fwrite($resource, $this->content);
rewind($resource);
return $resource;
}
$this->content = false;
return fopen('php://input', 'rb');
}
if ($currentContentIsResource) {
rewind($this->content);
return stream_get_contents($this->content);
}
if (null === $this->content || false === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
} | [
"public",
"function",
"getContent",
"(",
"$",
"asResource",
"=",
"false",
")",
"{",
"$",
"currentContentIsResource",
"=",
"is_resource",
"(",
"$",
"this",
"->",
"content",
")",
";",
"if",
"(",
"PHP_VERSION_ID",
"<",
"50600",
"&&",
"false",
"===",
"$",
"thi... | Returns the request body content.
@param bool $asResource If true, a resource will be returned
@return string|resource The request body content or a resource to read the body stream
@throws \LogicException | [
"Returns",
"the",
"request",
"body",
"content",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Request.php#L1590-L1629 |
txj123/zilf | src/Zilf/Queue/QueueServiceProvider.php | QueueServiceProvider.registerManager | protected function registerManager()
{
Zilf::$container->register(
'queue', function () {
// Once we have an instance of the queue manager, we will register the various
// resolvers for the queue connectors. These connectors are responsible for
// creating the classes that accept queue configs and instantiate queues.
return tap(
new QueueManager(), function ($manager) {
$this->registerConnectors($manager);
}
);
}
);
} | php | protected function registerManager()
{
Zilf::$container->register(
'queue', function () {
// Once we have an instance of the queue manager, we will register the various
// resolvers for the queue connectors. These connectors are responsible for
// creating the classes that accept queue configs and instantiate queues.
return tap(
new QueueManager(), function ($manager) {
$this->registerConnectors($manager);
}
);
}
);
} | [
"protected",
"function",
"registerManager",
"(",
")",
"{",
"Zilf",
"::",
"$",
"container",
"->",
"register",
"(",
"'queue'",
",",
"function",
"(",
")",
"{",
"// Once we have an instance of the queue manager, we will register the various",
"// resolvers for the queue connector... | Register the queue manager.
@return void | [
"Register",
"the",
"queue",
"manager",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/QueueServiceProvider.php#L48-L62 |
txj123/zilf | src/Zilf/Queue/QueueServiceProvider.php | QueueServiceProvider.registerFailedJobServices | protected function registerFailedJobServices()
{
Zilf::$container->register(
'queue.failer', function () {
$config = config('queue.failed');
return isset($config['table'])
? $this->databaseFailedJobProvider($config)
: new NullFailedJobProvider;
}
);
} | php | protected function registerFailedJobServices()
{
Zilf::$container->register(
'queue.failer', function () {
$config = config('queue.failed');
return isset($config['table'])
? $this->databaseFailedJobProvider($config)
: new NullFailedJobProvider;
}
);
} | [
"protected",
"function",
"registerFailedJobServices",
"(",
")",
"{",
"Zilf",
"::",
"$",
"container",
"->",
"register",
"(",
"'queue.failer'",
",",
"function",
"(",
")",
"{",
"$",
"config",
"=",
"config",
"(",
"'queue.failed'",
")",
";",
"return",
"isset",
"(... | Register the failed job services.
@return void | [
"Register",
"the",
"failed",
"job",
"services",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/QueueServiceProvider.php#L214-L225 |
oscarotero/uploader | src/Adapters/Base64.php | Base64.fixDestination | public static function fixDestination(Uploader $uploader, $original)
{
if (!$uploader->getFilename()) {
$uploader->setFilename(uniqid());
}
$fileData = explode(';base64,', $original, 2);
if (!$uploader->getExtension() && preg_match('|data:\w+/(\w+)|', $fileData[0], $match)) {
$uploader->setExtension($match[1]);
}
} | php | public static function fixDestination(Uploader $uploader, $original)
{
if (!$uploader->getFilename()) {
$uploader->setFilename(uniqid());
}
$fileData = explode(';base64,', $original, 2);
if (!$uploader->getExtension() && preg_match('|data:\w+/(\w+)|', $fileData[0], $match)) {
$uploader->setExtension($match[1]);
}
} | [
"public",
"static",
"function",
"fixDestination",
"(",
"Uploader",
"$",
"uploader",
",",
"$",
"original",
")",
"{",
"if",
"(",
"!",
"$",
"uploader",
"->",
"getFilename",
"(",
")",
")",
"{",
"$",
"uploader",
"->",
"setFilename",
"(",
"uniqid",
"(",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Adapters/Base64.php#L23-L34 |
oscarotero/uploader | src/Adapters/Base64.php | Base64.save | public static function save($original, $destination)
{
$fileData = explode(';base64,', $original, 2);
if (!@file_put_contents($destination, base64_decode($fileData[1]))) {
throw new \RuntimeException("Unable to copy base64 to '{$destination}'");
}
} | php | public static function save($original, $destination)
{
$fileData = explode(';base64,', $original, 2);
if (!@file_put_contents($destination, base64_decode($fileData[1]))) {
throw new \RuntimeException("Unable to copy base64 to '{$destination}'");
}
} | [
"public",
"static",
"function",
"save",
"(",
"$",
"original",
",",
"$",
"destination",
")",
"{",
"$",
"fileData",
"=",
"explode",
"(",
"';base64,'",
",",
"$",
"original",
",",
"2",
")",
";",
"if",
"(",
"!",
"@",
"file_put_contents",
"(",
"$",
"destinat... | {@inheritdoc} | [
"{"
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Adapters/Base64.php#L39-L46 |
txj123/zilf | src/Zilf/Cache/MemcachedConnector.php | MemcachedConnector.connect | public function connect(array $servers, $connectionId = null, array $options = [], array $credentials = [])
{
$memcached = $this->getMemcached(
$connectionId, $credentials, $options
);
if (! $memcached->getServerList()) {
// For each server in the array, we'll just extract the configuration and add
// the server to the Memcached connection. Once we have added all of these
// servers we'll verify the connection is successful and return it back.
foreach ($servers as $server) {
$memcached->addServer(
$server['host'], $server['port'], $server['weight']
);
}
}
return $this->validateConnection($memcached);
} | php | public function connect(array $servers, $connectionId = null, array $options = [], array $credentials = [])
{
$memcached = $this->getMemcached(
$connectionId, $credentials, $options
);
if (! $memcached->getServerList()) {
// For each server in the array, we'll just extract the configuration and add
// the server to the Memcached connection. Once we have added all of these
// servers we'll verify the connection is successful and return it back.
foreach ($servers as $server) {
$memcached->addServer(
$server['host'], $server['port'], $server['weight']
);
}
}
return $this->validateConnection($memcached);
} | [
"public",
"function",
"connect",
"(",
"array",
"$",
"servers",
",",
"$",
"connectionId",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"array",
"$",
"credentials",
"=",
"[",
"]",
")",
"{",
"$",
"memcached",
"=",
"$",
"this",
"->",
... | Create a new Memcached connection.
@param array $servers
@param string|null $connectionId
@param array $options
@param array $credentials
@return \Memcached
@throws \RuntimeException | [
"Create",
"a",
"new",
"Memcached",
"connection",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/MemcachedConnector.php#L21-L39 |
txj123/zilf | src/Zilf/Cache/MemcachedConnector.php | MemcachedConnector.validateConnection | protected function validateConnection($memcached)
{
$status = $memcached->getVersion();
if (! is_array($status)) {
throw new RuntimeException('No Memcached servers added.');
}
if (in_array('255.255.255', $status) && count(array_unique($status)) === 1) {
throw new RuntimeException('Could not establish Memcached connection.');
}
return $memcached;
} | php | protected function validateConnection($memcached)
{
$status = $memcached->getVersion();
if (! is_array($status)) {
throw new RuntimeException('No Memcached servers added.');
}
if (in_array('255.255.255', $status) && count(array_unique($status)) === 1) {
throw new RuntimeException('Could not establish Memcached connection.');
}
return $memcached;
} | [
"protected",
"function",
"validateConnection",
"(",
"$",
"memcached",
")",
"{",
"$",
"status",
"=",
"$",
"memcached",
"->",
"getVersion",
"(",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"status",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(... | Validate the given Memcached connection.
@param \Memcached $memcached
@return \Memcached | [
"Validate",
"the",
"given",
"Memcached",
"connection",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Cache/MemcachedConnector.php#L97-L110 |
awurth/SlimHelpers | Command/SentinelCreateUserCommand.php | SentinelCreateUserCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('admin')) {
$role = $this->sentinel->findRoleByName($this->options['admin_role']);
} else {
$role = $this->sentinel->findRoleByName($this->options['user_role']);
}
$user = $this->sentinel->registerAndActivate([
'username' => $input->getArgument('username'),
'email' => $input->getArgument('email'),
'password' => $input->getArgument('password'),
'permissions' => []
]);
$role->users()->attach($user);
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('admin')) {
$role = $this->sentinel->findRoleByName($this->options['admin_role']);
} else {
$role = $this->sentinel->findRoleByName($this->options['user_role']);
}
$user = $this->sentinel->registerAndActivate([
'username' => $input->getArgument('username'),
'email' => $input->getArgument('email'),
'password' => $input->getArgument('password'),
'permissions' => []
]);
$role->users()->attach($user);
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"if",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'admin'",
")",
")",
"{",
"$",
"role",
"=",
"$",
"this",
"->",
"sentinel",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Command/SentinelCreateUserCommand.php#L66-L84 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/StringLength.php | Zend_Validate_StringLength.setMin | public function setMin($min)
{
if (null !== $this->_max && $min > $this->_max) {
/**
* @see Zend_Validate_Exception
*/
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The minimum must be less than or equal to the maximum length, but $min >"
. " $this->_max"
);
}
$this->_min = max(0, (integer) $min);
return $this;
} | php | public function setMin($min)
{
if (null !== $this->_max && $min > $this->_max) {
/**
* @see Zend_Validate_Exception
*/
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The minimum must be less than or equal to the maximum length, but $min >"
. " $this->_max"
);
}
$this->_min = max(0, (integer) $min);
return $this;
} | [
"public",
"function",
"setMin",
"(",
"$",
"min",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"_max",
"&&",
"$",
"min",
">",
"$",
"this",
"->",
"_max",
")",
"{",
"/**\n * @see Zend_Validate_Exception\n */",
"include_once",
"'Z... | Sets the min option
@param integer $min
@throws Zend_Validate_Exception
@return Zend_Validate_StringLength Provides a fluent interface | [
"Sets",
"the",
"min",
"option"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/StringLength.php#L104-L118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.