repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
ynloultratech/graphql-bundle | src/Util/ClassUtils.php | ClassUtils.applyNamingConvention | public static function applyNamingConvention(string $namespace, string $path, ?string $node, string $name, ?string $suffix = null)
{
if (null === $node) {
return sprintf('%s\%s\%s%s', $namespace, $path, ucfirst($name), $suffix);
}
return sprintf('%s\%s\%s\%s%s', $namespace, $path, $node, ucfirst($name), $suffix);
} | php | public static function applyNamingConvention(string $namespace, string $path, ?string $node, string $name, ?string $suffix = null)
{
if (null === $node) {
return sprintf('%s\%s\%s%s', $namespace, $path, ucfirst($name), $suffix);
}
return sprintf('%s\%s\%s\%s%s', $namespace, $path, $node, ucfirst($name), $suffix);
} | [
"public",
"static",
"function",
"applyNamingConvention",
"(",
"string",
"$",
"namespace",
",",
"string",
"$",
"path",
",",
"?",
"string",
"$",
"node",
",",
"string",
"$",
"name",
",",
"?",
"string",
"$",
"suffix",
"=",
"null",
")",
"{",
"if",
"(",
"nul... | Apply a naming convention based on namespace and path for given node
e.g.
$namespace = AppBundle
$path = Form\Input
$node = User
$name = AddUser
$input = Input
result: AppBundle\Form\Input\User\AddUserInput
@param string $namespace
@param string $path
@param string $node
@param string $name
@param string|null $suffix
@return string | [
"Apply",
"a",
"naming",
"convention",
"based",
"on",
"namespace",
"and",
"path",
"for",
"given",
"node"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Util/ClassUtils.php#L55-L62 | train |
tinymighty/skinny | Skinny.class.php | Skinny.insertTemplatePF | public static function insertTemplatePF ($parser, $template, $spot=''){
//process additional arguments into a usable array
$params = array();
//sanitize the template name
$template = preg_replace('/[^A-Za-z0-9_\-]/', '_', $template);
//this will be stripped out, assuming the skin is based on Skinny.template
return '<p>ADDTEMPLATE('.$spot.'):'.$template.':ETALPMETDDA</p>';
} | php | public static function insertTemplatePF ($parser, $template, $spot=''){
//process additional arguments into a usable array
$params = array();
//sanitize the template name
$template = preg_replace('/[^A-Za-z0-9_\-]/', '_', $template);
//this will be stripped out, assuming the skin is based on Skinny.template
return '<p>ADDTEMPLATE('.$spot.'):'.$template.':ETALPMETDDA</p>';
} | [
"public",
"static",
"function",
"insertTemplatePF",
"(",
"$",
"parser",
",",
"$",
"template",
",",
"$",
"spot",
"=",
"''",
")",
"{",
"//process additional arguments into a usable array",
"$",
"params",
"=",
"array",
"(",
")",
";",
"//sanitize the template name",
"... | render a template from a skin template file... | [
"render",
"a",
"template",
"from",
"a",
"skin",
"template",
"file",
"..."
] | c653369c68e61522e6a22a729182a49f070cff21 | https://github.com/tinymighty/skinny/blob/c653369c68e61522e6a22a729182a49f070cff21/Skinny.class.php#L91-L98 | train |
tinymighty/skinny | Skinny.class.php | Skinny.getSkin | public static function getSkin($context, &$skin){
//there's probably a better way to check for this...
if(!isset($_GET['useskin'])){
$key = $GLOBALS['wgDefaultSkin'];
if( self::$pageSkin ){
$key = new self::$pageSkin;
}
$key = \Skin::normalizeKey( $key );
$skinNames = \Skin::getSkinNames();
$skinName = $skinNames[$key];
$className = "\Skin{$skinName}";
if (class_exists($className)) {
$skin = new $className();
if (isset(self::$skinLayout) && method_exists($skin, 'setLayout')) {
$skin->setLayout(self::$skinLayout);
}
}
}
self::$skin = $skin;
return true;
} | php | public static function getSkin($context, &$skin){
//there's probably a better way to check for this...
if(!isset($_GET['useskin'])){
$key = $GLOBALS['wgDefaultSkin'];
if( self::$pageSkin ){
$key = new self::$pageSkin;
}
$key = \Skin::normalizeKey( $key );
$skinNames = \Skin::getSkinNames();
$skinName = $skinNames[$key];
$className = "\Skin{$skinName}";
if (class_exists($className)) {
$skin = new $className();
if (isset(self::$skinLayout) && method_exists($skin, 'setLayout')) {
$skin->setLayout(self::$skinLayout);
}
}
}
self::$skin = $skin;
return true;
} | [
"public",
"static",
"function",
"getSkin",
"(",
"$",
"context",
",",
"&",
"$",
"skin",
")",
"{",
"//there's probably a better way to check for this...",
"if",
"(",
"!",
"isset",
"(",
"$",
"_GET",
"[",
"'useskin'",
"]",
")",
")",
"{",
"$",
"key",
"=",
"$",
... | hook for RequestContextCreateSkin | [
"hook",
"for",
"RequestContextCreateSkin"
] | c653369c68e61522e6a22a729182a49f070cff21 | https://github.com/tinymighty/skinny/blob/c653369c68e61522e6a22a729182a49f070cff21/Skinny.class.php#L195-L220 | train |
orchestral/control | src/Http/Presenters/Role.php | Role.table | public function table($model)
{
return $this->table->of('control.roles', function (TableGrid $table) use ($model) {
// attach Model and set pagination option to true.
$table->with($model)->paginate(true);
$table->sortable();
$table->searchable(['name']);
$table->layout('orchestra/foundation::components.table');
// Add columns.
$table->column(trans('orchestra/foundation::label.name'), 'name');
});
} | php | public function table($model)
{
return $this->table->of('control.roles', function (TableGrid $table) use ($model) {
// attach Model and set pagination option to true.
$table->with($model)->paginate(true);
$table->sortable();
$table->searchable(['name']);
$table->layout('orchestra/foundation::components.table');
// Add columns.
$table->column(trans('orchestra/foundation::label.name'), 'name');
});
} | [
"public",
"function",
"table",
"(",
"$",
"model",
")",
"{",
"return",
"$",
"this",
"->",
"table",
"->",
"of",
"(",
"'control.roles'",
",",
"function",
"(",
"TableGrid",
"$",
"table",
")",
"use",
"(",
"$",
"model",
")",
"{",
"// attach Model and set paginat... | View table generator for Orchestra\Model\Role.
@param \Orchestra\Model\Role|\Illuminate\Pagination\Paginator $model
@return \Orchestra\Contracts\Html\Table\Builder | [
"View",
"table",
"generator",
"for",
"Orchestra",
"\\",
"Model",
"\\",
"Role",
"."
] | 7c23db19373adbb0fe44491af12f370ba6547d2a | https://github.com/orchestral/control/blob/7c23db19373adbb0fe44491af12f370ba6547d2a/src/Http/Presenters/Role.php#L44-L58 | train |
orchestral/control | src/Http/Presenters/Role.php | Role.addEditButton | protected function addEditButton(Eloquent $role)
{
$link = handles("orchestra::control/roles/{$role->id}/edit");
$text = trans('orchestra/foundation::label.edit');
$attributes = ['class' => 'btn btn-xs btn-label btn-warning'];
return app('html')->link($link, $text, $attributes);
} | php | protected function addEditButton(Eloquent $role)
{
$link = handles("orchestra::control/roles/{$role->id}/edit");
$text = trans('orchestra/foundation::label.edit');
$attributes = ['class' => 'btn btn-xs btn-label btn-warning'];
return app('html')->link($link, $text, $attributes);
} | [
"protected",
"function",
"addEditButton",
"(",
"Eloquent",
"$",
"role",
")",
"{",
"$",
"link",
"=",
"handles",
"(",
"\"orchestra::control/roles/{$role->id}/edit\"",
")",
";",
"$",
"text",
"=",
"trans",
"(",
"'orchestra/foundation::label.edit'",
")",
";",
"$",
"att... | Add edit button.
@param \Orchestra\Model\Role $role
@return string | [
"Add",
"edit",
"button",
"."
] | 7c23db19373adbb0fe44491af12f370ba6547d2a | https://github.com/orchestral/control/blob/7c23db19373adbb0fe44491af12f370ba6547d2a/src/Http/Presenters/Role.php#L100-L107 | train |
orchestral/control | src/Http/Presenters/Role.php | Role.form | public function form(Eloquent $model)
{
return $this->form->of('control.roles', function (FormGrid $form) use ($model) {
$form->resource($this, 'orchestra::control/roles', $model);
$form->hidden('id');
$form->fieldset(function (Fieldset $fieldset) {
$fieldset->control('input:text', 'name')
->label(trans('orchestra/control::label.name'));
});
});
} | php | public function form(Eloquent $model)
{
return $this->form->of('control.roles', function (FormGrid $form) use ($model) {
$form->resource($this, 'orchestra::control/roles', $model);
$form->hidden('id');
$form->fieldset(function (Fieldset $fieldset) {
$fieldset->control('input:text', 'name')
->label(trans('orchestra/control::label.name'));
});
});
} | [
"public",
"function",
"form",
"(",
"Eloquent",
"$",
"model",
")",
"{",
"return",
"$",
"this",
"->",
"form",
"->",
"of",
"(",
"'control.roles'",
",",
"function",
"(",
"FormGrid",
"$",
"form",
")",
"use",
"(",
"$",
"model",
")",
"{",
"$",
"form",
"->",... | View form generator for Orchestra\Model\Role.
@param \Orchestra\Model\Role $model
@return \Orchestra\Contracts\Html\Form\Builder | [
"View",
"form",
"generator",
"for",
"Orchestra",
"\\",
"Model",
"\\",
"Role",
"."
] | 7c23db19373adbb0fe44491af12f370ba6547d2a | https://github.com/orchestral/control/blob/7c23db19373adbb0fe44491af12f370ba6547d2a/src/Http/Presenters/Role.php#L132-L143 | train |
psbhanu/whatsapi | src/Media/VCardReader.php | VCardReader.SaveFile | public function SaveFile($Key, $Index = 0, $TargetPath = '')
{
if (!isset($this->Data[$Key]))
{
return false;
}
if (!isset($this->Data[$Key][$Index]))
{
return false;
}
// Returing false if it is an image URL
if (stripos($this->Data[$Key][$Index]['Value'], 'uri:') === 0)
{
return false;
}
if (is_writable($TargetPath) || (!file_exists($TargetPath) && is_writable(dirname($TargetPath))))
{
$RawContent = $this->Data[$Key][$Index]['Value'];
if (isset($this->Data[$Key][$Index]['Encoding']) && $this->Data[$Key][$Index]['Encoding'] == 'b')
{
$RawContent = base64_decode($RawContent);
}
$Status = file_put_contents($TargetPath, $RawContent);
return (bool)$Status;
}
else
{
throw new Exception('vCard: Cannot save file ('.$Key.'), target path not writable ('.$TargetPath.')');
}
return false;
} | php | public function SaveFile($Key, $Index = 0, $TargetPath = '')
{
if (!isset($this->Data[$Key]))
{
return false;
}
if (!isset($this->Data[$Key][$Index]))
{
return false;
}
// Returing false if it is an image URL
if (stripos($this->Data[$Key][$Index]['Value'], 'uri:') === 0)
{
return false;
}
if (is_writable($TargetPath) || (!file_exists($TargetPath) && is_writable(dirname($TargetPath))))
{
$RawContent = $this->Data[$Key][$Index]['Value'];
if (isset($this->Data[$Key][$Index]['Encoding']) && $this->Data[$Key][$Index]['Encoding'] == 'b')
{
$RawContent = base64_decode($RawContent);
}
$Status = file_put_contents($TargetPath, $RawContent);
return (bool)$Status;
}
else
{
throw new Exception('vCard: Cannot save file ('.$Key.'), target path not writable ('.$TargetPath.')');
}
return false;
} | [
"public",
"function",
"SaveFile",
"(",
"$",
"Key",
",",
"$",
"Index",
"=",
"0",
",",
"$",
"TargetPath",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"Data",
"[",
"$",
"Key",
"]",
")",
")",
"{",
"return",
"false",
";",
... | Saves an embedded file
@param string Key
@param int Index of the file, defaults to 0
@param string Target path where the file should be saved, including the filename
@return bool Operation status | [
"Saves",
"an",
"embedded",
"file"
] | be34f35bb5e0fd3c6f2196260865bef65c1240c2 | https://github.com/psbhanu/whatsapi/blob/be34f35bb5e0fd3c6f2196260865bef65c1240c2/src/Media/VCardReader.php#L360-L392 | train |
psbhanu/whatsapi | src/Media/VCardReader.php | VCardReader.ParseStructuredValue | private static function ParseStructuredValue($Text, $Key)
{
$Text = array_map('trim', explode(';', $Text));
$Result = array();
$Ctr = 0;
foreach (self::$Spec_StructuredElements[$Key] as $Index => $StructurePart)
{
$Result[$StructurePart] = isset($Text[$Index]) ? $Text[$Index] : null;
}
return $Result;
} | php | private static function ParseStructuredValue($Text, $Key)
{
$Text = array_map('trim', explode(';', $Text));
$Result = array();
$Ctr = 0;
foreach (self::$Spec_StructuredElements[$Key] as $Index => $StructurePart)
{
$Result[$StructurePart] = isset($Text[$Index]) ? $Text[$Index] : null;
}
return $Result;
} | [
"private",
"static",
"function",
"ParseStructuredValue",
"(",
"$",
"Text",
",",
"$",
"Key",
")",
"{",
"$",
"Text",
"=",
"array_map",
"(",
"'trim'",
",",
"explode",
"(",
"';'",
",",
"$",
"Text",
")",
")",
";",
"$",
"Result",
"=",
"array",
"(",
")",
... | Separates the various parts of a structured value according to the spec.
@access private
@param string Raw text string
@param string Key (e.g., N, ADR, ORG, etc.)
@return array Parts in an associative array. | [
"Separates",
"the",
"various",
"parts",
"of",
"a",
"structured",
"value",
"according",
"to",
"the",
"spec",
"."
] | be34f35bb5e0fd3c6f2196260865bef65c1240c2 | https://github.com/psbhanu/whatsapi/blob/be34f35bb5e0fd3c6f2196260865bef65c1240c2/src/Media/VCardReader.php#L546-L558 | train |
eidsonator/SemanticReportsBundle | Classes/ReportFormats/RawReportFormat.php | RawReportFormat.prepareReport | public static function prepareReport(Report $report)
{
$contents = Report::getReportFileContents($report->getFullPath());
$report->content = $contents;
return $report;
} | php | public static function prepareReport(Report $report)
{
$contents = Report::getReportFileContents($report->getFullPath());
$report->content = $contents;
return $report;
} | [
"public",
"static",
"function",
"prepareReport",
"(",
"Report",
"$",
"report",
")",
"{",
"$",
"contents",
"=",
"Report",
"::",
"getReportFileContents",
"(",
"$",
"report",
"->",
"getFullPath",
"(",
")",
")",
";",
"$",
"report",
"->",
"content",
"=",
"$",
... | no need to instantiate a report object, just return the source | [
"no",
"need",
"to",
"instantiate",
"a",
"report",
"object",
"just",
"return",
"the",
"source"
] | 11c82be87551eae232280a74b2de7e3255666f85 | https://github.com/eidsonator/SemanticReportsBundle/blob/11c82be87551eae232280a74b2de7e3255666f85/Classes/ReportFormats/RawReportFormat.php#L20-L25 | train |
ekyna/Dpd | src/EPrint/Client.php | Client.call | public function call(string $method, array $arguments): ResponseInterface
{
try {
return $this->__soapCall($method, $arguments, null, $this->getHeader());
} catch (\Exception $e) {
$exception = new ClientException($e->getMessage(), $e->getCode(), $e);
if ($this->debug) {
$exception->request = ClientException::formatXml($this->__getLastRequest());
$exception->response = ClientException::formatXml($this->__getLastResponse());
}
throw $exception;
}
} | php | public function call(string $method, array $arguments): ResponseInterface
{
try {
return $this->__soapCall($method, $arguments, null, $this->getHeader());
} catch (\Exception $e) {
$exception = new ClientException($e->getMessage(), $e->getCode(), $e);
if ($this->debug) {
$exception->request = ClientException::formatXml($this->__getLastRequest());
$exception->response = ClientException::formatXml($this->__getLastResponse());
}
throw $exception;
}
} | [
"public",
"function",
"call",
"(",
"string",
"$",
"method",
",",
"array",
"$",
"arguments",
")",
":",
"ResponseInterface",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"__soapCall",
"(",
"$",
"method",
",",
"$",
"arguments",
",",
"null",
",",
"$",
"th... | Performs the soap call.
@param string $method
@param array $arguments
@return ResponseInterface
@throws ClientException | [
"Performs",
"the",
"soap",
"call",
"."
] | 67eabcff840b310021d5ca7ebb824fa7d7cb700b | https://github.com/ekyna/Dpd/blob/67eabcff840b310021d5ca7ebb824fa7d7cb700b/src/EPrint/Client.php#L101-L115 | train |
ekyna/Dpd | src/EPrint/Client.php | Client.getHeader | protected function getHeader(): \SoapHeader
{
if ($this->header) {
return $this->header;
}
return $this->header = new \SoapHeader(static::NAMESPACE, 'UserCredentials', [
'userid' => $this->login,
'password' => $this->password,
]);
} | php | protected function getHeader(): \SoapHeader
{
if ($this->header) {
return $this->header;
}
return $this->header = new \SoapHeader(static::NAMESPACE, 'UserCredentials', [
'userid' => $this->login,
'password' => $this->password,
]);
} | [
"protected",
"function",
"getHeader",
"(",
")",
":",
"\\",
"SoapHeader",
"{",
"if",
"(",
"$",
"this",
"->",
"header",
")",
"{",
"return",
"$",
"this",
"->",
"header",
";",
"}",
"return",
"$",
"this",
"->",
"header",
"=",
"new",
"\\",
"SoapHeader",
"(... | Returns the header.
@return \SoapHeader | [
"Returns",
"the",
"header",
"."
] | 67eabcff840b310021d5ca7ebb824fa7d7cb700b | https://github.com/ekyna/Dpd/blob/67eabcff840b310021d5ca7ebb824fa7d7cb700b/src/EPrint/Client.php#L122-L132 | train |
QuickenLoans/mcp-common | src/Clock.php | Clock.read | public function read(): ?TimePoint
{
try {
$datetime = new DateTime($this->current, $this->timezone);
} catch (BaseException $e) {
return null;
}
return $this->fromDateTime($datetime);
} | php | public function read(): ?TimePoint
{
try {
$datetime = new DateTime($this->current, $this->timezone);
} catch (BaseException $e) {
return null;
}
return $this->fromDateTime($datetime);
} | [
"public",
"function",
"read",
"(",
")",
":",
"?",
"TimePoint",
"{",
"try",
"{",
"$",
"datetime",
"=",
"new",
"DateTime",
"(",
"$",
"this",
"->",
"current",
",",
"$",
"this",
"->",
"timezone",
")",
";",
"}",
"catch",
"(",
"BaseException",
"$",
"e",
... | Get the current TimePoint
@return TimePoint|null | [
"Get",
"the",
"current",
"TimePoint"
] | 46ca6e2c5c9df4ec102808f8494ad1774f190021 | https://github.com/QuickenLoans/mcp-common/blob/46ca6e2c5c9df4ec102808f8494ad1774f190021/src/Clock.php#L98-L107 | train |
QuickenLoans/mcp-common | src/Clock.php | Clock.fromString | public function fromString($input, $format = null): ?TimePoint
{
if ($format === null) {
$formats = [
'Y-m-d\TH:i:sP', // RFC 3339
'Y-m-d\TH:i:s.uP', // RFC 3339 with fractional seconds
'Y-m-d\TH:i:sO', // ISO 8601
'Y-m-d\TH:i:s.uO', // ISO 8601 with fractional seconds and period
'Y-m-d\TH:i:s,uO', // ISO 8601 with fractional seconds and comma
'Y-m-d\TH:iO', // ISO 8601 with no seconds
];
do {
$datetime = DateTime::createFromFormat(array_shift($formats), $input, $this->timezone);
} while (!$datetime instanceof DateTime && count($formats) > 0);
} else {
$datetime = DateTime::createFromFormat($format, $input, $this->timezone);
}
return ($datetime instanceof DateTime) ? $this->fromDateTime($datetime) : null;
} | php | public function fromString($input, $format = null): ?TimePoint
{
if ($format === null) {
$formats = [
'Y-m-d\TH:i:sP', // RFC 3339
'Y-m-d\TH:i:s.uP', // RFC 3339 with fractional seconds
'Y-m-d\TH:i:sO', // ISO 8601
'Y-m-d\TH:i:s.uO', // ISO 8601 with fractional seconds and period
'Y-m-d\TH:i:s,uO', // ISO 8601 with fractional seconds and comma
'Y-m-d\TH:iO', // ISO 8601 with no seconds
];
do {
$datetime = DateTime::createFromFormat(array_shift($formats), $input, $this->timezone);
} while (!$datetime instanceof DateTime && count($formats) > 0);
} else {
$datetime = DateTime::createFromFormat($format, $input, $this->timezone);
}
return ($datetime instanceof DateTime) ? $this->fromDateTime($datetime) : null;
} | [
"public",
"function",
"fromString",
"(",
"$",
"input",
",",
"$",
"format",
"=",
"null",
")",
":",
"?",
"TimePoint",
"{",
"if",
"(",
"$",
"format",
"===",
"null",
")",
"{",
"$",
"formats",
"=",
"[",
"'Y-m-d\\TH:i:sP'",
",",
"// RFC 3339",
"'Y-m-d\\TH:i:s.... | Get a TimePoint from a formatted string
The format parameter should be a date() compatible string. If it is not provided this method will attempt to
parse in input with one of the following supported formats.
- UTC Implied (2015-12-10T10:10:00Z)
- RFC 3339 (2015-12-10T10:10:00+04:00, 2015-12-10T10:10:00.000000+04:00)
- ISO 8601 (2015-12-10T10:10:00+0000, 2015-12-10T10:10:00.000000+0000, 2015-12-10T10:10:00,000000+0000, etc)
Note that, if a timezone is not specified in the input string, the clock's timezone will be used.
@param string $input
@param string|null $format
@return TimePoint|null | [
"Get",
"a",
"TimePoint",
"from",
"a",
"formatted",
"string"
] | 46ca6e2c5c9df4ec102808f8494ad1774f190021 | https://github.com/QuickenLoans/mcp-common/blob/46ca6e2c5c9df4ec102808f8494ad1774f190021/src/Clock.php#L141-L162 | train |
QuickenLoans/mcp-common | src/Clock.php | Clock.inRange | public function inRange(TimePoint $expiration, TimePoint $creation = null, $skew = null): bool
{
$now = $this->read();
if ($skew !== null) {
if ($creation instanceof TimePoint) {
$creation = $creation->modify(sprintf('-%s', $skew));
}
$expiration = $expiration->modify(sprintf('+%s', $skew));
}
return $now->compare($expiration) !== 1 && (!$creation instanceof TimePoint || $now->compare($creation) !== -1);
} | php | public function inRange(TimePoint $expiration, TimePoint $creation = null, $skew = null): bool
{
$now = $this->read();
if ($skew !== null) {
if ($creation instanceof TimePoint) {
$creation = $creation->modify(sprintf('-%s', $skew));
}
$expiration = $expiration->modify(sprintf('+%s', $skew));
}
return $now->compare($expiration) !== 1 && (!$creation instanceof TimePoint || $now->compare($creation) !== -1);
} | [
"public",
"function",
"inRange",
"(",
"TimePoint",
"$",
"expiration",
",",
"TimePoint",
"$",
"creation",
"=",
"null",
",",
"$",
"skew",
"=",
"null",
")",
":",
"bool",
"{",
"$",
"now",
"=",
"$",
"this",
"->",
"read",
"(",
")",
";",
"if",
"(",
"$",
... | Check that the current time is within a specified range
Optionally, a strtotime() compatible skew modifier may be provided. This modifier allows for a certain amount
of clock skew between systems when performing the range check.
@param TimePoint $expiration
@param TimePoint|null $creation
@param string|null $skew
@throws Exception
@return bool | [
"Check",
"that",
"the",
"current",
"time",
"is",
"within",
"a",
"specified",
"range"
] | 46ca6e2c5c9df4ec102808f8494ad1774f190021 | https://github.com/QuickenLoans/mcp-common/blob/46ca6e2c5c9df4ec102808f8494ad1774f190021/src/Clock.php#L178-L191 | train |
cakemanager/cakephp-cakemanager | src/Model/Table/UsersTable.php | UsersTable.validateActivationKey | public function validateActivationKey($email, $activationKey)
{
$query = $this->findByEmailAndActivationKey($email, $activationKey);
if ($query->Count() > 0) {
return true;
}
return false;
} | php | public function validateActivationKey($email, $activationKey)
{
$query = $this->findByEmailAndActivationKey($email, $activationKey);
if ($query->Count() > 0) {
return true;
}
return false;
} | [
"public",
"function",
"validateActivationKey",
"(",
"$",
"email",
",",
"$",
"activationKey",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"findByEmailAndActivationKey",
"(",
"$",
"email",
",",
"$",
"activationKey",
")",
";",
"if",
"(",
"$",
"query",
"->... | Checks if an user is allowed to do an action with a required activation-key
User-data: e-mailaddress
@param string $email E-mailaddress of the user.
@param string $activationKey Activation key of the user.
@return bool | [
"Checks",
"if",
"an",
"user",
"is",
"allowed",
"to",
"do",
"an",
"action",
"with",
"a",
"required",
"activation",
"-",
"key"
] | 428f7bc32b64d4bfd51845aebdaf92922c7568b3 | https://github.com/cakemanager/cakephp-cakemanager/blob/428f7bc32b64d4bfd51845aebdaf92922c7568b3/src/Model/Table/UsersTable.php#L130-L139 | train |
cakemanager/cakephp-cakemanager | src/Model/Table/UsersTable.php | UsersTable.activateUser | public function activateUser($email, $activationKey)
{
if ($this->validateActivationKey($email, $activationKey)) {
$user = $this->findByEmailAndActivationKey($email, $activationKey)->first();
if ($user->active == 0) {
$user->active = 1;
$user->activation_key = null;
if ($this->save($user)) {
return true;
}
}
}
return false;
} | php | public function activateUser($email, $activationKey)
{
if ($this->validateActivationKey($email, $activationKey)) {
$user = $this->findByEmailAndActivationKey($email, $activationKey)->first();
if ($user->active == 0) {
$user->active = 1;
$user->activation_key = null;
if ($this->save($user)) {
return true;
}
}
}
return false;
} | [
"public",
"function",
"activateUser",
"(",
"$",
"email",
",",
"$",
"activationKey",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"validateActivationKey",
"(",
"$",
"email",
",",
"$",
"activationKey",
")",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"find... | Activates an user
@param string $email E-mailaddress of the user.
@param string $activationKey Activation key of the user.
@return bool | [
"Activates",
"an",
"user"
] | 428f7bc32b64d4bfd51845aebdaf92922c7568b3 | https://github.com/cakemanager/cakephp-cakemanager/blob/428f7bc32b64d4bfd51845aebdaf92922c7568b3/src/Model/Table/UsersTable.php#L148-L163 | train |
figdice/figdice | src/figdice/FunctionFactory.php | FunctionFactory.lookup | public final function lookup($funcName) {
if(isset(self::$functions[$funcName])) {
return self::$functions[$funcName];
}
//The assign-and-return is acceptable because isset(null) returns false.
return (self::$functions[$funcName] = $this->create($funcName));
} | php | public final function lookup($funcName) {
if(isset(self::$functions[$funcName])) {
return self::$functions[$funcName];
}
//The assign-and-return is acceptable because isset(null) returns false.
return (self::$functions[$funcName] = $this->create($funcName));
} | [
"public",
"final",
"function",
"lookup",
"(",
"$",
"funcName",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"functions",
"[",
"$",
"funcName",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"functions",
"[",
"$",
"funcName",
"]",
";",
"}... | Returns the instance of the Function class that
handles the requested function.
If it was not loaded yet, tries to instanciate by
calling the overriden create method.
Returns null if the factory could not produce an instance.
@param string $funcName
@return FigFunction | [
"Returns",
"the",
"instance",
"of",
"the",
"Function",
"class",
"that",
"handles",
"the",
"requested",
"function",
".",
"If",
"it",
"was",
"not",
"loaded",
"yet",
"tries",
"to",
"instanciate",
"by",
"calling",
"the",
"overriden",
"create",
"method",
".",
"Re... | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/FunctionFactory.php#L46-L52 | train |
ynloultratech/graphql-bundle | src/Exception/ControlledError.php | ControlledError.create | public static function create($code, $message = null, $category = null)
{
return new class($message, $code, $category) extends ControlledError
{
/**
* @var string
*/
protected $category;
/**
* @param string $message
* @param string $code
* @param null $category
*/
public function __construct($message, $code, $category = null)
{
if ($category) {
$this->category = $category;
}
parent:: __construct($message, $code);
}
/**
* @return string
*/
public function getCategory(): string
{
return $this->category ?? parent::getCategory();
}
};
} | php | public static function create($code, $message = null, $category = null)
{
return new class($message, $code, $category) extends ControlledError
{
/**
* @var string
*/
protected $category;
/**
* @param string $message
* @param string $code
* @param null $category
*/
public function __construct($message, $code, $category = null)
{
if ($category) {
$this->category = $category;
}
parent:: __construct($message, $code);
}
/**
* @return string
*/
public function getCategory(): string
{
return $this->category ?? parent::getCategory();
}
};
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"code",
",",
"$",
"message",
"=",
"null",
",",
"$",
"category",
"=",
"null",
")",
"{",
"return",
"new",
"class",
"(",
"$",
"message",
",",
"$",
"code",
",",
"$",
"category",
")",
"extends",
"Control... | Throw a controlled error dynamically
@param int|string $code
@param string $message
@param string|null $category
@return ControlledError | [
"Throw",
"a",
"controlled",
"error",
"dynamically"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Exception/ControlledError.php#L39-L69 | train |
figdice/figdice | src/figdice/classes/ViewElementTag.php | ViewElementTag.parseAttributes | protected function parseAttributes($figNamespace, array $attributes)
{
// A fig:call attribute on a tag, indicates that all the other attributes
// are arguments for the macro. They all are considered as expressions,
// and therefore there is no need to search for adhoc inside.
if (! $this->figCall) {
foreach ($attributes as $name => $value) {
// Process the non-fig attributes only
if (strpos($name, $figNamespace) === 0) {
continue;
}
// Search for inline conditional attributes
if (preg_match('/\|(.+)\|(.+)\|$/', $value, $matches)) {
$attributes[$name] = new InlineCondAttr($matches[1], $matches[2]);
//Element can no longer be squashed in optimizations, because it carries
// an active runtime piece.
$this->isDirective = true;
continue;
}
// Search for adhocs
if (preg_match_all('/\{([^\{]+)\}/', $value, $matches, PREG_OFFSET_CAPTURE)) {
$parts = [];
$previousPosition = 0;
$nMatches = count($matches[0]);
for($i = 0; $i < $nMatches; ++ $i) {
$expression = $matches[1][$i][0];
$position = $matches[1][$i][1];
if ($position > $previousPosition + 1) {
// +1 because we exclude the leading {
$parts []= substr($value, $previousPosition, $position - 1 - $previousPosition);
}
$parts []= new AdHoc($expression);
// Mark the current tag as being an active cell in the template,
// as opposed to a stupid static string with no logic.
$this->isDirective = true;
// +1 because we contiunue past the trailing }
$previousPosition = $position + strlen($expression) + 1;
}
// And finish with the trailing static part, past the last }
if ($previousPosition < strlen($value)) {
$parts []= substr($value, $previousPosition);
}
// At this stage, $parts is an index array of pieces,
// each piece is either a scalar string, or an instance of AdHoc.
// If there is only one part, let's simplify the array
if (count($parts) == 1) {
$parts = $parts[0];
}
// $parts can safely replace the origin value in $attributes,
// because the serializing and rendering engine are aware.
$attributes[$name] = $parts;
}
}
}
$this->attributes = $attributes;
} | php | protected function parseAttributes($figNamespace, array $attributes)
{
// A fig:call attribute on a tag, indicates that all the other attributes
// are arguments for the macro. They all are considered as expressions,
// and therefore there is no need to search for adhoc inside.
if (! $this->figCall) {
foreach ($attributes as $name => $value) {
// Process the non-fig attributes only
if (strpos($name, $figNamespace) === 0) {
continue;
}
// Search for inline conditional attributes
if (preg_match('/\|(.+)\|(.+)\|$/', $value, $matches)) {
$attributes[$name] = new InlineCondAttr($matches[1], $matches[2]);
//Element can no longer be squashed in optimizations, because it carries
// an active runtime piece.
$this->isDirective = true;
continue;
}
// Search for adhocs
if (preg_match_all('/\{([^\{]+)\}/', $value, $matches, PREG_OFFSET_CAPTURE)) {
$parts = [];
$previousPosition = 0;
$nMatches = count($matches[0]);
for($i = 0; $i < $nMatches; ++ $i) {
$expression = $matches[1][$i][0];
$position = $matches[1][$i][1];
if ($position > $previousPosition + 1) {
// +1 because we exclude the leading {
$parts []= substr($value, $previousPosition, $position - 1 - $previousPosition);
}
$parts []= new AdHoc($expression);
// Mark the current tag as being an active cell in the template,
// as opposed to a stupid static string with no logic.
$this->isDirective = true;
// +1 because we contiunue past the trailing }
$previousPosition = $position + strlen($expression) + 1;
}
// And finish with the trailing static part, past the last }
if ($previousPosition < strlen($value)) {
$parts []= substr($value, $previousPosition);
}
// At this stage, $parts is an index array of pieces,
// each piece is either a scalar string, or an instance of AdHoc.
// If there is only one part, let's simplify the array
if (count($parts) == 1) {
$parts = $parts[0];
}
// $parts can safely replace the origin value in $attributes,
// because the serializing and rendering engine are aware.
$attributes[$name] = $parts;
}
}
}
$this->attributes = $attributes;
} | [
"protected",
"function",
"parseAttributes",
"(",
"$",
"figNamespace",
",",
"array",
"$",
"attributes",
")",
"{",
"// A fig:call attribute on a tag, indicates that all the other attributes",
"// are arguments for the macro. They all are considered as expressions,",
"// and therefore there... | Split attributes by adhoc parts
and store the resulting array in the object member.
@param string $figNamespace
@param array $attributes | [
"Split",
"attributes",
"by",
"adhoc",
"parts",
"and",
"store",
"the",
"resulting",
"array",
"in",
"the",
"object",
"member",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/classes/ViewElementTag.php#L189-L253 | train |
figdice/figdice | src/figdice/classes/ViewElementTag.php | ViewElementTag.buildXMLAttributesString | private function buildXMLAttributesString(Context $context) {
$result = '';
$matches = null;
$attributes = $this->attributes;
$runtimeAttributes = $context->getRuntimeAttributes();
foreach($runtimeAttributes as $attributeName=>$runtimeAttr) {
$attributes[$attributeName] = $runtimeAttr;
}
foreach($attributes as $attribute=>$value) {
if( ! $context->view->isFigPrefix($attribute)) {
// a flag attribute is to be processed differently because
// it isn't a key=value pair.
if ($value instanceof Flag) {
// Flag attribute: there is no value. We print only the name of the flag.
$result .= " $attribute";
} else {
// We're potentially in presence of:
// - a plain scalar
// - an AdHoc instance
// - an array of the above.
// - an inline conditional attribute: InlineCondAttr
if ($value instanceof InlineCondAttr) {
/** @var InlineCondAttr $inlineCondAttr */
$inlineCondAttr = $value;
if ($this->evaluate($context, $inlineCondAttr->cond)) {
$value = $this->evaluate($context, $inlineCondAttr->val);
}
else {
continue;
}
}
if (! is_array($value)) {
$value = [$value];
}
$combined = '';
foreach ($value as $part) {
if ($part instanceof AdHoc) {
$evaluatedValue = $this->evaluate($context, $part->string);
if($evaluatedValue instanceof ViewElement) {
$evaluatedValue = $evaluatedValue->render($context);
}
if(is_array($evaluatedValue)) {
if(empty($evaluatedValue)) {
$evaluatedValue = '';
} else {
$message = 'Adhoc {' . $part->string . '} of attribute ' . $attribute . ' in tag "' . $this->name . '" evaluated to array.';
throw new TagRenderingException($this->getTagName(), $this->getLineNumber(), $message);
}
} else if (is_object($evaluatedValue)
&& ($evaluatedValue instanceof \DOMNode)) {
// Treat the special case of DOMNode descendants,
// for which we can evalute the text contents
$evaluatedValue = $evaluatedValue->nodeValue;
}
//The outcome of the evaluatedValue, coming from DB or other, might contain non-standard HTML characters.
//We assume that the FIG library targets HTML rendering.
//Therefore, let's have the outcome comply with HTML.
if(is_object($evaluatedValue)) {
//TODO: Log some warning!
$evaluatedValue = '### Object of class: ' . get_class($evaluatedValue) . ' ###';
} else {
$evaluatedValue = htmlspecialchars($evaluatedValue);
}
$part = $evaluatedValue;
}
// Append to what we had already (and if $part was a string in the first place,
// we use its direct value;
$combined .= $part;
}
$value = $combined;
$result .= " $attribute=\"$value\"";
}
}
}
return $result;
} | php | private function buildXMLAttributesString(Context $context) {
$result = '';
$matches = null;
$attributes = $this->attributes;
$runtimeAttributes = $context->getRuntimeAttributes();
foreach($runtimeAttributes as $attributeName=>$runtimeAttr) {
$attributes[$attributeName] = $runtimeAttr;
}
foreach($attributes as $attribute=>$value) {
if( ! $context->view->isFigPrefix($attribute)) {
// a flag attribute is to be processed differently because
// it isn't a key=value pair.
if ($value instanceof Flag) {
// Flag attribute: there is no value. We print only the name of the flag.
$result .= " $attribute";
} else {
// We're potentially in presence of:
// - a plain scalar
// - an AdHoc instance
// - an array of the above.
// - an inline conditional attribute: InlineCondAttr
if ($value instanceof InlineCondAttr) {
/** @var InlineCondAttr $inlineCondAttr */
$inlineCondAttr = $value;
if ($this->evaluate($context, $inlineCondAttr->cond)) {
$value = $this->evaluate($context, $inlineCondAttr->val);
}
else {
continue;
}
}
if (! is_array($value)) {
$value = [$value];
}
$combined = '';
foreach ($value as $part) {
if ($part instanceof AdHoc) {
$evaluatedValue = $this->evaluate($context, $part->string);
if($evaluatedValue instanceof ViewElement) {
$evaluatedValue = $evaluatedValue->render($context);
}
if(is_array($evaluatedValue)) {
if(empty($evaluatedValue)) {
$evaluatedValue = '';
} else {
$message = 'Adhoc {' . $part->string . '} of attribute ' . $attribute . ' in tag "' . $this->name . '" evaluated to array.';
throw new TagRenderingException($this->getTagName(), $this->getLineNumber(), $message);
}
} else if (is_object($evaluatedValue)
&& ($evaluatedValue instanceof \DOMNode)) {
// Treat the special case of DOMNode descendants,
// for which we can evalute the text contents
$evaluatedValue = $evaluatedValue->nodeValue;
}
//The outcome of the evaluatedValue, coming from DB or other, might contain non-standard HTML characters.
//We assume that the FIG library targets HTML rendering.
//Therefore, let's have the outcome comply with HTML.
if(is_object($evaluatedValue)) {
//TODO: Log some warning!
$evaluatedValue = '### Object of class: ' . get_class($evaluatedValue) . ' ###';
} else {
$evaluatedValue = htmlspecialchars($evaluatedValue);
}
$part = $evaluatedValue;
}
// Append to what we had already (and if $part was a string in the first place,
// we use its direct value;
$combined .= $part;
}
$value = $combined;
$result .= " $attribute=\"$value\"";
}
}
}
return $result;
} | [
"private",
"function",
"buildXMLAttributesString",
"(",
"Context",
"$",
"context",
")",
"{",
"$",
"result",
"=",
"''",
";",
"$",
"matches",
"=",
"null",
";",
"$",
"attributes",
"=",
"$",
"this",
"->",
"attributes",
";",
"$",
"runtimeAttributes",
"=",
"$",
... | Returns a string containing the space-separated
list of XML attributes of an element.
@param Context $context
@return string
@throws TagRenderingException | [
"Returns",
"a",
"string",
"containing",
"the",
"space",
"-",
"separated",
"list",
"of",
"XML",
"attributes",
"of",
"an",
"element",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/classes/ViewElementTag.php#L285-L377 | train |
figdice/figdice | src/figdice/classes/ViewElementTag.php | ViewElementTag.evalAttribute | protected function evalAttribute(Context $context, $name) {
$expression = $this->getAttribute($name, false);
if($expression) {
return $this->evaluate($context, $expression);
}
return false;
} | php | protected function evalAttribute(Context $context, $name) {
$expression = $this->getAttribute($name, false);
if($expression) {
return $this->evaluate($context, $expression);
}
return false;
} | [
"protected",
"function",
"evalAttribute",
"(",
"Context",
"$",
"context",
",",
"$",
"name",
")",
"{",
"$",
"expression",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"$",
"name",
",",
"false",
")",
";",
"if",
"(",
"$",
"expression",
")",
"{",
"return",... | Evaluates the expression written in specified attribute.
If attribute does not exist, returns false.
@param Context $context
@param string $name Attribute name
@return mixed | [
"Evaluates",
"the",
"expression",
"written",
"in",
"specified",
"attribute",
".",
"If",
"attribute",
"does",
"not",
"exist",
"returns",
"false",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/classes/ViewElementTag.php#L805-L811 | train |
figdice/figdice | src/figdice/classes/ViewElementTag.php | ViewElementTag.applyOutputFilter | private function applyOutputFilter(Context $context, $buffer) {
//TODO: Currently the filtering works only on non-slot tags.
//If applied on a slot tag, the transform is made on the special placeholder /==SLOT=.../
//rather than the future contents of the slot.
if($this->figFilter) {
$filterClass = $this->figFilter;
$filter = $this->instantiateFilter($context, $filterClass);
$buffer = $filter->transform($buffer);
}
return $buffer;
} | php | private function applyOutputFilter(Context $context, $buffer) {
//TODO: Currently the filtering works only on non-slot tags.
//If applied on a slot tag, the transform is made on the special placeholder /==SLOT=.../
//rather than the future contents of the slot.
if($this->figFilter) {
$filterClass = $this->figFilter;
$filter = $this->instantiateFilter($context, $filterClass);
$buffer = $filter->transform($buffer);
}
return $buffer;
} | [
"private",
"function",
"applyOutputFilter",
"(",
"Context",
"$",
"context",
",",
"$",
"buffer",
")",
"{",
"//TODO: Currently the filtering works only on non-slot tags.",
"//If applied on a slot tag, the transform is made on the special placeholder /==SLOT=.../",
"//rather than the future... | Applies a filter to the inner contents of an element.
Returns the filtered output.
@param Context $context
@param string $buffer the inner contents of the element, after rendering.
@return string
@throws RenderingException | [
"Applies",
"a",
"filter",
"to",
"the",
"inner",
"contents",
"of",
"an",
"element",
".",
"Returns",
"the",
"filtered",
"output",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/classes/ViewElementTag.php#L948-L958 | train |
figdice/figdice | src/figdice/classes/ViewElementTag.php | ViewElementTag.replaceLastChild_cdata | private function replaceLastChild_cdata(ViewElementCData $cdata)
{
$n = count($this->children);
if ( ($n > 1) && ($this->children[$n - 2] instanceof ViewElementCData) ) {
// Group the last-but-one cdata with this new cdata
$this->children[$n - 2]->outputBuffer .= $cdata->outputBuffer;
// and chop the final element off the children array.
array_pop($this->children);
} else {
$cdata->parent = $this;
$this->children[$n - 1] = $cdata;
}
} | php | private function replaceLastChild_cdata(ViewElementCData $cdata)
{
$n = count($this->children);
if ( ($n > 1) && ($this->children[$n - 2] instanceof ViewElementCData) ) {
// Group the last-but-one cdata with this new cdata
$this->children[$n - 2]->outputBuffer .= $cdata->outputBuffer;
// and chop the final element off the children array.
array_pop($this->children);
} else {
$cdata->parent = $this;
$this->children[$n - 1] = $cdata;
}
} | [
"private",
"function",
"replaceLastChild_cdata",
"(",
"ViewElementCData",
"$",
"cdata",
")",
"{",
"$",
"n",
"=",
"count",
"(",
"$",
"this",
"->",
"children",
")",
";",
"if",
"(",
"(",
"$",
"n",
">",
"1",
")",
"&&",
"(",
"$",
"this",
"->",
"children",... | If the last but one child is already a CData,
squash them together.
@param ViewElementCData $cdata | [
"If",
"the",
"last",
"but",
"one",
"child",
"is",
"already",
"a",
"CData",
"squash",
"them",
"together",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/classes/ViewElementTag.php#L1320-L1332 | train |
joomla-framework/console | src/Descriptor/ApplicationDescription.php | ApplicationDescription.inspectApplication | private function inspectApplication()
{
$this->commands = [];
$this->namespaces = [];
$all = $this->application->getAllCommands($this->namespace ? $this->application->findNamespace($this->namespace) : '');
foreach ($this->sortCommands($all) as $namespace => $commands)
{
$names = [];
/** @var AbstractCommand $command */
foreach ($commands as $name => $command)
{
if (!$command->getName() || (!$this->showHidden && $command->isHidden()))
{
continue;
}
if ($command->getName() === $name)
{
$this->commands[$name] = $command;
}
else
{
$this->aliases[$name] = $command;
}
$names[] = $name;
}
$this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names];
}
} | php | private function inspectApplication()
{
$this->commands = [];
$this->namespaces = [];
$all = $this->application->getAllCommands($this->namespace ? $this->application->findNamespace($this->namespace) : '');
foreach ($this->sortCommands($all) as $namespace => $commands)
{
$names = [];
/** @var AbstractCommand $command */
foreach ($commands as $name => $command)
{
if (!$command->getName() || (!$this->showHidden && $command->isHidden()))
{
continue;
}
if ($command->getName() === $name)
{
$this->commands[$name] = $command;
}
else
{
$this->aliases[$name] = $command;
}
$names[] = $name;
}
$this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names];
}
} | [
"private",
"function",
"inspectApplication",
"(",
")",
"{",
"$",
"this",
"->",
"commands",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"namespaces",
"=",
"[",
"]",
";",
"$",
"all",
"=",
"$",
"this",
"->",
"application",
"->",
"getAllCommands",
"(",
"$",
"... | Inspects the application.
@return void
@since __DEPLOY_VERSION__ | [
"Inspects",
"the",
"application",
"."
] | b8ab98ec0fab96002b22399dea8c2ff206a87380 | https://github.com/joomla-framework/console/blob/b8ab98ec0fab96002b22399dea8c2ff206a87380/src/Descriptor/ApplicationDescription.php#L167-L200 | train |
joomla-framework/console | src/Descriptor/ApplicationDescription.php | ApplicationDescription.sortCommands | private function sortCommands(array $commands): array
{
$namespacedCommands = [];
$globalCommands = [];
foreach ($commands as $name => $command)
{
$key = $this->extractNamespace($name, 1);
if (!$key)
{
$globalCommands[self::GLOBAL_NAMESPACE][$name] = $command;
}
else
{
$namespacedCommands[$key][$name] = $command;
}
}
ksort($namespacedCommands);
$namespacedCommands = array_merge($globalCommands, $namespacedCommands);
foreach ($namespacedCommands as &$commandsSet)
{
ksort($commandsSet);
}
// Unset reference to keep scope clear
unset($commandsSet);
return $namespacedCommands;
} | php | private function sortCommands(array $commands): array
{
$namespacedCommands = [];
$globalCommands = [];
foreach ($commands as $name => $command)
{
$key = $this->extractNamespace($name, 1);
if (!$key)
{
$globalCommands[self::GLOBAL_NAMESPACE][$name] = $command;
}
else
{
$namespacedCommands[$key][$name] = $command;
}
}
ksort($namespacedCommands);
$namespacedCommands = array_merge($globalCommands, $namespacedCommands);
foreach ($namespacedCommands as &$commandsSet)
{
ksort($commandsSet);
}
// Unset reference to keep scope clear
unset($commandsSet);
return $namespacedCommands;
} | [
"private",
"function",
"sortCommands",
"(",
"array",
"$",
"commands",
")",
":",
"array",
"{",
"$",
"namespacedCommands",
"=",
"[",
"]",
";",
"$",
"globalCommands",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"commands",
"as",
"$",
"name",
"=>",
"$",
"comm... | Sort a set of commands.
@param AbstractCommand[] $commands The commands to sort.
@return AbstractCommand[]
@since __DEPLOY_VERSION__ | [
"Sort",
"a",
"set",
"of",
"commands",
"."
] | b8ab98ec0fab96002b22399dea8c2ff206a87380 | https://github.com/joomla-framework/console/blob/b8ab98ec0fab96002b22399dea8c2ff206a87380/src/Descriptor/ApplicationDescription.php#L211-L242 | train |
ynloultratech/graphql-bundle | src/Annotation/Plugin/PluginConfigAnnotation.php | PluginConfigAnnotation.getConfig | public function getConfig(): array
{
$ref = new \ReflectionClass(get_class($this));
$properties = $ref->getProperties();
$config = [];
//set default values
foreach ($properties as $property) {
$value = $property->getValue($this);
if (null !== $value) {
$config[Inflector::tableize($property->getName())] = $property->getValue($this);
}
}
return $config;
} | php | public function getConfig(): array
{
$ref = new \ReflectionClass(get_class($this));
$properties = $ref->getProperties();
$config = [];
//set default values
foreach ($properties as $property) {
$value = $property->getValue($this);
if (null !== $value) {
$config[Inflector::tableize($property->getName())] = $property->getValue($this);
}
}
return $config;
} | [
"public",
"function",
"getConfig",
"(",
")",
":",
"array",
"{",
"$",
"ref",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"get_class",
"(",
"$",
"this",
")",
")",
";",
"$",
"properties",
"=",
"$",
"ref",
"->",
"getProperties",
"(",
")",
";",
"$",
"config... | Must return the array with plugin config
@return array | [
"Must",
"return",
"the",
"array",
"with",
"plugin",
"config"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Annotation/Plugin/PluginConfigAnnotation.php#L42-L57 | train |
ekyna/Dpd | src/EPrint/Model/Shipment.php | Shipment.getTrackingUrl | public function getTrackingUrl()
{
if (!isset($this->parcelnumber)) {
throw new RuntimeException("Shipment has no parcel number.");
}
return sprintf(Api::TRACKING_URL, $this->parcelnumber);
} | php | public function getTrackingUrl()
{
if (!isset($this->parcelnumber)) {
throw new RuntimeException("Shipment has no parcel number.");
}
return sprintf(Api::TRACKING_URL, $this->parcelnumber);
} | [
"public",
"function",
"getTrackingUrl",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"parcelnumber",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Shipment has no parcel number.\"",
")",
";",
"}",
"return",
"sprintf",
"(",
"Ap... | Returns the tracking url.
@return string
@throws RuntimeException | [
"Returns",
"the",
"tracking",
"url",
"."
] | 67eabcff840b310021d5ca7ebb824fa7d7cb700b | https://github.com/ekyna/Dpd/blob/67eabcff840b310021d5ca7ebb824fa7d7cb700b/src/EPrint/Model/Shipment.php#L32-L39 | train |
nyeholt/silverstripe-solr | code/service/querybuilders/SolrQueryBuilder.php | SolrQueryBuilder.addFilter | public function addFilter($query, $value = null) {
if ($value) {
$query = "$query:$value";
}
$this->filters[$query] = $query;
return $this;
} | php | public function addFilter($query, $value = null) {
if ($value) {
$query = "$query:$value";
}
$this->filters[$query] = $query;
return $this;
} | [
"public",
"function",
"addFilter",
"(",
"$",
"query",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
")",
"{",
"$",
"query",
"=",
"\"$query:$value\"",
";",
"}",
"$",
"this",
"->",
"filters",
"[",
"$",
"query",
"]",
"=",
"$",
"... | Add a filter query clause.
Filter queries simply restrict the result set without affecting the score of results
@param string $query | [
"Add",
"a",
"filter",
"query",
"clause",
"."
] | a573df88167ba9b2bec51e2660a4edfdad446fcf | https://github.com/nyeholt/silverstripe-solr/blob/a573df88167ba9b2bec51e2660a4edfdad446fcf/code/service/querybuilders/SolrQueryBuilder.php#L327-L333 | train |
nyeholt/silverstripe-solr | code/service/querybuilders/SolrQueryBuilder.php | SolrQueryBuilder.removeFilter | public function removeFilter($query, $value = null) {
if ($value) {
$query = "$query:$value";
}
unset($this->filters[$query]);
return $this;
} | php | public function removeFilter($query, $value = null) {
if ($value) {
$query = "$query:$value";
}
unset($this->filters[$query]);
return $this;
} | [
"public",
"function",
"removeFilter",
"(",
"$",
"query",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
")",
"{",
"$",
"query",
"=",
"\"$query:$value\"",
";",
"}",
"unset",
"(",
"$",
"this",
"->",
"filters",
"[",
"$",
"query",
"... | Remove a filter in place on this query
@param string $query
@param mixed $value | [
"Remove",
"a",
"filter",
"in",
"place",
"on",
"this",
"query"
] | a573df88167ba9b2bec51e2660a4edfdad446fcf | https://github.com/nyeholt/silverstripe-solr/blob/a573df88167ba9b2bec51e2660a4edfdad446fcf/code/service/querybuilders/SolrQueryBuilder.php#L341-L347 | train |
nyeholt/silverstripe-solr | code/service/querybuilders/SolrQueryBuilder.php | SolrQueryBuilder.restrictNearPoint | public function restrictNearPoint($point, $field, $radius) {
$this->addFilter("{!geofilt}");
$this->params['sfield'] = $field;
$this->params['pt'] = $point;
$this->params['d'] = $radius;
return $this;
} | php | public function restrictNearPoint($point, $field, $radius) {
$this->addFilter("{!geofilt}");
$this->params['sfield'] = $field;
$this->params['pt'] = $point;
$this->params['d'] = $radius;
return $this;
} | [
"public",
"function",
"restrictNearPoint",
"(",
"$",
"point",
",",
"$",
"field",
",",
"$",
"radius",
")",
"{",
"$",
"this",
"->",
"addFilter",
"(",
"\"{!geofilt}\"",
")",
";",
"$",
"this",
"->",
"params",
"[",
"'sfield'",
"]",
"=",
"$",
"field",
";",
... | Apply a geo field restriction around a particular point
@param string $point
The point in "lat,lon" format
@param string $field
@param float $radius | [
"Apply",
"a",
"geo",
"field",
"restriction",
"around",
"a",
"particular",
"point"
] | a573df88167ba9b2bec51e2660a4edfdad446fcf | https://github.com/nyeholt/silverstripe-solr/blob/a573df88167ba9b2bec51e2660a4edfdad446fcf/code/service/querybuilders/SolrQueryBuilder.php#L357-L365 | train |
magnus-eriksson/router | src/Router.php | Router.toRoute | public function toRoute($name, array $args = [], $code = 307)
{
$to = $this->getRoute($name, $args);
header("location: {$to}", true, $code);
exit;
} | php | public function toRoute($name, array $args = [], $code = 307)
{
$to = $this->getRoute($name, $args);
header("location: {$to}", true, $code);
exit;
} | [
"public",
"function",
"toRoute",
"(",
"$",
"name",
",",
"array",
"$",
"args",
"=",
"[",
"]",
",",
"$",
"code",
"=",
"307",
")",
"{",
"$",
"to",
"=",
"$",
"this",
"->",
"getRoute",
"(",
"$",
"name",
",",
"$",
"args",
")",
";",
"header",
"(",
"... | Redirect to a route
@param string $name
@param array $args
@param int $code
@return $this | [
"Redirect",
"to",
"a",
"route"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L155-L161 | train |
magnus-eriksson/router | src/Router.php | Router.crud | public function crud($pattern, $callback, array $params = [])
{
if (!is_string($callback)) {
throw new \Exception('Crud callbacks must be a string to a controller class');
}
if (!empty($params['name'])) {
$name = $params['name'];
}
$pattern = rtrim($pattern, '/');
$params['name'] = $name ? $name . '.create' : null;
$this->post("{$pattern}", "{$callback}@create", $params);
$params['name'] = $name ? $name . '.one' : null;
$this->get("{$pattern}/(:any)", "{$callback}@one", $params);
$params['name'] = $name ? $name . '.many' : null;
$this->get("{$pattern}", "{$callback}@many", $params);
$params['name'] = $name ? $name . '.update' : null;
$this->put("{$pattern}/(:any)", "{$callback}@update", $params);
$params['name'] = $name ? $name . '.delete' : null;
$this->delete("{$pattern}/(:any)", "{$callback}@delete", $params);
return $this;
} | php | public function crud($pattern, $callback, array $params = [])
{
if (!is_string($callback)) {
throw new \Exception('Crud callbacks must be a string to a controller class');
}
if (!empty($params['name'])) {
$name = $params['name'];
}
$pattern = rtrim($pattern, '/');
$params['name'] = $name ? $name . '.create' : null;
$this->post("{$pattern}", "{$callback}@create", $params);
$params['name'] = $name ? $name . '.one' : null;
$this->get("{$pattern}/(:any)", "{$callback}@one", $params);
$params['name'] = $name ? $name . '.many' : null;
$this->get("{$pattern}", "{$callback}@many", $params);
$params['name'] = $name ? $name . '.update' : null;
$this->put("{$pattern}/(:any)", "{$callback}@update", $params);
$params['name'] = $name ? $name . '.delete' : null;
$this->delete("{$pattern}/(:any)", "{$callback}@delete", $params);
return $this;
} | [
"public",
"function",
"crud",
"(",
"$",
"pattern",
",",
"$",
"callback",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"callback",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Crud callbacks ... | Add crud routes for a controller
@param string $pattern
@param string $callback
@param array $params
@return $this | [
"Add",
"crud",
"routes",
"for",
"a",
"controller"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L173-L200 | train |
magnus-eriksson/router | src/Router.php | Router.group | public function group(array $params, $callback)
{
$prefix = trim($this->getParam($params, 'prefix'), '/');
$before = $this->getParam($params, 'before');
$after = $this->getParam($params, 'after');
if ($prefix) {
$this->prefixes[] = $prefix;
$this->prefix = '/' . trim(implode('/', $this->prefixes), '/');
}
if ($before) {
$this->befores[] = $before;
$this->before = explode('|', implode('|', $this->befores));
}
if ($after) {
$this->afters[] = $after;
$this->after = explode('|', implode('|', $this->afters));
}
call_user_func_array($callback, [$this]);
if ($prefix) {
array_pop($this->prefixes);
$this->prefix = $this->prefixes ? '/' . trim(implode('/', $this->prefixes), '/') : null;
}
if ($before) {
array_pop($this->befores);
$this->before = explode('|', implode('|', $this->befores));
}
if ($after) {
array_pop($this->afters);
$this->after = explode('|', implode('|', $this->afters));
}
return $this;
} | php | public function group(array $params, $callback)
{
$prefix = trim($this->getParam($params, 'prefix'), '/');
$before = $this->getParam($params, 'before');
$after = $this->getParam($params, 'after');
if ($prefix) {
$this->prefixes[] = $prefix;
$this->prefix = '/' . trim(implode('/', $this->prefixes), '/');
}
if ($before) {
$this->befores[] = $before;
$this->before = explode('|', implode('|', $this->befores));
}
if ($after) {
$this->afters[] = $after;
$this->after = explode('|', implode('|', $this->afters));
}
call_user_func_array($callback, [$this]);
if ($prefix) {
array_pop($this->prefixes);
$this->prefix = $this->prefixes ? '/' . trim(implode('/', $this->prefixes), '/') : null;
}
if ($before) {
array_pop($this->befores);
$this->before = explode('|', implode('|', $this->befores));
}
if ($after) {
array_pop($this->afters);
$this->after = explode('|', implode('|', $this->afters));
}
return $this;
} | [
"public",
"function",
"group",
"(",
"array",
"$",
"params",
",",
"$",
"callback",
")",
"{",
"$",
"prefix",
"=",
"trim",
"(",
"$",
"this",
"->",
"getParam",
"(",
"$",
"params",
",",
"'prefix'",
")",
",",
"'/'",
")",
";",
"$",
"before",
"=",
"$",
"... | Create a new route group
@param array $params
@param mixed $callback
@return $this | [
"Create",
"a",
"new",
"route",
"group"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L211-L250 | train |
magnus-eriksson/router | src/Router.php | Router.getMatch | public function getMatch($method = null, $path = null)
{
$method = $method ?: $this->getRequestMethod();
$path = $path ?: $this->getRequestPath();
$method = strtoupper($method);
$methodNotAllowed = null;
foreach ($this->routes as $pattern => $methods) {
preg_match($this->regexifyPattern($pattern), $path, $matches);
if ($matches) {
$r = $this->getRouteObject($pattern, $method);
if (!$r) {
// We found a match but with the wrong method
$methodNotAllowed = true;
continue;
}
$r->method = strtoupper($method);
$r->args = $this->getMatchArgs($matches);
return $r;
}
}
if ($methodNotAllowed) {
if ($this->methodNotAllowed) {
return (object)[
'before' => [],
'after' => [],
'args' => [],
'callback' => &$this->methodNotAllowed,
];
}
throw new MethodNotAllowedException;
}
if ($this->notFound) {
return (object)[
'before' => [],
'after' => [],
'args' => [],
'callback' => &$this->notFound,
];
}
throw new NotFoundException;
} | php | public function getMatch($method = null, $path = null)
{
$method = $method ?: $this->getRequestMethod();
$path = $path ?: $this->getRequestPath();
$method = strtoupper($method);
$methodNotAllowed = null;
foreach ($this->routes as $pattern => $methods) {
preg_match($this->regexifyPattern($pattern), $path, $matches);
if ($matches) {
$r = $this->getRouteObject($pattern, $method);
if (!$r) {
// We found a match but with the wrong method
$methodNotAllowed = true;
continue;
}
$r->method = strtoupper($method);
$r->args = $this->getMatchArgs($matches);
return $r;
}
}
if ($methodNotAllowed) {
if ($this->methodNotAllowed) {
return (object)[
'before' => [],
'after' => [],
'args' => [],
'callback' => &$this->methodNotAllowed,
];
}
throw new MethodNotAllowedException;
}
if ($this->notFound) {
return (object)[
'before' => [],
'after' => [],
'args' => [],
'callback' => &$this->notFound,
];
}
throw new NotFoundException;
} | [
"public",
"function",
"getMatch",
"(",
"$",
"method",
"=",
"null",
",",
"$",
"path",
"=",
"null",
")",
"{",
"$",
"method",
"=",
"$",
"method",
"?",
":",
"$",
"this",
"->",
"getRequestMethod",
"(",
")",
";",
"$",
"path",
"=",
"$",
"path",
"?",
":"... | Get matching route
@param string $method
@param string $path
@return object
@throws MethodNotAllowedException
@throws NotFoundException | [
"Get",
"matching",
"route"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L264-L315 | train |
magnus-eriksson/router | src/Router.php | Router.dispatch | public function dispatch($method = null, $path = null)
{
$match = $this->getMatch($method, $path);
foreach ($match->before as $filter) {
if (empty($filter)) {
continue;
}
$response = $this->executeCallback($this->getFilterCallback($filter), $match->args, true);
if (!is_null($response)) {
return $response;
}
}
$routeResponse = $this->executeCallback($match->callback, $match->args);
foreach ($match->after as $filter) {
if (empty($filter)) {
continue;
}
array_unshift($match->args, $routeResponse);
$response = $this->executeCallback($this->getFilterCallback($filter), $match->args, true);
if (!is_null($response)) {
return $response;
}
}
return $routeResponse;
} | php | public function dispatch($method = null, $path = null)
{
$match = $this->getMatch($method, $path);
foreach ($match->before as $filter) {
if (empty($filter)) {
continue;
}
$response = $this->executeCallback($this->getFilterCallback($filter), $match->args, true);
if (!is_null($response)) {
return $response;
}
}
$routeResponse = $this->executeCallback($match->callback, $match->args);
foreach ($match->after as $filter) {
if (empty($filter)) {
continue;
}
array_unshift($match->args, $routeResponse);
$response = $this->executeCallback($this->getFilterCallback($filter), $match->args, true);
if (!is_null($response)) {
return $response;
}
}
return $routeResponse;
} | [
"public",
"function",
"dispatch",
"(",
"$",
"method",
"=",
"null",
",",
"$",
"path",
"=",
"null",
")",
"{",
"$",
"match",
"=",
"$",
"this",
"->",
"getMatch",
"(",
"$",
"method",
",",
"$",
"path",
")",
";",
"foreach",
"(",
"$",
"match",
"->",
"bef... | Get matching route and dispatch all filters and callbacks
@param string $method
@param string $path
@return mixed
@throws Exception
@throws MethodNotAllowedException
@throws NotFoundException | [
"Get",
"matching",
"route",
"and",
"dispatch",
"all",
"filters",
"and",
"callbacks"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L345-L373 | train |
magnus-eriksson/router | src/Router.php | Router.executeCallback | public function executeCallback($cb, array $args = [], $filter = false)
{
if ($cb instanceof Closure) {
return call_user_func_array($cb, $args);
}
if (is_string($cb) && strpos($cb, "@") !== false) {
$cb = explode('@', $cb);
}
if (is_array($cb) && count($cb) == 2) {
if (!is_object($cb[0])) {
$cb = $this->resolveCallback($cb);
}
if (isset($cb[0], $cb[1]) && is_object($cb[0]) && !method_exists($cb[0], $cb[1])) {
$name = get_class($cb[0]);
throw new ControllerNotFoundException("Controller '{$name}->{$cb[1]}' not found");
}
return call_user_func_array($cb, $args);
}
if (is_string($cb) && strpos($cb, "::") !== false) {
return call_user_func_array($cb, $args);
}
throw new Exception('Invalid callback');
} | php | public function executeCallback($cb, array $args = [], $filter = false)
{
if ($cb instanceof Closure) {
return call_user_func_array($cb, $args);
}
if (is_string($cb) && strpos($cb, "@") !== false) {
$cb = explode('@', $cb);
}
if (is_array($cb) && count($cb) == 2) {
if (!is_object($cb[0])) {
$cb = $this->resolveCallback($cb);
}
if (isset($cb[0], $cb[1]) && is_object($cb[0]) && !method_exists($cb[0], $cb[1])) {
$name = get_class($cb[0]);
throw new ControllerNotFoundException("Controller '{$name}->{$cb[1]}' not found");
}
return call_user_func_array($cb, $args);
}
if (is_string($cb) && strpos($cb, "::") !== false) {
return call_user_func_array($cb, $args);
}
throw new Exception('Invalid callback');
} | [
"public",
"function",
"executeCallback",
"(",
"$",
"cb",
",",
"array",
"$",
"args",
"=",
"[",
"]",
",",
"$",
"filter",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"cb",
"instanceof",
"Closure",
")",
"{",
"return",
"call_user_func_array",
"(",
"$",
"cb",
... | Execute a callback
@param mixed $cb
@param array $args
@param boolean $filter Set if the callback is a filter or not
@return mixed
@throws Exception If the filter is unknown
@throws Exception If the callback isn't in one of the accepted formats | [
"Execute",
"a",
"callback"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L456-L484 | train |
magnus-eriksson/router | src/Router.php | Router.getRoute | public function getRoute($name, array $args = [])
{
if (!isset($this->names[$name])) {
return null;
}
$route = $this->callbacks[$this->names[$name]];
if (strpos($route->pattern, '(') === false) {
// If we don't have any route parameters, just return the pattern
// straight off. No need for any regex stuff.
return $route->pattern;
}
// Convert all placeholders to %o = optional and %r = required
$from = ['/(\([^\/]+[\)]+[\?])/', '/(\([^\/]+\))/'];
$to = ['%o', '%r'];
$pattern = preg_replace($from, $to, $route->pattern);
$frags = explode('/', trim($pattern, '/'));
$url = [];
// Loop thru the pattern fragments and insert the arguments
foreach ($frags as $frag) {
if ($frag == '%r') {
if (!$args) {
// A required parameter, but no more arguments.
throw new Exception('Missing route parameters');
}
$url[] = array_shift($args);
continue;
}
if ($frag == "%o") {
if (!$args) {
// No argument for the optional parameter,
// just continue the iteration.
continue;
}
$url[] = array_shift($args);
continue;
}
$url[] = $frag;
}
return '/' . implode('/', $url);
} | php | public function getRoute($name, array $args = [])
{
if (!isset($this->names[$name])) {
return null;
}
$route = $this->callbacks[$this->names[$name]];
if (strpos($route->pattern, '(') === false) {
// If we don't have any route parameters, just return the pattern
// straight off. No need for any regex stuff.
return $route->pattern;
}
// Convert all placeholders to %o = optional and %r = required
$from = ['/(\([^\/]+[\)]+[\?])/', '/(\([^\/]+\))/'];
$to = ['%o', '%r'];
$pattern = preg_replace($from, $to, $route->pattern);
$frags = explode('/', trim($pattern, '/'));
$url = [];
// Loop thru the pattern fragments and insert the arguments
foreach ($frags as $frag) {
if ($frag == '%r') {
if (!$args) {
// A required parameter, but no more arguments.
throw new Exception('Missing route parameters');
}
$url[] = array_shift($args);
continue;
}
if ($frag == "%o") {
if (!$args) {
// No argument for the optional parameter,
// just continue the iteration.
continue;
}
$url[] = array_shift($args);
continue;
}
$url[] = $frag;
}
return '/' . implode('/', $url);
} | [
"public",
"function",
"getRoute",
"(",
"$",
"name",
",",
"array",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"names",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"route",
... | Get the URL of a named route
@param string $name
@param array $args
@return string
@throws Exception If there aren't enough arguments for all required parameters | [
"Get",
"the",
"URL",
"of",
"a",
"named",
"route"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L549-L596 | train |
magnus-eriksson/router | src/Router.php | Router.regexifyPattern | protected function regexifyPattern($pattern)
{
preg_match_all('/(\/?)\(:([^)]*)\)(\??)/', $pattern, $regExPatterns, PREG_SET_ORDER, 0);
$pattern = preg_quote($pattern, '/');
foreach ($regExPatterns as $regExPattern) {
if (!empty($regExPattern[2]) && key_exists($regExPattern[2], $this->patterns)) {
$replacement = sprintf(
'(%s%s)%s',
empty($regExPattern[1]) ? '' : '\/',
$this->patterns[$regExPattern[2]],
$regExPattern[3]
);
$pattern = str_replace(preg_quote($regExPattern[0], '/'), $replacement, $pattern);
}
}
return "/^$pattern$/";
} | php | protected function regexifyPattern($pattern)
{
preg_match_all('/(\/?)\(:([^)]*)\)(\??)/', $pattern, $regExPatterns, PREG_SET_ORDER, 0);
$pattern = preg_quote($pattern, '/');
foreach ($regExPatterns as $regExPattern) {
if (!empty($regExPattern[2]) && key_exists($regExPattern[2], $this->patterns)) {
$replacement = sprintf(
'(%s%s)%s',
empty($regExPattern[1]) ? '' : '\/',
$this->patterns[$regExPattern[2]],
$regExPattern[3]
);
$pattern = str_replace(preg_quote($regExPattern[0], '/'), $replacement, $pattern);
}
}
return "/^$pattern$/";
} | [
"protected",
"function",
"regexifyPattern",
"(",
"$",
"pattern",
")",
"{",
"preg_match_all",
"(",
"'/(\\/?)\\(:([^)]*)\\)(\\??)/'",
",",
"$",
"pattern",
",",
"$",
"regExPatterns",
",",
"PREG_SET_ORDER",
",",
"0",
")",
";",
"$",
"pattern",
"=",
"preg_quote",
"(",... | Replace placeholders to regular expressions
@param string $pattern
@return string | [
"Replace",
"placeholders",
"to",
"regular",
"expressions"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L621-L641 | train |
magnus-eriksson/router | src/Router.php | Router.getRouteObject | protected function getRouteObject($pattern, $method)
{
foreach (['REDIRECT', $method, 'ANY'] as $verb) {
if (array_key_exists($verb, $this->routes[$pattern])) {
$index = $this->routes[$pattern][$verb];
return $this->callbacks[$index];
}
}
return false;
} | php | protected function getRouteObject($pattern, $method)
{
foreach (['REDIRECT', $method, 'ANY'] as $verb) {
if (array_key_exists($verb, $this->routes[$pattern])) {
$index = $this->routes[$pattern][$verb];
return $this->callbacks[$index];
}
}
return false;
} | [
"protected",
"function",
"getRouteObject",
"(",
"$",
"pattern",
",",
"$",
"method",
")",
"{",
"foreach",
"(",
"[",
"'REDIRECT'",
",",
"$",
"method",
",",
"'ANY'",
"]",
"as",
"$",
"verb",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"verb",
",",
... | Get matched route from pattern and method
@param string $pattern
@param string $method
@return object|false | [
"Get",
"matched",
"route",
"from",
"pattern",
"and",
"method"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L652-L662 | train |
magnus-eriksson/router | src/Router.php | Router.getMatchArgs | protected function getMatchArgs(array $match)
{
// Remove the first element, the matching regex
array_shift($match);
// Iterate through the arguments and remove any unwanted slashes
foreach ($match as &$arg) {
$arg = trim($arg, '/');
}
return $match;
} | php | protected function getMatchArgs(array $match)
{
// Remove the first element, the matching regex
array_shift($match);
// Iterate through the arguments and remove any unwanted slashes
foreach ($match as &$arg) {
$arg = trim($arg, '/');
}
return $match;
} | [
"protected",
"function",
"getMatchArgs",
"(",
"array",
"$",
"match",
")",
"{",
"// Remove the first element, the matching regex",
"array_shift",
"(",
"$",
"match",
")",
";",
"// Iterate through the arguments and remove any unwanted slashes",
"foreach",
"(",
"$",
"match",
"a... | Get and clean route arguments
@param array $match
@return array | [
"Get",
"and",
"clean",
"route",
"arguments"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L672-L683 | train |
magnus-eriksson/router | src/Router.php | Router.storeRoute | protected function storeRoute(array $methods, array $route)
{
$this->callbacks[] = (object)$route;
$index = count($this->callbacks) - 1;
if (!isset($this->routes[$route['pattern']])) {
$this->routes[$route['pattern']] = [];
}
if ($route['name']) {
$this->names[$route['name']] = $index;
}
foreach ($methods as $method) {
$this->routes[$route['pattern']][strtoupper($method)] = $index;
}
} | php | protected function storeRoute(array $methods, array $route)
{
$this->callbacks[] = (object)$route;
$index = count($this->callbacks) - 1;
if (!isset($this->routes[$route['pattern']])) {
$this->routes[$route['pattern']] = [];
}
if ($route['name']) {
$this->names[$route['name']] = $index;
}
foreach ($methods as $method) {
$this->routes[$route['pattern']][strtoupper($method)] = $index;
}
} | [
"protected",
"function",
"storeRoute",
"(",
"array",
"$",
"methods",
",",
"array",
"$",
"route",
")",
"{",
"$",
"this",
"->",
"callbacks",
"[",
"]",
"=",
"(",
"object",
")",
"$",
"route",
";",
"$",
"index",
"=",
"count",
"(",
"$",
"this",
"->",
"ca... | Store a route in the route collection
@param array $methods
@param array $route | [
"Store",
"a",
"route",
"in",
"the",
"route",
"collection"
] | 0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff | https://github.com/magnus-eriksson/router/blob/0f74b3c575ebf852f0f8c78cd3a9bec6d75050ff/src/Router.php#L692-L708 | train |
skipify/vitexframework | vitex/Log.php | Log.interpolate | protected function interpolate($message, $context = array())
{
$replace = array();
foreach ($context as $key => $value) {
$replace['{' . $key . '}'] = $value;
}
return strtr($message, $replace);
} | php | protected function interpolate($message, $context = array())
{
$replace = array();
foreach ($context as $key => $value) {
$replace['{' . $key . '}'] = $value;
}
return strtr($message, $replace);
} | [
"protected",
"function",
"interpolate",
"(",
"$",
"message",
",",
"$",
"context",
"=",
"array",
"(",
")",
")",
"{",
"$",
"replace",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"context",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
... | Interpolate log message
@param mixed $message The log message
@param array $context An array of placeholder values
@return string The processed string | [
"Interpolate",
"log",
"message"
] | 9cb42307d31a88c1a9393e70548ae675d4c03c20 | https://github.com/skipify/vitexframework/blob/9cb42307d31a88c1a9393e70548ae675d4c03c20/vitex/Log.php#L234-L241 | train |
ynloultratech/graphql-bundle | src/Definition/Plugin/CRUDExtensionResolverPlugin.php | CRUDExtensionResolverPlugin.resolveInterfaceExtension | protected function resolveInterfaceExtension(InterfaceDefinition $definition, Endpoint $endpoint): void
{
$bundleNamespace = ClassUtils::relatedBundleNamespace($definition->getClass());
$extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $definition->getName().'Extension');
if (class_exists($extensionClass)) {
foreach ($definition->getImplementors() as $implementor) {
$definition->addExtension($extensionClass);
$object = $endpoint->getType($implementor);
if ($object instanceof HasExtensionsInterface) {
$object->addExtension($extensionClass);
}
}
}
} | php | protected function resolveInterfaceExtension(InterfaceDefinition $definition, Endpoint $endpoint): void
{
$bundleNamespace = ClassUtils::relatedBundleNamespace($definition->getClass());
$extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $definition->getName().'Extension');
if (class_exists($extensionClass)) {
foreach ($definition->getImplementors() as $implementor) {
$definition->addExtension($extensionClass);
$object = $endpoint->getType($implementor);
if ($object instanceof HasExtensionsInterface) {
$object->addExtension($extensionClass);
}
}
}
} | [
"protected",
"function",
"resolveInterfaceExtension",
"(",
"InterfaceDefinition",
"$",
"definition",
",",
"Endpoint",
"$",
"endpoint",
")",
":",
"void",
"{",
"$",
"bundleNamespace",
"=",
"ClassUtils",
"::",
"relatedBundleNamespace",
"(",
"$",
"definition",
"->",
"ge... | Using naming convention resolve CRUD extension for given interface definition and automatically register this extension
for all interface implementors
@param InterfaceDefinition $definition
@param Endpoint $endpoint | [
"Using",
"naming",
"convention",
"resolve",
"CRUD",
"extension",
"for",
"given",
"interface",
"definition",
"and",
"automatically",
"register",
"this",
"extension",
"for",
"all",
"interface",
"implementors"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Definition/Plugin/CRUDExtensionResolverPlugin.php#L55-L68 | train |
ynloultratech/graphql-bundle | src/Definition/Plugin/CRUDExtensionResolverPlugin.php | CRUDExtensionResolverPlugin.resolveObjectRealInterfaceExtensions | protected function resolveObjectRealInterfaceExtensions(ClassAwareDefinitionInterface $definition): void
{
$class = $definition->getClass();
if (class_exists($class)) {
$refClass = new \ReflectionClass($definition->getClass());
if ($interfaces = $refClass->getInterfaceNames()) {
foreach ($interfaces as $interface) {
$bundleNamespace = ClassUtils::relatedBundleNamespace($interface);
if (preg_match('/(\w+)Interface?$/', $interface, $matches)) {
$extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $matches[1].'Extension');
if (class_exists($extensionClass)) {
if ($definition instanceof HasExtensionsInterface) {
$definition->addExtension($extensionClass);
}
}
}
}
}
}
} | php | protected function resolveObjectRealInterfaceExtensions(ClassAwareDefinitionInterface $definition): void
{
$class = $definition->getClass();
if (class_exists($class)) {
$refClass = new \ReflectionClass($definition->getClass());
if ($interfaces = $refClass->getInterfaceNames()) {
foreach ($interfaces as $interface) {
$bundleNamespace = ClassUtils::relatedBundleNamespace($interface);
if (preg_match('/(\w+)Interface?$/', $interface, $matches)) {
$extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $matches[1].'Extension');
if (class_exists($extensionClass)) {
if ($definition instanceof HasExtensionsInterface) {
$definition->addExtension($extensionClass);
}
}
}
}
}
}
} | [
"protected",
"function",
"resolveObjectRealInterfaceExtensions",
"(",
"ClassAwareDefinitionInterface",
"$",
"definition",
")",
":",
"void",
"{",
"$",
"class",
"=",
"$",
"definition",
"->",
"getClass",
"(",
")",
";",
"if",
"(",
"class_exists",
"(",
"$",
"class",
... | Using naming convention resolve all extensions for given object
based on implemented interfaces.
This method use PHP real interfaces instead of registered interface types.
@param ClassAwareDefinitionInterface $definition
@throws \ReflectionException | [
"Using",
"naming",
"convention",
"resolve",
"all",
"extensions",
"for",
"given",
"object",
"based",
"on",
"implemented",
"interfaces",
"."
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Definition/Plugin/CRUDExtensionResolverPlugin.php#L80-L100 | train |
nyeholt/silverstripe-solr | code/thirdparty/Apache/Solr/Service.php | Apache_Solr_Service.getHttpTransport | public function getHttpTransport()
{
// lazy load a default if one has not be set
if ($this->_httpTransport === false)
{
require_once(dirname(__FILE__) . '/HttpTransport/FileGetContents.php');
$this->_httpTransport = new Apache_Solr_HttpTransport_FileGetContents();
}
return $this->_httpTransport;
} | php | public function getHttpTransport()
{
// lazy load a default if one has not be set
if ($this->_httpTransport === false)
{
require_once(dirname(__FILE__) . '/HttpTransport/FileGetContents.php');
$this->_httpTransport = new Apache_Solr_HttpTransport_FileGetContents();
}
return $this->_httpTransport;
} | [
"public",
"function",
"getHttpTransport",
"(",
")",
"{",
"// lazy load a default if one has not be set",
"if",
"(",
"$",
"this",
"->",
"_httpTransport",
"===",
"false",
")",
"{",
"require_once",
"(",
"dirname",
"(",
"__FILE__",
")",
".",
"'/HttpTransport/FileGetConten... | Get the current configured HTTP Transport
@return HttpTransportInterface | [
"Get",
"the",
"current",
"configured",
"HTTP",
"Transport"
] | a573df88167ba9b2bec51e2660a4edfdad446fcf | https://github.com/nyeholt/silverstripe-solr/blob/a573df88167ba9b2bec51e2660a4edfdad446fcf/code/thirdparty/Apache/Solr/Service.php#L481-L492 | train |
contao-community-alliance/translator | src/TranslatorChain.php | TranslatorChain.add | public function add(TranslatorInterface $translator)
{
$hash = spl_object_hash($translator);
$this->translators[$hash] = $translator;
return $this;
} | php | public function add(TranslatorInterface $translator)
{
$hash = spl_object_hash($translator);
$this->translators[$hash] = $translator;
return $this;
} | [
"public",
"function",
"add",
"(",
"TranslatorInterface",
"$",
"translator",
")",
"{",
"$",
"hash",
"=",
"spl_object_hash",
"(",
"$",
"translator",
")",
";",
"$",
"this",
"->",
"translators",
"[",
"$",
"hash",
"]",
"=",
"$",
"translator",
";",
"return",
"... | Add a translator to the chain.
@param TranslatorInterface $translator The translator to add.
@return TranslatorChain | [
"Add",
"a",
"translator",
"to",
"the",
"chain",
"."
] | daa920897510c10ee400b29c83840a866c17623a | https://github.com/contao-community-alliance/translator/blob/daa920897510c10ee400b29c83840a866c17623a/src/TranslatorChain.php#L82-L89 | train |
contao-community-alliance/translator | src/TranslatorChain.php | TranslatorChain.remove | public function remove(TranslatorInterface $translator)
{
$hash = spl_object_hash($translator);
unset($this->translators[$hash]);
return $this;
} | php | public function remove(TranslatorInterface $translator)
{
$hash = spl_object_hash($translator);
unset($this->translators[$hash]);
return $this;
} | [
"public",
"function",
"remove",
"(",
"TranslatorInterface",
"$",
"translator",
")",
"{",
"$",
"hash",
"=",
"spl_object_hash",
"(",
"$",
"translator",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"translators",
"[",
"$",
"hash",
"]",
")",
";",
"return",
"$"... | Remove a translator from the chain.
@param TranslatorInterface $translator The translator.
@return TranslatorChain | [
"Remove",
"a",
"translator",
"from",
"the",
"chain",
"."
] | daa920897510c10ee400b29c83840a866c17623a | https://github.com/contao-community-alliance/translator/blob/daa920897510c10ee400b29c83840a866c17623a/src/TranslatorChain.php#L98-L105 | train |
figdice/figdice | src/figdice/View.php | View.loadFile | public function loadFile($filename) {
$this->filename = $filename;
// If a cache directory was specified,
// try to load from it
if ($this->cachePath) {
if (! $this->templatesRoot) {
$this->templatesRoot = dirname($filename);
}
$cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename);
if ( file_exists($cacheFile)
&& (! file_exists($this->filename) || (filemtime($this->filename) < filemtime($cacheFile)) )
) {
$this->loadFromSerialized(file_get_contents($cacheFile));
return;
}
}
if(file_exists($filename)) {
$this->source = file_get_contents($filename);
} else {
$message = "File not found: $filename";
throw new FileNotFoundException($message, $filename);
}
} | php | public function loadFile($filename) {
$this->filename = $filename;
// If a cache directory was specified,
// try to load from it
if ($this->cachePath) {
if (! $this->templatesRoot) {
$this->templatesRoot = dirname($filename);
}
$cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename);
if ( file_exists($cacheFile)
&& (! file_exists($this->filename) || (filemtime($this->filename) < filemtime($cacheFile)) )
) {
$this->loadFromSerialized(file_get_contents($cacheFile));
return;
}
}
if(file_exists($filename)) {
$this->source = file_get_contents($filename);
} else {
$message = "File not found: $filename";
throw new FileNotFoundException($message, $filename);
}
} | [
"public",
"function",
"loadFile",
"(",
"$",
"filename",
")",
"{",
"$",
"this",
"->",
"filename",
"=",
"$",
"filename",
";",
"// If a cache directory was specified,",
"// try to load from it",
"if",
"(",
"$",
"this",
"->",
"cachePath",
")",
"{",
"if",
"(",
"!",... | Load from source file.
@param string $filename
@throws FileNotFoundException | [
"Load",
"from",
"source",
"file",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/View.php#L287-L312 | train |
figdice/figdice | src/figdice/View.php | View.parse | public function parse() {
if($this->bParsed) {
return;
}
if ($this->replacements) {
// We cannot rely of html_entity_decode,
// because it would replace & and < as well,
// whereas we need to keep them unmodified.
// We must do it manually, with a modified hardcopy
// of PHP 5.4+ 's get_html_translation_table(ENT_XHTML)
$this->source = XMLEntityTransformer::replace($this->source);
}
$this->xmlParser = xml_parser_create('UTF-8');
xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, false);
xml_set_object($this->xmlParser, $this);
xml_set_element_handler($this->xmlParser, 'openTagHandler', 'closeTagHandler');
xml_set_character_data_handler($this->xmlParser,'cdataHandler');
//Prepare the detection of the very first tag, in order to compute
//the offset in XML string as regarded by the parser.
$this->firstOpening = true;
try {
$bSuccess = xml_parse($this->xmlParser, $this->source);
} catch (RequiredAttributeException $ex) {
throw $ex->setFile($this->filename);
}
if ($bSuccess) {
$errMsg = '';
$lineNumber = 0;
} else {
$errMsg = xml_error_string(xml_get_error_code($this->xmlParser));
$lineNumber = xml_get_current_line_number($this->xmlParser);
if(count($this->stack)) {
$lastElement = $this->stack[count($this->stack) - 1];
if($lastElement instanceof ViewElementTag) {
$errMsg .= '. Last element: ' . $lastElement->getTagName() . '(' . $lineNumber . ')';
}
}
}
xml_parser_free($this->xmlParser);
$this->bParsed = $bSuccess;
if(! $bSuccess ) {
throw new XMLParsingException(
$errMsg,
$lineNumber);
}
// Store a serialized version of the parsed tree, if successfully parsed,
// and if we've got a cache path.
if ( ($this->cachePath) && ($this->filename !== null) && (! $this->unserialized) ) {
$cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename, true);
file_put_contents($cacheFile, serialize($this));
}
} | php | public function parse() {
if($this->bParsed) {
return;
}
if ($this->replacements) {
// We cannot rely of html_entity_decode,
// because it would replace & and < as well,
// whereas we need to keep them unmodified.
// We must do it manually, with a modified hardcopy
// of PHP 5.4+ 's get_html_translation_table(ENT_XHTML)
$this->source = XMLEntityTransformer::replace($this->source);
}
$this->xmlParser = xml_parser_create('UTF-8');
xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, false);
xml_set_object($this->xmlParser, $this);
xml_set_element_handler($this->xmlParser, 'openTagHandler', 'closeTagHandler');
xml_set_character_data_handler($this->xmlParser,'cdataHandler');
//Prepare the detection of the very first tag, in order to compute
//the offset in XML string as regarded by the parser.
$this->firstOpening = true;
try {
$bSuccess = xml_parse($this->xmlParser, $this->source);
} catch (RequiredAttributeException $ex) {
throw $ex->setFile($this->filename);
}
if ($bSuccess) {
$errMsg = '';
$lineNumber = 0;
} else {
$errMsg = xml_error_string(xml_get_error_code($this->xmlParser));
$lineNumber = xml_get_current_line_number($this->xmlParser);
if(count($this->stack)) {
$lastElement = $this->stack[count($this->stack) - 1];
if($lastElement instanceof ViewElementTag) {
$errMsg .= '. Last element: ' . $lastElement->getTagName() . '(' . $lineNumber . ')';
}
}
}
xml_parser_free($this->xmlParser);
$this->bParsed = $bSuccess;
if(! $bSuccess ) {
throw new XMLParsingException(
$errMsg,
$lineNumber);
}
// Store a serialized version of the parsed tree, if successfully parsed,
// and if we've got a cache path.
if ( ($this->cachePath) && ($this->filename !== null) && (! $this->unserialized) ) {
$cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename, true);
file_put_contents($cacheFile, serialize($this));
}
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"bParsed",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"replacements",
")",
"{",
"// We cannot rely of html_entity_decode,",
"// because it would replace & and < as ... | Parse source.
@throws RequiredAttributeException
@throws XMLParsingException | [
"Parse",
"source",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/View.php#L348-L409 | train |
figdice/figdice | src/figdice/View.php | View.makeCacheFilename | private function makeCacheFilename($cachePath, $templatesRoot, $filename, $mkdir = false)
{
// If the template filename is relative (ie. not starting by / and not specifying a scheme)
// then we first prefis it with the current working directory. And then we continue as if
// absolute.
if ( (substr($filename, 0, 1) != '/') && ! parse_url($filename, PHP_URL_SCHEME)) {
$filename = getcwd() . '/' . $filename;
}
$cacheFile = str_replace($templatesRoot, $cachePath . '/figs', $filename) . '.fig';
if ($mkdir) {
// Create the intermediary folders if not exist.
$intermed = dirname($cacheFile);
if (! file_exists($intermed)) {
// In case of permission problems, or file already exists (and is not a directory),
// the regular PHP warnings will be issued.
mkdir($intermed, 0700, true);
}
}
return $cacheFile;
} | php | private function makeCacheFilename($cachePath, $templatesRoot, $filename, $mkdir = false)
{
// If the template filename is relative (ie. not starting by / and not specifying a scheme)
// then we first prefis it with the current working directory. And then we continue as if
// absolute.
if ( (substr($filename, 0, 1) != '/') && ! parse_url($filename, PHP_URL_SCHEME)) {
$filename = getcwd() . '/' . $filename;
}
$cacheFile = str_replace($templatesRoot, $cachePath . '/figs', $filename) . '.fig';
if ($mkdir) {
// Create the intermediary folders if not exist.
$intermed = dirname($cacheFile);
if (! file_exists($intermed)) {
// In case of permission problems, or file already exists (and is not a directory),
// the regular PHP warnings will be issued.
mkdir($intermed, 0700, true);
}
}
return $cacheFile;
} | [
"private",
"function",
"makeCacheFilename",
"(",
"$",
"cachePath",
",",
"$",
"templatesRoot",
",",
"$",
"filename",
",",
"$",
"mkdir",
"=",
"false",
")",
"{",
"// If the template filename is relative (ie. not starting by / and not specifying a scheme)",
"// then we first pref... | The compiled file is at the same subfolder location as the source file,
relative to the templatesRoot directory, but under the tempPath directory.
In other words, tempPath and templatesRoot correspond together.
Example: if cachePath is /tmp/figdice
and templatesRoot is /var/www/html/app/templates
and filename is /var/www/html/app/templates/sub/footer.html
then cacheFile is /tmp/figdice/figs/sub/footer.html.fig
CAUTION: Relative path for the initial template file, is converted to absolute
using the current working directory (the way file_get_contents works).
You can work with exotic files (non local filesystem) provided that they are specified
with full (valid) scheme. @see http://php.net/manual/en/function.parse-url.php
@param string $cachePath
@param string $templatesRoot
@param string $filename
@param bool $mkdir Whether to create the intermediate folder structure
@return string | [
"The",
"compiled",
"file",
"is",
"at",
"the",
"same",
"subfolder",
"location",
"as",
"the",
"source",
"file",
"relative",
"to",
"the",
"templatesRoot",
"directory",
"but",
"under",
"the",
"tempPath",
"directory",
".",
"In",
"other",
"words",
"tempPath",
"and",... | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/View.php#L433-L453 | train |
figdice/figdice | src/figdice/View.php | View.render | public function render() {
if(! $this->bParsed) {
$this->parse();
}
if (! $this->rootNode) {
throw new XMLParsingException('No template file loaded', 0);
}
$context = new Context($this);
// DOCTYPE
// The doctype is necessarily on the root tag, declared as an attribute, example:
// fig:doctype="html"
// However, it can be on the root node of an included template (when using the reverse plug/slot pattern)
if ($this->rootNode instanceof ViewElementTag) {
$context->setDoctype($this->rootNode->getAttribute($this->figNamespace . 'doctype'));
}
try {
$result = $this->rootNode->render($context);
} catch (RequiredAttributeException $ex) {
throw $ex->setFile($context->getFilename());
} catch (TagRenderingException $ex) {
throw new RenderingException($ex->getTag(), $context->getFilename(), $ex->getLine(), $ex->getMessage(), $ex);
} catch (FeedClassNotFoundException $ex) {
throw $ex->setFile($context->getFilename());
}
$result = $this->plugIntoSlots($context, $result);
// Take care of the doctype at top of output
if ($context->getDoctype()) {
$result = '<!doctype ' . $context->getDoctype() . '>' . "\n" . $result;
}
return $result;
} | php | public function render() {
if(! $this->bParsed) {
$this->parse();
}
if (! $this->rootNode) {
throw new XMLParsingException('No template file loaded', 0);
}
$context = new Context($this);
// DOCTYPE
// The doctype is necessarily on the root tag, declared as an attribute, example:
// fig:doctype="html"
// However, it can be on the root node of an included template (when using the reverse plug/slot pattern)
if ($this->rootNode instanceof ViewElementTag) {
$context->setDoctype($this->rootNode->getAttribute($this->figNamespace . 'doctype'));
}
try {
$result = $this->rootNode->render($context);
} catch (RequiredAttributeException $ex) {
throw $ex->setFile($context->getFilename());
} catch (TagRenderingException $ex) {
throw new RenderingException($ex->getTag(), $context->getFilename(), $ex->getLine(), $ex->getMessage(), $ex);
} catch (FeedClassNotFoundException $ex) {
throw $ex->setFile($context->getFilename());
}
$result = $this->plugIntoSlots($context, $result);
// Take care of the doctype at top of output
if ($context->getDoctype()) {
$result = '<!doctype ' . $context->getDoctype() . '>' . "\n" . $result;
}
return $result;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"bParsed",
")",
"{",
"$",
"this",
"->",
"parse",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"rootNode",
")",
"{",
"throw",
"new",
"XMLParsingException",
... | Process parsed source and render view,
using the data universe.
@return string
@throws FeedClassNotFoundException
@throws RenderingException
@throws RequiredAttributeException
@throws XMLParsingException | [
"Process",
"parsed",
"source",
"and",
"render",
"view",
"using",
"the",
"data",
"universe",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/View.php#L464-L502 | train |
figdice/figdice | src/figdice/View.php | View.setCachePath | public function setCachePath($path, $templatesRoot = null) {
// Suppress the trailing slash
$this->cachePath = preg_replace('#/+$#', '', $path);
$this->templatesRoot = preg_replace('#/+$#', '', $templatesRoot);
} | php | public function setCachePath($path, $templatesRoot = null) {
// Suppress the trailing slash
$this->cachePath = preg_replace('#/+$#', '', $path);
$this->templatesRoot = preg_replace('#/+$#', '', $templatesRoot);
} | [
"public",
"function",
"setCachePath",
"(",
"$",
"path",
",",
"$",
"templatesRoot",
"=",
"null",
")",
"{",
"// Suppress the trailing slash",
"$",
"this",
"->",
"cachePath",
"=",
"preg_replace",
"(",
"'#/+$#'",
",",
"''",
",",
"$",
"path",
")",
";",
"$",
"th... | Specifies the folder in which the engine will be able to produce
temporary files, for JIT-compilation and caching purposes. The engine will
not attempt to use cache-based optimization features if you leave
this property blank.
@param string $path
@param string $templatesRoot | [
"Specifies",
"the",
"folder",
"in",
"which",
"the",
"engine",
"will",
"be",
"able",
"to",
"produce",
"temporary",
"files",
"for",
"JIT",
"-",
"compilation",
"and",
"caching",
"purposes",
".",
"The",
"engine",
"will",
"not",
"attempt",
"to",
"use",
"cache",
... | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/View.php#L513-L517 | train |
figdice/figdice | src/figdice/View.php | View.cdataHandler | private function cdataHandler($xmlParser, $cdata) {
//Last element in stack = parent element of the CDATA.
$currentElement = $this->stack[count($this->stack)-1];
$currentElement->appendCDataChild($cdata);
// hhvm invokes several cdata chunks if they contain \n
$this->previousCData .= $cdata;
} | php | private function cdataHandler($xmlParser, $cdata) {
//Last element in stack = parent element of the CDATA.
$currentElement = $this->stack[count($this->stack)-1];
$currentElement->appendCDataChild($cdata);
// hhvm invokes several cdata chunks if they contain \n
$this->previousCData .= $cdata;
} | [
"private",
"function",
"cdataHandler",
"(",
"$",
"xmlParser",
",",
"$",
"cdata",
")",
"{",
"//Last element in stack = parent element of the CDATA.",
"$",
"currentElement",
"=",
"$",
"this",
"->",
"stack",
"[",
"count",
"(",
"$",
"this",
"->",
"stack",
")",
"-",
... | XML parser handler for CDATA
@param resource $xmlParser
@param string $cdata | [
"XML",
"parser",
"handler",
"for",
"CDATA"
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/View.php#L724-L731 | train |
figdice/figdice | src/figdice/Feed.php | Feed.getParameter | public function getParameter($paramName) {
if(isset($this->params[$paramName])) {
return $this->params[$paramName];
}
return null;
} | php | public function getParameter($paramName) {
if(isset($this->params[$paramName])) {
return $this->params[$paramName];
}
return null;
} | [
"public",
"function",
"getParameter",
"(",
"$",
"paramName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"params",
"[",
"$",
"paramName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"params",
"[",
"$",
"paramName",
"]",
";",
"}",
"re... | Returns a Feed parameter, leaving it untyped.
Can be used to retrieve arrays, in particular.
@param string $paramName
@return mixed | [
"Returns",
"a",
"Feed",
"parameter",
"leaving",
"it",
"untyped",
".",
"Can",
"be",
"used",
"to",
"retrieve",
"arrays",
"in",
"particular",
"."
] | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/Feed.php#L81-L86 | train |
yuncms/yii2-payment | BaseGateway.php | BaseGateway.getState | protected function getState($key)
{
if (!Yii::$app->has('session')) {
return null;
}
/* @var \yii\web\Session $session */
$session = Yii::$app->get('session');
$key = $this->getStateKeyPrefix() . $key;
$value = $session->get($key);
return $value;
} | php | protected function getState($key)
{
if (!Yii::$app->has('session')) {
return null;
}
/* @var \yii\web\Session $session */
$session = Yii::$app->get('session');
$key = $this->getStateKeyPrefix() . $key;
$value = $session->get($key);
return $value;
} | [
"protected",
"function",
"getState",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"Yii",
"::",
"$",
"app",
"->",
"has",
"(",
"'session'",
")",
")",
"{",
"return",
"null",
";",
"}",
"/* @var \\yii\\web\\Session $session */",
"$",
"session",
"=",
"Yii",
"::"... | Returns persistent state value.
@param string $key state key.
@return mixed state value. | [
"Returns",
"persistent",
"state",
"value",
"."
] | 18af10263c29de2256d1586d58a642395969a5ca | https://github.com/yuncms/yii2-payment/blob/18af10263c29de2256d1586d58a642395969a5ca/BaseGateway.php#L289-L299 | train |
yuncms/yii2-payment | BaseGateway.php | BaseGateway.removeState | protected function removeState($key)
{
if (!Yii::$app->has('session')) {
return true;
}
/* @var \yii\web\Session $session */
$session = Yii::$app->get('session');
$key = $this->getStateKeyPrefix() . $key;
$session->remove($key);
return true;
} | php | protected function removeState($key)
{
if (!Yii::$app->has('session')) {
return true;
}
/* @var \yii\web\Session $session */
$session = Yii::$app->get('session');
$key = $this->getStateKeyPrefix() . $key;
$session->remove($key);
return true;
} | [
"protected",
"function",
"removeState",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"Yii",
"::",
"$",
"app",
"->",
"has",
"(",
"'session'",
")",
")",
"{",
"return",
"true",
";",
"}",
"/* @var \\yii\\web\\Session $session */",
"$",
"session",
"=",
"Yii",
"... | Removes persistent state value.
@param string $key state key.
@return boolean success. | [
"Removes",
"persistent",
"state",
"value",
"."
] | 18af10263c29de2256d1586d58a642395969a5ca | https://github.com/yuncms/yii2-payment/blob/18af10263c29de2256d1586d58a642395969a5ca/BaseGateway.php#L306-L316 | train |
btccom/cashaddress-php | src/CashAddress.php | CashAddress.pubKeyHashFromKey | public static function pubKeyHashFromKey($prefix, $publicKey)
{
$length = strlen($publicKey);
if ($length === 33) {
if ($publicKey[0] !== "\x02" && $publicKey[0] !== "\x03") {
throw new CashAddressException("Invalid public key");
}
} else if ($length === 65) {
if ($publicKey[0] !== "\x04") {
throw new CashAddressException("Invalid public key");
}
} else {
throw new CashAddressException("Invalid public key");
}
return self::pubKeyHash($prefix, hash('ripemd160', hash('sha256', $publicKey, true), true));
} | php | public static function pubKeyHashFromKey($prefix, $publicKey)
{
$length = strlen($publicKey);
if ($length === 33) {
if ($publicKey[0] !== "\x02" && $publicKey[0] !== "\x03") {
throw new CashAddressException("Invalid public key");
}
} else if ($length === 65) {
if ($publicKey[0] !== "\x04") {
throw new CashAddressException("Invalid public key");
}
} else {
throw new CashAddressException("Invalid public key");
}
return self::pubKeyHash($prefix, hash('ripemd160', hash('sha256', $publicKey, true), true));
} | [
"public",
"static",
"function",
"pubKeyHashFromKey",
"(",
"$",
"prefix",
",",
"$",
"publicKey",
")",
"{",
"$",
"length",
"=",
"strlen",
"(",
"$",
"publicKey",
")",
";",
"if",
"(",
"$",
"length",
"===",
"33",
")",
"{",
"if",
"(",
"$",
"publicKey",
"["... | This function does not validate public keys beyond their
size and prefix. It will hash the data and produce the address,
even if it's invalid. You MUST validate them elsewhere.
@param $prefix
@param $publicKey
@return string
@throws Base32Exception
@throws CashAddressException | [
"This",
"function",
"does",
"not",
"validate",
"public",
"keys",
"beyond",
"their",
"size",
"and",
"prefix",
".",
"It",
"will",
"hash",
"the",
"data",
"and",
"produce",
"the",
"address",
"even",
"if",
"it",
"s",
"invalid",
".",
"You",
"MUST",
"validate",
... | 6ce80a6ddb9cb5c55d3bf00794aa7d8bdbe76b04 | https://github.com/btccom/cashaddress-php/blob/6ce80a6ddb9cb5c55d3bf00794aa7d8bdbe76b04/src/CashAddress.php#L95-L111 | train |
PlasmaPHP/core | src/Utility.php | Utility.replaceParameters | static function replaceParameters(array $paramsInfo, array $params): array {
if(\count($params) !== \count($paramsInfo)) {
throw new \Plasma\Exception('Insufficient amount of parameters passed, expected '.\count($paramsInfo).', got '.\count($params));
}
$realParams = array();
$pos = (\array_key_exists(0, $params) ? 0 : 1);
foreach($paramsInfo as $param) {
$key = ($param[0] === ':' ? $param : ($pos++));
if(!\array_key_exists($key, $params)) {
throw new \Plasma\Exception('Missing parameter with key "'.$key.'"');
}
$realParams[] = $params[$key];
}
return $realParams;
} | php | static function replaceParameters(array $paramsInfo, array $params): array {
if(\count($params) !== \count($paramsInfo)) {
throw new \Plasma\Exception('Insufficient amount of parameters passed, expected '.\count($paramsInfo).', got '.\count($params));
}
$realParams = array();
$pos = (\array_key_exists(0, $params) ? 0 : 1);
foreach($paramsInfo as $param) {
$key = ($param[0] === ':' ? $param : ($pos++));
if(!\array_key_exists($key, $params)) {
throw new \Plasma\Exception('Missing parameter with key "'.$key.'"');
}
$realParams[] = $params[$key];
}
return $realParams;
} | [
"static",
"function",
"replaceParameters",
"(",
"array",
"$",
"paramsInfo",
",",
"array",
"$",
"params",
")",
":",
"array",
"{",
"if",
"(",
"\\",
"count",
"(",
"$",
"params",
")",
"!==",
"\\",
"count",
"(",
"$",
"paramsInfo",
")",
")",
"{",
"throw",
... | Replaces the user parameters keys with the correct parameters for the DBMS.
@param array $paramsInfo The parameters array from `parseParameters`.
@param array $params The parameters of the user.
@return array
@throws \Plasma\Exception | [
"Replaces",
"the",
"user",
"parameters",
"keys",
"with",
"the",
"correct",
"parameters",
"for",
"the",
"DBMS",
"."
] | ce9b1a206e3777f3cf884eec5eee686a073ddfb2 | https://github.com/PlasmaPHP/core/blob/ce9b1a206e3777f3cf884eec5eee686a073ddfb2/src/Utility.php#L48-L67 | train |
Arachne/EntityLoader | src/Application/EntityLoaderPresenterTrait.php | EntityLoaderPresenterTrait.storeRequest | public function storeRequest($request = null, $expiration = '+ 10 minutes'): string
{
// Both parameters are optional.
if ($request === null) {
$request = $this->getRequest();
} elseif (!$request instanceof Request) {
$expiration = $request;
$request = $this->getRequest();
}
assert($request instanceof Request);
$request = clone $request;
$this->unloader->filterOut($request);
$session = $this->getSession('Arachne.Application/requests');
do {
$key = Random::generate(5);
} while (isset($session[$key]));
$session[$key] = [$this->user !== null ? $this->user->getId() : null, $request];
$session->setExpiration($expiration, $key);
return $key;
} | php | public function storeRequest($request = null, $expiration = '+ 10 minutes'): string
{
// Both parameters are optional.
if ($request === null) {
$request = $this->getRequest();
} elseif (!$request instanceof Request) {
$expiration = $request;
$request = $this->getRequest();
}
assert($request instanceof Request);
$request = clone $request;
$this->unloader->filterOut($request);
$session = $this->getSession('Arachne.Application/requests');
do {
$key = Random::generate(5);
} while (isset($session[$key]));
$session[$key] = [$this->user !== null ? $this->user->getId() : null, $request];
$session->setExpiration($expiration, $key);
return $key;
} | [
"public",
"function",
"storeRequest",
"(",
"$",
"request",
"=",
"null",
",",
"$",
"expiration",
"=",
"'+ 10 minutes'",
")",
":",
"string",
"{",
"// Both parameters are optional.",
"if",
"(",
"$",
"request",
"===",
"null",
")",
"{",
"$",
"request",
"=",
"$",
... | Stores request to session.
@param mixed $request
@param mixed $expiration
@return string | [
"Stores",
"request",
"to",
"session",
"."
] | 1d577a5d6ce487150cde68ad01cf4db15f564dfc | https://github.com/Arachne/EntityLoader/blob/1d577a5d6ce487150cde68ad01cf4db15f564dfc/src/Application/EntityLoaderPresenterTrait.php#L48-L71 | train |
Arachne/EntityLoader | src/Application/EntityLoaderPresenterTrait.php | EntityLoaderPresenterTrait.restoreRequest | public function restoreRequest($key): void
{
$session = $this->getSession('Arachne.Application/requests');
if (!isset($session[$key]) || ($this->user !== null && $session[$key][0] !== null && $session[$key][0] !== $this->user->getId())) {
return;
}
$request = clone $session[$key][1];
unset($session[$key]);
try {
$this->loader->filterIn($request);
} catch (BadRequestException $e) {
return;
}
$request->setFlag(Request::RESTORED, true);
$parameters = $request->getParameters();
$parameters[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
$request->setParameters($parameters);
$this->sendResponse(new ForwardResponse($request));
} | php | public function restoreRequest($key): void
{
$session = $this->getSession('Arachne.Application/requests');
if (!isset($session[$key]) || ($this->user !== null && $session[$key][0] !== null && $session[$key][0] !== $this->user->getId())) {
return;
}
$request = clone $session[$key][1];
unset($session[$key]);
try {
$this->loader->filterIn($request);
} catch (BadRequestException $e) {
return;
}
$request->setFlag(Request::RESTORED, true);
$parameters = $request->getParameters();
$parameters[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
$request->setParameters($parameters);
$this->sendResponse(new ForwardResponse($request));
} | [
"public",
"function",
"restoreRequest",
"(",
"$",
"key",
")",
":",
"void",
"{",
"$",
"session",
"=",
"$",
"this",
"->",
"getSession",
"(",
"'Arachne.Application/requests'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"session",
"[",
"$",
"key",
"]",
"... | Restores request from session.
@param string $key | [
"Restores",
"request",
"from",
"session",
"."
] | 1d577a5d6ce487150cde68ad01cf4db15f564dfc | https://github.com/Arachne/EntityLoader/blob/1d577a5d6ce487150cde68ad01cf4db15f564dfc/src/Application/EntityLoaderPresenterTrait.php#L78-L97 | train |
thisdata/thisdata-php | src/Builder.php | Builder.build | public function build()
{
$client = $this->buildClient();
$requestHandler = $this->getRequestHandler();
// Pass through any configuration options set here which need to be made
// available elsewhere in the ThisData instance.
$configuration = [
self::CONF_EXPECT_JS_COOKIE => $this->expectJsCookie
];
return new ThisData($client, $requestHandler, $configuration);
} | php | public function build()
{
$client = $this->buildClient();
$requestHandler = $this->getRequestHandler();
// Pass through any configuration options set here which need to be made
// available elsewhere in the ThisData instance.
$configuration = [
self::CONF_EXPECT_JS_COOKIE => $this->expectJsCookie
];
return new ThisData($client, $requestHandler, $configuration);
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"client",
"=",
"$",
"this",
"->",
"buildClient",
"(",
")",
";",
"$",
"requestHandler",
"=",
"$",
"this",
"->",
"getRequestHandler",
"(",
")",
";",
"// Pass through any configuration options set here which need to ... | Create an instance of the ThisData API client abstraction after
configuration has been provided.
@return ThisData | [
"Create",
"an",
"instance",
"of",
"the",
"ThisData",
"API",
"client",
"abstraction",
"after",
"configuration",
"has",
"been",
"provided",
"."
] | 1b3144e6308d6a07a5d1d66b2a20df821edf6f99 | https://github.com/thisdata/thisdata-php/blob/1b3144e6308d6a07a5d1d66b2a20df821edf6f99/src/Builder.php#L205-L216 | train |
figdice/figdice | src/figdice/classes/Context.php | Context.translate | public function translate($key, $dictionaryName = null) {
//If a dictionary name is specified,
if(null !== $dictionaryName) {
// Use the nearest dictionary by this name,
// in current file upwards.
$dictionary = $this->getDictionary($dictionaryName);
if (null == $dictionary) {
throw new DictionaryNotFoundException($dictionaryName, $this->getFilename(), $this->tag->getLineNumber());
}
try {
return $dictionary->translate($key);
} catch (DictionaryEntryNotFoundException $ex) {
$ex->setDictionaryName($dictionaryName);
$ex->setTemplateFile($this->getFilename(), $this->tag->getLineNumber());
throw $ex;
}
}
//Walk the array of dictionaries, to try the lookup in all of them.
foreach($this->dictionaries[count($this->dictionaries) - 1] as $dictionary) {
try {
return $dictionary->translate($key);
} catch(DictionaryEntryNotFoundException $ex) {
// It is perfectly legitimate to not find a key in the first few registered dictionaries.
// But if in the end, we still didn't find a translation, it will be time to
// throw the exception.
}
}
throw new DictionaryEntryNotFoundException($key, $this->getFilename(), $this->tag->getLineNumber());
} | php | public function translate($key, $dictionaryName = null) {
//If a dictionary name is specified,
if(null !== $dictionaryName) {
// Use the nearest dictionary by this name,
// in current file upwards.
$dictionary = $this->getDictionary($dictionaryName);
if (null == $dictionary) {
throw new DictionaryNotFoundException($dictionaryName, $this->getFilename(), $this->tag->getLineNumber());
}
try {
return $dictionary->translate($key);
} catch (DictionaryEntryNotFoundException $ex) {
$ex->setDictionaryName($dictionaryName);
$ex->setTemplateFile($this->getFilename(), $this->tag->getLineNumber());
throw $ex;
}
}
//Walk the array of dictionaries, to try the lookup in all of them.
foreach($this->dictionaries[count($this->dictionaries) - 1] as $dictionary) {
try {
return $dictionary->translate($key);
} catch(DictionaryEntryNotFoundException $ex) {
// It is perfectly legitimate to not find a key in the first few registered dictionaries.
// But if in the end, we still didn't find a translation, it will be time to
// throw the exception.
}
}
throw new DictionaryEntryNotFoundException($key, $this->getFilename(), $this->tag->getLineNumber());
} | [
"public",
"function",
"translate",
"(",
"$",
"key",
",",
"$",
"dictionaryName",
"=",
"null",
")",
"{",
"//If a dictionary name is specified,",
"if",
"(",
"null",
"!==",
"$",
"dictionaryName",
")",
"{",
"// Use the nearest dictionary by this name,",
"// in current file u... | If a dictionary name is specified, performs the lookup only in this one.
If the dictionary name is not in the perimeter of the current file,
bubbles up the translation request if a parent file exists.
Finally throws DictionaryNotFoundException if the dictionary name is not
found anywhere in the hierarchy.
If the entry is not found in the current file's named dictionary,
throws DictionaryEntryNotFoundException.
If no dictionary name parameter is specified, performs the lookup in every dictionary attached
to the current FIG file, and only if not found in any, bubbles up the request.
@param $key
@param string $dictionaryName
@return string
@throws DictionaryEntryNotFoundException
@throws DictionaryNotFoundException | [
"If",
"a",
"dictionary",
"name",
"is",
"specified",
"performs",
"the",
"lookup",
"only",
"in",
"this",
"one",
".",
"If",
"the",
"dictionary",
"name",
"is",
"not",
"in",
"the",
"perimeter",
"of",
"the",
"current",
"file",
"bubbles",
"up",
"the",
"translatio... | 896bbe3aec365c416e368dcc6b888a6cf1832afc | https://github.com/figdice/figdice/blob/896bbe3aec365c416e368dcc6b888a6cf1832afc/src/figdice/classes/Context.php#L226-L256 | train |
eidsonator/SemanticReportsBundle | lib/PhpReports/PhpReports.php | PhpReports.getMailTransport | protected static function getMailTransport() {
if(!isset(PhpReports::$config['mail_settings'])) PhpReports::$config['mail_settings'] = array();
if(!isset(PhpReports::$config['mail_settings']['method'])) PhpReports::$config['mail_settings']['method'] = 'mail';
switch(PhpReports::$config['mail_settings']['method']) {
case 'mail':
return Swift_MailTransport::newInstance();
case 'sendmail':
return Swift_MailTransport::newInstance(
isset(PhpReports::$config['mail_settings']['command'])? PhpReports::$config['mail_settings']['command'] : '/usr/sbin/sendmail -bs'
);
case 'smtp':
if(!isset(PhpReports::$config['mail_settings']['server'])) throw new Exception("SMTP server must be configured");
$transport = Swift_SmtpTransport::newInstance(
PhpReports::$config['mail_settings']['server'],
isset(PhpReports::$config['mail_settings']['port'])? PhpReports::$config['mail_settings']['port'] : 25
);
//if username/password
if(isset(PhpReports::$config['mail_settings']['username'])) {
$transport->setUsername(PhpReports::$config['mail_settings']['username']);
$transport->setPassword(PhpReports::$config['mail_settings']['password']);
}
//if using encryption
if(isset(PhpReports::$config['mail_settings']['encryption'])) {
$transport->setEncryption(PhpReports::$config['mail_settings']['encryption']);
}
return $transport;
default:
throw new Exception("Mail method must be either 'mail', 'sendmail', or 'smtp'");
}
} | php | protected static function getMailTransport() {
if(!isset(PhpReports::$config['mail_settings'])) PhpReports::$config['mail_settings'] = array();
if(!isset(PhpReports::$config['mail_settings']['method'])) PhpReports::$config['mail_settings']['method'] = 'mail';
switch(PhpReports::$config['mail_settings']['method']) {
case 'mail':
return Swift_MailTransport::newInstance();
case 'sendmail':
return Swift_MailTransport::newInstance(
isset(PhpReports::$config['mail_settings']['command'])? PhpReports::$config['mail_settings']['command'] : '/usr/sbin/sendmail -bs'
);
case 'smtp':
if(!isset(PhpReports::$config['mail_settings']['server'])) throw new Exception("SMTP server must be configured");
$transport = Swift_SmtpTransport::newInstance(
PhpReports::$config['mail_settings']['server'],
isset(PhpReports::$config['mail_settings']['port'])? PhpReports::$config['mail_settings']['port'] : 25
);
//if username/password
if(isset(PhpReports::$config['mail_settings']['username'])) {
$transport->setUsername(PhpReports::$config['mail_settings']['username']);
$transport->setPassword(PhpReports::$config['mail_settings']['password']);
}
//if using encryption
if(isset(PhpReports::$config['mail_settings']['encryption'])) {
$transport->setEncryption(PhpReports::$config['mail_settings']['encryption']);
}
return $transport;
default:
throw new Exception("Mail method must be either 'mail', 'sendmail', or 'smtp'");
}
} | [
"protected",
"static",
"function",
"getMailTransport",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"PhpReports",
"::",
"$",
"config",
"[",
"'mail_settings'",
"]",
")",
")",
"PhpReports",
"::",
"$",
"config",
"[",
"'mail_settings'",
"]",
"=",
"array",
"(",... | Determines the email transport to use based on the configuration settings | [
"Determines",
"the",
"email",
"transport",
"to",
"use",
"based",
"on",
"the",
"configuration",
"settings"
] | 11c82be87551eae232280a74b2de7e3255666f85 | https://github.com/eidsonator/SemanticReportsBundle/blob/11c82be87551eae232280a74b2de7e3255666f85/lib/PhpReports/PhpReports.php#L521-L554 | train |
thisdata/thisdata-php | src/Endpoint/AbstractEndpoint.php | AbstractEndpoint.findValue | protected function findValue($key, $pool, $default = null)
{
if (is_null($pool)) {
return $default;
} else {
return array_key_exists($key, $pool) ? $pool[$key] : $default;
}
} | php | protected function findValue($key, $pool, $default = null)
{
if (is_null($pool)) {
return $default;
} else {
return array_key_exists($key, $pool) ? $pool[$key] : $default;
}
} | [
"protected",
"function",
"findValue",
"(",
"$",
"key",
",",
"$",
"pool",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"pool",
")",
")",
"{",
"return",
"$",
"default",
";",
"}",
"else",
"{",
"return",
"array_key_exists",... | Utility method to retrieve a value from an array, or a default if not found.
@param string $key
@param array $pool
@param mixed|null $default
@return mixed|null | [
"Utility",
"method",
"to",
"retrieve",
"a",
"value",
"from",
"an",
"array",
"or",
"a",
"default",
"if",
"not",
"found",
"."
] | 1b3144e6308d6a07a5d1d66b2a20df821edf6f99 | https://github.com/thisdata/thisdata-php/blob/1b3144e6308d6a07a5d1d66b2a20df821edf6f99/src/Endpoint/AbstractEndpoint.php#L95-L102 | train |
thisdata/thisdata-php | src/Endpoint/AbstractEndpoint.php | AbstractEndpoint.synchronousExecute | protected function synchronousExecute($method, $verb, array $data = [])
{
$request = new Request($method, $verb, [], $this->serialize($data));
$response = $this->client->send($request);
return $response;
} | php | protected function synchronousExecute($method, $verb, array $data = [])
{
$request = new Request($method, $verb, [], $this->serialize($data));
$response = $this->client->send($request);
return $response;
} | [
"protected",
"function",
"synchronousExecute",
"(",
"$",
"method",
",",
"$",
"verb",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"request",
"=",
"new",
"Request",
"(",
"$",
"method",
",",
"$",
"verb",
",",
"[",
"]",
",",
"$",
"this",
... | Returns the response for a synchronous request
@param string $method HTTP method to use for the request
@param string $verb ThisData verb to be used on this endpoint
@param array $data Request body data containing event metadata | [
"Returns",
"the",
"response",
"for",
"a",
"synchronous",
"request"
] | 1b3144e6308d6a07a5d1d66b2a20df821edf6f99 | https://github.com/thisdata/thisdata-php/blob/1b3144e6308d6a07a5d1d66b2a20df821edf6f99/src/Endpoint/AbstractEndpoint.php#L132-L138 | train |
ynloultratech/graphql-bundle | src/Util/TypeUtil.php | TypeUtil.resolveObjectType | public static function resolveObjectType(Endpoint $endpoint, $object): ?string
{
if ($object instanceof PolymorphicObjectInterface && $object->getConcreteType()) {
return $object->getConcreteType();
}
$class = DoctrineClassUtils::getClass($object);
if (!$endpoint->hasTypeForClass($class)) {
return null;
}
$types = $endpoint->getTypesForClass($class);
//if only one type for given object class return the type
if (count($types) === 1) {
return $types[0];
}
//in case of multiple types using polymorphic definitions
foreach ($types as $type) {
$definition = $endpoint->getType($type);
if ($definition instanceof PolymorphicDefinitionInterface) {
return self::resolveConcreteType($endpoint, $definition, $object);
}
}
//as fallback use the first type in the list
return $types[0];
} | php | public static function resolveObjectType(Endpoint $endpoint, $object): ?string
{
if ($object instanceof PolymorphicObjectInterface && $object->getConcreteType()) {
return $object->getConcreteType();
}
$class = DoctrineClassUtils::getClass($object);
if (!$endpoint->hasTypeForClass($class)) {
return null;
}
$types = $endpoint->getTypesForClass($class);
//if only one type for given object class return the type
if (count($types) === 1) {
return $types[0];
}
//in case of multiple types using polymorphic definitions
foreach ($types as $type) {
$definition = $endpoint->getType($type);
if ($definition instanceof PolymorphicDefinitionInterface) {
return self::resolveConcreteType($endpoint, $definition, $object);
}
}
//as fallback use the first type in the list
return $types[0];
} | [
"public",
"static",
"function",
"resolveObjectType",
"(",
"Endpoint",
"$",
"endpoint",
",",
"$",
"object",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"object",
"instanceof",
"PolymorphicObjectInterface",
"&&",
"$",
"object",
"->",
"getConcreteType",
"(",
")... | Resolve the object type for given object instance
@param Endpoint $endpoint
@param mixed $object
@return null|string | [
"Resolve",
"the",
"object",
"type",
"for",
"given",
"object",
"instance"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Util/TypeUtil.php#L36-L64 | train |
ynloultratech/graphql-bundle | src/Util/TypeUtil.php | TypeUtil.resolveConcreteType | public static function resolveConcreteType(Endpoint $endpoint, PolymorphicDefinitionInterface $definition, $object)
{
//if discriminator map is set is used to get the value type
if ($map = $definition->getDiscriminatorMap()) {
//get concrete type based on property
if ($definition->getDiscriminatorProperty()) {
$property = $definition->getDiscriminatorProperty();
$accessor = new PropertyAccessor();
$propValue = $accessor->getValue($object, $property);
$resolvedType = $map[$propValue] ?? null;
}
//get concrete type based on class
if (!$resolvedType) {
$class = DoctrineClassUtils::getClass($object);
$resolvedType = $map[$class] ?? null;
}
}
//final solution in case of not mapping is guess type based on class
if (!$resolvedType && $definition instanceof InterfaceDefinition) {
foreach ($definition->getImplementors() as $implementor) {
$implementorDef = $endpoint->getType($implementor);
if ($implementorDef instanceof ClassAwareDefinitionInterface
&& $implementorDef->getClass() === DoctrineClassUtils::getClass($object)) {
$resolvedType = $implementorDef->getName();
}
}
}
if ($endpoint->hasType($resolvedType)) {
$resolvedTypeDefinition = $endpoint->getType($resolvedType);
if ($resolvedTypeDefinition instanceof PolymorphicDefinitionInterface) {
$resolvedType = self::resolveConcreteType($endpoint, $resolvedTypeDefinition, $object);
}
}
return $resolvedType;
} | php | public static function resolveConcreteType(Endpoint $endpoint, PolymorphicDefinitionInterface $definition, $object)
{
//if discriminator map is set is used to get the value type
if ($map = $definition->getDiscriminatorMap()) {
//get concrete type based on property
if ($definition->getDiscriminatorProperty()) {
$property = $definition->getDiscriminatorProperty();
$accessor = new PropertyAccessor();
$propValue = $accessor->getValue($object, $property);
$resolvedType = $map[$propValue] ?? null;
}
//get concrete type based on class
if (!$resolvedType) {
$class = DoctrineClassUtils::getClass($object);
$resolvedType = $map[$class] ?? null;
}
}
//final solution in case of not mapping is guess type based on class
if (!$resolvedType && $definition instanceof InterfaceDefinition) {
foreach ($definition->getImplementors() as $implementor) {
$implementorDef = $endpoint->getType($implementor);
if ($implementorDef instanceof ClassAwareDefinitionInterface
&& $implementorDef->getClass() === DoctrineClassUtils::getClass($object)) {
$resolvedType = $implementorDef->getName();
}
}
}
if ($endpoint->hasType($resolvedType)) {
$resolvedTypeDefinition = $endpoint->getType($resolvedType);
if ($resolvedTypeDefinition instanceof PolymorphicDefinitionInterface) {
$resolvedType = self::resolveConcreteType($endpoint, $resolvedTypeDefinition, $object);
}
}
return $resolvedType;
} | [
"public",
"static",
"function",
"resolveConcreteType",
"(",
"Endpoint",
"$",
"endpoint",
",",
"PolymorphicDefinitionInterface",
"$",
"definition",
",",
"$",
"object",
")",
"{",
"//if discriminator map is set is used to get the value type",
"if",
"(",
"$",
"map",
"=",
"$... | Resolve the object type for given object instance when object use polymorphic definitions
@param Endpoint $endpoint
@param PolymorphicDefinitionInterface $definition
@param mixed $object
@return null|string | [
"Resolve",
"the",
"object",
"type",
"for",
"given",
"object",
"instance",
"when",
"object",
"use",
"polymorphic",
"definitions"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Util/TypeUtil.php#L75-L113 | train |
orchestral/control | src/Processor/Theme.php | Theme.showByType | public function showByType(Selector $listener, string $type)
{
if (! in_array($type, $this->type)) {
return $listener->themeFailedVerification();
}
$current = $this->memory->get("site.theme.{$type}");
$themes = $this->getAvailableTheme($type);
return $listener->showThemeSelection(compact('current', 'themes', 'type'));
} | php | public function showByType(Selector $listener, string $type)
{
if (! in_array($type, $this->type)) {
return $listener->themeFailedVerification();
}
$current = $this->memory->get("site.theme.{$type}");
$themes = $this->getAvailableTheme($type);
return $listener->showThemeSelection(compact('current', 'themes', 'type'));
} | [
"public",
"function",
"showByType",
"(",
"Selector",
"$",
"listener",
",",
"string",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"type",
",",
"$",
"this",
"->",
"type",
")",
")",
"{",
"return",
"$",
"listener",
"->",
"themeFailedVerifi... | List available theme.
@param \Orchestra\Contracts\Theme\Listener\Selector $listener
@param string $type
@return mixed | [
"List",
"available",
"theme",
"."
] | 7c23db19373adbb0fe44491af12f370ba6547d2a | https://github.com/orchestral/control/blob/7c23db19373adbb0fe44491af12f370ba6547d2a/src/Processor/Theme.php#L37-L47 | train |
orchestral/control | src/Processor/Theme.php | Theme.activate | public function activate(Selector $listener, string $type, string $id)
{
$theme = $this->getAvailableTheme($type)->get($id);
if (! in_array($type, $this->type) || is_null($theme)) {
return $listener->themeFailedVerification();
}
$this->memory->put("site.theme.{$type}", $id);
return $listener->themeHasActivated($type, $id);
} | php | public function activate(Selector $listener, string $type, string $id)
{
$theme = $this->getAvailableTheme($type)->get($id);
if (! in_array($type, $this->type) || is_null($theme)) {
return $listener->themeFailedVerification();
}
$this->memory->put("site.theme.{$type}", $id);
return $listener->themeHasActivated($type, $id);
} | [
"public",
"function",
"activate",
"(",
"Selector",
"$",
"listener",
",",
"string",
"$",
"type",
",",
"string",
"$",
"id",
")",
"{",
"$",
"theme",
"=",
"$",
"this",
"->",
"getAvailableTheme",
"(",
"$",
"type",
")",
"->",
"get",
"(",
"$",
"id",
")",
... | Activate a theme.
@param \Orchestra\Contracts\Theme\Listener\Selector $listener
@param string $type
@param string $id
@return mixed | [
"Activate",
"a",
"theme",
"."
] | 7c23db19373adbb0fe44491af12f370ba6547d2a | https://github.com/orchestral/control/blob/7c23db19373adbb0fe44491af12f370ba6547d2a/src/Processor/Theme.php#L58-L69 | train |
orchestral/control | src/Processor/Theme.php | Theme.getAvailableTheme | protected function getAvailableTheme(string $type): Collection
{
$themes = $this->foundation->make('orchestra.theme.finder')->detect();
return $themes->filter(function ($manifest) use ($type) {
if (! empty($manifest->type) && ! in_array($type, $manifest->type)) {
return null;
}
return $manifest;
});
} | php | protected function getAvailableTheme(string $type): Collection
{
$themes = $this->foundation->make('orchestra.theme.finder')->detect();
return $themes->filter(function ($manifest) use ($type) {
if (! empty($manifest->type) && ! in_array($type, $manifest->type)) {
return null;
}
return $manifest;
});
} | [
"protected",
"function",
"getAvailableTheme",
"(",
"string",
"$",
"type",
")",
":",
"Collection",
"{",
"$",
"themes",
"=",
"$",
"this",
"->",
"foundation",
"->",
"make",
"(",
"'orchestra.theme.finder'",
")",
"->",
"detect",
"(",
")",
";",
"return",
"$",
"t... | Get all available theme.
@param string $type
@return \Illuminate\Support\Collection | [
"Get",
"all",
"available",
"theme",
"."
] | 7c23db19373adbb0fe44491af12f370ba6547d2a | https://github.com/orchestral/control/blob/7c23db19373adbb0fe44491af12f370ba6547d2a/src/Processor/Theme.php#L78-L89 | train |
raymondjavaxx/jsonbuilder | libraries/jsonbuilder/JSONBuilder.php | JSONBuilder.object | public static function object(\Closure $callback) {
$obj = new Object;
$callback->__invoke($obj);
return json_encode($obj);
} | php | public static function object(\Closure $callback) {
$obj = new Object;
$callback->__invoke($obj);
return json_encode($obj);
} | [
"public",
"static",
"function",
"object",
"(",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"obj",
"=",
"new",
"Object",
";",
"$",
"callback",
"->",
"__invoke",
"(",
"$",
"obj",
")",
";",
"return",
"json_encode",
"(",
"$",
"obj",
")",
";",
"}"
] | Builds a JSON object by invoking a callback function.
echo JSONBuilder::object(function($json) {
$json->hello = "world!";
});
// {"hello":"world!"}
@param \Closure $callback
@return string | [
"Builds",
"a",
"JSON",
"object",
"by",
"invoking",
"a",
"callback",
"function",
"."
] | 7d274782dfed58a9385725667a83c69346f727c5 | https://github.com/raymondjavaxx/jsonbuilder/blob/7d274782dfed58a9385725667a83c69346f727c5/libraries/jsonbuilder/JSONBuilder.php#L34-L38 | train |
ynloultratech/graphql-bundle | src/Query/Node/AllNodesWithPagination.php | AllNodesWithPagination.applyFilters | protected function applyFilters(QueryBuilder $qb, array $filters)
{
$definition = $this->objectDefinition;
foreach ($filters as $field => $value) {
if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
continue;
}
$entityField = sprintf('%s.%s', $this->queryAlias, $prop);
switch (gettype($value)) {
case 'string':
$qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
break;
case 'integer':
case 'double':
$qb->andWhere($qb->expr()->eq($entityField, $value));
break;
case 'boolean':
$qb->andWhere($qb->expr()->eq($entityField, (int) $value));
break;
case 'array':
if (empty($value)) {
$qb->andWhere($qb->expr()->isNull($entityField));
} else {
$qb->andWhere($qb->expr()->in($entityField, $value));
}
break;
case 'NULL':
$qb->andWhere($qb->expr()->isNull($entityField));
break;
}
}
} | php | protected function applyFilters(QueryBuilder $qb, array $filters)
{
$definition = $this->objectDefinition;
foreach ($filters as $field => $value) {
if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
continue;
}
$entityField = sprintf('%s.%s', $this->queryAlias, $prop);
switch (gettype($value)) {
case 'string':
$qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
break;
case 'integer':
case 'double':
$qb->andWhere($qb->expr()->eq($entityField, $value));
break;
case 'boolean':
$qb->andWhere($qb->expr()->eq($entityField, (int) $value));
break;
case 'array':
if (empty($value)) {
$qb->andWhere($qb->expr()->isNull($entityField));
} else {
$qb->andWhere($qb->expr()->in($entityField, $value));
}
break;
case 'NULL':
$qb->andWhere($qb->expr()->isNull($entityField));
break;
}
}
} | [
"protected",
"function",
"applyFilters",
"(",
"QueryBuilder",
"$",
"qb",
",",
"array",
"$",
"filters",
")",
"{",
"$",
"definition",
"=",
"$",
"this",
"->",
"objectDefinition",
";",
"foreach",
"(",
"$",
"filters",
"as",
"$",
"field",
"=>",
"$",
"value",
"... | Apply advanced filters
@deprecated since v1.1, `applyWhere` should be used instead | [
"Apply",
"advanced",
"filters"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Query/Node/AllNodesWithPagination.php#L128-L161 | train |
MetaModels/attribute_alias | src/Attribute/Alias.php | Alias.isMetaField | protected function isMetaField($strField)
{
$strField = \trim($strField);
if (\in_array($strField, $this->getMetaModelsSystemColumns())) {
return true;
}
return false;
} | php | protected function isMetaField($strField)
{
$strField = \trim($strField);
if (\in_array($strField, $this->getMetaModelsSystemColumns())) {
return true;
}
return false;
} | [
"protected",
"function",
"isMetaField",
"(",
"$",
"strField",
")",
"{",
"$",
"strField",
"=",
"\\",
"trim",
"(",
"$",
"strField",
")",
";",
"if",
"(",
"\\",
"in_array",
"(",
"$",
"strField",
",",
"$",
"this",
"->",
"getMetaModelsSystemColumns",
"(",
")",... | Check if we have a meta field from metamodels.
@param string $strField The selected value.
@return boolean True => Yes we have | False => nope. | [
"Check",
"if",
"we",
"have",
"a",
"meta",
"field",
"from",
"metamodels",
"."
] | 710dd8356ccec4e37de49988f1191c34aad21631 | https://github.com/MetaModels/attribute_alias/blob/710dd8356ccec4e37de49988f1191c34aad21631/src/Attribute/Alias.php#L169-L178 | train |
TypiCMS/Settings | src/Http/Controllers/AdminController.php | AdminController.save | public function save(Request $request, FileUploader $fileUploader)
{
$data = $request->except('_token');
if ($request->hasFile('image')) {
$file = $fileUploader->handle($request->file('image'), 'settings');
$this->deleteImage();
$data['image'] = $file['filename'];
}
foreach ($data as $group_name => $array) {
if (!is_array($array)) {
$array = [$group_name => $array];
$group_name = 'config';
}
foreach ($array as $key_name => $value) {
$model = Setting::firstOrCreate(['key_name' => $key_name, 'group_name' => $group_name]);
$model->value = $value;
$model->save();
$this->repository->forgetCache();
}
}
return redirect()->route('admin::index-settings');
} | php | public function save(Request $request, FileUploader $fileUploader)
{
$data = $request->except('_token');
if ($request->hasFile('image')) {
$file = $fileUploader->handle($request->file('image'), 'settings');
$this->deleteImage();
$data['image'] = $file['filename'];
}
foreach ($data as $group_name => $array) {
if (!is_array($array)) {
$array = [$group_name => $array];
$group_name = 'config';
}
foreach ($array as $key_name => $value) {
$model = Setting::firstOrCreate(['key_name' => $key_name, 'group_name' => $group_name]);
$model->value = $value;
$model->save();
$this->repository->forgetCache();
}
}
return redirect()->route('admin::index-settings');
} | [
"public",
"function",
"save",
"(",
"Request",
"$",
"request",
",",
"FileUploader",
"$",
"fileUploader",
")",
"{",
"$",
"data",
"=",
"$",
"request",
"->",
"except",
"(",
"'_token'",
")",
";",
"if",
"(",
"$",
"request",
"->",
"hasFile",
"(",
"'image'",
"... | Save settings.
@return \Illuminate\Http\RedirectResponse | [
"Save",
"settings",
"."
] | 106e8509df8281ca3f1bddc14812bae6610dac40 | https://github.com/TypiCMS/Settings/blob/106e8509df8281ca3f1bddc14812bae6610dac40/src/Http/Controllers/AdminController.php#L40-L64 | train |
TypiCMS/Settings | src/Http/Controllers/AdminController.php | AdminController.deleteImage | public function deleteImage()
{
if ($filename = Setting::where('key_name', 'image')->value('value')) {
try {
Croppa::delete('storage/settings/'.$filename);
} catch (Exception $e) {
Log::info($e->getMessage());
}
}
Setting::where('key_name', 'image')->delete();
$this->repository->forgetCache();
} | php | public function deleteImage()
{
if ($filename = Setting::where('key_name', 'image')->value('value')) {
try {
Croppa::delete('storage/settings/'.$filename);
} catch (Exception $e) {
Log::info($e->getMessage());
}
}
Setting::where('key_name', 'image')->delete();
$this->repository->forgetCache();
} | [
"public",
"function",
"deleteImage",
"(",
")",
"{",
"if",
"(",
"$",
"filename",
"=",
"Setting",
"::",
"where",
"(",
"'key_name'",
",",
"'image'",
")",
"->",
"value",
"(",
"'value'",
")",
")",
"{",
"try",
"{",
"Croppa",
"::",
"delete",
"(",
"'storage/se... | Delete image.
@return null | [
"Delete",
"image",
"."
] | 106e8509df8281ca3f1bddc14812bae6610dac40 | https://github.com/TypiCMS/Settings/blob/106e8509df8281ca3f1bddc14812bae6610dac40/src/Http/Controllers/AdminController.php#L71-L82 | train |
joomla-framework/console | src/Command/ListCommand.php | ListCommand.doExecute | protected function doExecute(InputInterface $input, OutputInterface $output): int
{
$descriptor = new DescriptorHelper;
$this->getHelperSet()->set($descriptor);
$descriptor->describe(
$output,
$this->getApplication(),
[
'namespace' => $input->getArgument('namespace'),
]
);
return 0;
} | php | protected function doExecute(InputInterface $input, OutputInterface $output): int
{
$descriptor = new DescriptorHelper;
$this->getHelperSet()->set($descriptor);
$descriptor->describe(
$output,
$this->getApplication(),
[
'namespace' => $input->getArgument('namespace'),
]
);
return 0;
} | [
"protected",
"function",
"doExecute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"int",
"{",
"$",
"descriptor",
"=",
"new",
"DescriptorHelper",
";",
"$",
"this",
"->",
"getHelperSet",
"(",
")",
"->",
"set",
"(",
"... | Internal function to execute the command.
@param InputInterface $input The input to inject into the command.
@param OutputInterface $output The output to inject into the command.
@return integer The command exit code
@since __DEPLOY_VERSION__ | [
"Internal",
"function",
"to",
"execute",
"the",
"command",
"."
] | b8ab98ec0fab96002b22399dea8c2ff206a87380 | https://github.com/joomla-framework/console/blob/b8ab98ec0fab96002b22399dea8c2ff206a87380/src/Command/ListCommand.php#L60-L75 | train |
spiral/vault | source/Vault/Models/Item.php | Item.isVisible | public function isVisible(): bool
{
if (!empty($this->item['permission'])) {
return $this->vault->getGuard()->allows($this->item['permission']);
}
//Remove :action
$target = current(explode(':', $this->getTarget()));
return $this->vault->getGuard()->allows(
"{$this->vault->getConfig()->guardNamespace()}.{$target}"
);
} | php | public function isVisible(): bool
{
if (!empty($this->item['permission'])) {
return $this->vault->getGuard()->allows($this->item['permission']);
}
//Remove :action
$target = current(explode(':', $this->getTarget()));
return $this->vault->getGuard()->allows(
"{$this->vault->getConfig()->guardNamespace()}.{$target}"
);
} | [
"public",
"function",
"isVisible",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"item",
"[",
"'permission'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"vault",
"->",
"getGuard",
"(",
")",
"->",
"allows",
"(",
... | Check if item is visible.
@return bool | [
"Check",
"if",
"item",
"is",
"visible",
"."
] | fb64c1bcaa3aa4e926ff94902bf08e059ad849bf | https://github.com/spiral/vault/blob/fb64c1bcaa3aa4e926ff94902bf08e059ad849bf/source/Vault/Models/Item.php#L80-L92 | train |
PlasmaPHP/core | src/Transaction.php | Transaction.runQuery | function runQuery(\Plasma\QueryBuilderInterface $query): \React\Promise\PromiseInterface {
if($this->driver === null) {
throw new \Plasma\TransactionException('Transaction has been committed or rolled back');
}
return $this->driver->runQuery($this->client, $query);
} | php | function runQuery(\Plasma\QueryBuilderInterface $query): \React\Promise\PromiseInterface {
if($this->driver === null) {
throw new \Plasma\TransactionException('Transaction has been committed or rolled back');
}
return $this->driver->runQuery($this->client, $query);
} | [
"function",
"runQuery",
"(",
"\\",
"Plasma",
"\\",
"QueryBuilderInterface",
"$",
"query",
")",
":",
"\\",
"React",
"\\",
"Promise",
"\\",
"PromiseInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"driver",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"Pla... | Runs the given querybuilder on the underlying driver instance.
The driver CAN throw an exception if the given querybuilder is not supported.
An example would be a SQL querybuilder and a Cassandra driver.
@param \Plasma\QueryBuilderInterface $query
@return \React\Promise\PromiseInterface
@throws \Plasma\Exception | [
"Runs",
"the",
"given",
"querybuilder",
"on",
"the",
"underlying",
"driver",
"instance",
".",
"The",
"driver",
"CAN",
"throw",
"an",
"exception",
"if",
"the",
"given",
"querybuilder",
"is",
"not",
"supported",
".",
"An",
"example",
"would",
"be",
"a",
"SQL",... | ce9b1a206e3777f3cf884eec5eee686a073ddfb2 | https://github.com/PlasmaPHP/core/blob/ce9b1a206e3777f3cf884eec5eee686a073ddfb2/src/Transaction.php#L160-L166 | train |
PlasmaPHP/core | src/Transaction.php | Transaction.commit | function commit(): \React\Promise\PromiseInterface {
return $this->query('COMMIT')->then(function () {
$this->driver->endTransaction();
$this->client->checkinConnection($this->driver);
$this->driver = null;
});
} | php | function commit(): \React\Promise\PromiseInterface {
return $this->query('COMMIT')->then(function () {
$this->driver->endTransaction();
$this->client->checkinConnection($this->driver);
$this->driver = null;
});
} | [
"function",
"commit",
"(",
")",
":",
"\\",
"React",
"\\",
"Promise",
"\\",
"PromiseInterface",
"{",
"return",
"$",
"this",
"->",
"query",
"(",
"'COMMIT'",
")",
"->",
"then",
"(",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"driver",
"->",
"endTransac... | Commits the changes.
@return \React\Promise\PromiseInterface
@throws \Plasma\TransactionException Thrown if the transaction has been committed or rolled back. | [
"Commits",
"the",
"changes",
"."
] | ce9b1a206e3777f3cf884eec5eee686a073ddfb2 | https://github.com/PlasmaPHP/core/blob/ce9b1a206e3777f3cf884eec5eee686a073ddfb2/src/Transaction.php#L173-L179 | train |
PlasmaPHP/core | src/Transaction.php | Transaction.createSavepoint | function createSavepoint(string $identifier): \React\Promise\PromiseInterface {
return $this->query('SAVEPOINT '.$this->quote($identifier));
} | php | function createSavepoint(string $identifier): \React\Promise\PromiseInterface {
return $this->query('SAVEPOINT '.$this->quote($identifier));
} | [
"function",
"createSavepoint",
"(",
"string",
"$",
"identifier",
")",
":",
"\\",
"React",
"\\",
"Promise",
"\\",
"PromiseInterface",
"{",
"return",
"$",
"this",
"->",
"query",
"(",
"'SAVEPOINT '",
".",
"$",
"this",
"->",
"quote",
"(",
"$",
"identifier",
")... | Creates a savepoint with the given identifier.
@param string $identifier
@return \React\Promise\PromiseInterface
@throws \Plasma\TransactionException Thrown if the transaction has been committed or rolled back. | [
"Creates",
"a",
"savepoint",
"with",
"the",
"given",
"identifier",
"."
] | ce9b1a206e3777f3cf884eec5eee686a073ddfb2 | https://github.com/PlasmaPHP/core/blob/ce9b1a206e3777f3cf884eec5eee686a073ddfb2/src/Transaction.php#L200-L202 | train |
joomla-framework/console | src/Event/ApplicationErrorEvent.php | ApplicationErrorEvent.getExitCode | public function getExitCode(): int
{
return $this->exitCode ?: (\is_int($this->error->getCode()) && $this->error->getCode() !== 0 ? $this->error->getCode() : 1);
} | php | public function getExitCode(): int
{
return $this->exitCode ?: (\is_int($this->error->getCode()) && $this->error->getCode() !== 0 ? $this->error->getCode() : 1);
} | [
"public",
"function",
"getExitCode",
"(",
")",
":",
"int",
"{",
"return",
"$",
"this",
"->",
"exitCode",
"?",
":",
"(",
"\\",
"is_int",
"(",
"$",
"this",
"->",
"error",
"->",
"getCode",
"(",
")",
")",
"&&",
"$",
"this",
"->",
"error",
"->",
"getCod... | Gets the exit code.
@return integer
@since __DEPLOY_VERSION__ | [
"Gets",
"the",
"exit",
"code",
"."
] | b8ab98ec0fab96002b22399dea8c2ff206a87380 | https://github.com/joomla-framework/console/blob/b8ab98ec0fab96002b22399dea8c2ff206a87380/src/Event/ApplicationErrorEvent.php#L73-L76 | train |
ynloultratech/graphql-bundle | src/Behat/Context/DatabaseContext.php | DatabaseContext.shouldExistInTableARecordMatching | public function shouldExistInTableARecordMatching($table, YamlStringNode $criteria)
{
$count = $this->countRecordsInTableMatching($table, $criteria->toArray());
Assert::assertEquals(1, $count, sprintf('Does not exist any record in the database "%s" matching given conditions', $table));
} | php | public function shouldExistInTableARecordMatching($table, YamlStringNode $criteria)
{
$count = $this->countRecordsInTableMatching($table, $criteria->toArray());
Assert::assertEquals(1, $count, sprintf('Does not exist any record in the database "%s" matching given conditions', $table));
} | [
"public",
"function",
"shouldExistInTableARecordMatching",
"(",
"$",
"table",
",",
"YamlStringNode",
"$",
"criteria",
")",
"{",
"$",
"count",
"=",
"$",
"this",
"->",
"countRecordsInTableMatching",
"(",
"$",
"table",
",",
"$",
"criteria",
"->",
"toArray",
"(",
... | Use a YAML syntax to create a criteria to match a record in given table
Example: Then should exist in table "post" a record matching:
"""
title: "Welcome"
body: "Welcome to web page"
"""
Expression syntax is allowed
Example: Then should exist in table "post" a record matching:
"""
title: "{variables.input.title}"
body: "{variables.input.body}"
"""
@Given /^should exist in table "([^"]*)" a record matching:$/ | [
"Use",
"a",
"YAML",
"syntax",
"to",
"create",
"a",
"criteria",
"to",
"match",
"a",
"record",
"in",
"given",
"table"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Behat/Context/DatabaseContext.php#L47-L51 | train |
ynloultratech/graphql-bundle | src/Behat/Context/DatabaseContext.php | DatabaseContext.shouldExistInTableRecordsMatching | public function shouldExistInTableRecordsMatching($table, YamlStringNode $criteria)
{
foreach ($criteria->toArray() as $row) {
$count = $this->countRecordsInTableMatching($table, $row);
Assert::assertEquals(1, $count, sprintf('Does not exist any record in the database "%s" matching given conditions', $table));
}
} | php | public function shouldExistInTableRecordsMatching($table, YamlStringNode $criteria)
{
foreach ($criteria->toArray() as $row) {
$count = $this->countRecordsInTableMatching($table, $row);
Assert::assertEquals(1, $count, sprintf('Does not exist any record in the database "%s" matching given conditions', $table));
}
} | [
"public",
"function",
"shouldExistInTableRecordsMatching",
"(",
"$",
"table",
",",
"YamlStringNode",
"$",
"criteria",
")",
"{",
"foreach",
"(",
"$",
"criteria",
"->",
"toArray",
"(",
")",
"as",
"$",
"row",
")",
"{",
"$",
"count",
"=",
"$",
"this",
"->",
... | Use a YAML syntax to create a criteria to match many records in given table
Example: Then should exist in table "post" a record matching:
"""
- title: "Welcome"
body: "Welcome to web page"
- title: "Another Post"
body: "This is another Post"
"""
@Given /^should exist in table "([^"]*)" records matching:$/ | [
"Use",
"a",
"YAML",
"syntax",
"to",
"create",
"a",
"criteria",
"to",
"match",
"many",
"records",
"in",
"given",
"table"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Behat/Context/DatabaseContext.php#L67-L73 | train |
ynloultratech/graphql-bundle | src/Behat/Context/DatabaseContext.php | DatabaseContext.countRecordsInTableMatching | public function countRecordsInTableMatching($table, $criteria = []): int
{
$where = '';
foreach ($criteria as $field => $vale) {
if ($where) {
$where .= ' AND ';
}
if ($vale === null) {
$where .= sprintf('%s IS NULL', $field);
} else {
$where .= sprintf('%s = :%s', $field, $field);
}
}
$query = sprintf('SELECT count(*) AS records FROM %s WHERE %s', $table, $where);
/** @var EntityManager $manager */
$manager = $this->client->getContainer()->get('doctrine')->getManager();
$rsm = new ResultSetMapping();
$rsm->addScalarResult('records', 'records', 'integer');
$query = $manager->createNativeQuery($query, $rsm);
$query->setParameters($criteria);
return (int) $query->getSingleScalarResult();
} | php | public function countRecordsInTableMatching($table, $criteria = []): int
{
$where = '';
foreach ($criteria as $field => $vale) {
if ($where) {
$where .= ' AND ';
}
if ($vale === null) {
$where .= sprintf('%s IS NULL', $field);
} else {
$where .= sprintf('%s = :%s', $field, $field);
}
}
$query = sprintf('SELECT count(*) AS records FROM %s WHERE %s', $table, $where);
/** @var EntityManager $manager */
$manager = $this->client->getContainer()->get('doctrine')->getManager();
$rsm = new ResultSetMapping();
$rsm->addScalarResult('records', 'records', 'integer');
$query = $manager->createNativeQuery($query, $rsm);
$query->setParameters($criteria);
return (int) $query->getSingleScalarResult();
} | [
"public",
"function",
"countRecordsInTableMatching",
"(",
"$",
"table",
",",
"$",
"criteria",
"=",
"[",
"]",
")",
":",
"int",
"{",
"$",
"where",
"=",
"''",
";",
"foreach",
"(",
"$",
"criteria",
"as",
"$",
"field",
"=>",
"$",
"vale",
")",
"{",
"if",
... | Count records in table matching criteria
@param string $table
@param array $criteria
@return int
@throws \Doctrine\ORM\NonUniqueResultException | [
"Count",
"records",
"in",
"table",
"matching",
"criteria"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Behat/Context/DatabaseContext.php#L132-L155 | train |
contao-community-alliance/translator | src/BackportedTranslator.php | BackportedTranslator.loadLanguageFile | private function loadLanguageFile($name)
{
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($name);
} | php | private function loadLanguageFile($name)
{
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($name);
} | [
"private",
"function",
"loadLanguageFile",
"(",
"$",
"name",
")",
"{",
"/** @var System $system */",
"$",
"system",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"System",
"::",
"class",
")",
";",
"$",
"system",
"->",
"loadLanguageFile",
"(",
... | Loads a Contao framework language file.
@param string $name The name of the language file to load.
@return void | [
"Loads",
"a",
"Contao",
"framework",
"language",
"file",
"."
] | daa920897510c10ee400b29c83840a866c17623a | https://github.com/contao-community-alliance/translator/blob/daa920897510c10ee400b29c83840a866c17623a/src/BackportedTranslator.php#L148-L153 | train |
contao-community-alliance/translator | src/Contao/LangArrayTranslator.php | LangArrayTranslator.loadDomain | protected function loadDomain($domain, $locale)
{
$event = new LoadLanguageFileEvent($domain, $locale);
$this->eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
} | php | protected function loadDomain($domain, $locale)
{
$event = new LoadLanguageFileEvent($domain, $locale);
$this->eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
} | [
"protected",
"function",
"loadDomain",
"(",
"$",
"domain",
",",
"$",
"locale",
")",
"{",
"$",
"event",
"=",
"new",
"LoadLanguageFileEvent",
"(",
"$",
"domain",
",",
"$",
"locale",
")",
";",
"$",
"this",
"->",
"eventDispatcher",
"->",
"dispatch",
"(",
"Co... | Load the language strings for the given domain in the passed locale.
@param string $domain The domain to load.
@param string $locale The locale to use.
@return void
@codeCoverageIgnore | [
"Load",
"the",
"language",
"strings",
"for",
"the",
"given",
"domain",
"in",
"the",
"passed",
"locale",
"."
] | daa920897510c10ee400b29c83840a866c17623a | https://github.com/contao-community-alliance/translator/blob/daa920897510c10ee400b29c83840a866c17623a/src/Contao/LangArrayTranslator.php#L103-L108 | train |
ynloultratech/graphql-bundle | src/Resolver/DeferredBuffer.php | DeferredBuffer.getLoadedEntity | public function getLoadedEntity(NodeInterface $entity): NodeInterface
{
$class = ClassUtils::getClass($entity);
if (isset(self::$deferred[$class][$entity->getId()]) && self::$deferred[$class][$entity->getId()] instanceof NodeInterface) {
return self::$deferred[$class][$entity->getId()];
}
//fallback
return $entity;
} | php | public function getLoadedEntity(NodeInterface $entity): NodeInterface
{
$class = ClassUtils::getClass($entity);
if (isset(self::$deferred[$class][$entity->getId()]) && self::$deferred[$class][$entity->getId()] instanceof NodeInterface) {
return self::$deferred[$class][$entity->getId()];
}
//fallback
return $entity;
} | [
"public",
"function",
"getLoadedEntity",
"(",
"NodeInterface",
"$",
"entity",
")",
":",
"NodeInterface",
"{",
"$",
"class",
"=",
"ClassUtils",
"::",
"getClass",
"(",
"$",
"entity",
")",
";",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"deferred",
"[",
"$... | Return the loaded entity for given not initialized entity | [
"Return",
"the",
"loaded",
"entity",
"for",
"given",
"not",
"initialized",
"entity"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Resolver/DeferredBuffer.php#L55-L64 | train |
ynloultratech/graphql-bundle | src/Resolver/DeferredBuffer.php | DeferredBuffer.loadBuffer | public function loadBuffer(): void
{
if (self::$loaded) {
return;
}
self::$loaded = true;
foreach (self::$deferred as $class => $ids) {
/** @var EntityRepository $repo */
$repo = $this->registry->getRepository($class);
$qb = $repo->createQueryBuilder('o', 'o.id');
$entities = $qb->where($qb->expr()->in('o.id', array_values($ids)))
->getQuery()
->getResult();
foreach ($entities as $entity) {
if ($entity instanceof NodeInterface) {
self::$deferred[$class][$entity->getId()] = $entity;
}
}
}
} | php | public function loadBuffer(): void
{
if (self::$loaded) {
return;
}
self::$loaded = true;
foreach (self::$deferred as $class => $ids) {
/** @var EntityRepository $repo */
$repo = $this->registry->getRepository($class);
$qb = $repo->createQueryBuilder('o', 'o.id');
$entities = $qb->where($qb->expr()->in('o.id', array_values($ids)))
->getQuery()
->getResult();
foreach ($entities as $entity) {
if ($entity instanceof NodeInterface) {
self::$deferred[$class][$entity->getId()] = $entity;
}
}
}
} | [
"public",
"function",
"loadBuffer",
"(",
")",
":",
"void",
"{",
"if",
"(",
"self",
"::",
"$",
"loaded",
")",
"{",
"return",
";",
"}",
"self",
"::",
"$",
"loaded",
"=",
"true",
";",
"foreach",
"(",
"self",
"::",
"$",
"deferred",
"as",
"$",
"class",
... | Load buffer of entities | [
"Load",
"buffer",
"of",
"entities"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Resolver/DeferredBuffer.php#L69-L89 | train |
spiral/vault | source/Vault/Vault.php | Vault.uri | public function uri(string $target, $parameters = []): UriInterface
{
if (strpos($target, ':') !== false) {
list($controller, $action) = explode(':', $target);
} else {
$controller = $target;
$action = $parameters['action'] ?? null;
}
if (!$this->config->hasController($controller)) {
throw new VaultException("Unable to generate uri, undefined controller '{$controller}'");
}
return $this->route->withDefaults(compact('controller', 'action'))->uri($parameters);
} | php | public function uri(string $target, $parameters = []): UriInterface
{
if (strpos($target, ':') !== false) {
list($controller, $action) = explode(':', $target);
} else {
$controller = $target;
$action = $parameters['action'] ?? null;
}
if (!$this->config->hasController($controller)) {
throw new VaultException("Unable to generate uri, undefined controller '{$controller}'");
}
return $this->route->withDefaults(compact('controller', 'action'))->uri($parameters);
} | [
"public",
"function",
"uri",
"(",
"string",
"$",
"target",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
":",
"UriInterface",
"{",
"if",
"(",
"strpos",
"(",
"$",
"target",
",",
"':'",
")",
"!==",
"false",
")",
"{",
"list",
"(",
"$",
"controller",
","... | Get vault specific uri.
@param string $target Target controller and action in a form of "controller::action" or
"controller:action" or "controller".
@param array|mixed $parameters
@return UriInterface
@throws VaultException | [
"Get",
"vault",
"specific",
"uri",
"."
] | fb64c1bcaa3aa4e926ff94902bf08e059ad849bf | https://github.com/spiral/vault/blob/fb64c1bcaa3aa4e926ff94902bf08e059ad849bf/source/Vault/Vault.php#L108-L122 | train |
portphp/steps | src/StepAggregator.php | StepAggregator.buildPipeline | private function buildPipeline()
{
$nextCallable = function ($item) {
// the final callable is a no-op
};
foreach ($this->getStepsSortedDescByPriority() as $step) {
$nextCallable = function ($item) use ($step, $nextCallable) {
return $step->process($item, $nextCallable);
};
}
return $nextCallable;
} | php | private function buildPipeline()
{
$nextCallable = function ($item) {
// the final callable is a no-op
};
foreach ($this->getStepsSortedDescByPriority() as $step) {
$nextCallable = function ($item) use ($step, $nextCallable) {
return $step->process($item, $nextCallable);
};
}
return $nextCallable;
} | [
"private",
"function",
"buildPipeline",
"(",
")",
"{",
"$",
"nextCallable",
"=",
"function",
"(",
"$",
"item",
")",
"{",
"// the final callable is a no-op",
"}",
";",
"foreach",
"(",
"$",
"this",
"->",
"getStepsSortedDescByPriority",
"(",
")",
"as",
"$",
"step... | Builds the pipeline
@return callable | [
"Builds",
"the",
"pipeline"
] | cd87c96fbfe2b87a2af53fab974e81d454cfcb52 | https://github.com/portphp/steps/blob/cd87c96fbfe2b87a2af53fab974e81d454cfcb52/src/StepAggregator.php#L170-L183 | train |
portphp/steps | src/StepAggregator.php | StepAggregator.getStepsSortedDescByPriority | private function getStepsSortedDescByPriority()
{
$steps = $this->steps;
// Use illogically large and small priorities
$steps[-255][] = new Step\ArrayCheckStep;
foreach ($this->writers as $writer) {
$steps[-256][] = new Step\WriterStep($writer);
}
krsort($steps);
$sortedStep = [];
/** @var Step[] $stepsAtSamePriority */
foreach ($steps as $stepsAtSamePriority) {
foreach ($stepsAtSamePriority as $step) {
$sortedStep[] = $step;
}
}
return array_reverse($sortedStep);
} | php | private function getStepsSortedDescByPriority()
{
$steps = $this->steps;
// Use illogically large and small priorities
$steps[-255][] = new Step\ArrayCheckStep;
foreach ($this->writers as $writer) {
$steps[-256][] = new Step\WriterStep($writer);
}
krsort($steps);
$sortedStep = [];
/** @var Step[] $stepsAtSamePriority */
foreach ($steps as $stepsAtSamePriority) {
foreach ($stepsAtSamePriority as $step) {
$sortedStep[] = $step;
}
}
return array_reverse($sortedStep);
} | [
"private",
"function",
"getStepsSortedDescByPriority",
"(",
")",
"{",
"$",
"steps",
"=",
"$",
"this",
"->",
"steps",
";",
"// Use illogically large and small priorities",
"$",
"steps",
"[",
"-",
"255",
"]",
"[",
"]",
"=",
"new",
"Step",
"\\",
"ArrayCheckStep",
... | Sorts the internal list of steps and writers by priority in reverse order.
@return Step[] | [
"Sorts",
"the",
"internal",
"list",
"of",
"steps",
"and",
"writers",
"by",
"priority",
"in",
"reverse",
"order",
"."
] | cd87c96fbfe2b87a2af53fab974e81d454cfcb52 | https://github.com/portphp/steps/blob/cd87c96fbfe2b87a2af53fab974e81d454cfcb52/src/StepAggregator.php#L190-L210 | train |
API-Skeletons/zf-doctrine-audit | src/Tools/RevisionAuditTool.php | RevisionAuditTool.close | public function close()
{
$userId = 0;
$userName = 'guest';
$userEmail = '';
if ($this->authenticationService) {
if ($this->authenticationService->getIdentity() instanceof OAuth2AuthenticatedIdentity) {
$user = $this->authenticationService->getIdentity()->getUser();
if (method_exists($user, 'getId')) {
$userId = $user->getId();
}
if (method_exists($user, 'getDisplayName')) {
$userName = $user->getDisplayName();
}
if (method_exists($user, 'getEmail')) {
$userEmail = $user->getEmail();
}
} elseif ($this->authenticationService->getIdentity() instanceof AuthenticatedIdentity) {
$userId = $this->authenticationService->getIdentity()->getAuthenticationIdentity()['user_id'];
$userName = $this->authenticationService->getIdentity()->getName();
} elseif ($this->authenticationService->getIdentity() instanceof GuestIdentity) {
} else {
// Is null or other identity
}
}
$query = $this->getObjectManager()
->createNativeQuery(
"
SELECT close_revision_audit(:userId, :userName, :userEmail, :comment)
",
new ResultSetMapping()
)
->setParameter('userId', $userId)
->setParameter('userName', $userName)
->setParameter('userEmail', $userEmail)
->setParameter('comment', $this->revisionComment->getComment());
;
$query->getResult();
// Reset the revision comment
$this->revisionComment->setComment('');
} | php | public function close()
{
$userId = 0;
$userName = 'guest';
$userEmail = '';
if ($this->authenticationService) {
if ($this->authenticationService->getIdentity() instanceof OAuth2AuthenticatedIdentity) {
$user = $this->authenticationService->getIdentity()->getUser();
if (method_exists($user, 'getId')) {
$userId = $user->getId();
}
if (method_exists($user, 'getDisplayName')) {
$userName = $user->getDisplayName();
}
if (method_exists($user, 'getEmail')) {
$userEmail = $user->getEmail();
}
} elseif ($this->authenticationService->getIdentity() instanceof AuthenticatedIdentity) {
$userId = $this->authenticationService->getIdentity()->getAuthenticationIdentity()['user_id'];
$userName = $this->authenticationService->getIdentity()->getName();
} elseif ($this->authenticationService->getIdentity() instanceof GuestIdentity) {
} else {
// Is null or other identity
}
}
$query = $this->getObjectManager()
->createNativeQuery(
"
SELECT close_revision_audit(:userId, :userName, :userEmail, :comment)
",
new ResultSetMapping()
)
->setParameter('userId', $userId)
->setParameter('userName', $userName)
->setParameter('userEmail', $userEmail)
->setParameter('comment', $this->revisionComment->getComment());
;
$query->getResult();
// Reset the revision comment
$this->revisionComment->setComment('');
} | [
"public",
"function",
"close",
"(",
")",
"{",
"$",
"userId",
"=",
"0",
";",
"$",
"userName",
"=",
"'guest'",
";",
"$",
"userEmail",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"authenticationService",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"auth... | Close a revision - can be done manually or automatically via postFlush | [
"Close",
"a",
"revision",
"-",
"can",
"be",
"done",
"manually",
"or",
"automatically",
"via",
"postFlush"
] | fff09b25ff85073088e50232bd493b01cd69349b | https://github.com/API-Skeletons/zf-doctrine-audit/blob/fff09b25ff85073088e50232bd493b01cd69349b/src/Tools/RevisionAuditTool.php#L38-L85 | train |
spiral/vault | source/Vault/Models/Navigation.php | Navigation.getSections | public function getSections(): \Generator
{
foreach ($this->vault->getConfig()->navigationSections() as $section) {
yield new Section($this->vault, $section);
}
} | php | public function getSections(): \Generator
{
foreach ($this->vault->getConfig()->navigationSections() as $section) {
yield new Section($this->vault, $section);
}
} | [
"public",
"function",
"getSections",
"(",
")",
":",
"\\",
"Generator",
"{",
"foreach",
"(",
"$",
"this",
"->",
"vault",
"->",
"getConfig",
"(",
")",
"->",
"navigationSections",
"(",
")",
"as",
"$",
"section",
")",
"{",
"yield",
"new",
"Section",
"(",
"... | Get all navigation sections. This is generator.
@generator
@return \Generator|Section[] | [
"Get",
"all",
"navigation",
"sections",
".",
"This",
"is",
"generator",
"."
] | fb64c1bcaa3aa4e926ff94902bf08e059ad849bf | https://github.com/spiral/vault/blob/fb64c1bcaa3aa4e926ff94902bf08e059ad849bf/source/Vault/Models/Navigation.php#L58-L63 | train |
ynloultratech/graphql-bundle | src/Util/Uuid.php | Uuid.createFromData | public static function createFromData($data, $upper = false): string
{
if (\is_array($data) || \is_object($data)) {
$data = serialize($data);
}
$hash = $upper ? strtoupper(md5($data)) : strtolower(md5($data));
return implode(
'-',
[
substr($hash, 0, 8),
substr($hash, 8, 4),
substr($hash, 12, 4),
substr($hash, 16, 4),
substr($hash, 20, 8),
]
);
} | php | public static function createFromData($data, $upper = false): string
{
if (\is_array($data) || \is_object($data)) {
$data = serialize($data);
}
$hash = $upper ? strtoupper(md5($data)) : strtolower(md5($data));
return implode(
'-',
[
substr($hash, 0, 8),
substr($hash, 8, 4),
substr($hash, 12, 4),
substr($hash, 16, 4),
substr($hash, 20, 8),
]
);
} | [
"public",
"static",
"function",
"createFromData",
"(",
"$",
"data",
",",
"$",
"upper",
"=",
"false",
")",
":",
"string",
"{",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"data",
")",
"||",
"\\",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
"$",
"data",... | Create universal identifier for given data.
Helpful to create unique across then system, but the same when use the same data
@param mixed $data
@param boolean $upper
@return string | [
"Create",
"universal",
"identifier",
"for",
"given",
"data",
".",
"Helpful",
"to",
"create",
"unique",
"across",
"then",
"system",
"but",
"the",
"same",
"when",
"use",
"the",
"same",
"data"
] | 390aa1ca77cf00ae02688839ea4fca1026954501 | https://github.com/ynloultratech/graphql-bundle/blob/390aa1ca77cf00ae02688839ea4fca1026954501/src/Util/Uuid.php#L24-L42 | train |
Arachne/EntityLoader | src/Application/ParameterFinder.php | ParameterFinder.getMapping | public function getMapping(Request $request): array
{
return $this->cache->load($this->getCacheKey($request), function (&$dependencies) use ($request) {
return $this->loadMapping($request->getPresenterName(), $request->getParameters(), $dependencies);
});
} | php | public function getMapping(Request $request): array
{
return $this->cache->load($this->getCacheKey($request), function (&$dependencies) use ($request) {
return $this->loadMapping($request->getPresenterName(), $request->getParameters(), $dependencies);
});
} | [
"public",
"function",
"getMapping",
"(",
"Request",
"$",
"request",
")",
":",
"array",
"{",
"return",
"$",
"this",
"->",
"cache",
"->",
"load",
"(",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"request",
")",
",",
"function",
"(",
"&",
"$",
"dependenci... | Returns parameters information based on the request.
@return stdClass[] | [
"Returns",
"parameters",
"information",
"based",
"on",
"the",
"request",
"."
] | 1d577a5d6ce487150cde68ad01cf4db15f564dfc | https://github.com/Arachne/EntityLoader/blob/1d577a5d6ce487150cde68ad01cf4db15f564dfc/src/Application/ParameterFinder.php#L66-L71 | train |
nyeholt/silverstripe-solr | code/extensions/SiteTreePermissionIndexExtension.php | SiteTreePermissionIndexExtension.additionalSolrValues | public function additionalSolrValues() {
if(($this->owner->CanViewType === 'Inherit') && $this->owner->ParentID) {
// Recursively determine the site tree element permissions where required.
return $this->owner->Parent()->additionalSolrValues();
}
else if($this->owner->CanViewType === 'OnlyTheseUsers') {
// Return the listing of groups that have access.
$groups = array();
foreach($this->owner->ViewerGroups() as $group) {
$groups[] = (string)$group->ID;
}
return array(
$this->index => $groups
);
}
else if($this->owner->CanViewType === 'LoggedInUsers') {
// Return an appropriate flag for logged in access.
return array(
$this->index => array(
'logged-in'
)
);
}
else {
// Return an appropriate flag for general public access.
return array(
$this->index => array(
'anyone'
)
);
}
} | php | public function additionalSolrValues() {
if(($this->owner->CanViewType === 'Inherit') && $this->owner->ParentID) {
// Recursively determine the site tree element permissions where required.
return $this->owner->Parent()->additionalSolrValues();
}
else if($this->owner->CanViewType === 'OnlyTheseUsers') {
// Return the listing of groups that have access.
$groups = array();
foreach($this->owner->ViewerGroups() as $group) {
$groups[] = (string)$group->ID;
}
return array(
$this->index => $groups
);
}
else if($this->owner->CanViewType === 'LoggedInUsers') {
// Return an appropriate flag for logged in access.
return array(
$this->index => array(
'logged-in'
)
);
}
else {
// Return an appropriate flag for general public access.
return array(
$this->index => array(
'anyone'
)
);
}
} | [
"public",
"function",
"additionalSolrValues",
"(",
")",
"{",
"if",
"(",
"(",
"$",
"this",
"->",
"owner",
"->",
"CanViewType",
"===",
"'Inherit'",
")",
"&&",
"$",
"this",
"->",
"owner",
"->",
"ParentID",
")",
"{",
"// Recursively determine the site tree element p... | Retrieve the custom search index value for the current site tree element, returning the listing of groups that have access.
@return array | [
"Retrieve",
"the",
"custom",
"search",
"index",
"value",
"for",
"the",
"current",
"site",
"tree",
"element",
"returning",
"the",
"listing",
"of",
"groups",
"that",
"have",
"access",
"."
] | a573df88167ba9b2bec51e2660a4edfdad446fcf | https://github.com/nyeholt/silverstripe-solr/blob/a573df88167ba9b2bec51e2660a4edfdad446fcf/code/extensions/SiteTreePermissionIndexExtension.php#L32-L72 | train |
nyeholt/silverstripe-solr | code/extensions/SolrGeoExtension.php | SolrGeoExtension.getGeoSelectableFields | public function getGeoSelectableFields() {
$all = $this->owner->getSelectableFields(null, false);
$listTypes = $this->owner->searchableTypes('Page');
$geoFields = array();
foreach ($listTypes as $classType) {
$db = Config::inst()->get($classType, 'db');
foreach ($db as $name => $type) {
if (is_subclass_of($type, 'SolrGeoPoint') || $type == 'SolrGeoPoint') {
$geoFields[$name] = $name;
}
}
}
ksort($geoFields);
return $geoFields;
} | php | public function getGeoSelectableFields() {
$all = $this->owner->getSelectableFields(null, false);
$listTypes = $this->owner->searchableTypes('Page');
$geoFields = array();
foreach ($listTypes as $classType) {
$db = Config::inst()->get($classType, 'db');
foreach ($db as $name => $type) {
if (is_subclass_of($type, 'SolrGeoPoint') || $type == 'SolrGeoPoint') {
$geoFields[$name] = $name;
}
}
}
ksort($geoFields);
return $geoFields;
} | [
"public",
"function",
"getGeoSelectableFields",
"(",
")",
"{",
"$",
"all",
"=",
"$",
"this",
"->",
"owner",
"->",
"getSelectableFields",
"(",
"null",
",",
"false",
")",
";",
"$",
"listTypes",
"=",
"$",
"this",
"->",
"owner",
"->",
"searchableTypes",
"(",
... | Get a list of geopoint fields that are selectable | [
"Get",
"a",
"list",
"of",
"geopoint",
"fields",
"that",
"are",
"selectable"
] | a573df88167ba9b2bec51e2660a4edfdad446fcf | https://github.com/nyeholt/silverstripe-solr/blob/a573df88167ba9b2bec51e2660a4edfdad446fcf/code/extensions/SolrGeoExtension.php#L56-L72 | train |
psbhanu/whatsapi | src/MessageManager.php | MessageManager.image | public function image($file, $caption = null)
{
$this->messages[] = $this->media->compile($file, $caption, 'image');
} | php | public function image($file, $caption = null)
{
$this->messages[] = $this->media->compile($file, $caption, 'image');
} | [
"public",
"function",
"image",
"(",
"$",
"file",
",",
"$",
"caption",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"messages",
"[",
"]",
"=",
"$",
"this",
"->",
"media",
"->",
"compile",
"(",
"$",
"file",
",",
"$",
"caption",
",",
"'image'",
")",
";... | Send image message
<code>
WA::send('See this cool image !', function($send)
{
$send->to('5219622222222');
// From local storage
$send->image('/home/xaamin/example.jpg', 'Cool image');
// or from web url
$send->image('http://itnovado.com/example.jpg', 'Cool image');
}):
</code>
@param string $file File location
@param string Caption
@return void | [
"Send",
"image",
"message"
] | be34f35bb5e0fd3c6f2196260865bef65c1240c2 | https://github.com/psbhanu/whatsapi/blob/be34f35bb5e0fd3c6f2196260865bef65c1240c2/src/MessageManager.php#L162-L165 | train |
psbhanu/whatsapi | src/MessageManager.php | MessageManager.location | public function location($longitude, $latitude, $caption = null, $url = null)
{
$location = new stdClass();
$location->type = 'location';
$location->longitude = $longitude;
$location->latitude = $latitude;
$location->caption = $caption;
$location->url = $url;
$this->messages[] = $location;
} | php | public function location($longitude, $latitude, $caption = null, $url = null)
{
$location = new stdClass();
$location->type = 'location';
$location->longitude = $longitude;
$location->latitude = $latitude;
$location->caption = $caption;
$location->url = $url;
$this->messages[] = $location;
} | [
"public",
"function",
"location",
"(",
"$",
"longitude",
",",
"$",
"latitude",
",",
"$",
"caption",
"=",
"null",
",",
"$",
"url",
"=",
"null",
")",
"{",
"$",
"location",
"=",
"new",
"stdClass",
"(",
")",
";",
"$",
"location",
"->",
"type",
"=",
"'l... | Send location message
<code>
WA::send('Go to itnovado !', function($send)
{
$send->to('5219622222222');
$send->location(-89.164138, 19.412405, 'Itnovado Location');
}):
</code>
@param float $longitude
@param float $latitude
@param string Caption
@param string $url
@return void | [
"Send",
"location",
"message"
] | be34f35bb5e0fd3c6f2196260865bef65c1240c2 | https://github.com/psbhanu/whatsapi/blob/be34f35bb5e0fd3c6f2196260865bef65c1240c2/src/MessageManager.php#L184-L194 | train |
psbhanu/whatsapi | src/MessageManager.php | MessageManager.vcard | public function vcard($name, VCard $vcard)
{
$card = new stdClass();
$card->type = 'vcard';
$card->name = $name;
$card->vcard = $vcard;
$this->messages[] = $card;
} | php | public function vcard($name, VCard $vcard)
{
$card = new stdClass();
$card->type = 'vcard';
$card->name = $name;
$card->vcard = $vcard;
$this->messages[] = $card;
} | [
"public",
"function",
"vcard",
"(",
"$",
"name",
",",
"VCard",
"$",
"vcard",
")",
"{",
"$",
"card",
"=",
"new",
"stdClass",
"(",
")",
";",
"$",
"card",
"->",
"type",
"=",
"'vcard'",
";",
"$",
"card",
"->",
"name",
"=",
"$",
"name",
";",
"$",
"c... | Send Virtual Cards
<code>
// Create VCard Instance
$vcard = new psbhanu\Whatsapi\Media\VCard();
// Set properties
$vcard->set('data', array(
'first_name' => 'John',
'last_name' => 'Doe',
'tel' => '9611111111',
));
// Send
WA::send('Hi, meet to Xaamin !', function($send) use ($vcard)
{
$send->to('5219622222222');
$send->vcard('Xaamin Mat', $vcard);
}):
</code>
@param string $name Person name
@param vCard $vCard vCard Object
@return void | [
"Send",
"Virtual",
"Cards"
] | be34f35bb5e0fd3c6f2196260865bef65c1240c2 | https://github.com/psbhanu/whatsapi/blob/be34f35bb5e0fd3c6f2196260865bef65c1240c2/src/MessageManager.php#L222-L230 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.