repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
alexpts/psr15-middlewares
|
src/StaticHeader.php
|
StaticHeader.withStaticHeaders
|
protected function withStaticHeaders(ResponseInterface $response, array $headers): ResponseInterface
{
foreach ($headers as $name => $header) {
$response = $response->withAddedHeader($name, $header);
}
return $response;
}
|
php
|
protected function withStaticHeaders(ResponseInterface $response, array $headers): ResponseInterface
{
foreach ($headers as $name => $header) {
$response = $response->withAddedHeader($name, $header);
}
return $response;
}
|
[
"protected",
"function",
"withStaticHeaders",
"(",
"ResponseInterface",
"$",
"response",
",",
"array",
"$",
"headers",
")",
":",
"ResponseInterface",
"{",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"name",
"=>",
"$",
"header",
")",
"{",
"$",
"response",
"=",
"$",
"response",
"->",
"withAddedHeader",
"(",
"$",
"name",
",",
"$",
"header",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] |
@param ResponseInterface $response
@param array $headers - header is array of values or string value
@return ResponseInterface
@throws \InvalidArgumentException
|
[
"@param",
"ResponseInterface",
"$response",
"@param",
"array",
"$headers",
"-",
"header",
"is",
"array",
"of",
"values",
"or",
"string",
"value"
] |
train
|
https://github.com/alexpts/psr15-middlewares/blob/bff2887d5af01c54d9288fd19c20f0f593b69358/src/StaticHeader.php#L43-L50
|
WebDevTmas/date-repetition
|
src/DateRepetition/DailyDateRepetition.php
|
DailyDateRepetition.newFromTimeString
|
public static function newFromTimeString($timeString)
{
try {
$dateTime = new DateTime($timeString);
} catch(\Exception $e) {
throw new InvalidArgumentException('Time string must be valid, see DateTime for documentation');
}
return new self($dateTime->format('G'), $dateTime->format('i'));
}
|
php
|
public static function newFromTimeString($timeString)
{
try {
$dateTime = new DateTime($timeString);
} catch(\Exception $e) {
throw new InvalidArgumentException('Time string must be valid, see DateTime for documentation');
}
return new self($dateTime->format('G'), $dateTime->format('i'));
}
|
[
"public",
"static",
"function",
"newFromTimeString",
"(",
"$",
"timeString",
")",
"{",
"try",
"{",
"$",
"dateTime",
"=",
"new",
"DateTime",
"(",
"$",
"timeString",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Time string must be valid, see DateTime for documentation'",
")",
";",
"}",
"return",
"new",
"self",
"(",
"$",
"dateTime",
"->",
"format",
"(",
"'G'",
")",
",",
"$",
"dateTime",
"->",
"format",
"(",
"'i'",
")",
")",
";",
"}"
] |
Creates new DailyDateRepetition from string readable by DateTime
@param string time string
@return DailyDateRepetition
|
[
"Creates",
"new",
"DailyDateRepetition",
"from",
"string",
"readable",
"by",
"DateTime"
] |
train
|
https://github.com/WebDevTmas/date-repetition/blob/3ebd59f4ab3aab4b7497ebd767a57fad08277c6d/src/DateRepetition/DailyDateRepetition.php#L34-L42
|
WebDevTmas/date-repetition
|
src/DateRepetition/DailyDateRepetition.php
|
DailyDateRepetition.setHour
|
public function setHour($hour)
{
if(! in_array($hour, range(0, 23))) {
throw new InvalidArgumentException('Hour must be between 0 and 23');
}
$this->hour = $hour;
return $this;
}
|
php
|
public function setHour($hour)
{
if(! in_array($hour, range(0, 23))) {
throw new InvalidArgumentException('Hour must be between 0 and 23');
}
$this->hour = $hour;
return $this;
}
|
[
"public",
"function",
"setHour",
"(",
"$",
"hour",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"hour",
",",
"range",
"(",
"0",
",",
"23",
")",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Hour must be between 0 and 23'",
")",
";",
"}",
"$",
"this",
"->",
"hour",
"=",
"$",
"hour",
";",
"return",
"$",
"this",
";",
"}"
] |
Sets hour of repetition
@param integer hour
@return this
|
[
"Sets",
"hour",
"of",
"repetition"
] |
train
|
https://github.com/WebDevTmas/date-repetition/blob/3ebd59f4ab3aab4b7497ebd767a57fad08277c6d/src/DateRepetition/DailyDateRepetition.php#L60-L67
|
alexpts/psr15-middlewares
|
src/PhpInputToBody.php
|
PhpInputToBody.process
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$body = $this->parseBody($request);
$parsedBody = $request->getParsedBody();
$request = $request->withParsedBody(array_merge($body, $parsedBody));
return $handler->handle($request);
}
|
php
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$body = $this->parseBody($request);
$parsedBody = $request->getParsedBody();
$request = $request->withParsedBody(array_merge($body, $parsedBody));
return $handler->handle($request);
}
|
[
"public",
"function",
"process",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"RequestHandlerInterface",
"$",
"handler",
")",
":",
"ResponseInterface",
"{",
"$",
"body",
"=",
"$",
"this",
"->",
"parseBody",
"(",
"$",
"request",
")",
";",
"$",
"parsedBody",
"=",
"$",
"request",
"->",
"getParsedBody",
"(",
")",
";",
"$",
"request",
"=",
"$",
"request",
"->",
"withParsedBody",
"(",
"array_merge",
"(",
"$",
"body",
",",
"$",
"parsedBody",
")",
")",
";",
"return",
"$",
"handler",
"->",
"handle",
"(",
"$",
"request",
")",
";",
"}"
] |
@param ServerRequestInterface $request
@param RequestHandlerInterface $handler
@return ResponseInterface
@throws \InvalidArgumentException
@throws \RuntimeException
|
[
"@param",
"ServerRequestInterface",
"$request",
"@param",
"RequestHandlerInterface",
"$handler"
] |
train
|
https://github.com/alexpts/psr15-middlewares/blob/bff2887d5af01c54d9288fd19c20f0f593b69358/src/PhpInputToBody.php#L22-L30
|
alexpts/psr15-middlewares
|
src/PhpInputToBody.php
|
PhpInputToBody.parseBody
|
protected function parseBody(ServerRequestInterface $request): array
{
$body = [];
parse_str($request->getBody()->getContents(), $body);
return $body;
}
|
php
|
protected function parseBody(ServerRequestInterface $request): array
{
$body = [];
parse_str($request->getBody()->getContents(), $body);
return $body;
}
|
[
"protected",
"function",
"parseBody",
"(",
"ServerRequestInterface",
"$",
"request",
")",
":",
"array",
"{",
"$",
"body",
"=",
"[",
"]",
";",
"parse_str",
"(",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
",",
"$",
"body",
")",
";",
"return",
"$",
"body",
";",
"}"
] |
@param ServerRequestInterface $request
@return array
@throws \RuntimeException
|
[
"@param",
"ServerRequestInterface",
"$request"
] |
train
|
https://github.com/alexpts/psr15-middlewares/blob/bff2887d5af01c54d9288fd19c20f0f593b69358/src/PhpInputToBody.php#L39-L45
|
bigpaulie/yii2-fancybox
|
src/Widget.php
|
Widget.registerScripts
|
protected function registerScripts(\yii\web\View $view){
if ($this->clientOptions !== false) {
$options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
$js = "jQuery('#{$this->id}').fancybox($options);";
$view->registerJs($js , View::POS_READY);
}
}
|
php
|
protected function registerScripts(\yii\web\View $view){
if ($this->clientOptions !== false) {
$options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
$js = "jQuery('#{$this->id}').fancybox($options);";
$view->registerJs($js , View::POS_READY);
}
}
|
[
"protected",
"function",
"registerScripts",
"(",
"\\",
"yii",
"\\",
"web",
"\\",
"View",
"$",
"view",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"clientOptions",
"!==",
"false",
")",
"{",
"$",
"options",
"=",
"empty",
"(",
"$",
"this",
"->",
"clientOptions",
")",
"?",
"''",
":",
"Json",
"::",
"encode",
"(",
"$",
"this",
"->",
"clientOptions",
")",
";",
"$",
"js",
"=",
"\"jQuery('#{$this->id}').fancybox($options);\"",
";",
"$",
"view",
"->",
"registerJs",
"(",
"$",
"js",
",",
"View",
"::",
"POS_READY",
")",
";",
"}",
"}"
] |
Register scripts
@param View $view
|
[
"Register",
"scripts"
] |
train
|
https://github.com/bigpaulie/yii2-fancybox/blob/a961789a9ab94b0ebb129f3c6c57489d1298525b/src/Widget.php#L41-L47
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.processModule
|
protected function processModule($moduleId, array $moduleData)
{
$this->resetTemporaryModelCache();
// fill cache with current module's data
$this->moduleId = $moduleId;
$this->module = $moduleData;
// set default model data
$this->model = [
'module' => $moduleId,
'name' => $this->normalizeModelName($this->module['name']),
'table' => null,
'cached' => config('pxlcms.generator.models.enable_rememberable_cache'),
'is_translated' => false,
'is_translation' => false,
'is_listified' => false,
'ordered_by' => [],
'timestamps' => null,
// attributes
'normal_fillable' => [],
'translated_fillable' => [],
'hidden' => [],
'casts' => [],
'dates' => [],
'defaults' => [],
'normal_attributes' => [],
'translated_attributes' => [],
// categories
'has_categories' => (bool) array_get($this->module, 'client_cat_control'),
// relationships
'relations_config' => [],
'relationships' => [
'normal' => [],
'reverse' => [],
'image' => [],
'file' => [],
'checkbox' => [],
],
// special
'sluggable' => false,
'sluggable_setup' => [],
'scope_active' => null, // config determines
'scope_position' => null, // config determines
];
// process manual/automatic sorting of entries
$this->processModuleSorting();
// set overrides in model data
$this->prepareModelOverrides();
// add module fields as attribute data
$this->processModuleFields();
// override relationship data found while processing fields
$this->applyOverridesForRelationships();
// make sure we do not use a reserved class name
$this->checkForReservedClassName($this->model['name']);
// save completely built up model to context
$this->context->output['models'][ $moduleId ] = $this->model;
}
|
php
|
protected function processModule($moduleId, array $moduleData)
{
$this->resetTemporaryModelCache();
// fill cache with current module's data
$this->moduleId = $moduleId;
$this->module = $moduleData;
// set default model data
$this->model = [
'module' => $moduleId,
'name' => $this->normalizeModelName($this->module['name']),
'table' => null,
'cached' => config('pxlcms.generator.models.enable_rememberable_cache'),
'is_translated' => false,
'is_translation' => false,
'is_listified' => false,
'ordered_by' => [],
'timestamps' => null,
// attributes
'normal_fillable' => [],
'translated_fillable' => [],
'hidden' => [],
'casts' => [],
'dates' => [],
'defaults' => [],
'normal_attributes' => [],
'translated_attributes' => [],
// categories
'has_categories' => (bool) array_get($this->module, 'client_cat_control'),
// relationships
'relations_config' => [],
'relationships' => [
'normal' => [],
'reverse' => [],
'image' => [],
'file' => [],
'checkbox' => [],
],
// special
'sluggable' => false,
'sluggable_setup' => [],
'scope_active' => null, // config determines
'scope_position' => null, // config determines
];
// process manual/automatic sorting of entries
$this->processModuleSorting();
// set overrides in model data
$this->prepareModelOverrides();
// add module fields as attribute data
$this->processModuleFields();
// override relationship data found while processing fields
$this->applyOverridesForRelationships();
// make sure we do not use a reserved class name
$this->checkForReservedClassName($this->model['name']);
// save completely built up model to context
$this->context->output['models'][ $moduleId ] = $this->model;
}
|
[
"protected",
"function",
"processModule",
"(",
"$",
"moduleId",
",",
"array",
"$",
"moduleData",
")",
"{",
"$",
"this",
"->",
"resetTemporaryModelCache",
"(",
")",
";",
"// fill cache with current module's data",
"$",
"this",
"->",
"moduleId",
"=",
"$",
"moduleId",
";",
"$",
"this",
"->",
"module",
"=",
"$",
"moduleData",
";",
"// set default model data",
"$",
"this",
"->",
"model",
"=",
"[",
"'module'",
"=>",
"$",
"moduleId",
",",
"'name'",
"=>",
"$",
"this",
"->",
"normalizeModelName",
"(",
"$",
"this",
"->",
"module",
"[",
"'name'",
"]",
")",
",",
"'table'",
"=>",
"null",
",",
"'cached'",
"=>",
"config",
"(",
"'pxlcms.generator.models.enable_rememberable_cache'",
")",
",",
"'is_translated'",
"=>",
"false",
",",
"'is_translation'",
"=>",
"false",
",",
"'is_listified'",
"=>",
"false",
",",
"'ordered_by'",
"=>",
"[",
"]",
",",
"'timestamps'",
"=>",
"null",
",",
"// attributes",
"'normal_fillable'",
"=>",
"[",
"]",
",",
"'translated_fillable'",
"=>",
"[",
"]",
",",
"'hidden'",
"=>",
"[",
"]",
",",
"'casts'",
"=>",
"[",
"]",
",",
"'dates'",
"=>",
"[",
"]",
",",
"'defaults'",
"=>",
"[",
"]",
",",
"'normal_attributes'",
"=>",
"[",
"]",
",",
"'translated_attributes'",
"=>",
"[",
"]",
",",
"// categories",
"'has_categories'",
"=>",
"(",
"bool",
")",
"array_get",
"(",
"$",
"this",
"->",
"module",
",",
"'client_cat_control'",
")",
",",
"// relationships",
"'relations_config'",
"=>",
"[",
"]",
",",
"'relationships'",
"=>",
"[",
"'normal'",
"=>",
"[",
"]",
",",
"'reverse'",
"=>",
"[",
"]",
",",
"'image'",
"=>",
"[",
"]",
",",
"'file'",
"=>",
"[",
"]",
",",
"'checkbox'",
"=>",
"[",
"]",
",",
"]",
",",
"// special",
"'sluggable'",
"=>",
"false",
",",
"'sluggable_setup'",
"=>",
"[",
"]",
",",
"'scope_active'",
"=>",
"null",
",",
"// config determines",
"'scope_position'",
"=>",
"null",
",",
"// config determines",
"]",
";",
"// process manual/automatic sorting of entries",
"$",
"this",
"->",
"processModuleSorting",
"(",
")",
";",
"// set overrides in model data",
"$",
"this",
"->",
"prepareModelOverrides",
"(",
")",
";",
"// add module fields as attribute data",
"$",
"this",
"->",
"processModuleFields",
"(",
")",
";",
"// override relationship data found while processing fields",
"$",
"this",
"->",
"applyOverridesForRelationships",
"(",
")",
";",
"// make sure we do not use a reserved class name",
"$",
"this",
"->",
"checkForReservedClassName",
"(",
"$",
"this",
"->",
"model",
"[",
"'name'",
"]",
")",
";",
"// save completely built up model to context",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"moduleId",
"]",
"=",
"$",
"this",
"->",
"model",
";",
"}"
] |
Process a single module (to model)
@param int $moduleId
@param array $moduleData
@throws Exception
|
[
"Process",
"a",
"single",
"module",
"(",
"to",
"model",
")"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L85-L148
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.processModuleSorting
|
protected function processModuleSorting()
{
$this->model['is_listified'] = false;
$this->model['ordered_by'] = [];
// if there can be only 1 entry, it makes no sense to listify or order in any case
if ($this->module['max_entries'] == 1) {
return;
}
// if manually sorted, use listify and do not set sorting columns
if ($this->module['sort_entries_manually']) {
$this->model['is_listified'] = true;
return;
}
// if automatically sorted, check and extract the sorting columns
// listify is disabled by default, but may be overridden (might be useful some day)
$this->model['is_listified'] = false;
$sorting = trim(strtolower($this->module['sort_entries_by']));
if (empty($sorting)) return;
foreach (explode(',', $sorting) as $sortClauseString) {
if ( ! preg_match("#^\s*[`'](.*)[`']\s+(asc|desc)\s*$#i", $sortClauseString, $matches)) {
$this->context->log(
"Could not interpret sorting clause '{$sortClauseString}' for module #{$this->moduleId}",
Generator::LOG_LEVEL_ERROR
);
continue;
}
// store direction per column as key
$this->model['ordered_by'][ $matches[1] ] = $matches[2];
}
}
|
php
|
protected function processModuleSorting()
{
$this->model['is_listified'] = false;
$this->model['ordered_by'] = [];
// if there can be only 1 entry, it makes no sense to listify or order in any case
if ($this->module['max_entries'] == 1) {
return;
}
// if manually sorted, use listify and do not set sorting columns
if ($this->module['sort_entries_manually']) {
$this->model['is_listified'] = true;
return;
}
// if automatically sorted, check and extract the sorting columns
// listify is disabled by default, but may be overridden (might be useful some day)
$this->model['is_listified'] = false;
$sorting = trim(strtolower($this->module['sort_entries_by']));
if (empty($sorting)) return;
foreach (explode(',', $sorting) as $sortClauseString) {
if ( ! preg_match("#^\s*[`'](.*)[`']\s+(asc|desc)\s*$#i", $sortClauseString, $matches)) {
$this->context->log(
"Could not interpret sorting clause '{$sortClauseString}' for module #{$this->moduleId}",
Generator::LOG_LEVEL_ERROR
);
continue;
}
// store direction per column as key
$this->model['ordered_by'][ $matches[1] ] = $matches[2];
}
}
|
[
"protected",
"function",
"processModuleSorting",
"(",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'is_listified'",
"]",
"=",
"false",
";",
"$",
"this",
"->",
"model",
"[",
"'ordered_by'",
"]",
"=",
"[",
"]",
";",
"// if there can be only 1 entry, it makes no sense to listify or order in any case",
"if",
"(",
"$",
"this",
"->",
"module",
"[",
"'max_entries'",
"]",
"==",
"1",
")",
"{",
"return",
";",
"}",
"// if manually sorted, use listify and do not set sorting columns",
"if",
"(",
"$",
"this",
"->",
"module",
"[",
"'sort_entries_manually'",
"]",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'is_listified'",
"]",
"=",
"true",
";",
"return",
";",
"}",
"// if automatically sorted, check and extract the sorting columns",
"// listify is disabled by default, but may be overridden (might be useful some day)",
"$",
"this",
"->",
"model",
"[",
"'is_listified'",
"]",
"=",
"false",
";",
"$",
"sorting",
"=",
"trim",
"(",
"strtolower",
"(",
"$",
"this",
"->",
"module",
"[",
"'sort_entries_by'",
"]",
")",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"sorting",
")",
")",
"return",
";",
"foreach",
"(",
"explode",
"(",
"','",
",",
"$",
"sorting",
")",
"as",
"$",
"sortClauseString",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"\"#^\\s*[`'](.*)[`']\\s+(asc|desc)\\s*$#i\"",
",",
"$",
"sortClauseString",
",",
"$",
"matches",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Could not interpret sorting clause '{$sortClauseString}' for module #{$this->moduleId}\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"continue",
";",
"}",
"// store direction per column as key",
"$",
"this",
"->",
"model",
"[",
"'ordered_by'",
"]",
"[",
"$",
"matches",
"[",
"1",
"]",
"]",
"=",
"$",
"matches",
"[",
"2",
"]",
";",
"}",
"}"
] |
Determines and stores information about the sorting configuration
found for entries of the module
|
[
"Determines",
"and",
"stores",
"information",
"about",
"the",
"sorting",
"configuration",
"found",
"for",
"entries",
"of",
"the",
"module"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L181-L218
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.prepareModelOverrides
|
protected function prepareModelOverrides()
{
$this->overrides = $this->getOverrideConfigForModel($this->moduleId);
// determine name to use, handle pluralization and check database table override
if (array_key_exists('name', $this->overrides)) {
$name = $this->overrides['name'];
} else {
$name = array_get($this->module, 'prefixed_name') ?: $this->model['name'];
if (config('pxlcms.generator.models.model_name.singularize_model_names')) {
if ($this->context->dutchMode) {
$name = $this->dutchSingularize($name);
} else {
$name = str_singular($name);
}
}
}
// make sure we force set a table name if it does not follow convention
$tableOverride = null;
if (str_plural($this->normalizeDb($name)) != $this->normalizeDb($this->module['name'])) {
$tableOverride = $this->getModuleTablePrefix($this->moduleId)
. $this->normalizeDb($this->module['name']);
}
// force listified?
$listified = array_key_exists('listify', $this->overrides)
? (bool) $this->overrides['listify']
: $this->model['is_listified'];
// override hidden attributes?
$this->overrideHidden = [];
if ( ! is_null(array_get($this->overrides, 'attributes.hidden'))
&& ! array_get($this->overrides, 'attributes.hidden-empty')
) {
$this->overrideHidden = array_get($this->overrides, 'attributes.hidden');
if ( ! is_array($this->overrideHidden)) $this->overrideHidden = [ (string) $this->overrideHidden ];
}
// apply overrides to model data
$this->model['name'] = $name;
$this->model['table'] = $tableOverride;
$this->model['is_listified'] = $listified;
$this->model['hidden'] = $this->overrideHidden;
$this->model['casts'] = array_get($this->overrides, 'attributes.casts', []);
}
|
php
|
protected function prepareModelOverrides()
{
$this->overrides = $this->getOverrideConfigForModel($this->moduleId);
// determine name to use, handle pluralization and check database table override
if (array_key_exists('name', $this->overrides)) {
$name = $this->overrides['name'];
} else {
$name = array_get($this->module, 'prefixed_name') ?: $this->model['name'];
if (config('pxlcms.generator.models.model_name.singularize_model_names')) {
if ($this->context->dutchMode) {
$name = $this->dutchSingularize($name);
} else {
$name = str_singular($name);
}
}
}
// make sure we force set a table name if it does not follow convention
$tableOverride = null;
if (str_plural($this->normalizeDb($name)) != $this->normalizeDb($this->module['name'])) {
$tableOverride = $this->getModuleTablePrefix($this->moduleId)
. $this->normalizeDb($this->module['name']);
}
// force listified?
$listified = array_key_exists('listify', $this->overrides)
? (bool) $this->overrides['listify']
: $this->model['is_listified'];
// override hidden attributes?
$this->overrideHidden = [];
if ( ! is_null(array_get($this->overrides, 'attributes.hidden'))
&& ! array_get($this->overrides, 'attributes.hidden-empty')
) {
$this->overrideHidden = array_get($this->overrides, 'attributes.hidden');
if ( ! is_array($this->overrideHidden)) $this->overrideHidden = [ (string) $this->overrideHidden ];
}
// apply overrides to model data
$this->model['name'] = $name;
$this->model['table'] = $tableOverride;
$this->model['is_listified'] = $listified;
$this->model['hidden'] = $this->overrideHidden;
$this->model['casts'] = array_get($this->overrides, 'attributes.casts', []);
}
|
[
"protected",
"function",
"prepareModelOverrides",
"(",
")",
"{",
"$",
"this",
"->",
"overrides",
"=",
"$",
"this",
"->",
"getOverrideConfigForModel",
"(",
"$",
"this",
"->",
"moduleId",
")",
";",
"// determine name to use, handle pluralization and check database table override",
"if",
"(",
"array_key_exists",
"(",
"'name'",
",",
"$",
"this",
"->",
"overrides",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"overrides",
"[",
"'name'",
"]",
";",
"}",
"else",
"{",
"$",
"name",
"=",
"array_get",
"(",
"$",
"this",
"->",
"module",
",",
"'prefixed_name'",
")",
"?",
":",
"$",
"this",
"->",
"model",
"[",
"'name'",
"]",
";",
"if",
"(",
"config",
"(",
"'pxlcms.generator.models.model_name.singularize_model_names'",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"context",
"->",
"dutchMode",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"dutchSingularize",
"(",
"$",
"name",
")",
";",
"}",
"else",
"{",
"$",
"name",
"=",
"str_singular",
"(",
"$",
"name",
")",
";",
"}",
"}",
"}",
"// make sure we force set a table name if it does not follow convention",
"$",
"tableOverride",
"=",
"null",
";",
"if",
"(",
"str_plural",
"(",
"$",
"this",
"->",
"normalizeDb",
"(",
"$",
"name",
")",
")",
"!=",
"$",
"this",
"->",
"normalizeDb",
"(",
"$",
"this",
"->",
"module",
"[",
"'name'",
"]",
")",
")",
"{",
"$",
"tableOverride",
"=",
"$",
"this",
"->",
"getModuleTablePrefix",
"(",
"$",
"this",
"->",
"moduleId",
")",
".",
"$",
"this",
"->",
"normalizeDb",
"(",
"$",
"this",
"->",
"module",
"[",
"'name'",
"]",
")",
";",
"}",
"// force listified?",
"$",
"listified",
"=",
"array_key_exists",
"(",
"'listify'",
",",
"$",
"this",
"->",
"overrides",
")",
"?",
"(",
"bool",
")",
"$",
"this",
"->",
"overrides",
"[",
"'listify'",
"]",
":",
"$",
"this",
"->",
"model",
"[",
"'is_listified'",
"]",
";",
"// override hidden attributes?",
"$",
"this",
"->",
"overrideHidden",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"is_null",
"(",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.hidden'",
")",
")",
"&&",
"!",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.hidden-empty'",
")",
")",
"{",
"$",
"this",
"->",
"overrideHidden",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.hidden'",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"overrideHidden",
")",
")",
"$",
"this",
"->",
"overrideHidden",
"=",
"[",
"(",
"string",
")",
"$",
"this",
"->",
"overrideHidden",
"]",
";",
"}",
"// apply overrides to model data",
"$",
"this",
"->",
"model",
"[",
"'name'",
"]",
"=",
"$",
"name",
";",
"$",
"this",
"->",
"model",
"[",
"'table'",
"]",
"=",
"$",
"tableOverride",
";",
"$",
"this",
"->",
"model",
"[",
"'is_listified'",
"]",
"=",
"$",
"listified",
";",
"$",
"this",
"->",
"model",
"[",
"'hidden'",
"]",
"=",
"$",
"this",
"->",
"overrideHidden",
";",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.casts'",
",",
"[",
"]",
")",
";",
"}"
] |
Prepares override cache for current model being assembled
|
[
"Prepares",
"override",
"cache",
"for",
"current",
"model",
"being",
"assembled"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L223-L279
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.processModuleFields
|
protected function processModuleFields()
{
$overrideCasts = array_get($this->overrides, 'attributes.casts', []);
$removeCasts = array_get($this->overrides, 'attributes.casts-remove', []);
foreach ($this->module['fields'] as $fieldId => $fieldData) {
$attributeName = $this->normalizeDb($fieldData['name']);
$relationName = camel_case($attributeName);
switch ($fieldData['field_type_id']) {
// references
case FieldType::TYPE_REFERENCE:
case FieldType::TYPE_REFERENCE_CROSS:
case FieldType::TYPE_REFERENCE_NEGATIVE:
// add foreign key if it is different than the targeted model name
// (would break the convention) -- this is NOT necessary, since the convention
// for the CmsModel class is to use the relation name anyway!
//
// this only needs to be set if the relation name ends up being different
// from the relation name
//
// todo: so keep a close eye on the reversed relationships!
$keyName = null;
//if ($relationName !== studly_case($this->data->rawData['modules'][ $fieldData['refers_to_module'] ]['name'])) {
// $keyName = $attributeName;
//}
// attribute names with numbers in them wreak havoc on the name conversion methods
// so always add the key for those
if (preg_match('#\d#', $relationName)) {
$keyName = $attributeName;
}
// in some weird cases, cmses have been destroyed by leaving in relationships
// that do not refer to any model; these should be skipped
if (empty($fieldData['refers_to_module'])) {
$this->context->log(
"Relation '{$relationName}', field #{$fieldId} does not refer to any module, skipped.",
Generator::LOG_LEVEL_ERROR
);
break;
}
$this->model['relationships']['normal'][ $relationName ] = [
'type' => Generator::RELATIONSHIP_BELONGS_TO, // reverse of hasOne
'model' => $fieldData['refers_to_module'],
'single' => ($fieldData['value_count'] == 1),
'count' => $fieldData['value_count'], // should always be 1 for single ref
'field' => $fieldId,
'key' => $keyName,
'negative' => ($fieldData['field_type_id'] == FieldType::TYPE_REFERENCE_NEGATIVE),
'special' => CmsModel::RELATION_TYPE_MODEL,
];
if (config('pxlcms.generator.models.hide_foreign_key_attributes')) {
$this->model['hidden'][] = $attributeName;
}
break;
case FieldType::TYPE_REFERENCE_MANY:
case FieldType::TYPE_REFERENCE_AUTOSORT:
case FieldType::TYPE_REFERENCE_CHECKBOXES:
if (empty($fieldData['refers_to_module'])) {
$this->context->log(
"Relation '{$relationName}', field #{$fieldId} does not refer to any module, skipped.",
Generator::LOG_LEVEL_ERROR
);
break;
}
$this->model['relationships']['normal'][ $relationName ] = [
'type' => Generator::RELATIONSHIP_BELONGS_TO_MANY,
'model' => $fieldData['refers_to_module'],
'single' => false,
'count' => $fieldData['value_count'], // 0 for no limit
'field' => $fieldId,
'negative' => false,
'special' => CmsModel::RELATION_TYPE_MODEL,
];
break;
// special references
case FieldType::TYPE_IMAGE:
case FieldType::TYPE_IMAGE_MULTI:
$this->model['relationships']['image'][ $relationName ] = [
'type' => ($fieldData['value_count'] == 1)
? Generator::RELATIONSHIP_HAS_ONE
: Generator::RELATIONSHIP_HAS_MANY,
'single' => ($fieldData['value_count'] == 1),
'count' => $fieldData['value_count'],
'field' => $fieldId,
'translated' => (bool) $fieldData['multilingual'],
'resizes' => $this->getImageResizesForField($fieldId),
'special' => CmsModel::RELATION_TYPE_IMAGE,
];
break;
case FieldType::TYPE_FILE:
$this->model['relationships']['file'][ $relationName ] = [
'type' => ($fieldData['value_count'] == 1)
? Generator::RELATIONSHIP_HAS_ONE
: Generator::RELATIONSHIP_HAS_MANY,
'single' => ($fieldData['value_count'] == 1),
'count' => $fieldData['value_count'],
'field' => $fieldId,
'translated' => (bool) $fieldData['multilingual'],
'special' => CmsModel::RELATION_TYPE_FILE,
];
break;
case FieldType::TYPE_CHECKBOX:
$this->model['relationships']['checkbox'][ $relationName ] = [
'type' => Generator::RELATIONSHIP_HAS_MANY,
'single' => false,
'count' => $fieldData['value_count'],
'field' => $fieldId,
'special' => CmsModel::RELATION_TYPE_CHECKBOX,
];
break;
// normal fields
case FieldType::TYPE_INPUT:
case FieldType::TYPE_DROPDOWN:
case FieldType::TYPE_LABEL:
case FieldType::TYPE_COLORCODE:
case FieldType::TYPE_TEXT:
case FieldType::TYPE_TEXT_HTML_FLEX:
case FieldType::TYPE_TEXT_HTML_RAW:
case FieldType::TYPE_TEXT_HTML_FCK:
case FieldType::TYPE_TEXT_HTML_ALOHA:
case FieldType::TYPE_TEXT_LONG:
case FieldType::TYPE_BOOLEAN:
case FieldType::TYPE_INTEGER:
case FieldType::TYPE_NUMERIC:
case FieldType::TYPE_FLOAT:
case FieldType::TYPE_DATE:
case FieldType::TYPE_CUSTOM_HIDDEN:
case FieldType::TYPE_CUSTOM:
case FieldType::TYPE_SLIDER:
case FieldType::TYPE_LOCATION:
switch ($fieldData['field_type_id']) {
case FieldType::TYPE_BOOLEAN:
$this->model['casts'][ $attributeName ] = 'boolean';
break;
case FieldType::TYPE_INTEGER:
case FieldType::TYPE_SLIDER:
$this->model['casts'][ $attributeName ] = 'integer';
break;
case FieldType::TYPE_NUMERIC:
case FieldType::TYPE_FLOAT:
$this->model['casts'][ $attributeName ] = 'float';
break;
case FieldType::TYPE_DATE:
if ( ! array_key_exists($attributeName, $overrideCasts)) {
$this->model['dates'][] = $attributeName;
}
break;
case FieldType::TYPE_LOCATION:
$this->model['casts'][ $attributeName ] = 'array';
break;
// default omitted on purpose
}
if ($fieldData['multilingual']) {
$this->model['is_translated'] = true;
$this->model['translated_attributes'][] = $attributeName;
$this->model['translated_fillable'][] = $attributeName;
} else {
$this->model['normal_attributes'][] = $attributeName;
$this->model['normal_fillable'][] = $attributeName;
}
// if a default is set, store it
if ( $fieldData['default'] !== null
&& $fieldData['default'] !== ''
) {
$default = "'" . $fieldData['default'] . "'";
if (array_key_exists($attributeName, $this->model['casts'])) {
switch ($this->model['casts'][ $attributeName ]) {
case 'boolean':
$default = ($fieldData['default'] == '1' || $fieldData['default'] == 'true') ? 'true' : 'false';
break;
case 'integer':
case 'float':
$default = $fieldData['default'];
break;
// default omitted on purpose
}
}
$this->model['defaults'][ $attributeName ] = $default;
}
break;
case FieldType::TYPE_RANGE:
default:
throw new Exception(
"Unknown/unhandled field type {$fieldData['field_type_id']} "
. "({$fieldData['field_type_name']})"
);
}
}
// force hidden override
if (count($this->model['hidden']) && ! count($this->overrideHidden)) {
$this->model['hidden'] = array_merge(
$this->model['hidden'],
config('pxlcms.generator.models.default_hidden_fields', [])
);
}
// clear, set or remove fillable attributes by override
if (array_get($this->overrides, 'attributes.fillable-empty')) {
$this->model['normal_fillable'] = [];
$this->model['translated_fillable'] = [];
} elseif ($overrideFillable = array_get($this->overrides, 'attributes.fillable', [])) {
$this->model['normal_fillable'] = $overrideFillable;
$this->model['translated_fillable'] = [];
} elseif ($removeFillable = array_get($this->overrides, 'attributes.fillable-remove', [])) {
$this->model['normal_fillable'] = array_diff($this->model['normal_fillable'], $removeFillable);
$this->model['translated_fillable'] = array_diff($this->model['translated_fillable'], $removeFillable);
}
// force casts as overridden
foreach ($overrideCasts as $attributeName => $type) {
if (array_key_exists($attributeName, $this->model['casts'])) {
$this->model['casts'][ $attributeName ] = $type;
}
}
foreach ($removeCasts as $attributeName) {
if (array_key_exists($attributeName, $this->model['casts'])) {
unset ($this->model['casts'][ $attributeName ]);
}
}
// enable timestamps?
if ( config('pxlcms.generator.models.enable_timestamps_on_models_with_suitable_attributes')
&& in_array('created_at', $this->model['dates'])
&& in_array('updated_at', $this->model['dates'])
) {
$this->model['timestamps'] = true;
}
}
|
php
|
protected function processModuleFields()
{
$overrideCasts = array_get($this->overrides, 'attributes.casts', []);
$removeCasts = array_get($this->overrides, 'attributes.casts-remove', []);
foreach ($this->module['fields'] as $fieldId => $fieldData) {
$attributeName = $this->normalizeDb($fieldData['name']);
$relationName = camel_case($attributeName);
switch ($fieldData['field_type_id']) {
// references
case FieldType::TYPE_REFERENCE:
case FieldType::TYPE_REFERENCE_CROSS:
case FieldType::TYPE_REFERENCE_NEGATIVE:
// add foreign key if it is different than the targeted model name
// (would break the convention) -- this is NOT necessary, since the convention
// for the CmsModel class is to use the relation name anyway!
//
// this only needs to be set if the relation name ends up being different
// from the relation name
//
// todo: so keep a close eye on the reversed relationships!
$keyName = null;
//if ($relationName !== studly_case($this->data->rawData['modules'][ $fieldData['refers_to_module'] ]['name'])) {
// $keyName = $attributeName;
//}
// attribute names with numbers in them wreak havoc on the name conversion methods
// so always add the key for those
if (preg_match('#\d#', $relationName)) {
$keyName = $attributeName;
}
// in some weird cases, cmses have been destroyed by leaving in relationships
// that do not refer to any model; these should be skipped
if (empty($fieldData['refers_to_module'])) {
$this->context->log(
"Relation '{$relationName}', field #{$fieldId} does not refer to any module, skipped.",
Generator::LOG_LEVEL_ERROR
);
break;
}
$this->model['relationships']['normal'][ $relationName ] = [
'type' => Generator::RELATIONSHIP_BELONGS_TO, // reverse of hasOne
'model' => $fieldData['refers_to_module'],
'single' => ($fieldData['value_count'] == 1),
'count' => $fieldData['value_count'], // should always be 1 for single ref
'field' => $fieldId,
'key' => $keyName,
'negative' => ($fieldData['field_type_id'] == FieldType::TYPE_REFERENCE_NEGATIVE),
'special' => CmsModel::RELATION_TYPE_MODEL,
];
if (config('pxlcms.generator.models.hide_foreign_key_attributes')) {
$this->model['hidden'][] = $attributeName;
}
break;
case FieldType::TYPE_REFERENCE_MANY:
case FieldType::TYPE_REFERENCE_AUTOSORT:
case FieldType::TYPE_REFERENCE_CHECKBOXES:
if (empty($fieldData['refers_to_module'])) {
$this->context->log(
"Relation '{$relationName}', field #{$fieldId} does not refer to any module, skipped.",
Generator::LOG_LEVEL_ERROR
);
break;
}
$this->model['relationships']['normal'][ $relationName ] = [
'type' => Generator::RELATIONSHIP_BELONGS_TO_MANY,
'model' => $fieldData['refers_to_module'],
'single' => false,
'count' => $fieldData['value_count'], // 0 for no limit
'field' => $fieldId,
'negative' => false,
'special' => CmsModel::RELATION_TYPE_MODEL,
];
break;
// special references
case FieldType::TYPE_IMAGE:
case FieldType::TYPE_IMAGE_MULTI:
$this->model['relationships']['image'][ $relationName ] = [
'type' => ($fieldData['value_count'] == 1)
? Generator::RELATIONSHIP_HAS_ONE
: Generator::RELATIONSHIP_HAS_MANY,
'single' => ($fieldData['value_count'] == 1),
'count' => $fieldData['value_count'],
'field' => $fieldId,
'translated' => (bool) $fieldData['multilingual'],
'resizes' => $this->getImageResizesForField($fieldId),
'special' => CmsModel::RELATION_TYPE_IMAGE,
];
break;
case FieldType::TYPE_FILE:
$this->model['relationships']['file'][ $relationName ] = [
'type' => ($fieldData['value_count'] == 1)
? Generator::RELATIONSHIP_HAS_ONE
: Generator::RELATIONSHIP_HAS_MANY,
'single' => ($fieldData['value_count'] == 1),
'count' => $fieldData['value_count'],
'field' => $fieldId,
'translated' => (bool) $fieldData['multilingual'],
'special' => CmsModel::RELATION_TYPE_FILE,
];
break;
case FieldType::TYPE_CHECKBOX:
$this->model['relationships']['checkbox'][ $relationName ] = [
'type' => Generator::RELATIONSHIP_HAS_MANY,
'single' => false,
'count' => $fieldData['value_count'],
'field' => $fieldId,
'special' => CmsModel::RELATION_TYPE_CHECKBOX,
];
break;
// normal fields
case FieldType::TYPE_INPUT:
case FieldType::TYPE_DROPDOWN:
case FieldType::TYPE_LABEL:
case FieldType::TYPE_COLORCODE:
case FieldType::TYPE_TEXT:
case FieldType::TYPE_TEXT_HTML_FLEX:
case FieldType::TYPE_TEXT_HTML_RAW:
case FieldType::TYPE_TEXT_HTML_FCK:
case FieldType::TYPE_TEXT_HTML_ALOHA:
case FieldType::TYPE_TEXT_LONG:
case FieldType::TYPE_BOOLEAN:
case FieldType::TYPE_INTEGER:
case FieldType::TYPE_NUMERIC:
case FieldType::TYPE_FLOAT:
case FieldType::TYPE_DATE:
case FieldType::TYPE_CUSTOM_HIDDEN:
case FieldType::TYPE_CUSTOM:
case FieldType::TYPE_SLIDER:
case FieldType::TYPE_LOCATION:
switch ($fieldData['field_type_id']) {
case FieldType::TYPE_BOOLEAN:
$this->model['casts'][ $attributeName ] = 'boolean';
break;
case FieldType::TYPE_INTEGER:
case FieldType::TYPE_SLIDER:
$this->model['casts'][ $attributeName ] = 'integer';
break;
case FieldType::TYPE_NUMERIC:
case FieldType::TYPE_FLOAT:
$this->model['casts'][ $attributeName ] = 'float';
break;
case FieldType::TYPE_DATE:
if ( ! array_key_exists($attributeName, $overrideCasts)) {
$this->model['dates'][] = $attributeName;
}
break;
case FieldType::TYPE_LOCATION:
$this->model['casts'][ $attributeName ] = 'array';
break;
// default omitted on purpose
}
if ($fieldData['multilingual']) {
$this->model['is_translated'] = true;
$this->model['translated_attributes'][] = $attributeName;
$this->model['translated_fillable'][] = $attributeName;
} else {
$this->model['normal_attributes'][] = $attributeName;
$this->model['normal_fillable'][] = $attributeName;
}
// if a default is set, store it
if ( $fieldData['default'] !== null
&& $fieldData['default'] !== ''
) {
$default = "'" . $fieldData['default'] . "'";
if (array_key_exists($attributeName, $this->model['casts'])) {
switch ($this->model['casts'][ $attributeName ]) {
case 'boolean':
$default = ($fieldData['default'] == '1' || $fieldData['default'] == 'true') ? 'true' : 'false';
break;
case 'integer':
case 'float':
$default = $fieldData['default'];
break;
// default omitted on purpose
}
}
$this->model['defaults'][ $attributeName ] = $default;
}
break;
case FieldType::TYPE_RANGE:
default:
throw new Exception(
"Unknown/unhandled field type {$fieldData['field_type_id']} "
. "({$fieldData['field_type_name']})"
);
}
}
// force hidden override
if (count($this->model['hidden']) && ! count($this->overrideHidden)) {
$this->model['hidden'] = array_merge(
$this->model['hidden'],
config('pxlcms.generator.models.default_hidden_fields', [])
);
}
// clear, set or remove fillable attributes by override
if (array_get($this->overrides, 'attributes.fillable-empty')) {
$this->model['normal_fillable'] = [];
$this->model['translated_fillable'] = [];
} elseif ($overrideFillable = array_get($this->overrides, 'attributes.fillable', [])) {
$this->model['normal_fillable'] = $overrideFillable;
$this->model['translated_fillable'] = [];
} elseif ($removeFillable = array_get($this->overrides, 'attributes.fillable-remove', [])) {
$this->model['normal_fillable'] = array_diff($this->model['normal_fillable'], $removeFillable);
$this->model['translated_fillable'] = array_diff($this->model['translated_fillable'], $removeFillable);
}
// force casts as overridden
foreach ($overrideCasts as $attributeName => $type) {
if (array_key_exists($attributeName, $this->model['casts'])) {
$this->model['casts'][ $attributeName ] = $type;
}
}
foreach ($removeCasts as $attributeName) {
if (array_key_exists($attributeName, $this->model['casts'])) {
unset ($this->model['casts'][ $attributeName ]);
}
}
// enable timestamps?
if ( config('pxlcms.generator.models.enable_timestamps_on_models_with_suitable_attributes')
&& in_array('created_at', $this->model['dates'])
&& in_array('updated_at', $this->model['dates'])
) {
$this->model['timestamps'] = true;
}
}
|
[
"protected",
"function",
"processModuleFields",
"(",
")",
"{",
"$",
"overrideCasts",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.casts'",
",",
"[",
"]",
")",
";",
"$",
"removeCasts",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.casts-remove'",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"module",
"[",
"'fields'",
"]",
"as",
"$",
"fieldId",
"=>",
"$",
"fieldData",
")",
"{",
"$",
"attributeName",
"=",
"$",
"this",
"->",
"normalizeDb",
"(",
"$",
"fieldData",
"[",
"'name'",
"]",
")",
";",
"$",
"relationName",
"=",
"camel_case",
"(",
"$",
"attributeName",
")",
";",
"switch",
"(",
"$",
"fieldData",
"[",
"'field_type_id'",
"]",
")",
"{",
"// references",
"case",
"FieldType",
"::",
"TYPE_REFERENCE",
":",
"case",
"FieldType",
"::",
"TYPE_REFERENCE_CROSS",
":",
"case",
"FieldType",
"::",
"TYPE_REFERENCE_NEGATIVE",
":",
"// add foreign key if it is different than the targeted model name",
"// (would break the convention) -- this is NOT necessary, since the convention",
"// for the CmsModel class is to use the relation name anyway!",
"//",
"// this only needs to be set if the relation name ends up being different",
"// from the relation name",
"//",
"// todo: so keep a close eye on the reversed relationships!",
"$",
"keyName",
"=",
"null",
";",
"//if ($relationName !== studly_case($this->data->rawData['modules'][ $fieldData['refers_to_module'] ]['name'])) {",
"// $keyName = $attributeName;",
"//}",
"// attribute names with numbers in them wreak havoc on the name conversion methods",
"// so always add the key for those",
"if",
"(",
"preg_match",
"(",
"'#\\d#'",
",",
"$",
"relationName",
")",
")",
"{",
"$",
"keyName",
"=",
"$",
"attributeName",
";",
"}",
"// in some weird cases, cmses have been destroyed by leaving in relationships",
"// that do not refer to any model; these should be skipped",
"if",
"(",
"empty",
"(",
"$",
"fieldData",
"[",
"'refers_to_module'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Relation '{$relationName}', field #{$fieldId} does not refer to any module, skipped.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"break",
";",
"}",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"'normal'",
"]",
"[",
"$",
"relationName",
"]",
"=",
"[",
"'type'",
"=>",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO",
",",
"// reverse of hasOne",
"'model'",
"=>",
"$",
"fieldData",
"[",
"'refers_to_module'",
"]",
",",
"'single'",
"=>",
"(",
"$",
"fieldData",
"[",
"'value_count'",
"]",
"==",
"1",
")",
",",
"'count'",
"=>",
"$",
"fieldData",
"[",
"'value_count'",
"]",
",",
"// should always be 1 for single ref",
"'field'",
"=>",
"$",
"fieldId",
",",
"'key'",
"=>",
"$",
"keyName",
",",
"'negative'",
"=>",
"(",
"$",
"fieldData",
"[",
"'field_type_id'",
"]",
"==",
"FieldType",
"::",
"TYPE_REFERENCE_NEGATIVE",
")",
",",
"'special'",
"=>",
"CmsModel",
"::",
"RELATION_TYPE_MODEL",
",",
"]",
";",
"if",
"(",
"config",
"(",
"'pxlcms.generator.models.hide_foreign_key_attributes'",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'hidden'",
"]",
"[",
"]",
"=",
"$",
"attributeName",
";",
"}",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_REFERENCE_MANY",
":",
"case",
"FieldType",
"::",
"TYPE_REFERENCE_AUTOSORT",
":",
"case",
"FieldType",
"::",
"TYPE_REFERENCE_CHECKBOXES",
":",
"if",
"(",
"empty",
"(",
"$",
"fieldData",
"[",
"'refers_to_module'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Relation '{$relationName}', field #{$fieldId} does not refer to any module, skipped.\"",
",",
"Generator",
"::",
"LOG_LEVEL_ERROR",
")",
";",
"break",
";",
"}",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"'normal'",
"]",
"[",
"$",
"relationName",
"]",
"=",
"[",
"'type'",
"=>",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO_MANY",
",",
"'model'",
"=>",
"$",
"fieldData",
"[",
"'refers_to_module'",
"]",
",",
"'single'",
"=>",
"false",
",",
"'count'",
"=>",
"$",
"fieldData",
"[",
"'value_count'",
"]",
",",
"// 0 for no limit",
"'field'",
"=>",
"$",
"fieldId",
",",
"'negative'",
"=>",
"false",
",",
"'special'",
"=>",
"CmsModel",
"::",
"RELATION_TYPE_MODEL",
",",
"]",
";",
"break",
";",
"// special references",
"case",
"FieldType",
"::",
"TYPE_IMAGE",
":",
"case",
"FieldType",
"::",
"TYPE_IMAGE_MULTI",
":",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"'image'",
"]",
"[",
"$",
"relationName",
"]",
"=",
"[",
"'type'",
"=>",
"(",
"$",
"fieldData",
"[",
"'value_count'",
"]",
"==",
"1",
")",
"?",
"Generator",
"::",
"RELATIONSHIP_HAS_ONE",
":",
"Generator",
"::",
"RELATIONSHIP_HAS_MANY",
",",
"'single'",
"=>",
"(",
"$",
"fieldData",
"[",
"'value_count'",
"]",
"==",
"1",
")",
",",
"'count'",
"=>",
"$",
"fieldData",
"[",
"'value_count'",
"]",
",",
"'field'",
"=>",
"$",
"fieldId",
",",
"'translated'",
"=>",
"(",
"bool",
")",
"$",
"fieldData",
"[",
"'multilingual'",
"]",
",",
"'resizes'",
"=>",
"$",
"this",
"->",
"getImageResizesForField",
"(",
"$",
"fieldId",
")",
",",
"'special'",
"=>",
"CmsModel",
"::",
"RELATION_TYPE_IMAGE",
",",
"]",
";",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_FILE",
":",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"'file'",
"]",
"[",
"$",
"relationName",
"]",
"=",
"[",
"'type'",
"=>",
"(",
"$",
"fieldData",
"[",
"'value_count'",
"]",
"==",
"1",
")",
"?",
"Generator",
"::",
"RELATIONSHIP_HAS_ONE",
":",
"Generator",
"::",
"RELATIONSHIP_HAS_MANY",
",",
"'single'",
"=>",
"(",
"$",
"fieldData",
"[",
"'value_count'",
"]",
"==",
"1",
")",
",",
"'count'",
"=>",
"$",
"fieldData",
"[",
"'value_count'",
"]",
",",
"'field'",
"=>",
"$",
"fieldId",
",",
"'translated'",
"=>",
"(",
"bool",
")",
"$",
"fieldData",
"[",
"'multilingual'",
"]",
",",
"'special'",
"=>",
"CmsModel",
"::",
"RELATION_TYPE_FILE",
",",
"]",
";",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_CHECKBOX",
":",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"'checkbox'",
"]",
"[",
"$",
"relationName",
"]",
"=",
"[",
"'type'",
"=>",
"Generator",
"::",
"RELATIONSHIP_HAS_MANY",
",",
"'single'",
"=>",
"false",
",",
"'count'",
"=>",
"$",
"fieldData",
"[",
"'value_count'",
"]",
",",
"'field'",
"=>",
"$",
"fieldId",
",",
"'special'",
"=>",
"CmsModel",
"::",
"RELATION_TYPE_CHECKBOX",
",",
"]",
";",
"break",
";",
"// normal fields",
"case",
"FieldType",
"::",
"TYPE_INPUT",
":",
"case",
"FieldType",
"::",
"TYPE_DROPDOWN",
":",
"case",
"FieldType",
"::",
"TYPE_LABEL",
":",
"case",
"FieldType",
"::",
"TYPE_COLORCODE",
":",
"case",
"FieldType",
"::",
"TYPE_TEXT",
":",
"case",
"FieldType",
"::",
"TYPE_TEXT_HTML_FLEX",
":",
"case",
"FieldType",
"::",
"TYPE_TEXT_HTML_RAW",
":",
"case",
"FieldType",
"::",
"TYPE_TEXT_HTML_FCK",
":",
"case",
"FieldType",
"::",
"TYPE_TEXT_HTML_ALOHA",
":",
"case",
"FieldType",
"::",
"TYPE_TEXT_LONG",
":",
"case",
"FieldType",
"::",
"TYPE_BOOLEAN",
":",
"case",
"FieldType",
"::",
"TYPE_INTEGER",
":",
"case",
"FieldType",
"::",
"TYPE_NUMERIC",
":",
"case",
"FieldType",
"::",
"TYPE_FLOAT",
":",
"case",
"FieldType",
"::",
"TYPE_DATE",
":",
"case",
"FieldType",
"::",
"TYPE_CUSTOM_HIDDEN",
":",
"case",
"FieldType",
"::",
"TYPE_CUSTOM",
":",
"case",
"FieldType",
"::",
"TYPE_SLIDER",
":",
"case",
"FieldType",
"::",
"TYPE_LOCATION",
":",
"switch",
"(",
"$",
"fieldData",
"[",
"'field_type_id'",
"]",
")",
"{",
"case",
"FieldType",
"::",
"TYPE_BOOLEAN",
":",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
"=",
"'boolean'",
";",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_INTEGER",
":",
"case",
"FieldType",
"::",
"TYPE_SLIDER",
":",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
"=",
"'integer'",
";",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_NUMERIC",
":",
"case",
"FieldType",
"::",
"TYPE_FLOAT",
":",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
"=",
"'float'",
";",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_DATE",
":",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"attributeName",
",",
"$",
"overrideCasts",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'dates'",
"]",
"[",
"]",
"=",
"$",
"attributeName",
";",
"}",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_LOCATION",
":",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
"=",
"'array'",
";",
"break",
";",
"// default omitted on purpose",
"}",
"if",
"(",
"$",
"fieldData",
"[",
"'multilingual'",
"]",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'is_translated'",
"]",
"=",
"true",
";",
"$",
"this",
"->",
"model",
"[",
"'translated_attributes'",
"]",
"[",
"]",
"=",
"$",
"attributeName",
";",
"$",
"this",
"->",
"model",
"[",
"'translated_fillable'",
"]",
"[",
"]",
"=",
"$",
"attributeName",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"model",
"[",
"'normal_attributes'",
"]",
"[",
"]",
"=",
"$",
"attributeName",
";",
"$",
"this",
"->",
"model",
"[",
"'normal_fillable'",
"]",
"[",
"]",
"=",
"$",
"attributeName",
";",
"}",
"// if a default is set, store it",
"if",
"(",
"$",
"fieldData",
"[",
"'default'",
"]",
"!==",
"null",
"&&",
"$",
"fieldData",
"[",
"'default'",
"]",
"!==",
"''",
")",
"{",
"$",
"default",
"=",
"\"'\"",
".",
"$",
"fieldData",
"[",
"'default'",
"]",
".",
"\"'\"",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"attributeName",
",",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
")",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
")",
"{",
"case",
"'boolean'",
":",
"$",
"default",
"=",
"(",
"$",
"fieldData",
"[",
"'default'",
"]",
"==",
"'1'",
"||",
"$",
"fieldData",
"[",
"'default'",
"]",
"==",
"'true'",
")",
"?",
"'true'",
":",
"'false'",
";",
"break",
";",
"case",
"'integer'",
":",
"case",
"'float'",
":",
"$",
"default",
"=",
"$",
"fieldData",
"[",
"'default'",
"]",
";",
"break",
";",
"// default omitted on purpose",
"}",
"}",
"$",
"this",
"->",
"model",
"[",
"'defaults'",
"]",
"[",
"$",
"attributeName",
"]",
"=",
"$",
"default",
";",
"}",
"break",
";",
"case",
"FieldType",
"::",
"TYPE_RANGE",
":",
"default",
":",
"throw",
"new",
"Exception",
"(",
"\"Unknown/unhandled field type {$fieldData['field_type_id']} \"",
".",
"\"({$fieldData['field_type_name']})\"",
")",
";",
"}",
"}",
"// force hidden override",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"model",
"[",
"'hidden'",
"]",
")",
"&&",
"!",
"count",
"(",
"$",
"this",
"->",
"overrideHidden",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'hidden'",
"]",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"model",
"[",
"'hidden'",
"]",
",",
"config",
"(",
"'pxlcms.generator.models.default_hidden_fields'",
",",
"[",
"]",
")",
")",
";",
"}",
"// clear, set or remove fillable attributes by override",
"if",
"(",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.fillable-empty'",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'normal_fillable'",
"]",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"model",
"[",
"'translated_fillable'",
"]",
"=",
"[",
"]",
";",
"}",
"elseif",
"(",
"$",
"overrideFillable",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.fillable'",
",",
"[",
"]",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'normal_fillable'",
"]",
"=",
"$",
"overrideFillable",
";",
"$",
"this",
"->",
"model",
"[",
"'translated_fillable'",
"]",
"=",
"[",
"]",
";",
"}",
"elseif",
"(",
"$",
"removeFillable",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'attributes.fillable-remove'",
",",
"[",
"]",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'normal_fillable'",
"]",
"=",
"array_diff",
"(",
"$",
"this",
"->",
"model",
"[",
"'normal_fillable'",
"]",
",",
"$",
"removeFillable",
")",
";",
"$",
"this",
"->",
"model",
"[",
"'translated_fillable'",
"]",
"=",
"array_diff",
"(",
"$",
"this",
"->",
"model",
"[",
"'translated_fillable'",
"]",
",",
"$",
"removeFillable",
")",
";",
"}",
"// force casts as overridden",
"foreach",
"(",
"$",
"overrideCasts",
"as",
"$",
"attributeName",
"=>",
"$",
"type",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"attributeName",
",",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
"=",
"$",
"type",
";",
"}",
"}",
"foreach",
"(",
"$",
"removeCasts",
"as",
"$",
"attributeName",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"attributeName",
",",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"model",
"[",
"'casts'",
"]",
"[",
"$",
"attributeName",
"]",
")",
";",
"}",
"}",
"// enable timestamps?",
"if",
"(",
"config",
"(",
"'pxlcms.generator.models.enable_timestamps_on_models_with_suitable_attributes'",
")",
"&&",
"in_array",
"(",
"'created_at'",
",",
"$",
"this",
"->",
"model",
"[",
"'dates'",
"]",
")",
"&&",
"in_array",
"(",
"'updated_at'",
",",
"$",
"this",
"->",
"model",
"[",
"'dates'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'timestamps'",
"]",
"=",
"true",
";",
"}",
"}"
] |
Processes field data from the module
|
[
"Processes",
"field",
"data",
"from",
"the",
"module"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L284-L559
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.applyOverridesForRelationships
|
protected function applyOverridesForRelationships()
{
$overrides = array_get($this->overrides, 'relationships');
if (empty($overrides)) return;
$removeRelations = [];
foreach ($overrides as $overrideName => $override) {
// find the relationship
foreach (['normal', 'image', 'file', 'checkbox'] as $type) {
foreach ($this->model['relationships'][ $type ] as $name => &$relationData) {
if ($name === $overrideName) {
// apply overrides and change the model data
$newName = array_get($override, 'name');
$preventReverse = array_get($override, 'prevent_reverse', false);
$reverseName = array_get($override, 'reverse_name', false);
if ($preventReverse) {
$relationData['prevent_reverse'] = true;
}
if ( ! empty($reverseName)) {
$relationData['reverse_name'] = $reverseName;
}
if ( ! empty($newName)) {
$this->model['relationships'][ $type ][ $newName ] = $relationData;
$removeRelations[] = $type . '.' . $overrideName;
$removeRelations = array_diff($removeRelations, [ $newName ]);
}
$this->context->log(
"Override applied for relationship {$overrideName} on module {$this->moduleId}."
);
break 2;
}
}
}
}
unset($relationData);
// remove now 'moved' relationships
array_forget($this->model['relationships'], $removeRelations);
}
|
php
|
protected function applyOverridesForRelationships()
{
$overrides = array_get($this->overrides, 'relationships');
if (empty($overrides)) return;
$removeRelations = [];
foreach ($overrides as $overrideName => $override) {
// find the relationship
foreach (['normal', 'image', 'file', 'checkbox'] as $type) {
foreach ($this->model['relationships'][ $type ] as $name => &$relationData) {
if ($name === $overrideName) {
// apply overrides and change the model data
$newName = array_get($override, 'name');
$preventReverse = array_get($override, 'prevent_reverse', false);
$reverseName = array_get($override, 'reverse_name', false);
if ($preventReverse) {
$relationData['prevent_reverse'] = true;
}
if ( ! empty($reverseName)) {
$relationData['reverse_name'] = $reverseName;
}
if ( ! empty($newName)) {
$this->model['relationships'][ $type ][ $newName ] = $relationData;
$removeRelations[] = $type . '.' . $overrideName;
$removeRelations = array_diff($removeRelations, [ $newName ]);
}
$this->context->log(
"Override applied for relationship {$overrideName} on module {$this->moduleId}."
);
break 2;
}
}
}
}
unset($relationData);
// remove now 'moved' relationships
array_forget($this->model['relationships'], $removeRelations);
}
|
[
"protected",
"function",
"applyOverridesForRelationships",
"(",
")",
"{",
"$",
"overrides",
"=",
"array_get",
"(",
"$",
"this",
"->",
"overrides",
",",
"'relationships'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"overrides",
")",
")",
"return",
";",
"$",
"removeRelations",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"overrides",
"as",
"$",
"overrideName",
"=>",
"$",
"override",
")",
"{",
"// find the relationship",
"foreach",
"(",
"[",
"'normal'",
",",
"'image'",
",",
"'file'",
",",
"'checkbox'",
"]",
"as",
"$",
"type",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"$",
"type",
"]",
"as",
"$",
"name",
"=>",
"&",
"$",
"relationData",
")",
"{",
"if",
"(",
"$",
"name",
"===",
"$",
"overrideName",
")",
"{",
"// apply overrides and change the model data",
"$",
"newName",
"=",
"array_get",
"(",
"$",
"override",
",",
"'name'",
")",
";",
"$",
"preventReverse",
"=",
"array_get",
"(",
"$",
"override",
",",
"'prevent_reverse'",
",",
"false",
")",
";",
"$",
"reverseName",
"=",
"array_get",
"(",
"$",
"override",
",",
"'reverse_name'",
",",
"false",
")",
";",
"if",
"(",
"$",
"preventReverse",
")",
"{",
"$",
"relationData",
"[",
"'prevent_reverse'",
"]",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"reverseName",
")",
")",
"{",
"$",
"relationData",
"[",
"'reverse_name'",
"]",
"=",
"$",
"reverseName",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"newName",
")",
")",
"{",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
"[",
"$",
"type",
"]",
"[",
"$",
"newName",
"]",
"=",
"$",
"relationData",
";",
"$",
"removeRelations",
"[",
"]",
"=",
"$",
"type",
".",
"'.'",
".",
"$",
"overrideName",
";",
"$",
"removeRelations",
"=",
"array_diff",
"(",
"$",
"removeRelations",
",",
"[",
"$",
"newName",
"]",
")",
";",
"}",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Override applied for relationship {$overrideName} on module {$this->moduleId}.\"",
")",
";",
"break",
"2",
";",
"}",
"}",
"}",
"}",
"unset",
"(",
"$",
"relationData",
")",
";",
"// remove now 'moved' relationships",
"array_forget",
"(",
"$",
"this",
"->",
"model",
"[",
"'relationships'",
"]",
",",
"$",
"removeRelations",
")",
";",
"}"
] |
Applies overrides set in the config for analyzed relationships
|
[
"Applies",
"overrides",
"set",
"in",
"the",
"config",
"for",
"analyzed",
"relationships"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L564-L618
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.generateReversedRelationships
|
protected function generateReversedRelationships()
{
foreach ($this->context->output['models'] as $modelFromKey => $modelFrom) {
foreach ($modelFrom['relationships']['normal'] as $relationName => $relationship) {
// skip negative references for now, don't reverse them
if ($relationship['negative']) {
$this->context->log(
"Skipped negative relationship for reversing (model: {$modelFromKey} to "
. "{$relationship['model']}, field: {$relationship['field']})"
);
continue;
}
// also skip any relationship we've overridden not to reverse
if (array_get($relationship, 'prevent_reverse')) {
$this->context->log(
"Skipped relationship for reversing due to override (model: {$modelFromKey} to "
. "{$relationship['model']}, field: {$relationship['field']})"
);
continue;
}
// special case, referencing model is itself
$selfReference = ($modelFromKey == $relationship['model']);
$partOfMultiple = $this->multipleBelongsToRelationsBetweenModels($modelFromKey, $relationship['model']);
$reverseType = null;
$reverseCount = 0;
$reverseForeignKey = null;
// For non-cms_m_references relations, we need to be careful about
// foreign keys not following the expected laravel convention
// since they expect the name to be based on the model names, whereas
// it is actually defined by the field name in the CMS module,
// which conforms to the relation name of the OPPOSITE relation.
//
// Too tricky to determine automatically, so force a foreign key parameter
// if required.
if ($relationship['type'] !== Generator::RELATIONSHIP_BELONGS_TO_MANY) {
if (array_get($relationship, 'key')) {
$reverseForeignKey = $relationship['key'];
} elseif ($relationName !== camel_case($this->context->output['models'][ $relationship['model'] ]['name'])) {
$reverseForeignKey = $this->normalizeDb($relationName);
}
}
// determine type and one/many (count) for reverse relationship
switch ($relationship['type']) {
case Generator::RELATIONSHIP_HAS_ONE:
case Generator::RELATIONSHIP_HAS_MANY:
$reverseType = Generator::RELATIONSHIP_BELONGS_TO;
break;
case Generator::RELATIONSHIP_BELONGS_TO:
// for single-entry modules, a hasOne will do
if ($this->data->rawData['modules'][ $modelFromKey ]['max_entries'] == 1) {
$reverseType = Generator::RELATIONSHIP_HAS_ONE;
$reverseCount = 1;
} else {
$reverseType = Generator::RELATIONSHIP_HAS_MANY;
}
break;
case Generator::RELATIONSHIP_BELONGS_TO_MANY:
$reverseType = Generator::RELATIONSHIP_BELONGS_TO_MANY;
break;
// default omitted on purpose
}
// pluralize the name if configured to and it's a to many relationship
$pluralizeName = (
$reverseCount !== 1
&& config('pxlcms.generator.models.pluralize_reversed_relationship_names')
&& ! $partOfMultiple
&& ( ! $selfReference
|| config('pxlcms.generator.models.pluralize_reversed_relationship_names_for_self_reference')
)
);
// name of the relationship reversed
// default is name of the model referred to
$baseName = $relationName;
if ($partOfMultiple) {
$baseName = camel_case($modelFrom['name']) . ucfirst($baseName);
} elseif ( ! $selfReference) {
$baseName = $modelFrom['name'];
}
if ($pluralizeName) {
$baseName = ($this->context->dutchMode) ? $this->dutchPluralize($baseName) : str_plural($baseName);
}
if (array_get($relationship, 'reverse_name')) {
// hard override is applied without any checks
$reverseName = $relationship['reverse_name'];
} elseif ($selfReference || $partOfMultiple) {
// self-referencing is an exception, since using the model name won't be useful
// part of multiple belongsto is an exception, to avoid duplicates
$reverseName = $baseName
. config('pxlcms.generator.models.relationship_reverse_postfix', 'Reverse');
} else {
$reverseName = camel_case($baseName);
}
$reverseNameSnakeCase = snake_case($reverseName);
// if already taken by an attribute, add custom string
if ( in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['normal_attributes'])
|| in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['translated_attributes'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['normal'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['image'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['file'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['checkbox'])
) {
$reverseName .= config('pxlcms.generator.models.relationship_fallback_postfix', 'Reference');
}
$this->context->output['models'][ $relationship['model'] ]['relationships']['reverse'][ $reverseName ] = [
'type' => $reverseType,
'model' => $modelFromKey,
'single' => ($reverseCount == 1),
'count' => $reverseCount,
'field' => $relationship['field'],
'key' => $reverseForeignKey,
'negative' => false,
];
}
}
}
|
php
|
protected function generateReversedRelationships()
{
foreach ($this->context->output['models'] as $modelFromKey => $modelFrom) {
foreach ($modelFrom['relationships']['normal'] as $relationName => $relationship) {
// skip negative references for now, don't reverse them
if ($relationship['negative']) {
$this->context->log(
"Skipped negative relationship for reversing (model: {$modelFromKey} to "
. "{$relationship['model']}, field: {$relationship['field']})"
);
continue;
}
// also skip any relationship we've overridden not to reverse
if (array_get($relationship, 'prevent_reverse')) {
$this->context->log(
"Skipped relationship for reversing due to override (model: {$modelFromKey} to "
. "{$relationship['model']}, field: {$relationship['field']})"
);
continue;
}
// special case, referencing model is itself
$selfReference = ($modelFromKey == $relationship['model']);
$partOfMultiple = $this->multipleBelongsToRelationsBetweenModels($modelFromKey, $relationship['model']);
$reverseType = null;
$reverseCount = 0;
$reverseForeignKey = null;
// For non-cms_m_references relations, we need to be careful about
// foreign keys not following the expected laravel convention
// since they expect the name to be based on the model names, whereas
// it is actually defined by the field name in the CMS module,
// which conforms to the relation name of the OPPOSITE relation.
//
// Too tricky to determine automatically, so force a foreign key parameter
// if required.
if ($relationship['type'] !== Generator::RELATIONSHIP_BELONGS_TO_MANY) {
if (array_get($relationship, 'key')) {
$reverseForeignKey = $relationship['key'];
} elseif ($relationName !== camel_case($this->context->output['models'][ $relationship['model'] ]['name'])) {
$reverseForeignKey = $this->normalizeDb($relationName);
}
}
// determine type and one/many (count) for reverse relationship
switch ($relationship['type']) {
case Generator::RELATIONSHIP_HAS_ONE:
case Generator::RELATIONSHIP_HAS_MANY:
$reverseType = Generator::RELATIONSHIP_BELONGS_TO;
break;
case Generator::RELATIONSHIP_BELONGS_TO:
// for single-entry modules, a hasOne will do
if ($this->data->rawData['modules'][ $modelFromKey ]['max_entries'] == 1) {
$reverseType = Generator::RELATIONSHIP_HAS_ONE;
$reverseCount = 1;
} else {
$reverseType = Generator::RELATIONSHIP_HAS_MANY;
}
break;
case Generator::RELATIONSHIP_BELONGS_TO_MANY:
$reverseType = Generator::RELATIONSHIP_BELONGS_TO_MANY;
break;
// default omitted on purpose
}
// pluralize the name if configured to and it's a to many relationship
$pluralizeName = (
$reverseCount !== 1
&& config('pxlcms.generator.models.pluralize_reversed_relationship_names')
&& ! $partOfMultiple
&& ( ! $selfReference
|| config('pxlcms.generator.models.pluralize_reversed_relationship_names_for_self_reference')
)
);
// name of the relationship reversed
// default is name of the model referred to
$baseName = $relationName;
if ($partOfMultiple) {
$baseName = camel_case($modelFrom['name']) . ucfirst($baseName);
} elseif ( ! $selfReference) {
$baseName = $modelFrom['name'];
}
if ($pluralizeName) {
$baseName = ($this->context->dutchMode) ? $this->dutchPluralize($baseName) : str_plural($baseName);
}
if (array_get($relationship, 'reverse_name')) {
// hard override is applied without any checks
$reverseName = $relationship['reverse_name'];
} elseif ($selfReference || $partOfMultiple) {
// self-referencing is an exception, since using the model name won't be useful
// part of multiple belongsto is an exception, to avoid duplicates
$reverseName = $baseName
. config('pxlcms.generator.models.relationship_reverse_postfix', 'Reverse');
} else {
$reverseName = camel_case($baseName);
}
$reverseNameSnakeCase = snake_case($reverseName);
// if already taken by an attribute, add custom string
if ( in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['normal_attributes'])
|| in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['translated_attributes'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['normal'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['image'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['file'])
|| in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['checkbox'])
) {
$reverseName .= config('pxlcms.generator.models.relationship_fallback_postfix', 'Reference');
}
$this->context->output['models'][ $relationship['model'] ]['relationships']['reverse'][ $reverseName ] = [
'type' => $reverseType,
'model' => $modelFromKey,
'single' => ($reverseCount == 1),
'count' => $reverseCount,
'field' => $relationship['field'],
'key' => $reverseForeignKey,
'negative' => false,
];
}
}
}
|
[
"protected",
"function",
"generateReversedRelationships",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"as",
"$",
"modelFromKey",
"=>",
"$",
"modelFrom",
")",
"{",
"foreach",
"(",
"$",
"modelFrom",
"[",
"'relationships'",
"]",
"[",
"'normal'",
"]",
"as",
"$",
"relationName",
"=>",
"$",
"relationship",
")",
"{",
"// skip negative references for now, don't reverse them",
"if",
"(",
"$",
"relationship",
"[",
"'negative'",
"]",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Skipped negative relationship for reversing (model: {$modelFromKey} to \"",
".",
"\"{$relationship['model']}, field: {$relationship['field']})\"",
")",
";",
"continue",
";",
"}",
"// also skip any relationship we've overridden not to reverse",
"if",
"(",
"array_get",
"(",
"$",
"relationship",
",",
"'prevent_reverse'",
")",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"log",
"(",
"\"Skipped relationship for reversing due to override (model: {$modelFromKey} to \"",
".",
"\"{$relationship['model']}, field: {$relationship['field']})\"",
")",
";",
"continue",
";",
"}",
"// special case, referencing model is itself",
"$",
"selfReference",
"=",
"(",
"$",
"modelFromKey",
"==",
"$",
"relationship",
"[",
"'model'",
"]",
")",
";",
"$",
"partOfMultiple",
"=",
"$",
"this",
"->",
"multipleBelongsToRelationsBetweenModels",
"(",
"$",
"modelFromKey",
",",
"$",
"relationship",
"[",
"'model'",
"]",
")",
";",
"$",
"reverseType",
"=",
"null",
";",
"$",
"reverseCount",
"=",
"0",
";",
"$",
"reverseForeignKey",
"=",
"null",
";",
"// For non-cms_m_references relations, we need to be careful about",
"// foreign keys not following the expected laravel convention",
"// since they expect the name to be based on the model names, whereas",
"// it is actually defined by the field name in the CMS module,",
"// which conforms to the relation name of the OPPOSITE relation.",
"//",
"// Too tricky to determine automatically, so force a foreign key parameter",
"// if required.",
"if",
"(",
"$",
"relationship",
"[",
"'type'",
"]",
"!==",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO_MANY",
")",
"{",
"if",
"(",
"array_get",
"(",
"$",
"relationship",
",",
"'key'",
")",
")",
"{",
"$",
"reverseForeignKey",
"=",
"$",
"relationship",
"[",
"'key'",
"]",
";",
"}",
"elseif",
"(",
"$",
"relationName",
"!==",
"camel_case",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'name'",
"]",
")",
")",
"{",
"$",
"reverseForeignKey",
"=",
"$",
"this",
"->",
"normalizeDb",
"(",
"$",
"relationName",
")",
";",
"}",
"}",
"// determine type and one/many (count) for reverse relationship",
"switch",
"(",
"$",
"relationship",
"[",
"'type'",
"]",
")",
"{",
"case",
"Generator",
"::",
"RELATIONSHIP_HAS_ONE",
":",
"case",
"Generator",
"::",
"RELATIONSHIP_HAS_MANY",
":",
"$",
"reverseType",
"=",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO",
";",
"break",
";",
"case",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO",
":",
"// for single-entry modules, a hasOne will do",
"if",
"(",
"$",
"this",
"->",
"data",
"->",
"rawData",
"[",
"'modules'",
"]",
"[",
"$",
"modelFromKey",
"]",
"[",
"'max_entries'",
"]",
"==",
"1",
")",
"{",
"$",
"reverseType",
"=",
"Generator",
"::",
"RELATIONSHIP_HAS_ONE",
";",
"$",
"reverseCount",
"=",
"1",
";",
"}",
"else",
"{",
"$",
"reverseType",
"=",
"Generator",
"::",
"RELATIONSHIP_HAS_MANY",
";",
"}",
"break",
";",
"case",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO_MANY",
":",
"$",
"reverseType",
"=",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO_MANY",
";",
"break",
";",
"// default omitted on purpose",
"}",
"// pluralize the name if configured to and it's a to many relationship",
"$",
"pluralizeName",
"=",
"(",
"$",
"reverseCount",
"!==",
"1",
"&&",
"config",
"(",
"'pxlcms.generator.models.pluralize_reversed_relationship_names'",
")",
"&&",
"!",
"$",
"partOfMultiple",
"&&",
"(",
"!",
"$",
"selfReference",
"||",
"config",
"(",
"'pxlcms.generator.models.pluralize_reversed_relationship_names_for_self_reference'",
")",
")",
")",
";",
"// name of the relationship reversed",
"// default is name of the model referred to",
"$",
"baseName",
"=",
"$",
"relationName",
";",
"if",
"(",
"$",
"partOfMultiple",
")",
"{",
"$",
"baseName",
"=",
"camel_case",
"(",
"$",
"modelFrom",
"[",
"'name'",
"]",
")",
".",
"ucfirst",
"(",
"$",
"baseName",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"selfReference",
")",
"{",
"$",
"baseName",
"=",
"$",
"modelFrom",
"[",
"'name'",
"]",
";",
"}",
"if",
"(",
"$",
"pluralizeName",
")",
"{",
"$",
"baseName",
"=",
"(",
"$",
"this",
"->",
"context",
"->",
"dutchMode",
")",
"?",
"$",
"this",
"->",
"dutchPluralize",
"(",
"$",
"baseName",
")",
":",
"str_plural",
"(",
"$",
"baseName",
")",
";",
"}",
"if",
"(",
"array_get",
"(",
"$",
"relationship",
",",
"'reverse_name'",
")",
")",
"{",
"// hard override is applied without any checks",
"$",
"reverseName",
"=",
"$",
"relationship",
"[",
"'reverse_name'",
"]",
";",
"}",
"elseif",
"(",
"$",
"selfReference",
"||",
"$",
"partOfMultiple",
")",
"{",
"// self-referencing is an exception, since using the model name won't be useful",
"// part of multiple belongsto is an exception, to avoid duplicates",
"$",
"reverseName",
"=",
"$",
"baseName",
".",
"config",
"(",
"'pxlcms.generator.models.relationship_reverse_postfix'",
",",
"'Reverse'",
")",
";",
"}",
"else",
"{",
"$",
"reverseName",
"=",
"camel_case",
"(",
"$",
"baseName",
")",
";",
"}",
"$",
"reverseNameSnakeCase",
"=",
"snake_case",
"(",
"$",
"reverseName",
")",
";",
"// if already taken by an attribute, add custom string",
"if",
"(",
"in_array",
"(",
"$",
"reverseNameSnakeCase",
",",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'normal_attributes'",
"]",
")",
"||",
"in_array",
"(",
"$",
"reverseNameSnakeCase",
",",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'translated_attributes'",
"]",
")",
"||",
"in_array",
"(",
"$",
"reverseName",
",",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'relationships'",
"]",
"[",
"'normal'",
"]",
")",
"||",
"in_array",
"(",
"$",
"reverseName",
",",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'relationships'",
"]",
"[",
"'image'",
"]",
")",
"||",
"in_array",
"(",
"$",
"reverseName",
",",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'relationships'",
"]",
"[",
"'file'",
"]",
")",
"||",
"in_array",
"(",
"$",
"reverseName",
",",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'relationships'",
"]",
"[",
"'checkbox'",
"]",
")",
")",
"{",
"$",
"reverseName",
".=",
"config",
"(",
"'pxlcms.generator.models.relationship_fallback_postfix'",
",",
"'Reference'",
")",
";",
"}",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"relationship",
"[",
"'model'",
"]",
"]",
"[",
"'relationships'",
"]",
"[",
"'reverse'",
"]",
"[",
"$",
"reverseName",
"]",
"=",
"[",
"'type'",
"=>",
"$",
"reverseType",
",",
"'model'",
"=>",
"$",
"modelFromKey",
",",
"'single'",
"=>",
"(",
"$",
"reverseCount",
"==",
"1",
")",
",",
"'count'",
"=>",
"$",
"reverseCount",
",",
"'field'",
"=>",
"$",
"relationship",
"[",
"'field'",
"]",
",",
"'key'",
"=>",
"$",
"reverseForeignKey",
",",
"'negative'",
"=>",
"false",
",",
"]",
";",
"}",
"}",
"}"
] |
Generates model data for reversed relationships, for all available models
|
[
"Generates",
"model",
"data",
"for",
"reversed",
"relationships",
"for",
"all",
"available",
"models"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L624-L773
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.multipleBelongsToRelationsBetweenModels
|
protected function multipleBelongsToRelationsBetweenModels($fromModuleId, $toModuleId)
{
$count = 0;
foreach ($this->context->output['models'][ $fromModuleId ]['relationships']['normal'] as $relationship) {
if ( $relationship['model'] == $toModuleId
&& $relationship['type'] == Generator::RELATIONSHIP_BELONGS_TO
&& ! array_get($relationship, 'negative')
) {
$count++;
}
}
return ($count > 1);
}
|
php
|
protected function multipleBelongsToRelationsBetweenModels($fromModuleId, $toModuleId)
{
$count = 0;
foreach ($this->context->output['models'][ $fromModuleId ]['relationships']['normal'] as $relationship) {
if ( $relationship['model'] == $toModuleId
&& $relationship['type'] == Generator::RELATIONSHIP_BELONGS_TO
&& ! array_get($relationship, 'negative')
) {
$count++;
}
}
return ($count > 1);
}
|
[
"protected",
"function",
"multipleBelongsToRelationsBetweenModels",
"(",
"$",
"fromModuleId",
",",
"$",
"toModuleId",
")",
"{",
"$",
"count",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"context",
"->",
"output",
"[",
"'models'",
"]",
"[",
"$",
"fromModuleId",
"]",
"[",
"'relationships'",
"]",
"[",
"'normal'",
"]",
"as",
"$",
"relationship",
")",
"{",
"if",
"(",
"$",
"relationship",
"[",
"'model'",
"]",
"==",
"$",
"toModuleId",
"&&",
"$",
"relationship",
"[",
"'type'",
"]",
"==",
"Generator",
"::",
"RELATIONSHIP_BELONGS_TO",
"&&",
"!",
"array_get",
"(",
"$",
"relationship",
",",
"'negative'",
")",
")",
"{",
"$",
"count",
"++",
";",
"}",
"}",
"return",
"(",
"$",
"count",
">",
"1",
")",
";",
"}"
] |
Returns whether there are multiple relationships from one model to the other
@param int $fromModuleId
@param int $toModuleId
@return bool
|
[
"Returns",
"whether",
"there",
"are",
"multiple",
"relationships",
"from",
"one",
"model",
"to",
"the",
"other"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L783-L798
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.getImageResizesForField
|
protected function getImageResizesForField($fieldId)
{
if ( ! array_key_exists('resizes', $this->data->rawData['fields'][ $fieldId ])
|| ! count($this->data->rawData['fields'][ $fieldId ]['resizes'])
) {
return [];
}
$resizes = [];
foreach ($this->data->rawData['fields'][ $fieldId ]['resizes'] as $resizeId => $resize) {
$resizes[] = [
'resize' => $resizeId,
'prefix' => $resize['prefix'],
'width' => (int) $resize['width'],
'height' => (int) $resize['height'],
];
}
// sort resizes.. by prefix name, or by image size?
uasort($resizes, function ($a, $b) {
//return $a['width'] * $a['height'] - $b['width'] * $b['height'];
return strcmp($a['prefix'], $b['prefix']);
});
return $resizes;
}
|
php
|
protected function getImageResizesForField($fieldId)
{
if ( ! array_key_exists('resizes', $this->data->rawData['fields'][ $fieldId ])
|| ! count($this->data->rawData['fields'][ $fieldId ]['resizes'])
) {
return [];
}
$resizes = [];
foreach ($this->data->rawData['fields'][ $fieldId ]['resizes'] as $resizeId => $resize) {
$resizes[] = [
'resize' => $resizeId,
'prefix' => $resize['prefix'],
'width' => (int) $resize['width'],
'height' => (int) $resize['height'],
];
}
// sort resizes.. by prefix name, or by image size?
uasort($resizes, function ($a, $b) {
//return $a['width'] * $a['height'] - $b['width'] * $b['height'];
return strcmp($a['prefix'], $b['prefix']);
});
return $resizes;
}
|
[
"protected",
"function",
"getImageResizesForField",
"(",
"$",
"fieldId",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'resizes'",
",",
"$",
"this",
"->",
"data",
"->",
"rawData",
"[",
"'fields'",
"]",
"[",
"$",
"fieldId",
"]",
")",
"||",
"!",
"count",
"(",
"$",
"this",
"->",
"data",
"->",
"rawData",
"[",
"'fields'",
"]",
"[",
"$",
"fieldId",
"]",
"[",
"'resizes'",
"]",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"resizes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"->",
"rawData",
"[",
"'fields'",
"]",
"[",
"$",
"fieldId",
"]",
"[",
"'resizes'",
"]",
"as",
"$",
"resizeId",
"=>",
"$",
"resize",
")",
"{",
"$",
"resizes",
"[",
"]",
"=",
"[",
"'resize'",
"=>",
"$",
"resizeId",
",",
"'prefix'",
"=>",
"$",
"resize",
"[",
"'prefix'",
"]",
",",
"'width'",
"=>",
"(",
"int",
")",
"$",
"resize",
"[",
"'width'",
"]",
",",
"'height'",
"=>",
"(",
"int",
")",
"$",
"resize",
"[",
"'height'",
"]",
",",
"]",
";",
"}",
"// sort resizes.. by prefix name, or by image size?",
"uasort",
"(",
"$",
"resizes",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"//return $a['width'] * $a['height'] - $b['width'] * $b['height'];",
"return",
"strcmp",
"(",
"$",
"a",
"[",
"'prefix'",
"]",
",",
"$",
"b",
"[",
"'prefix'",
"]",
")",
";",
"}",
")",
";",
"return",
"$",
"resizes",
";",
"}"
] |
Returns data about resizes for an image field
@param int $fieldId
@return array
|
[
"Returns",
"data",
"about",
"resizes",
"for",
"an",
"image",
"field"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L806-L833
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.checkForReservedClassName
|
protected function checkForReservedClassName($name)
{
$name = trim(strtolower($name));
if (in_array($name, config('pxlcms.generator.reserved', []))) {
throw new \InvalidArgumentException("Cannot use {$name} as a module name, it is reserved!");
}
}
|
php
|
protected function checkForReservedClassName($name)
{
$name = trim(strtolower($name));
if (in_array($name, config('pxlcms.generator.reserved', []))) {
throw new \InvalidArgumentException("Cannot use {$name} as a module name, it is reserved!");
}
}
|
[
"protected",
"function",
"checkForReservedClassName",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"trim",
"(",
"strtolower",
"(",
"$",
"name",
")",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"config",
"(",
"'pxlcms.generator.reserved'",
",",
"[",
"]",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Cannot use {$name} as a module name, it is reserved!\"",
")",
";",
"}",
"}"
] |
Checks whether a given name is on the reserved list
@param string $name
|
[
"Checks",
"whether",
"a",
"given",
"name",
"is",
"on",
"the",
"reserved",
"list"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L840-L847
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.dutchSingularize
|
protected function dutchSingularize($name)
{
if (empty($this->dutchHelper)) return $name;
return $this->dutchHelper->singularize($name);
}
|
php
|
protected function dutchSingularize($name)
{
if (empty($this->dutchHelper)) return $name;
return $this->dutchHelper->singularize($name);
}
|
[
"protected",
"function",
"dutchSingularize",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"dutchHelper",
")",
")",
"return",
"$",
"name",
";",
"return",
"$",
"this",
"->",
"dutchHelper",
"->",
"singularize",
"(",
"$",
"name",
")",
";",
"}"
] |
Singularizes a noun/name for Dutch content
@param string $name
@return string
|
[
"Singularizes",
"a",
"noun",
"/",
"name",
"for",
"Dutch",
"content"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L866-L871
|
czim/laravel-pxlcms
|
src/Generator/Analyzer/Steps/AnalyzeModels.php
|
AnalyzeModels.dutchPluralize
|
protected function dutchPluralize($name)
{
if (empty($this->dutchHelper)) return $name;
return $this->dutchHelper->pluralize($name);
}
|
php
|
protected function dutchPluralize($name)
{
if (empty($this->dutchHelper)) return $name;
return $this->dutchHelper->pluralize($name);
}
|
[
"protected",
"function",
"dutchPluralize",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"dutchHelper",
")",
")",
"return",
"$",
"name",
";",
"return",
"$",
"this",
"->",
"dutchHelper",
"->",
"pluralize",
"(",
"$",
"name",
")",
";",
"}"
] |
Pluralizes a noun/name for Dutch content
@param string $name
@return string
|
[
"Pluralizes",
"a",
"noun",
"/",
"name",
"for",
"Dutch",
"content"
] |
train
|
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Analyzer/Steps/AnalyzeModels.php#L879-L884
|
ellipsephp/container
|
src/Container/CompositeServiceFactory.php
|
CompositeServiceFactory.extended
|
private function extended(callable $previous = null, callable $current): callable
{
return is_null($previous) ? $current : new Extension($current, $previous);
}
|
php
|
private function extended(callable $previous = null, callable $current): callable
{
return is_null($previous) ? $current : new Extension($current, $previous);
}
|
[
"private",
"function",
"extended",
"(",
"callable",
"$",
"previous",
"=",
"null",
",",
"callable",
"$",
"current",
")",
":",
"callable",
"{",
"return",
"is_null",
"(",
"$",
"previous",
")",
"?",
"$",
"current",
":",
"new",
"Extension",
"(",
"$",
"current",
",",
"$",
"previous",
")",
";",
"}"
] |
Return the previous service factory extended with the current service
factory.
@param callable $previous
@param callable $current
@return callable
|
[
"Return",
"the",
"previous",
"service",
"factory",
"extended",
"with",
"the",
"current",
"service",
"factory",
"."
] |
train
|
https://github.com/ellipsephp/container/blob/ae0836b071fa1751f41b50fc33e3196fcbced6bf/src/Container/CompositeServiceFactory.php#L47-L50
|
bfitech/zapcore
|
src/Header.php
|
Header.get_header_string
|
final public static function get_header_string(int $code) {
if (!isset(self::$header_string[$code]))
$code = 404;
return [
'code' => $code,
'msg' => self::$header_string[$code],
];
}
|
php
|
final public static function get_header_string(int $code) {
if (!isset(self::$header_string[$code]))
$code = 404;
return [
'code' => $code,
'msg' => self::$header_string[$code],
];
}
|
[
"final",
"public",
"static",
"function",
"get_header_string",
"(",
"int",
"$",
"code",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"header_string",
"[",
"$",
"code",
"]",
")",
")",
"$",
"code",
"=",
"404",
";",
"return",
"[",
"'code'",
"=>",
"$",
"code",
",",
"'msg'",
"=>",
"self",
"::",
"$",
"header_string",
"[",
"$",
"code",
"]",
",",
"]",
";",
"}"
] |
Get HTTP code.
@param int $code HTTP code.
@return array A dict containing code and message if
`$code` is valid, 404 dict otherwise.
|
[
"Get",
"HTTP",
"code",
"."
] |
train
|
https://github.com/bfitech/zapcore/blob/0ae4cb9370876ab3583556bf272063685ec57948/src/Header.php#L76-L83
|
bfitech/zapcore
|
src/Header.php
|
Header.start_header
|
public static function start_header(
int $code=200, int $cache=0, array $headers=[]
) {
$msg = 'OK';
extract(self::get_header_string($code));
$proto = isset($_SERVER['SERVER_PROTOCOL'])
? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
static::header("$proto $code $msg");
if ($cache) {
$cache = intval($cache);
$expire = time() + $cache;
static::header("Expires: " .
gmdate("D, d M Y H:i:s", $expire)." GMT");
static::header("Cache-Control: must-revalidate");
} else {
static::header("Expires: Mon, 27 Jul 1996 07:00:00 GMT");
static::header(
"Cache-Control: no-store, no-cache, must-revalidate");
static::header("Cache-Control: post-check=0, pre-check=0");
static::header("Pragma: no-cache");
}
static::header("Last-Modified: " .
gmdate("D, d M Y H:i:s")." GMT");
static::header("X-Powered-By: Zap!", true);
if (!$headers)
return;
foreach ($headers as $header)
static::header($header);
}
|
php
|
public static function start_header(
int $code=200, int $cache=0, array $headers=[]
) {
$msg = 'OK';
extract(self::get_header_string($code));
$proto = isset($_SERVER['SERVER_PROTOCOL'])
? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
static::header("$proto $code $msg");
if ($cache) {
$cache = intval($cache);
$expire = time() + $cache;
static::header("Expires: " .
gmdate("D, d M Y H:i:s", $expire)." GMT");
static::header("Cache-Control: must-revalidate");
} else {
static::header("Expires: Mon, 27 Jul 1996 07:00:00 GMT");
static::header(
"Cache-Control: no-store, no-cache, must-revalidate");
static::header("Cache-Control: post-check=0, pre-check=0");
static::header("Pragma: no-cache");
}
static::header("Last-Modified: " .
gmdate("D, d M Y H:i:s")." GMT");
static::header("X-Powered-By: Zap!", true);
if (!$headers)
return;
foreach ($headers as $header)
static::header($header);
}
|
[
"public",
"static",
"function",
"start_header",
"(",
"int",
"$",
"code",
"=",
"200",
",",
"int",
"$",
"cache",
"=",
"0",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"msg",
"=",
"'OK'",
";",
"extract",
"(",
"self",
"::",
"get_header_string",
"(",
"$",
"code",
")",
")",
";",
"$",
"proto",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'SERVER_PROTOCOL'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'SERVER_PROTOCOL'",
"]",
":",
"'HTTP/1.1'",
";",
"static",
"::",
"header",
"(",
"\"$proto $code $msg\"",
")",
";",
"if",
"(",
"$",
"cache",
")",
"{",
"$",
"cache",
"=",
"intval",
"(",
"$",
"cache",
")",
";",
"$",
"expire",
"=",
"time",
"(",
")",
"+",
"$",
"cache",
";",
"static",
"::",
"header",
"(",
"\"Expires: \"",
".",
"gmdate",
"(",
"\"D, d M Y H:i:s\"",
",",
"$",
"expire",
")",
".",
"\" GMT\"",
")",
";",
"static",
"::",
"header",
"(",
"\"Cache-Control: must-revalidate\"",
")",
";",
"}",
"else",
"{",
"static",
"::",
"header",
"(",
"\"Expires: Mon, 27 Jul 1996 07:00:00 GMT\"",
")",
";",
"static",
"::",
"header",
"(",
"\"Cache-Control: no-store, no-cache, must-revalidate\"",
")",
";",
"static",
"::",
"header",
"(",
"\"Cache-Control: post-check=0, pre-check=0\"",
")",
";",
"static",
"::",
"header",
"(",
"\"Pragma: no-cache\"",
")",
";",
"}",
"static",
"::",
"header",
"(",
"\"Last-Modified: \"",
".",
"gmdate",
"(",
"\"D, d M Y H:i:s\"",
")",
".",
"\" GMT\"",
")",
";",
"static",
"::",
"header",
"(",
"\"X-Powered-By: Zap!\"",
",",
"true",
")",
";",
"if",
"(",
"!",
"$",
"headers",
")",
"return",
";",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"header",
")",
"static",
"::",
"header",
"(",
"$",
"header",
")",
";",
"}"
] |
Start sending response headers.
@param int $code HTTP code.
@param int $cache Cache age, 0 for no cache.
@param array $headers Additional headers.
|
[
"Start",
"sending",
"response",
"headers",
"."
] |
train
|
https://github.com/bfitech/zapcore/blob/0ae4cb9370876ab3583556bf272063685ec57948/src/Header.php#L144-L174
|
bfitech/zapcore
|
src/Header.php
|
Header.send_file
|
public static function send_file(
string $fpath, $disposition=null, int $code=200, int $cache=0,
array $headers=[], bool $xsendfile=null,
callable $callback_notfound=null
) {
if (!file_exists($fpath) || is_dir($fpath)) {
static::start_header(404, 0, $headers);
if (is_callable($callback_notfound)) {
$callback_notfound();
static::halt();
}
return;
}
static::start_header($code, $cache, $headers);
static::header('Content-Length: ' .
filesize($fpath));
static::header("Content-Type: " .
Common::get_mimetype($fpath));
if ($disposition) {
if ($disposition === true)
$disposition = htmlspecialchars(
basename($fpath), ENT_QUOTES);
static::header(sprintf(
'Content-Disposition: attachment; filename="%s"',
$disposition));
}
if (!$xsendfile)
readfile($fpath);
static::halt();
}
|
php
|
public static function send_file(
string $fpath, $disposition=null, int $code=200, int $cache=0,
array $headers=[], bool $xsendfile=null,
callable $callback_notfound=null
) {
if (!file_exists($fpath) || is_dir($fpath)) {
static::start_header(404, 0, $headers);
if (is_callable($callback_notfound)) {
$callback_notfound();
static::halt();
}
return;
}
static::start_header($code, $cache, $headers);
static::header('Content-Length: ' .
filesize($fpath));
static::header("Content-Type: " .
Common::get_mimetype($fpath));
if ($disposition) {
if ($disposition === true)
$disposition = htmlspecialchars(
basename($fpath), ENT_QUOTES);
static::header(sprintf(
'Content-Disposition: attachment; filename="%s"',
$disposition));
}
if (!$xsendfile)
readfile($fpath);
static::halt();
}
|
[
"public",
"static",
"function",
"send_file",
"(",
"string",
"$",
"fpath",
",",
"$",
"disposition",
"=",
"null",
",",
"int",
"$",
"code",
"=",
"200",
",",
"int",
"$",
"cache",
"=",
"0",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
",",
"bool",
"$",
"xsendfile",
"=",
"null",
",",
"callable",
"$",
"callback_notfound",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"fpath",
")",
"||",
"is_dir",
"(",
"$",
"fpath",
")",
")",
"{",
"static",
"::",
"start_header",
"(",
"404",
",",
"0",
",",
"$",
"headers",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"callback_notfound",
")",
")",
"{",
"$",
"callback_notfound",
"(",
")",
";",
"static",
"::",
"halt",
"(",
")",
";",
"}",
"return",
";",
"}",
"static",
"::",
"start_header",
"(",
"$",
"code",
",",
"$",
"cache",
",",
"$",
"headers",
")",
";",
"static",
"::",
"header",
"(",
"'Content-Length: '",
".",
"filesize",
"(",
"$",
"fpath",
")",
")",
";",
"static",
"::",
"header",
"(",
"\"Content-Type: \"",
".",
"Common",
"::",
"get_mimetype",
"(",
"$",
"fpath",
")",
")",
";",
"if",
"(",
"$",
"disposition",
")",
"{",
"if",
"(",
"$",
"disposition",
"===",
"true",
")",
"$",
"disposition",
"=",
"htmlspecialchars",
"(",
"basename",
"(",
"$",
"fpath",
")",
",",
"ENT_QUOTES",
")",
";",
"static",
"::",
"header",
"(",
"sprintf",
"(",
"'Content-Disposition: attachment; filename=\"%s\"'",
",",
"$",
"disposition",
")",
")",
";",
"}",
"if",
"(",
"!",
"$",
"xsendfile",
")",
"readfile",
"(",
"$",
"fpath",
")",
";",
"static",
"::",
"halt",
"(",
")",
";",
"}"
] |
Send file.
Using higher-level Route::static_file_default is enough for
standard usage. Wrap this in Route::static_file_custom to make
a more elaborate static file serving instead of calling it
directly.
@param string $fpath Path to file.
@param mixed $disposition If set as string, this will be used
as filename on content disposition. If set to true, content
disposition is inferred from basename. Otherwise, no
content disposition header is sent.
@param int $code HTTP code. Typically it's 200, but this can
be anything since we can serve, e.g. 404 with a text file.
@param int $cache Cache age, 0 for no cache.
@param array $headers Additional headers.
@param bool $xsendfile If true, response is delegated to
web server. Appropriate header must be set via $headers,
e.g.: `X-Accel-Redirect` on Nginx or `X-Sendfile` on
Apache.
@param callable $callback_notfound What to do when the file
is not found. If no callback is provided, the method will
just immediately halt.
|
[
"Send",
"file",
"."
] |
train
|
https://github.com/bfitech/zapcore/blob/0ae4cb9370876ab3583556bf272063685ec57948/src/Header.php#L201-L236
|
bfitech/zapcore
|
src/Header.php
|
Header.print_json
|
final public static function print_json(
int $errno=0, $data=null, int $http_code=200, int $cache=0
) {
$json = json_encode(compact('errno', 'data'));
self::start_header($http_code, $cache, [
'Content-Length: ' . strlen($json),
'Content-Type: application/json',
]);
static::halt($json);
}
|
php
|
final public static function print_json(
int $errno=0, $data=null, int $http_code=200, int $cache=0
) {
$json = json_encode(compact('errno', 'data'));
self::start_header($http_code, $cache, [
'Content-Length: ' . strlen($json),
'Content-Type: application/json',
]);
static::halt($json);
}
|
[
"final",
"public",
"static",
"function",
"print_json",
"(",
"int",
"$",
"errno",
"=",
"0",
",",
"$",
"data",
"=",
"null",
",",
"int",
"$",
"http_code",
"=",
"200",
",",
"int",
"$",
"cache",
"=",
"0",
")",
"{",
"$",
"json",
"=",
"json_encode",
"(",
"compact",
"(",
"'errno'",
",",
"'data'",
")",
")",
";",
"self",
"::",
"start_header",
"(",
"$",
"http_code",
",",
"$",
"cache",
",",
"[",
"'Content-Length: '",
".",
"strlen",
"(",
"$",
"json",
")",
",",
"'Content-Type: application/json'",
",",
"]",
")",
";",
"static",
"::",
"halt",
"(",
"$",
"json",
")",
";",
"}"
] |
Convenience method for JSON response.
@param int $errno Error number to return.
@param array $data Data to return.
@param int $http_code Valid HTTP response code.
@param int $cache Cache duration in seconds. 0 for no cache.
|
[
"Convenience",
"method",
"for",
"JSON",
"response",
"."
] |
train
|
https://github.com/bfitech/zapcore/blob/0ae4cb9370876ab3583556bf272063685ec57948/src/Header.php#L246-L255
|
bfitech/zapcore
|
src/Header.php
|
Header.pj
|
final public static function pj(
$retval, int $forbidden_code=null, int $cache=0
) {
$http_code = 200;
if (!is_array($retval)) {
$retval = [-1, null];
$forbidden_code = 500;
}
if ($retval[0] !== 0) {
$http_code = 401;
if ($forbidden_code)
$http_code = $forbidden_code;
}
if (!isset($retval[1]))
$retval[1] = null;
self::print_json($retval[0], $retval[1], $http_code, $cache);
}
|
php
|
final public static function pj(
$retval, int $forbidden_code=null, int $cache=0
) {
$http_code = 200;
if (!is_array($retval)) {
$retval = [-1, null];
$forbidden_code = 500;
}
if ($retval[0] !== 0) {
$http_code = 401;
if ($forbidden_code)
$http_code = $forbidden_code;
}
if (!isset($retval[1]))
$retval[1] = null;
self::print_json($retval[0], $retval[1], $http_code, $cache);
}
|
[
"final",
"public",
"static",
"function",
"pj",
"(",
"$",
"retval",
",",
"int",
"$",
"forbidden_code",
"=",
"null",
",",
"int",
"$",
"cache",
"=",
"0",
")",
"{",
"$",
"http_code",
"=",
"200",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"retval",
")",
")",
"{",
"$",
"retval",
"=",
"[",
"-",
"1",
",",
"null",
"]",
";",
"$",
"forbidden_code",
"=",
"500",
";",
"}",
"if",
"(",
"$",
"retval",
"[",
"0",
"]",
"!==",
"0",
")",
"{",
"$",
"http_code",
"=",
"401",
";",
"if",
"(",
"$",
"forbidden_code",
")",
"$",
"http_code",
"=",
"$",
"forbidden_code",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"retval",
"[",
"1",
"]",
")",
")",
"$",
"retval",
"[",
"1",
"]",
"=",
"null",
";",
"self",
"::",
"print_json",
"(",
"$",
"retval",
"[",
"0",
"]",
",",
"$",
"retval",
"[",
"1",
"]",
",",
"$",
"http_code",
",",
"$",
"cache",
")",
";",
"}"
] |
Even shorter JSON response formatter.
@param array $retval Return value of typical Zap HTTP response.
Invalid format will send 500 HTTP error.
@param int $forbidden_code If `$retval[0] == 0`, HTTP code is
200. Otherwise it defaults to 401 which we can override with
this parameter, e.g. 403.
@param int $cache Cache duration in seconds. 0 for no cache.
@see Header::print_json.
@cond
@SuppressWarnings(PHPMD.ShortMethodName)
@endcond
|
[
"Even",
"shorter",
"JSON",
"response",
"formatter",
"."
] |
train
|
https://github.com/bfitech/zapcore/blob/0ae4cb9370876ab3583556bf272063685ec57948/src/Header.php#L272-L288
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.registerServiceProvider
|
protected function registerServiceProvider($pluggable)
{
$pluggable = Str::studly($pluggable['slug']);
$file = $this->getPath()."/{$pluggable}/Providers/{$pluggable}ServiceProvider.php";
$namespace = $this->getNamespace()."{$pluggable}\\Providers\\{$pluggable}ServiceProvider";
if (!$this->files->exists($file)) {
$message = "Pluggable [{$pluggable}] must have a \"{$pluggable}/Providers/{$pluggable}ServiceProvider.php\" file";
throw new FileNotFoundException($message);
}
App::register($namespace);
}
|
php
|
protected function registerServiceProvider($pluggable)
{
$pluggable = Str::studly($pluggable['slug']);
$file = $this->getPath()."/{$pluggable}/Providers/{$pluggable}ServiceProvider.php";
$namespace = $this->getNamespace()."{$pluggable}\\Providers\\{$pluggable}ServiceProvider";
if (!$this->files->exists($file)) {
$message = "Pluggable [{$pluggable}] must have a \"{$pluggable}/Providers/{$pluggable}ServiceProvider.php\" file";
throw new FileNotFoundException($message);
}
App::register($namespace);
}
|
[
"protected",
"function",
"registerServiceProvider",
"(",
"$",
"pluggable",
")",
"{",
"$",
"pluggable",
"=",
"Str",
"::",
"studly",
"(",
"$",
"pluggable",
"[",
"'slug'",
"]",
")",
";",
"$",
"file",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
".",
"\"/{$pluggable}/Providers/{$pluggable}ServiceProvider.php\"",
";",
"$",
"namespace",
"=",
"$",
"this",
"->",
"getNamespace",
"(",
")",
".",
"\"{$pluggable}\\\\Providers\\\\{$pluggable}ServiceProvider\"",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"files",
"->",
"exists",
"(",
"$",
"file",
")",
")",
"{",
"$",
"message",
"=",
"\"Pluggable [{$pluggable}] must have a \\\"{$pluggable}/Providers/{$pluggable}ServiceProvider.php\\\" file\"",
";",
"throw",
"new",
"FileNotFoundException",
"(",
"$",
"message",
")",
";",
"}",
"App",
"::",
"register",
"(",
"$",
"namespace",
")",
";",
"}"
] |
Register the module service provider.
@param $pluggable
@throws FileNotFoundException
|
[
"Register",
"the",
"module",
"service",
"provider",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L59-L72
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.all
|
public function all()
{
$pluggables = [];
$allPlugs = $this->getAllBaseNames();
foreach ($allPlugs as $plug) {
$pluggables[] = $this->getJsonContents($plug);
}
return new Collection($this->sortByOrder($pluggables));
}
|
php
|
public function all()
{
$pluggables = [];
$allPlugs = $this->getAllBaseNames();
foreach ($allPlugs as $plug) {
$pluggables[] = $this->getJsonContents($plug);
}
return new Collection($this->sortByOrder($pluggables));
}
|
[
"public",
"function",
"all",
"(",
")",
"{",
"$",
"pluggables",
"=",
"[",
"]",
";",
"$",
"allPlugs",
"=",
"$",
"this",
"->",
"getAllBaseNames",
"(",
")",
";",
"foreach",
"(",
"$",
"allPlugs",
"as",
"$",
"plug",
")",
"{",
"$",
"pluggables",
"[",
"]",
"=",
"$",
"this",
"->",
"getJsonContents",
"(",
"$",
"plug",
")",
";",
"}",
"return",
"new",
"Collection",
"(",
"$",
"this",
"->",
"sortByOrder",
"(",
"$",
"pluggables",
")",
")",
";",
"}"
] |
Get all the pluggables.
@return Collection
|
[
"Get",
"all",
"the",
"pluggables",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L79-L89
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.getAllBaseNames
|
protected function getAllBaseNames()
{
$pluggables = [];
$path = $this->getPath();
if (!is_dir($path)) {
return $pluggables;
}
$folders = $this->files->directories($path);
foreach ($folders as $plug) {
$pluggables[] = basename($plug);
}
return $pluggables;
}
|
php
|
protected function getAllBaseNames()
{
$pluggables = [];
$path = $this->getPath();
if (!is_dir($path)) {
return $pluggables;
}
$folders = $this->files->directories($path);
foreach ($folders as $plug) {
$pluggables[] = basename($plug);
}
return $pluggables;
}
|
[
"protected",
"function",
"getAllBaseNames",
"(",
")",
"{",
"$",
"pluggables",
"=",
"[",
"]",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"path",
")",
")",
"{",
"return",
"$",
"pluggables",
";",
"}",
"$",
"folders",
"=",
"$",
"this",
"->",
"files",
"->",
"directories",
"(",
"$",
"path",
")",
";",
"foreach",
"(",
"$",
"folders",
"as",
"$",
"plug",
")",
"{",
"$",
"pluggables",
"[",
"]",
"=",
"basename",
"(",
"$",
"plug",
")",
";",
"}",
"return",
"$",
"pluggables",
";",
"}"
] |
Get all pluggable basenames.
@return array
|
[
"Get",
"all",
"pluggable",
"basenames",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L96-L113
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.getAllSlugs
|
protected function getAllSlugs()
{
$pluggables = $this->all();
$slugs = [];
foreach ($pluggables as $plug) {
$slugs[] = $plug['slug'];
}
return $slugs;
}
|
php
|
protected function getAllSlugs()
{
$pluggables = $this->all();
$slugs = [];
foreach ($pluggables as $plug) {
$slugs[] = $plug['slug'];
}
return $slugs;
}
|
[
"protected",
"function",
"getAllSlugs",
"(",
")",
"{",
"$",
"pluggables",
"=",
"$",
"this",
"->",
"all",
"(",
")",
";",
"$",
"slugs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pluggables",
"as",
"$",
"plug",
")",
"{",
"$",
"slugs",
"[",
"]",
"=",
"$",
"plug",
"[",
"'slug'",
"]",
";",
"}",
"return",
"$",
"slugs",
";",
"}"
] |
Get all pluggable slugs.
@return array
|
[
"Get",
"all",
"pluggable",
"slugs",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L120-L129
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.pathExists
|
protected function pathExists($folder)
{
$folder = Str::studly($folder);
return in_array($folder, $this->getAllBaseNames());
}
|
php
|
protected function pathExists($folder)
{
$folder = Str::studly($folder);
return in_array($folder, $this->getAllBaseNames());
}
|
[
"protected",
"function",
"pathExists",
"(",
"$",
"folder",
")",
"{",
"$",
"folder",
"=",
"Str",
"::",
"studly",
"(",
"$",
"folder",
")",
";",
"return",
"in_array",
"(",
"$",
"folder",
",",
"$",
"this",
"->",
"getAllBaseNames",
"(",
")",
")",
";",
"}"
] |
Check if given pluggable path exists.
@param string $folder
@return bool
|
[
"Check",
"if",
"given",
"pluggable",
"path",
"exists",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L138-L143
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.getPluggablePath
|
public function getPluggablePath($slug, $allowNotExists = false)
{
$pluggable = Str::studly($slug);
if (!$this->pathExists($pluggable) && $allowNotExists === false) {
return;
}
return $this->getPath()."/{$pluggable}/";
}
|
php
|
public function getPluggablePath($slug, $allowNotExists = false)
{
$pluggable = Str::studly($slug);
if (!$this->pathExists($pluggable) && $allowNotExists === false) {
return;
}
return $this->getPath()."/{$pluggable}/";
}
|
[
"public",
"function",
"getPluggablePath",
"(",
"$",
"slug",
",",
"$",
"allowNotExists",
"=",
"false",
")",
"{",
"$",
"pluggable",
"=",
"Str",
"::",
"studly",
"(",
"$",
"slug",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"pathExists",
"(",
"$",
"pluggable",
")",
"&&",
"$",
"allowNotExists",
"===",
"false",
")",
"{",
"return",
";",
"}",
"return",
"$",
"this",
"->",
"getPath",
"(",
")",
".",
"\"/{$pluggable}/\"",
";",
"}"
] |
Get path for the specified pluggable.
@param string $slug
@return string
|
[
"Get",
"path",
"for",
"the",
"specified",
"pluggable",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L210-L219
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.getProperty
|
public function getProperty($property, $default = null)
{
list($pluggable, $key) = explode('::', $property);
return array_get($this->getJsonContents($pluggable), $key, $default);
}
|
php
|
public function getProperty($property, $default = null)
{
list($pluggable, $key) = explode('::', $property);
return array_get($this->getJsonContents($pluggable), $key, $default);
}
|
[
"public",
"function",
"getProperty",
"(",
"$",
"property",
",",
"$",
"default",
"=",
"null",
")",
"{",
"list",
"(",
"$",
"pluggable",
",",
"$",
"key",
")",
"=",
"explode",
"(",
"'::'",
",",
"$",
"property",
")",
";",
"return",
"array_get",
"(",
"$",
"this",
"->",
"getJsonContents",
"(",
"$",
"pluggable",
")",
",",
"$",
"key",
",",
"$",
"default",
")",
";",
"}"
] |
Get a pluggable property value.
@param string $property
@param mixed $default
@return mixed
|
[
"Get",
"a",
"pluggable",
"property",
"value",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L241-L246
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.setProperty
|
public function setProperty($property, $value)
{
list($pluggable, $key) = explode('::', $property);
$content = $this->getJsonContents($pluggable);
if (count($content)) {
if (isset($content[$key])) {
unset($content[$key]);
}
$content[$key] = $value;
$this->setJsonContents($pluggable, $content);
return true;
}
return false;
}
|
php
|
public function setProperty($property, $value)
{
list($pluggable, $key) = explode('::', $property);
$content = $this->getJsonContents($pluggable);
if (count($content)) {
if (isset($content[$key])) {
unset($content[$key]);
}
$content[$key] = $value;
$this->setJsonContents($pluggable, $content);
return true;
}
return false;
}
|
[
"public",
"function",
"setProperty",
"(",
"$",
"property",
",",
"$",
"value",
")",
"{",
"list",
"(",
"$",
"pluggable",
",",
"$",
"key",
")",
"=",
"explode",
"(",
"'::'",
",",
"$",
"property",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"getJsonContents",
"(",
"$",
"pluggable",
")",
";",
"if",
"(",
"count",
"(",
"$",
"content",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"content",
"[",
"$",
"key",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"content",
"[",
"$",
"key",
"]",
")",
";",
"}",
"$",
"content",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"setJsonContents",
"(",
"$",
"pluggable",
",",
"$",
"content",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Set a pluggale property value.
@param string $property
@param mixed $value
@return bool
|
[
"Set",
"a",
"pluggale",
"property",
"value",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L256-L274
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.getByEnabled
|
public function getByEnabled($enabled = true)
{
$disabledPluggables = [];
$enabledPluggables = [];
$pluggables = $this->all();
// Iterate through each pluggable
foreach ($pluggables as $pluggable) {
if ($this->isEnabled($pluggable['slug'])) {
$enabledPluggables[] = $pluggable;
} else {
$disabledPluggables[] = $pluggable;
}
}
if ($enabled === true) {
return $this->sortByOrder($enabledPluggables);
}
return $this->sortByOrder($disabledPluggables);
}
|
php
|
public function getByEnabled($enabled = true)
{
$disabledPluggables = [];
$enabledPluggables = [];
$pluggables = $this->all();
// Iterate through each pluggable
foreach ($pluggables as $pluggable) {
if ($this->isEnabled($pluggable['slug'])) {
$enabledPluggables[] = $pluggable;
} else {
$disabledPluggables[] = $pluggable;
}
}
if ($enabled === true) {
return $this->sortByOrder($enabledPluggables);
}
return $this->sortByOrder($disabledPluggables);
}
|
[
"public",
"function",
"getByEnabled",
"(",
"$",
"enabled",
"=",
"true",
")",
"{",
"$",
"disabledPluggables",
"=",
"[",
"]",
";",
"$",
"enabledPluggables",
"=",
"[",
"]",
";",
"$",
"pluggables",
"=",
"$",
"this",
"->",
"all",
"(",
")",
";",
"// Iterate through each pluggable",
"foreach",
"(",
"$",
"pluggables",
"as",
"$",
"pluggable",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isEnabled",
"(",
"$",
"pluggable",
"[",
"'slug'",
"]",
")",
")",
"{",
"$",
"enabledPluggables",
"[",
"]",
"=",
"$",
"pluggable",
";",
"}",
"else",
"{",
"$",
"disabledPluggables",
"[",
"]",
"=",
"$",
"pluggable",
";",
"}",
"}",
"if",
"(",
"$",
"enabled",
"===",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"sortByOrder",
"(",
"$",
"enabledPluggables",
")",
";",
"}",
"return",
"$",
"this",
"->",
"sortByOrder",
"(",
"$",
"disabledPluggables",
")",
";",
"}"
] |
Find a pluggable with enabled status given.
@param bool $enabled
@return array
|
[
"Find",
"a",
"pluggable",
"with",
"enabled",
"status",
"given",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L283-L304
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.getJsonContents
|
protected function getJsonContents($pluggable)
{
$pluggable = Str::studly($pluggable);
$default = [];
if (!$this->pathExists($pluggable)) {
return $default;
}
$path = $this->getJsonPath($pluggable);
if ($this->files->exists($path)) {
$contents = $this->files->get($path);
return json_decode($contents, true);
} else {
$message = "Pluggable [{$pluggable}] must have a valid pluggable.json file.";
throw new FileNotFoundException($message);
}
}
|
php
|
protected function getJsonContents($pluggable)
{
$pluggable = Str::studly($pluggable);
$default = [];
if (!$this->pathExists($pluggable)) {
return $default;
}
$path = $this->getJsonPath($pluggable);
if ($this->files->exists($path)) {
$contents = $this->files->get($path);
return json_decode($contents, true);
} else {
$message = "Pluggable [{$pluggable}] must have a valid pluggable.json file.";
throw new FileNotFoundException($message);
}
}
|
[
"protected",
"function",
"getJsonContents",
"(",
"$",
"pluggable",
")",
"{",
"$",
"pluggable",
"=",
"Str",
"::",
"studly",
"(",
"$",
"pluggable",
")",
";",
"$",
"default",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"pathExists",
"(",
"$",
"pluggable",
")",
")",
"{",
"return",
"$",
"default",
";",
"}",
"$",
"path",
"=",
"$",
"this",
"->",
"getJsonPath",
"(",
"$",
"pluggable",
")",
";",
"if",
"(",
"$",
"this",
"->",
"files",
"->",
"exists",
"(",
"$",
"path",
")",
")",
"{",
"$",
"contents",
"=",
"$",
"this",
"->",
"files",
"->",
"get",
"(",
"$",
"path",
")",
";",
"return",
"json_decode",
"(",
"$",
"contents",
",",
"true",
")",
";",
"}",
"else",
"{",
"$",
"message",
"=",
"\"Pluggable [{$pluggable}] must have a valid pluggable.json file.\"",
";",
"throw",
"new",
"FileNotFoundException",
"(",
"$",
"message",
")",
";",
"}",
"}"
] |
Get pluggable JSON content as an array.
@param string $pluggable
@throws FileNotFoundException
@return array|mixed
|
[
"Get",
"pluggable",
"JSON",
"content",
"as",
"an",
"array",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L383-L403
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.sortByOrder
|
public function sortByOrder($pluggables)
{
$orderedPluggables = [];
foreach ($pluggables as $pluggable) {
if (!isset($pluggable['order'])) {
$pluggable['order'] = 9001; // It's over 9000!
}
$orderedPluggables[] = $pluggable;
}
if (count($orderedPluggables) > 0) {
$orderedPluggables = $this->arrayOrderBy($orderedPluggables, 'order', SORT_ASC, 'slug', SORT_ASC);
}
return $orderedPluggables;
}
|
php
|
public function sortByOrder($pluggables)
{
$orderedPluggables = [];
foreach ($pluggables as $pluggable) {
if (!isset($pluggable['order'])) {
$pluggable['order'] = 9001; // It's over 9000!
}
$orderedPluggables[] = $pluggable;
}
if (count($orderedPluggables) > 0) {
$orderedPluggables = $this->arrayOrderBy($orderedPluggables, 'order', SORT_ASC, 'slug', SORT_ASC);
}
return $orderedPluggables;
}
|
[
"public",
"function",
"sortByOrder",
"(",
"$",
"pluggables",
")",
"{",
"$",
"orderedPluggables",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pluggables",
"as",
"$",
"pluggable",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"pluggable",
"[",
"'order'",
"]",
")",
")",
"{",
"$",
"pluggable",
"[",
"'order'",
"]",
"=",
"9001",
";",
"// It's over 9000!",
"}",
"$",
"orderedPluggables",
"[",
"]",
"=",
"$",
"pluggable",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"orderedPluggables",
")",
">",
"0",
")",
"{",
"$",
"orderedPluggables",
"=",
"$",
"this",
"->",
"arrayOrderBy",
"(",
"$",
"orderedPluggables",
",",
"'order'",
",",
"SORT_ASC",
",",
"'slug'",
",",
"SORT_ASC",
")",
";",
"}",
"return",
"$",
"orderedPluggables",
";",
"}"
] |
Sort pluggables by order.
@param array $pluggables
@return array
|
[
"Sort",
"pluggables",
"by",
"order",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L440-L456
|
aindong/pluggables
|
src/Aindong/Pluggables/Pluggables.php
|
Pluggables.arrayOrderBy
|
protected function arrayOrderBy()
{
$arguments = func_get_args();
$data = array_shift($arguments);
foreach ($arguments as $argument => $field) {
if (is_string($field)) {
$temp = [];
foreach ($data as $key => $row) {
$temp[$key] = $row[$field];
}
$arguments[$argument] = $temp;
}
}
$arguments[] = &$data;
call_user_func_array('array_multisort', $arguments);
return array_pop($arguments);
}
|
php
|
protected function arrayOrderBy()
{
$arguments = func_get_args();
$data = array_shift($arguments);
foreach ($arguments as $argument => $field) {
if (is_string($field)) {
$temp = [];
foreach ($data as $key => $row) {
$temp[$key] = $row[$field];
}
$arguments[$argument] = $temp;
}
}
$arguments[] = &$data;
call_user_func_array('array_multisort', $arguments);
return array_pop($arguments);
}
|
[
"protected",
"function",
"arrayOrderBy",
"(",
")",
"{",
"$",
"arguments",
"=",
"func_get_args",
"(",
")",
";",
"$",
"data",
"=",
"array_shift",
"(",
"$",
"arguments",
")",
";",
"foreach",
"(",
"$",
"arguments",
"as",
"$",
"argument",
"=>",
"$",
"field",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"field",
")",
")",
"{",
"$",
"temp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"row",
")",
"{",
"$",
"temp",
"[",
"$",
"key",
"]",
"=",
"$",
"row",
"[",
"$",
"field",
"]",
";",
"}",
"$",
"arguments",
"[",
"$",
"argument",
"]",
"=",
"$",
"temp",
";",
"}",
"}",
"$",
"arguments",
"[",
"]",
"=",
"&",
"$",
"data",
";",
"call_user_func_array",
"(",
"'array_multisort'",
",",
"$",
"arguments",
")",
";",
"return",
"array_pop",
"(",
"$",
"arguments",
")",
";",
"}"
] |
Helper method to order multiple values easily.
@return array
|
[
"Helper",
"method",
"to",
"order",
"multiple",
"values",
"easily",
"."
] |
train
|
https://github.com/aindong/pluggables/blob/bf8bab46fb65268043fb4b98db21f8e0338b5e96/src/Aindong/Pluggables/Pluggables.php#L463-L480
|
darkwebdesign/doctrine-unit-testing
|
src/Mocks/UnitOfWorkMock.php
|
UnitOfWorkMock.getEntityPersister
|
public function getEntityPersister($entityName)
{
return isset($this->_persisterMock[$entityName])
? $this->_persisterMock[$entityName]
: parent::getEntityPersister($entityName);
}
|
php
|
public function getEntityPersister($entityName)
{
return isset($this->_persisterMock[$entityName])
? $this->_persisterMock[$entityName]
: parent::getEntityPersister($entityName);
}
|
[
"public",
"function",
"getEntityPersister",
"(",
"$",
"entityName",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"_persisterMock",
"[",
"$",
"entityName",
"]",
")",
"?",
"$",
"this",
"->",
"_persisterMock",
"[",
"$",
"entityName",
"]",
":",
"parent",
"::",
"getEntityPersister",
"(",
"$",
"entityName",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/darkwebdesign/doctrine-unit-testing/blob/0daf50359563bc0679925e573a7105d6cd57168a/src/Mocks/UnitOfWorkMock.php#L25-L30
|
darkwebdesign/doctrine-unit-testing
|
src/Mocks/UnitOfWorkMock.php
|
UnitOfWorkMock.&
|
public function & getEntityChangeSet($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->_mockDataChangeSets[$oid])) {
return $this->_mockDataChangeSets[$oid];
}
$data = parent::getEntityChangeSet($entity);
return $data;
}
|
php
|
public function & getEntityChangeSet($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->_mockDataChangeSets[$oid])) {
return $this->_mockDataChangeSets[$oid];
}
$data = parent::getEntityChangeSet($entity);
return $data;
}
|
[
"public",
"function",
"&",
"getEntityChangeSet",
"(",
"$",
"entity",
")",
"{",
"$",
"oid",
"=",
"spl_object_hash",
"(",
"$",
"entity",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_mockDataChangeSets",
"[",
"$",
"oid",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"_mockDataChangeSets",
"[",
"$",
"oid",
"]",
";",
"}",
"$",
"data",
"=",
"parent",
"::",
"getEntityChangeSet",
"(",
"$",
"entity",
")",
";",
"return",
"$",
"data",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/darkwebdesign/doctrine-unit-testing/blob/0daf50359563bc0679925e573a7105d6cd57168a/src/Mocks/UnitOfWorkMock.php#L35-L46
|
okvpn/fixture-bundle
|
src/Migration/DataFixturesExecutor.php
|
DataFixturesExecutor.execute
|
public function execute(array $fixtures, $fixturesType)
{
$event = new DataFixturesEvent($this->em, $fixturesType, $this->logger);
$this->eventDispatcher->dispatch(FixturesEvents::DATA_FIXTURES_PRE_LOAD, $event);
$executor = new ORMExecutor($this->em);
if (null !== $this->logger) {
$executor->setLogger($this->logger);
}
$executor->execute($fixtures, true);
$this->eventDispatcher->dispatch(FixturesEvents::DATA_FIXTURES_POST_LOAD, $event);
}
|
php
|
public function execute(array $fixtures, $fixturesType)
{
$event = new DataFixturesEvent($this->em, $fixturesType, $this->logger);
$this->eventDispatcher->dispatch(FixturesEvents::DATA_FIXTURES_PRE_LOAD, $event);
$executor = new ORMExecutor($this->em);
if (null !== $this->logger) {
$executor->setLogger($this->logger);
}
$executor->execute($fixtures, true);
$this->eventDispatcher->dispatch(FixturesEvents::DATA_FIXTURES_POST_LOAD, $event);
}
|
[
"public",
"function",
"execute",
"(",
"array",
"$",
"fixtures",
",",
"$",
"fixturesType",
")",
"{",
"$",
"event",
"=",
"new",
"DataFixturesEvent",
"(",
"$",
"this",
"->",
"em",
",",
"$",
"fixturesType",
",",
"$",
"this",
"->",
"logger",
")",
";",
"$",
"this",
"->",
"eventDispatcher",
"->",
"dispatch",
"(",
"FixturesEvents",
"::",
"DATA_FIXTURES_PRE_LOAD",
",",
"$",
"event",
")",
";",
"$",
"executor",
"=",
"new",
"ORMExecutor",
"(",
"$",
"this",
"->",
"em",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"executor",
"->",
"setLogger",
"(",
"$",
"this",
"->",
"logger",
")",
";",
"}",
"$",
"executor",
"->",
"execute",
"(",
"$",
"fixtures",
",",
"true",
")",
";",
"$",
"this",
"->",
"eventDispatcher",
"->",
"dispatch",
"(",
"FixturesEvents",
"::",
"DATA_FIXTURES_POST_LOAD",
",",
"$",
"event",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/okvpn/fixture-bundle/blob/243b5e4dff9773e97fa447280e929c936a5d66ae/src/Migration/DataFixturesExecutor.php#L37-L49
|
verschoof/bunq-api
|
src/Resource/PaymentResource.php
|
PaymentResource.listPayments
|
public function listPayments($userId, $monetaryAccountId)
{
$payments = $this->client->get($this->getResourceEndpoint($userId, $monetaryAccountId));
foreach ($payments['Response'] as $key => $payment) {
$payments['Response'][$key]['Payment']['amount']['value'] = $this->floatToCents($payment['Payment']['amount']['value']);
}
return $payments;
}
|
php
|
public function listPayments($userId, $monetaryAccountId)
{
$payments = $this->client->get($this->getResourceEndpoint($userId, $monetaryAccountId));
foreach ($payments['Response'] as $key => $payment) {
$payments['Response'][$key]['Payment']['amount']['value'] = $this->floatToCents($payment['Payment']['amount']['value']);
}
return $payments;
}
|
[
"public",
"function",
"listPayments",
"(",
"$",
"userId",
",",
"$",
"monetaryAccountId",
")",
"{",
"$",
"payments",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"this",
"->",
"getResourceEndpoint",
"(",
"$",
"userId",
",",
"$",
"monetaryAccountId",
")",
")",
";",
"foreach",
"(",
"$",
"payments",
"[",
"'Response'",
"]",
"as",
"$",
"key",
"=>",
"$",
"payment",
")",
"{",
"$",
"payments",
"[",
"'Response'",
"]",
"[",
"$",
"key",
"]",
"[",
"'Payment'",
"]",
"[",
"'amount'",
"]",
"[",
"'value'",
"]",
"=",
"$",
"this",
"->",
"floatToCents",
"(",
"$",
"payment",
"[",
"'Payment'",
"]",
"[",
"'amount'",
"]",
"[",
"'value'",
"]",
")",
";",
"}",
"return",
"$",
"payments",
";",
"}"
] |
Lists all payments.
@param integer $userId
@param integer $monetaryAccountId
@return array
|
[
"Lists",
"all",
"payments",
"."
] |
train
|
https://github.com/verschoof/bunq-api/blob/df9aa19f384275f4f0deb26de0cb5e5f8b45ffcd/src/Resource/PaymentResource.php#L30-L38
|
verschoof/bunq-api
|
src/Resource/PaymentResource.php
|
PaymentResource.getPayment
|
public function getPayment($userId, $monetaryAccountId, $id)
{
$paymentResponse = $this->client->get($this->getResourceEndpoint($userId, $monetaryAccountId) . '/' . (int)$id);
$payment = $paymentResponse['Response'][0]['Payment'];
$payment['amount']['value'] = $this->floatToCents($payment['amount']['value']);
return $payment;
}
|
php
|
public function getPayment($userId, $monetaryAccountId, $id)
{
$paymentResponse = $this->client->get($this->getResourceEndpoint($userId, $monetaryAccountId) . '/' . (int)$id);
$payment = $paymentResponse['Response'][0]['Payment'];
$payment['amount']['value'] = $this->floatToCents($payment['amount']['value']);
return $payment;
}
|
[
"public",
"function",
"getPayment",
"(",
"$",
"userId",
",",
"$",
"monetaryAccountId",
",",
"$",
"id",
")",
"{",
"$",
"paymentResponse",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"this",
"->",
"getResourceEndpoint",
"(",
"$",
"userId",
",",
"$",
"monetaryAccountId",
")",
".",
"'/'",
".",
"(",
"int",
")",
"$",
"id",
")",
";",
"$",
"payment",
"=",
"$",
"paymentResponse",
"[",
"'Response'",
"]",
"[",
"0",
"]",
"[",
"'Payment'",
"]",
";",
"$",
"payment",
"[",
"'amount'",
"]",
"[",
"'value'",
"]",
"=",
"$",
"this",
"->",
"floatToCents",
"(",
"$",
"payment",
"[",
"'amount'",
"]",
"[",
"'value'",
"]",
")",
";",
"return",
"$",
"payment",
";",
"}"
] |
Gets a user its payment information.
@param integer $userId
@param integer $monetaryAccountId
@param integer $id
@return array
|
[
"Gets",
"a",
"user",
"its",
"payment",
"information",
"."
] |
train
|
https://github.com/verschoof/bunq-api/blob/df9aa19f384275f4f0deb26de0cb5e5f8b45ffcd/src/Resource/PaymentResource.php#L49-L58
|
prooph/link-app-core
|
src/Controller/ConfigurationController.php
|
ConfigurationController.changeNodeNameAction
|
public function changeNodeNameAction()
{
$nodeName = $this->bodyParam('node_name');
if (! is_string($nodeName) || strlen($nodeName) < 3) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The node name must be at least 3 characters long')));
}
$this->commandBus->dispatch(ChangeNodeName::to(
NodeName::fromString($nodeName),
ConfigLocation::fromPath(Definition::getSystemConfigDir())
));
return ['success' => true];
}
|
php
|
public function changeNodeNameAction()
{
$nodeName = $this->bodyParam('node_name');
if (! is_string($nodeName) || strlen($nodeName) < 3) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The node name must be at least 3 characters long')));
}
$this->commandBus->dispatch(ChangeNodeName::to(
NodeName::fromString($nodeName),
ConfigLocation::fromPath(Definition::getSystemConfigDir())
));
return ['success' => true];
}
|
[
"public",
"function",
"changeNodeNameAction",
"(",
")",
"{",
"$",
"nodeName",
"=",
"$",
"this",
"->",
"bodyParam",
"(",
"'node_name'",
")",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"nodeName",
")",
"||",
"strlen",
"(",
"$",
"nodeName",
")",
"<",
"3",
")",
"{",
"return",
"new",
"ApiProblemResponse",
"(",
"new",
"ApiProblem",
"(",
"422",
",",
"$",
"this",
"->",
"translator",
"->",
"translate",
"(",
"'The node name must be at least 3 characters long'",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"commandBus",
"->",
"dispatch",
"(",
"ChangeNodeName",
"::",
"to",
"(",
"NodeName",
"::",
"fromString",
"(",
"$",
"nodeName",
")",
",",
"ConfigLocation",
"::",
"fromPath",
"(",
"Definition",
"::",
"getSystemConfigDir",
"(",
")",
")",
")",
")",
";",
"return",
"[",
"'success'",
"=>",
"true",
"]",
";",
"}"
] |
Handles a POST request that want to change the node name
|
[
"Handles",
"a",
"POST",
"request",
"that",
"want",
"to",
"change",
"the",
"node",
"name"
] |
train
|
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Controller/ConfigurationController.php#L37-L51
|
prooph/link-app-core
|
src/Controller/ConfigurationController.php
|
ConfigurationController.configureJavascriptTickerAction
|
public function configureJavascriptTickerAction()
{
$tickerEnabled = $this->bodyParam('enabled');
$tickerInterval = $this->bodyParam('interval');
if (! is_bool($tickerEnabled)) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The enabled flag should be a boolean value')));
}
if (! is_int($tickerInterval) || $tickerInterval <= 0) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The ticker interval should greater than zero')));
}
$this->commandBus->dispatch(
ConfigureJavascriptTicker::set(
$tickerEnabled,
$tickerInterval,
ConfigLocation::fromPath(Definition::getSystemConfigDir())
)
);
return ['success' => true];
}
|
php
|
public function configureJavascriptTickerAction()
{
$tickerEnabled = $this->bodyParam('enabled');
$tickerInterval = $this->bodyParam('interval');
if (! is_bool($tickerEnabled)) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The enabled flag should be a boolean value')));
}
if (! is_int($tickerInterval) || $tickerInterval <= 0) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The ticker interval should greater than zero')));
}
$this->commandBus->dispatch(
ConfigureJavascriptTicker::set(
$tickerEnabled,
$tickerInterval,
ConfigLocation::fromPath(Definition::getSystemConfigDir())
)
);
return ['success' => true];
}
|
[
"public",
"function",
"configureJavascriptTickerAction",
"(",
")",
"{",
"$",
"tickerEnabled",
"=",
"$",
"this",
"->",
"bodyParam",
"(",
"'enabled'",
")",
";",
"$",
"tickerInterval",
"=",
"$",
"this",
"->",
"bodyParam",
"(",
"'interval'",
")",
";",
"if",
"(",
"!",
"is_bool",
"(",
"$",
"tickerEnabled",
")",
")",
"{",
"return",
"new",
"ApiProblemResponse",
"(",
"new",
"ApiProblem",
"(",
"422",
",",
"$",
"this",
"->",
"translator",
"->",
"translate",
"(",
"'The enabled flag should be a boolean value'",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"is_int",
"(",
"$",
"tickerInterval",
")",
"||",
"$",
"tickerInterval",
"<=",
"0",
")",
"{",
"return",
"new",
"ApiProblemResponse",
"(",
"new",
"ApiProblem",
"(",
"422",
",",
"$",
"this",
"->",
"translator",
"->",
"translate",
"(",
"'The ticker interval should greater than zero'",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"commandBus",
"->",
"dispatch",
"(",
"ConfigureJavascriptTicker",
"::",
"set",
"(",
"$",
"tickerEnabled",
",",
"$",
"tickerInterval",
",",
"ConfigLocation",
"::",
"fromPath",
"(",
"Definition",
"::",
"getSystemConfigDir",
"(",
")",
")",
")",
")",
";",
"return",
"[",
"'success'",
"=>",
"true",
"]",
";",
"}"
] |
Handles a POST request to configure the javascript ticker
|
[
"Handles",
"a",
"POST",
"request",
"to",
"configure",
"the",
"javascript",
"ticker"
] |
train
|
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Controller/ConfigurationController.php#L56-L78
|
prooph/link-app-core
|
src/Controller/ConfigurationController.php
|
ConfigurationController.configureWorkflowProcessorMessageQueueAction
|
public function configureWorkflowProcessorMessageQueueAction()
{
$queueEnabled = $this->bodyParam('enabled');
if (! is_bool($queueEnabled)) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The enabled flag should be a boolean value')));
}
if ($queueEnabled) {
$this->commandBus->dispatch(
EnableWorkflowProcessorMessageQueue::in(ConfigLocation::fromPath(Definition::getSystemConfigDir()))
);
} else {
$this->commandBus->dispatch(
DisableWorkflowProcessorMessageQueue::in(ConfigLocation::fromPath(Definition::getSystemConfigDir()))
);
}
return ['success' => true];
}
|
php
|
public function configureWorkflowProcessorMessageQueueAction()
{
$queueEnabled = $this->bodyParam('enabled');
if (! is_bool($queueEnabled)) {
return new ApiProblemResponse(new ApiProblem(422, $this->translator->translate('The enabled flag should be a boolean value')));
}
if ($queueEnabled) {
$this->commandBus->dispatch(
EnableWorkflowProcessorMessageQueue::in(ConfigLocation::fromPath(Definition::getSystemConfigDir()))
);
} else {
$this->commandBus->dispatch(
DisableWorkflowProcessorMessageQueue::in(ConfigLocation::fromPath(Definition::getSystemConfigDir()))
);
}
return ['success' => true];
}
|
[
"public",
"function",
"configureWorkflowProcessorMessageQueueAction",
"(",
")",
"{",
"$",
"queueEnabled",
"=",
"$",
"this",
"->",
"bodyParam",
"(",
"'enabled'",
")",
";",
"if",
"(",
"!",
"is_bool",
"(",
"$",
"queueEnabled",
")",
")",
"{",
"return",
"new",
"ApiProblemResponse",
"(",
"new",
"ApiProblem",
"(",
"422",
",",
"$",
"this",
"->",
"translator",
"->",
"translate",
"(",
"'The enabled flag should be a boolean value'",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"queueEnabled",
")",
"{",
"$",
"this",
"->",
"commandBus",
"->",
"dispatch",
"(",
"EnableWorkflowProcessorMessageQueue",
"::",
"in",
"(",
"ConfigLocation",
"::",
"fromPath",
"(",
"Definition",
"::",
"getSystemConfigDir",
"(",
")",
")",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"commandBus",
"->",
"dispatch",
"(",
"DisableWorkflowProcessorMessageQueue",
"::",
"in",
"(",
"ConfigLocation",
"::",
"fromPath",
"(",
"Definition",
"::",
"getSystemConfigDir",
"(",
")",
")",
")",
")",
";",
"}",
"return",
"[",
"'success'",
"=>",
"true",
"]",
";",
"}"
] |
Handles a POST request to enable or disable the workflow processor message queue
|
[
"Handles",
"a",
"POST",
"request",
"to",
"enable",
"or",
"disable",
"the",
"workflow",
"processor",
"message",
"queue"
] |
train
|
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Controller/ConfigurationController.php#L83-L102
|
esperecyan/dictionary-php
|
src/serializer/PictsenseSerializer.php
|
PictsenseSerializer.serializeWord
|
protected function serializeWord(array $word): string
{
if (!isset($word['type'][0]) || $word['type'][0] !== 'selection') {
$answers = $this->getOrderedAnswers($word);
if ($answers) {
$pictsenseParser = new PictsenseParser();
foreach ($answers as $answer) {
if (!$pictsenseParser->isHiraganaCodePoints($answer)) {
break;
}
if (mb_strlen($answer, 'UTF-8') <= PictsenseParser::WORD_MAX) {
$output = $answer;
break;
}
}
}
}
if (!isset($output)) {
$output = '';
$this->logUnserializableError('ピクトセンス', $word);
}
return $output;
}
|
php
|
protected function serializeWord(array $word): string
{
if (!isset($word['type'][0]) || $word['type'][0] !== 'selection') {
$answers = $this->getOrderedAnswers($word);
if ($answers) {
$pictsenseParser = new PictsenseParser();
foreach ($answers as $answer) {
if (!$pictsenseParser->isHiraganaCodePoints($answer)) {
break;
}
if (mb_strlen($answer, 'UTF-8') <= PictsenseParser::WORD_MAX) {
$output = $answer;
break;
}
}
}
}
if (!isset($output)) {
$output = '';
$this->logUnserializableError('ピクトセンス', $word);
}
return $output;
}
|
[
"protected",
"function",
"serializeWord",
"(",
"array",
"$",
"word",
")",
":",
"string",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"word",
"[",
"'type'",
"]",
"[",
"0",
"]",
")",
"||",
"$",
"word",
"[",
"'type'",
"]",
"[",
"0",
"]",
"!==",
"'selection'",
")",
"{",
"$",
"answers",
"=",
"$",
"this",
"->",
"getOrderedAnswers",
"(",
"$",
"word",
")",
";",
"if",
"(",
"$",
"answers",
")",
"{",
"$",
"pictsenseParser",
"=",
"new",
"PictsenseParser",
"(",
")",
";",
"foreach",
"(",
"$",
"answers",
"as",
"$",
"answer",
")",
"{",
"if",
"(",
"!",
"$",
"pictsenseParser",
"->",
"isHiraganaCodePoints",
"(",
"$",
"answer",
")",
")",
"{",
"break",
";",
"}",
"if",
"(",
"mb_strlen",
"(",
"$",
"answer",
",",
"'UTF-8'",
")",
"<=",
"PictsenseParser",
"::",
"WORD_MAX",
")",
"{",
"$",
"output",
"=",
"$",
"answer",
";",
"break",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"output",
")",
")",
"{",
"$",
"output",
"=",
"''",
";",
"$",
"this",
"->",
"logUnserializableError",
"(",
"'ピクトセンス', $word);",
"",
"",
"",
"",
"",
"}",
"return",
"$",
"output",
";",
"}"
] |
一つのお題を表す配列を直列化します。
@param (string|string[]|float)[][] $word
@return string 末尾に改行は含みません。直列化できないお題だった場合は空文字列を返します。
|
[
"一つのお題を表す配列を直列化します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/PictsenseSerializer.php#L18-L41
|
etki/opencart-core-installer
|
src/DebugPrinter.php
|
DebugPrinter.log
|
public static function log($message, $args = null)
{
if (getenv('DEBUG') || getenv('OPENCART_INSTALLER_DEBUG')) {
if ($args) {
if (!is_array($args)) {
$args = array($args);
}
$message = vsprintf($message, $args);
}
echo 'OpencartInstaller: ' . $message . PHP_EOL;
}
}
|
php
|
public static function log($message, $args = null)
{
if (getenv('DEBUG') || getenv('OPENCART_INSTALLER_DEBUG')) {
if ($args) {
if (!is_array($args)) {
$args = array($args);
}
$message = vsprintf($message, $args);
}
echo 'OpencartInstaller: ' . $message . PHP_EOL;
}
}
|
[
"public",
"static",
"function",
"log",
"(",
"$",
"message",
",",
"$",
"args",
"=",
"null",
")",
"{",
"if",
"(",
"getenv",
"(",
"'DEBUG'",
")",
"||",
"getenv",
"(",
"'OPENCART_INSTALLER_DEBUG'",
")",
")",
"{",
"if",
"(",
"$",
"args",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"args",
")",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"$",
"args",
")",
";",
"}",
"$",
"message",
"=",
"vsprintf",
"(",
"$",
"message",
",",
"$",
"args",
")",
";",
"}",
"echo",
"'OpencartInstaller: '",
".",
"$",
"message",
".",
"PHP_EOL",
";",
"}",
"}"
] |
Writes debug message to stdout.
@param string $message Message to be shown.
@param array|string|null $args Additional arguments for message
formatting.
@return void
@since 0.1.0
|
[
"Writes",
"debug",
"message",
"to",
"stdout",
"."
] |
train
|
https://github.com/etki/opencart-core-installer/blob/e651c94982afe966cd36977bbdc2ff4f7e785475/src/DebugPrinter.php#L24-L35
|
darkwebdesign/doctrine-unit-testing
|
src/Mocks/DriverMock.php
|
DriverMock.getSchemaManager
|
public function getSchemaManager(Connection $conn)
{
if ($this->_schemaManagerMock == null) {
return new SchemaManagerMock($conn);
}
return $this->_schemaManagerMock;
}
|
php
|
public function getSchemaManager(Connection $conn)
{
if ($this->_schemaManagerMock == null) {
return new SchemaManagerMock($conn);
}
return $this->_schemaManagerMock;
}
|
[
"public",
"function",
"getSchemaManager",
"(",
"Connection",
"$",
"conn",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_schemaManagerMock",
"==",
"null",
")",
"{",
"return",
"new",
"SchemaManagerMock",
"(",
"$",
"conn",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_schemaManagerMock",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/darkwebdesign/doctrine-unit-testing/blob/0daf50359563bc0679925e573a7105d6cd57168a/src/Mocks/DriverMock.php#L47-L54
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.open
|
public function open($save_path, $name)
{
$this->path = $this->config[ 'filePath' ];
if ($this->isSupported() === false) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_UNSUPPORTED', [$this->path]);
}
return false;
}
$this->filePath = $this->path
. $name . '-' // we'll use the session cookie name as a prefix to avoid collisions
. ($this->config[ 'match' ]->ip ? md5($_SERVER[ 'REMOTE_ADDR' ]) . '-' : '');
return true;
}
|
php
|
public function open($save_path, $name)
{
$this->path = $this->config[ 'filePath' ];
if ($this->isSupported() === false) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_UNSUPPORTED', [$this->path]);
}
return false;
}
$this->filePath = $this->path
. $name . '-' // we'll use the session cookie name as a prefix to avoid collisions
. ($this->config[ 'match' ]->ip ? md5($_SERVER[ 'REMOTE_ADDR' ]) . '-' : '');
return true;
}
|
[
"public",
"function",
"open",
"(",
"$",
"save_path",
",",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"path",
"=",
"$",
"this",
"->",
"config",
"[",
"'filePath'",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"isSupported",
"(",
")",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'SESSION_E_FILE_UNSUPPORTED'",
",",
"[",
"$",
"this",
"->",
"path",
"]",
")",
";",
"}",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"filePath",
"=",
"$",
"this",
"->",
"path",
".",
"$",
"name",
".",
"'-'",
"// we'll use the session cookie name as a prefix to avoid collisions\r",
".",
"(",
"$",
"this",
"->",
"config",
"[",
"'match'",
"]",
"->",
"ip",
"?",
"md5",
"(",
"$",
"_SERVER",
"[",
"'REMOTE_ADDR'",
"]",
")",
".",
"'-'",
":",
"''",
")",
";",
"return",
"true",
";",
"}"
] |
FileHandler::open
Initialize session
@link http://php.net/manual/en/sessionhandlerinterface.open.php
@param string $save_path The path where to store/retrieve the session.
@param string $name The session name.
@return bool <p>
The return value (usually TRUE on success, FALSE on failure).
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0
|
[
"FileHandler",
"::",
"open"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L81-L98
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.isSupported
|
public function isSupported()
{
if ( ! is_writable($this->path)) {
@mkdir($this->path, 0777, true);
}
return (bool)is_writable($this->path);
}
|
php
|
public function isSupported()
{
if ( ! is_writable($this->path)) {
@mkdir($this->path, 0777, true);
}
return (bool)is_writable($this->path);
}
|
[
"public",
"function",
"isSupported",
"(",
")",
"{",
"if",
"(",
"!",
"is_writable",
"(",
"$",
"this",
"->",
"path",
")",
")",
"{",
"@",
"mkdir",
"(",
"$",
"this",
"->",
"path",
",",
"0777",
",",
"true",
")",
";",
"}",
"return",
"(",
"bool",
")",
"is_writable",
"(",
"$",
"this",
"->",
"path",
")",
";",
"}"
] |
FileHandler::isSupported
Checks if this platform is supported on this system.
@return bool Returns FALSE if unsupported.
|
[
"FileHandler",
"::",
"isSupported"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L109-L116
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.destroy
|
public function destroy($session_id)
{
if ($this->close()) {
return file_exists($this->filePath . $session_id)
? (unlink($this->filePath . $session_id) && $this->destroyCookie())
: true;
} elseif ($this->filePath !== null) {
clearstatcache();
return file_exists($this->filePath . $session_id)
? (unlink($this->filePath . $session_id) && $this->destroyCookie())
: true;
}
return false;
}
|
php
|
public function destroy($session_id)
{
if ($this->close()) {
return file_exists($this->filePath . $session_id)
? (unlink($this->filePath . $session_id) && $this->destroyCookie())
: true;
} elseif ($this->filePath !== null) {
clearstatcache();
return file_exists($this->filePath . $session_id)
? (unlink($this->filePath . $session_id) && $this->destroyCookie())
: true;
}
return false;
}
|
[
"public",
"function",
"destroy",
"(",
"$",
"session_id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"close",
"(",
")",
")",
"{",
"return",
"file_exists",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
")",
"?",
"(",
"unlink",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
")",
"&&",
"$",
"this",
"->",
"destroyCookie",
"(",
")",
")",
":",
"true",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"filePath",
"!==",
"null",
")",
"{",
"clearstatcache",
"(",
")",
";",
"return",
"file_exists",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
")",
"?",
"(",
"unlink",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
")",
"&&",
"$",
"this",
"->",
"destroyCookie",
"(",
")",
")",
":",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
FileHandler::destroy
Destroy a session
@link http://php.net/manual/en/sessionhandlerinterface.destroy.php
@param string $session_id The session ID being destroyed.
@return bool <p>
The return value (usually TRUE on success, FALSE on failure).
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0
|
[
"FileHandler",
"::",
"destroy"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L135-L150
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.close
|
public function close()
{
if (is_resource($this->file)) {
flock($this->file, LOCK_UN);
fclose($this->file);
$this->file = $this->isNewFile = $this->sessionId = null;
return true;
}
return true;
}
|
php
|
public function close()
{
if (is_resource($this->file)) {
flock($this->file, LOCK_UN);
fclose($this->file);
$this->file = $this->isNewFile = $this->sessionId = null;
return true;
}
return true;
}
|
[
"public",
"function",
"close",
"(",
")",
"{",
"if",
"(",
"is_resource",
"(",
"$",
"this",
"->",
"file",
")",
")",
"{",
"flock",
"(",
"$",
"this",
"->",
"file",
",",
"LOCK_UN",
")",
";",
"fclose",
"(",
"$",
"this",
"->",
"file",
")",
";",
"$",
"this",
"->",
"file",
"=",
"$",
"this",
"->",
"isNewFile",
"=",
"$",
"this",
"->",
"sessionId",
"=",
"null",
";",
"return",
"true",
";",
"}",
"return",
"true",
";",
"}"
] |
FileHandler::close
Close the session
@link http://php.net/manual/en/sessionhandlerinterface.close.php
@return bool <p>
The return value (usually TRUE on success, FALSE on failure).
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0
|
[
"FileHandler",
"::",
"close"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L166-L178
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.gc
|
public function gc($maxlifetime)
{
if ( ! is_dir($this->path) || ($directory = opendir($this->path)) === false) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_ON_GC', [$this->path]);
}
return false;
}
$ts = time() - $maxlifetime;
while (($file = readdir($directory)) !== false) {
// If the filename doesn't match this pattern, it's either not a session file or is not ours
if ( ! preg_match('/[' . $this->config[ 'name' ] . '-]+[0-9-a-f]+/', $file)
|| ! is_file($this->path . '/' . $file)
|| ($mtime = filemtime($this->path . '/' . $file)) === false
|| $mtime > $ts
) {
continue;
}
unlink($this->path . '/' . $file);
}
closedir($directory);
return true;
}
|
php
|
public function gc($maxlifetime)
{
if ( ! is_dir($this->path) || ($directory = opendir($this->path)) === false) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_ON_GC', [$this->path]);
}
return false;
}
$ts = time() - $maxlifetime;
while (($file = readdir($directory)) !== false) {
// If the filename doesn't match this pattern, it's either not a session file or is not ours
if ( ! preg_match('/[' . $this->config[ 'name' ] . '-]+[0-9-a-f]+/', $file)
|| ! is_file($this->path . '/' . $file)
|| ($mtime = filemtime($this->path . '/' . $file)) === false
|| $mtime > $ts
) {
continue;
}
unlink($this->path . '/' . $file);
}
closedir($directory);
return true;
}
|
[
"public",
"function",
"gc",
"(",
"$",
"maxlifetime",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"this",
"->",
"path",
")",
"||",
"(",
"$",
"directory",
"=",
"opendir",
"(",
"$",
"this",
"->",
"path",
")",
")",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'SESSION_E_FILE_ON_GC'",
",",
"[",
"$",
"this",
"->",
"path",
"]",
")",
";",
"}",
"return",
"false",
";",
"}",
"$",
"ts",
"=",
"time",
"(",
")",
"-",
"$",
"maxlifetime",
";",
"while",
"(",
"(",
"$",
"file",
"=",
"readdir",
"(",
"$",
"directory",
")",
")",
"!==",
"false",
")",
"{",
"// If the filename doesn't match this pattern, it's either not a session file or is not ours\r",
"if",
"(",
"!",
"preg_match",
"(",
"'/['",
".",
"$",
"this",
"->",
"config",
"[",
"'name'",
"]",
".",
"'-]+[0-9-a-f]+/'",
",",
"$",
"file",
")",
"||",
"!",
"is_file",
"(",
"$",
"this",
"->",
"path",
".",
"'/'",
".",
"$",
"file",
")",
"||",
"(",
"$",
"mtime",
"=",
"filemtime",
"(",
"$",
"this",
"->",
"path",
".",
"'/'",
".",
"$",
"file",
")",
")",
"===",
"false",
"||",
"$",
"mtime",
">",
"$",
"ts",
")",
"{",
"continue",
";",
"}",
"unlink",
"(",
"$",
"this",
"->",
"path",
".",
"'/'",
".",
"$",
"file",
")",
";",
"}",
"closedir",
"(",
"$",
"directory",
")",
";",
"return",
"true",
";",
"}"
] |
FileHandler::gc
Cleanup old sessions
@link http://php.net/manual/en/sessionhandlerinterface.gc.php
@param int $maxlifetime <p>
Sessions that have not updated for
the last maxlifetime seconds will be removed.
</p>
@return bool <p>
The return value (usually TRUE on success, FALSE on failure).
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0
|
[
"FileHandler",
"::",
"gc"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L200-L228
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.write
|
public function write($session_id, $session_data)
{
// If the two IDs don't match, we have a session_regenerate_id() call
// and we need to close the old handle and open a new one
if ($session_id !== $this->sessionId && ( ! $this->close() || $this->read($session_id) === false)) {
return false;
}
if ( ! is_resource($this->file)) {
return false;
} elseif ($this->fingerprint === md5($session_data)) {
return ($this->isNewFile)
? true
: touch($this->filePath . $session_id);
}
if ( ! $this->isNewFile) {
ftruncate($this->file, 0);
rewind($this->file);
}
if (($length = strlen($session_data)) > 0) {
for ($written = 0; $written < $length; $written += $result) {
if (($result = fwrite($this->file, substr($session_data, $written))) === false) {
break;
}
}
if ( ! is_int($result)) {
$this->fingerprint = md5(substr($session_data, 0, $written));
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_ON_WRITE');
}
return false;
}
}
$this->fingerprint = md5($session_data);
return true;
}
|
php
|
public function write($session_id, $session_data)
{
// If the two IDs don't match, we have a session_regenerate_id() call
// and we need to close the old handle and open a new one
if ($session_id !== $this->sessionId && ( ! $this->close() || $this->read($session_id) === false)) {
return false;
}
if ( ! is_resource($this->file)) {
return false;
} elseif ($this->fingerprint === md5($session_data)) {
return ($this->isNewFile)
? true
: touch($this->filePath . $session_id);
}
if ( ! $this->isNewFile) {
ftruncate($this->file, 0);
rewind($this->file);
}
if (($length = strlen($session_data)) > 0) {
for ($written = 0; $written < $length; $written += $result) {
if (($result = fwrite($this->file, substr($session_data, $written))) === false) {
break;
}
}
if ( ! is_int($result)) {
$this->fingerprint = md5(substr($session_data, 0, $written));
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_ON_WRITE');
}
return false;
}
}
$this->fingerprint = md5($session_data);
return true;
}
|
[
"public",
"function",
"write",
"(",
"$",
"session_id",
",",
"$",
"session_data",
")",
"{",
"// If the two IDs don't match, we have a session_regenerate_id() call\r",
"// and we need to close the old handle and open a new one\r",
"if",
"(",
"$",
"session_id",
"!==",
"$",
"this",
"->",
"sessionId",
"&&",
"(",
"!",
"$",
"this",
"->",
"close",
"(",
")",
"||",
"$",
"this",
"->",
"read",
"(",
"$",
"session_id",
")",
"===",
"false",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"this",
"->",
"file",
")",
")",
"{",
"return",
"false",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"fingerprint",
"===",
"md5",
"(",
"$",
"session_data",
")",
")",
"{",
"return",
"(",
"$",
"this",
"->",
"isNewFile",
")",
"?",
"true",
":",
"touch",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"isNewFile",
")",
"{",
"ftruncate",
"(",
"$",
"this",
"->",
"file",
",",
"0",
")",
";",
"rewind",
"(",
"$",
"this",
"->",
"file",
")",
";",
"}",
"if",
"(",
"(",
"$",
"length",
"=",
"strlen",
"(",
"$",
"session_data",
")",
")",
">",
"0",
")",
"{",
"for",
"(",
"$",
"written",
"=",
"0",
";",
"$",
"written",
"<",
"$",
"length",
";",
"$",
"written",
"+=",
"$",
"result",
")",
"{",
"if",
"(",
"(",
"$",
"result",
"=",
"fwrite",
"(",
"$",
"this",
"->",
"file",
",",
"substr",
"(",
"$",
"session_data",
",",
"$",
"written",
")",
")",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"is_int",
"(",
"$",
"result",
")",
")",
"{",
"$",
"this",
"->",
"fingerprint",
"=",
"md5",
"(",
"substr",
"(",
"$",
"session_data",
",",
"0",
",",
"$",
"written",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'SESSION_E_FILE_ON_WRITE'",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"$",
"this",
"->",
"fingerprint",
"=",
"md5",
"(",
"$",
"session_data",
")",
";",
"return",
"true",
";",
"}"
] |
FileHandler::write
Write session data
@link http://php.net/manual/en/sessionhandlerinterface.write.php
@param string $session_id The session id.
@param string $session_data <p>
The encoded session data. This data is the
result of the PHP internally encoding
the $_SESSION superglobal to a serialized
string and passing it as this parameter.
Please note sessions use an alternative serialization method.
</p>
@return bool <p>
The return value (usually TRUE on success, FALSE on failure).
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0
|
[
"FileHandler",
"::",
"write"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L254-L296
|
o2system/session
|
src/Handlers/FileHandler.php
|
FileHandler.read
|
public function read($session_id)
{
// This might seem weird, but PHP 5.6 introduced session_reset(),
// which re-reads session data
if ($this->file === null) {
if (($this->file = fopen($this->filePath . $session_id, 'c+b')) === false) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_ON_READ', [$this->filePath . $session_id]);
}
return false;
}
if (flock($this->file, LOCK_EX) === false) {
fclose($this->file);
$this->file = null;
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_ON_LOCK', [$this->filePath . $session_id]);
}
return false;
}
// Needed by write() to detect session_regenerate_id() calls
$this->sessionId = $session_id;
if ($this->isNewFile) {
chmod($this->filePath . $session_id, 0600);
$this->fingerprint = md5('');
return '';
}
} else {
rewind($this->file);
}
$sessionData = '';
for ($read = 0, $length = filesize($this->filePath . $session_id); $read < $length; $read += strlen(
$buffer
)
) {
if (($buffer = fread($this->file, $length - $read)) === false) {
break;
}
$sessionData .= $buffer;
}
$this->fingerprint = md5($sessionData);
return $sessionData;
}
|
php
|
public function read($session_id)
{
// This might seem weird, but PHP 5.6 introduced session_reset(),
// which re-reads session data
if ($this->file === null) {
if (($this->file = fopen($this->filePath . $session_id, 'c+b')) === false) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_FILE_ON_READ', [$this->filePath . $session_id]);
}
return false;
}
if (flock($this->file, LOCK_EX) === false) {
fclose($this->file);
$this->file = null;
if ($this->logger instanceof LoggerInterface) {
$this->logger->error('SESSION_E_ON_LOCK', [$this->filePath . $session_id]);
}
return false;
}
// Needed by write() to detect session_regenerate_id() calls
$this->sessionId = $session_id;
if ($this->isNewFile) {
chmod($this->filePath . $session_id, 0600);
$this->fingerprint = md5('');
return '';
}
} else {
rewind($this->file);
}
$sessionData = '';
for ($read = 0, $length = filesize($this->filePath . $session_id); $read < $length; $read += strlen(
$buffer
)
) {
if (($buffer = fread($this->file, $length - $read)) === false) {
break;
}
$sessionData .= $buffer;
}
$this->fingerprint = md5($sessionData);
return $sessionData;
}
|
[
"public",
"function",
"read",
"(",
"$",
"session_id",
")",
"{",
"// This might seem weird, but PHP 5.6 introduced session_reset(),\r",
"// which re-reads session data\r",
"if",
"(",
"$",
"this",
"->",
"file",
"===",
"null",
")",
"{",
"if",
"(",
"(",
"$",
"this",
"->",
"file",
"=",
"fopen",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
",",
"'c+b'",
")",
")",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'SESSION_E_FILE_ON_READ'",
",",
"[",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
"]",
")",
";",
"}",
"return",
"false",
";",
"}",
"if",
"(",
"flock",
"(",
"$",
"this",
"->",
"file",
",",
"LOCK_EX",
")",
"===",
"false",
")",
"{",
"fclose",
"(",
"$",
"this",
"->",
"file",
")",
";",
"$",
"this",
"->",
"file",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'SESSION_E_ON_LOCK'",
",",
"[",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
"]",
")",
";",
"}",
"return",
"false",
";",
"}",
"// Needed by write() to detect session_regenerate_id() calls\r",
"$",
"this",
"->",
"sessionId",
"=",
"$",
"session_id",
";",
"if",
"(",
"$",
"this",
"->",
"isNewFile",
")",
"{",
"chmod",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
",",
"0600",
")",
";",
"$",
"this",
"->",
"fingerprint",
"=",
"md5",
"(",
"''",
")",
";",
"return",
"''",
";",
"}",
"}",
"else",
"{",
"rewind",
"(",
"$",
"this",
"->",
"file",
")",
";",
"}",
"$",
"sessionData",
"=",
"''",
";",
"for",
"(",
"$",
"read",
"=",
"0",
",",
"$",
"length",
"=",
"filesize",
"(",
"$",
"this",
"->",
"filePath",
".",
"$",
"session_id",
")",
";",
"$",
"read",
"<",
"$",
"length",
";",
"$",
"read",
"+=",
"strlen",
"(",
"$",
"buffer",
")",
")",
"{",
"if",
"(",
"(",
"$",
"buffer",
"=",
"fread",
"(",
"$",
"this",
"->",
"file",
",",
"$",
"length",
"-",
"$",
"read",
")",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"$",
"sessionData",
".=",
"$",
"buffer",
";",
"}",
"$",
"this",
"->",
"fingerprint",
"=",
"md5",
"(",
"$",
"sessionData",
")",
";",
"return",
"$",
"sessionData",
";",
"}"
] |
FileHandler::read
Read session data
@link http://php.net/manual/en/sessionhandlerinterface.read.php
@param string $session_id The session id to read data for.
@return string <p>
Returns an encoded string of the read data.
If nothing was read, it must return an empty string.
Note this value is returned internally to PHP for processing.
</p>
@since 5.4.0
|
[
"FileHandler",
"::",
"read"
] |
train
|
https://github.com/o2system/session/blob/49f2af67b876a58c0895ac80fc64a01b27ea6a6d/src/Handlers/FileHandler.php#L316-L368
|
ryanwachtl/silverstripe-foundation-forms
|
code/pagetypes/FoundationFormPage.php
|
FoundationFormPage_Controller.submitFoundationForm
|
function submitFoundationForm($data, $form) {
if(isset($data['SecurityID'])) {
unset($data['SecurityID']);
}
Session::set('FoundationForm' . $this->ID, $data);
return $this->redirect($this->Link());
}
|
php
|
function submitFoundationForm($data, $form) {
if(isset($data['SecurityID'])) {
unset($data['SecurityID']);
}
Session::set('FoundationForm' . $this->ID, $data);
return $this->redirect($this->Link());
}
|
[
"function",
"submitFoundationForm",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'SecurityID'",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"data",
"[",
"'SecurityID'",
"]",
")",
";",
"}",
"Session",
"::",
"set",
"(",
"'FoundationForm'",
".",
"$",
"this",
"->",
"ID",
",",
"$",
"data",
")",
";",
"return",
"$",
"this",
"->",
"redirect",
"(",
"$",
"this",
"->",
"Link",
"(",
")",
")",
";",
"}"
] |
submit the form and redirect back to the form
|
[
"submit",
"the",
"form",
"and",
"redirect",
"back",
"to",
"the",
"form"
] |
train
|
https://github.com/ryanwachtl/silverstripe-foundation-forms/blob/9055449fcb895811187124d81e57b7c93948403f/code/pagetypes/FoundationFormPage.php#L145-L152
|
crossjoin/Css
|
src/Crossjoin/Css/Format/Rule/AtImport/ImportRule.php
|
ImportRule.parseRuleString
|
protected function parseRuleString($ruleString)
{
$charset = $this->getCharset();
// Remove at-rule and unnecessary white-spaces
$ruleString = preg_replace('/^[ \r\n\t\f]*@import[ \r\n\t\f]+/i', '', $ruleString);
$ruleString = trim($ruleString, " \r\n\t\f");
// Remove trailing semicolon
$ruleString = rtrim($ruleString, ";");
$isEscaped = false;
$inFunction = false;
$url = "";
$mediaQuery = "";
$currentPart = "";
for ($i = 0, $j = mb_strlen($ruleString, $charset); $i < $j; $i++) {
$char = mb_substr($ruleString, $i, 1, $charset);
if ($char === "\\") {
if ($isEscaped === false) {
$isEscaped = true;
} else {
$isEscaped = false;
}
} else {
if ($char === " ") {
if ($isEscaped === false) {
if ($inFunction == false) {
$currentPart = trim($currentPart, " \r\n\t\f");
if ($currentPart !== "") {
if ($url === "") {
$url = trim($currentPart, " \r\n\t\f");
} else {
$mediaQuery .= trim($currentPart, " \r\n\t\f");
$mediaQuery .= $char;
}
$currentPart = "";
}
}
} else {
$currentPart .= $char;
}
} elseif ($isEscaped === false && $char === "(") {
$inFunction = true;
$currentPart .= $char;
} elseif ($isEscaped === false && $char === ")") {
$inFunction = false;
$currentPart .= $char;
} else {
$currentPart .= $char;
}
}
// Reset escaped flag
if ($isEscaped === true && $char !== "\\") {
$isEscaped = false;
}
}
if ($currentPart !== "") {
$currentPart = trim($currentPart, " \r\n\t\f");
if ($currentPart !== "") {
if ($url === "") {
$url = trim($currentPart, " \r\n\t\f");
} else {
$mediaQuery .= trim($currentPart, " \r\n\t\f");
}
}
}
// Get URL value
$url = Url::extractUrl($url);
$this->setUrl($url);
// Process media query
$mediaRule = new MediaRule($mediaQuery);
$this->setQueries($mediaRule->getQueries());
}
|
php
|
protected function parseRuleString($ruleString)
{
$charset = $this->getCharset();
// Remove at-rule and unnecessary white-spaces
$ruleString = preg_replace('/^[ \r\n\t\f]*@import[ \r\n\t\f]+/i', '', $ruleString);
$ruleString = trim($ruleString, " \r\n\t\f");
// Remove trailing semicolon
$ruleString = rtrim($ruleString, ";");
$isEscaped = false;
$inFunction = false;
$url = "";
$mediaQuery = "";
$currentPart = "";
for ($i = 0, $j = mb_strlen($ruleString, $charset); $i < $j; $i++) {
$char = mb_substr($ruleString, $i, 1, $charset);
if ($char === "\\") {
if ($isEscaped === false) {
$isEscaped = true;
} else {
$isEscaped = false;
}
} else {
if ($char === " ") {
if ($isEscaped === false) {
if ($inFunction == false) {
$currentPart = trim($currentPart, " \r\n\t\f");
if ($currentPart !== "") {
if ($url === "") {
$url = trim($currentPart, " \r\n\t\f");
} else {
$mediaQuery .= trim($currentPart, " \r\n\t\f");
$mediaQuery .= $char;
}
$currentPart = "";
}
}
} else {
$currentPart .= $char;
}
} elseif ($isEscaped === false && $char === "(") {
$inFunction = true;
$currentPart .= $char;
} elseif ($isEscaped === false && $char === ")") {
$inFunction = false;
$currentPart .= $char;
} else {
$currentPart .= $char;
}
}
// Reset escaped flag
if ($isEscaped === true && $char !== "\\") {
$isEscaped = false;
}
}
if ($currentPart !== "") {
$currentPart = trim($currentPart, " \r\n\t\f");
if ($currentPart !== "") {
if ($url === "") {
$url = trim($currentPart, " \r\n\t\f");
} else {
$mediaQuery .= trim($currentPart, " \r\n\t\f");
}
}
}
// Get URL value
$url = Url::extractUrl($url);
$this->setUrl($url);
// Process media query
$mediaRule = new MediaRule($mediaQuery);
$this->setQueries($mediaRule->getQueries());
}
|
[
"protected",
"function",
"parseRuleString",
"(",
"$",
"ruleString",
")",
"{",
"$",
"charset",
"=",
"$",
"this",
"->",
"getCharset",
"(",
")",
";",
"// Remove at-rule and unnecessary white-spaces",
"$",
"ruleString",
"=",
"preg_replace",
"(",
"'/^[ \\r\\n\\t\\f]*@import[ \\r\\n\\t\\f]+/i'",
",",
"''",
",",
"$",
"ruleString",
")",
";",
"$",
"ruleString",
"=",
"trim",
"(",
"$",
"ruleString",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"// Remove trailing semicolon",
"$",
"ruleString",
"=",
"rtrim",
"(",
"$",
"ruleString",
",",
"\";\"",
")",
";",
"$",
"isEscaped",
"=",
"false",
";",
"$",
"inFunction",
"=",
"false",
";",
"$",
"url",
"=",
"\"\"",
";",
"$",
"mediaQuery",
"=",
"\"\"",
";",
"$",
"currentPart",
"=",
"\"\"",
";",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"j",
"=",
"mb_strlen",
"(",
"$",
"ruleString",
",",
"$",
"charset",
")",
";",
"$",
"i",
"<",
"$",
"j",
";",
"$",
"i",
"++",
")",
"{",
"$",
"char",
"=",
"mb_substr",
"(",
"$",
"ruleString",
",",
"$",
"i",
",",
"1",
",",
"$",
"charset",
")",
";",
"if",
"(",
"$",
"char",
"===",
"\"\\\\\"",
")",
"{",
"if",
"(",
"$",
"isEscaped",
"===",
"false",
")",
"{",
"$",
"isEscaped",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"isEscaped",
"=",
"false",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"char",
"===",
"\" \"",
")",
"{",
"if",
"(",
"$",
"isEscaped",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"inFunction",
"==",
"false",
")",
"{",
"$",
"currentPart",
"=",
"trim",
"(",
"$",
"currentPart",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"if",
"(",
"$",
"currentPart",
"!==",
"\"\"",
")",
"{",
"if",
"(",
"$",
"url",
"===",
"\"\"",
")",
"{",
"$",
"url",
"=",
"trim",
"(",
"$",
"currentPart",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"}",
"else",
"{",
"$",
"mediaQuery",
".=",
"trim",
"(",
"$",
"currentPart",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"$",
"mediaQuery",
".=",
"$",
"char",
";",
"}",
"$",
"currentPart",
"=",
"\"\"",
";",
"}",
"}",
"}",
"else",
"{",
"$",
"currentPart",
".=",
"$",
"char",
";",
"}",
"}",
"elseif",
"(",
"$",
"isEscaped",
"===",
"false",
"&&",
"$",
"char",
"===",
"\"(\"",
")",
"{",
"$",
"inFunction",
"=",
"true",
";",
"$",
"currentPart",
".=",
"$",
"char",
";",
"}",
"elseif",
"(",
"$",
"isEscaped",
"===",
"false",
"&&",
"$",
"char",
"===",
"\")\"",
")",
"{",
"$",
"inFunction",
"=",
"false",
";",
"$",
"currentPart",
".=",
"$",
"char",
";",
"}",
"else",
"{",
"$",
"currentPart",
".=",
"$",
"char",
";",
"}",
"}",
"// Reset escaped flag",
"if",
"(",
"$",
"isEscaped",
"===",
"true",
"&&",
"$",
"char",
"!==",
"\"\\\\\"",
")",
"{",
"$",
"isEscaped",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"$",
"currentPart",
"!==",
"\"\"",
")",
"{",
"$",
"currentPart",
"=",
"trim",
"(",
"$",
"currentPart",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"if",
"(",
"$",
"currentPart",
"!==",
"\"\"",
")",
"{",
"if",
"(",
"$",
"url",
"===",
"\"\"",
")",
"{",
"$",
"url",
"=",
"trim",
"(",
"$",
"currentPart",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"}",
"else",
"{",
"$",
"mediaQuery",
".=",
"trim",
"(",
"$",
"currentPart",
",",
"\" \\r\\n\\t\\f\"",
")",
";",
"}",
"}",
"}",
"// Get URL value",
"$",
"url",
"=",
"Url",
"::",
"extractUrl",
"(",
"$",
"url",
")",
";",
"$",
"this",
"->",
"setUrl",
"(",
"$",
"url",
")",
";",
"// Process media query",
"$",
"mediaRule",
"=",
"new",
"MediaRule",
"(",
"$",
"mediaQuery",
")",
";",
"$",
"this",
"->",
"setQueries",
"(",
"$",
"mediaRule",
"->",
"getQueries",
"(",
")",
")",
";",
"}"
] |
Parses the import rule.
@param string $ruleString
|
[
"Parses",
"the",
"import",
"rule",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/AtImport/ImportRule.php#L109-L186
|
shawnsandy/ui-pages
|
src/Classes/Markdown.php
|
Markdown.markdown
|
public function markdown($markdown, $page = null)
{
$file = $markdown . '.md';
if (isset($page)) {
$file = $page . '/' . $markdown . '.md';
}
if (!Storage::disk('markdown')->exists($file)) {
return false;
}
$array = $this->markdownToArray($file);
return $array ;
}
|
php
|
public function markdown($markdown, $page = null)
{
$file = $markdown . '.md';
if (isset($page)) {
$file = $page . '/' . $markdown . '.md';
}
if (!Storage::disk('markdown')->exists($file)) {
return false;
}
$array = $this->markdownToArray($file);
return $array ;
}
|
[
"public",
"function",
"markdown",
"(",
"$",
"markdown",
",",
"$",
"page",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"$",
"markdown",
".",
"'.md'",
";",
"if",
"(",
"isset",
"(",
"$",
"page",
")",
")",
"{",
"$",
"file",
"=",
"$",
"page",
".",
"'/'",
".",
"$",
"markdown",
".",
"'.md'",
";",
"}",
"if",
"(",
"!",
"Storage",
"::",
"disk",
"(",
"'markdown'",
")",
"->",
"exists",
"(",
"$",
"file",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"array",
"=",
"$",
"this",
"->",
"markdownToArray",
"(",
"$",
"file",
")",
";",
"return",
"$",
"array",
";",
"}"
] |
Parses and output a markdown file
@param string $markdown File name
@param null $page File directory
@return string
|
[
"Parses",
"and",
"output",
"a",
"markdown",
"file"
] |
train
|
https://github.com/shawnsandy/ui-pages/blob/11584c12fa3e2b9a5c513f4ec9e2eaf78c206ca8/src/Classes/Markdown.php#L44-L60
|
shawnsandy/ui-pages
|
src/Classes/Markdown.php
|
Markdown.markdownLink
|
public function markdownLink($file_path, $type = '')
{
$array = explode('/', $file_path);
$dir = $array[0];
$replace = array('-', '_');
$url = trim($dir, '.md');
$display_name = str_replace($replace, ' ', trim($dir, '.md'));
if (count($array) > 1) {
$name = trim($array[1], '.md');
$url = $dir . '?page=' . $name;
$display_name = str_replace($replace, ' ', $name);
}
$link = ($type == 'url') ? '/md/' . $url :
'<a href="/md/' . $url . '" class="markdown-link">' . $display_name .
'</a>';
return $link;
}
|
php
|
public function markdownLink($file_path, $type = '')
{
$array = explode('/', $file_path);
$dir = $array[0];
$replace = array('-', '_');
$url = trim($dir, '.md');
$display_name = str_replace($replace, ' ', trim($dir, '.md'));
if (count($array) > 1) {
$name = trim($array[1], '.md');
$url = $dir . '?page=' . $name;
$display_name = str_replace($replace, ' ', $name);
}
$link = ($type == 'url') ? '/md/' . $url :
'<a href="/md/' . $url . '" class="markdown-link">' . $display_name .
'</a>';
return $link;
}
|
[
"public",
"function",
"markdownLink",
"(",
"$",
"file_path",
",",
"$",
"type",
"=",
"''",
")",
"{",
"$",
"array",
"=",
"explode",
"(",
"'/'",
",",
"$",
"file_path",
")",
";",
"$",
"dir",
"=",
"$",
"array",
"[",
"0",
"]",
";",
"$",
"replace",
"=",
"array",
"(",
"'-'",
",",
"'_'",
")",
";",
"$",
"url",
"=",
"trim",
"(",
"$",
"dir",
",",
"'.md'",
")",
";",
"$",
"display_name",
"=",
"str_replace",
"(",
"$",
"replace",
",",
"' '",
",",
"trim",
"(",
"$",
"dir",
",",
"'.md'",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"array",
")",
">",
"1",
")",
"{",
"$",
"name",
"=",
"trim",
"(",
"$",
"array",
"[",
"1",
"]",
",",
"'.md'",
")",
";",
"$",
"url",
"=",
"$",
"dir",
".",
"'?page='",
".",
"$",
"name",
";",
"$",
"display_name",
"=",
"str_replace",
"(",
"$",
"replace",
",",
"' '",
",",
"$",
"name",
")",
";",
"}",
"$",
"link",
"=",
"(",
"$",
"type",
"==",
"'url'",
")",
"?",
"'/md/'",
".",
"$",
"url",
":",
"'<a href=\"/md/'",
".",
"$",
"url",
".",
"'\" class=\"markdown-link\">'",
".",
"$",
"display_name",
".",
"'</a>'",
";",
"return",
"$",
"link",
";",
"}"
] |
Converts a give md file path to a link
@param string $file_path file path
@param string $type url/link
@return mixed
|
[
"Converts",
"a",
"give",
"md",
"file",
"path",
"to",
"a",
"link"
] |
train
|
https://github.com/shawnsandy/ui-pages/blob/11584c12fa3e2b9a5c513f4ec9e2eaf78c206ca8/src/Classes/Markdown.php#L94-L116
|
shawnsandy/ui-pages
|
src/Classes/Markdown.php
|
Markdown.markdownMenu
|
public function markdownMenu($dir = null)
{
$md_files = $this->markdownFiles($dir);
$links = [];
foreach ($md_files as $file) {
$links[] = $this->markdownLink($file, $this->type);
}
return $links;
}
|
php
|
public function markdownMenu($dir = null)
{
$md_files = $this->markdownFiles($dir);
$links = [];
foreach ($md_files as $file) {
$links[] = $this->markdownLink($file, $this->type);
}
return $links;
}
|
[
"public",
"function",
"markdownMenu",
"(",
"$",
"dir",
"=",
"null",
")",
"{",
"$",
"md_files",
"=",
"$",
"this",
"->",
"markdownFiles",
"(",
"$",
"dir",
")",
";",
"$",
"links",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"md_files",
"as",
"$",
"file",
")",
"{",
"$",
"links",
"[",
"]",
"=",
"$",
"this",
"->",
"markdownLink",
"(",
"$",
"file",
",",
"$",
"this",
"->",
"type",
")",
";",
"}",
"return",
"$",
"links",
";",
"}"
] |
Returns an list or directory of array of markdown files
@param string $dir file dir
@return array
|
[
"Returns",
"an",
"list",
"or",
"directory",
"of",
"array",
"of",
"markdown",
"files"
] |
train
|
https://github.com/shawnsandy/ui-pages/blob/11584c12fa3e2b9a5c513f4ec9e2eaf78c206ca8/src/Classes/Markdown.php#L125-L136
|
shawnsandy/ui-pages
|
src/Classes/Markdown.php
|
Markdown.markdownPosts
|
public function markdownPosts($dir = null)
{
$source = collect($this->markdownFiles($dir));
if (empty($source)) {
return false;
}
//map files
$files = $source->map(
function ($file) {
$array = $this->markdownToArray($file);
$arr['url'] = $array['url'];
$arr['last_modified'] = $array['last_modified'];
$arr['time_ago'] = $array['time_ago'];
$arr['link'] = $array['link'];
$arr['title'] = $array['title'];
$arr['excerpt'] = $array['excerpt'];
$arr['content'] = $array['content'];
return $arr;
}
);
return $files;
}
|
php
|
public function markdownPosts($dir = null)
{
$source = collect($this->markdownFiles($dir));
if (empty($source)) {
return false;
}
//map files
$files = $source->map(
function ($file) {
$array = $this->markdownToArray($file);
$arr['url'] = $array['url'];
$arr['last_modified'] = $array['last_modified'];
$arr['time_ago'] = $array['time_ago'];
$arr['link'] = $array['link'];
$arr['title'] = $array['title'];
$arr['excerpt'] = $array['excerpt'];
$arr['content'] = $array['content'];
return $arr;
}
);
return $files;
}
|
[
"public",
"function",
"markdownPosts",
"(",
"$",
"dir",
"=",
"null",
")",
"{",
"$",
"source",
"=",
"collect",
"(",
"$",
"this",
"->",
"markdownFiles",
"(",
"$",
"dir",
")",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"source",
")",
")",
"{",
"return",
"false",
";",
"}",
"//map files",
"$",
"files",
"=",
"$",
"source",
"->",
"map",
"(",
"function",
"(",
"$",
"file",
")",
"{",
"$",
"array",
"=",
"$",
"this",
"->",
"markdownToArray",
"(",
"$",
"file",
")",
";",
"$",
"arr",
"[",
"'url'",
"]",
"=",
"$",
"array",
"[",
"'url'",
"]",
";",
"$",
"arr",
"[",
"'last_modified'",
"]",
"=",
"$",
"array",
"[",
"'last_modified'",
"]",
";",
"$",
"arr",
"[",
"'time_ago'",
"]",
"=",
"$",
"array",
"[",
"'time_ago'",
"]",
";",
"$",
"arr",
"[",
"'link'",
"]",
"=",
"$",
"array",
"[",
"'link'",
"]",
";",
"$",
"arr",
"[",
"'title'",
"]",
"=",
"$",
"array",
"[",
"'title'",
"]",
";",
"$",
"arr",
"[",
"'excerpt'",
"]",
"=",
"$",
"array",
"[",
"'excerpt'",
"]",
";",
"$",
"arr",
"[",
"'content'",
"]",
"=",
"$",
"array",
"[",
"'content'",
"]",
";",
"return",
"$",
"arr",
";",
"}",
")",
";",
"return",
"$",
"files",
";",
"}"
] |
Return and array of markdown
@param string $dir location of md directory
@return mixed
|
[
"Return",
"and",
"array",
"of",
"markdown"
] |
train
|
https://github.com/shawnsandy/ui-pages/blob/11584c12fa3e2b9a5c513f4ec9e2eaf78c206ca8/src/Classes/Markdown.php#L157-L185
|
shawnsandy/ui-pages
|
src/Classes/Markdown.php
|
Markdown.markdownToArray
|
public function markdownToArray($file)
{
$markdown = $this->markdown->transform(
Storage::disk('markdown')
->get($file)
);
$array = explode("\n", $markdown);
$data['url'] = $this->markdownLink($file, 'url');
$data['last_modified'] = date(
'Y-m-d',
Storage::disk('markdown')->lastModified($file)
);
$posted = Carbon::now()->parse($data['last_modified'])->diffForHumans();
$data['time_ago'] = $posted;
$data['link'] = $this->markdownLink($file);
$data['title'] = $array[0];
$data['excerpt'] = $array[2];
$data['content'] = str_replace($data['title'], '', $markdown);
return $data ;
}
|
php
|
public function markdownToArray($file)
{
$markdown = $this->markdown->transform(
Storage::disk('markdown')
->get($file)
);
$array = explode("\n", $markdown);
$data['url'] = $this->markdownLink($file, 'url');
$data['last_modified'] = date(
'Y-m-d',
Storage::disk('markdown')->lastModified($file)
);
$posted = Carbon::now()->parse($data['last_modified'])->diffForHumans();
$data['time_ago'] = $posted;
$data['link'] = $this->markdownLink($file);
$data['title'] = $array[0];
$data['excerpt'] = $array[2];
$data['content'] = str_replace($data['title'], '', $markdown);
return $data ;
}
|
[
"public",
"function",
"markdownToArray",
"(",
"$",
"file",
")",
"{",
"$",
"markdown",
"=",
"$",
"this",
"->",
"markdown",
"->",
"transform",
"(",
"Storage",
"::",
"disk",
"(",
"'markdown'",
")",
"->",
"get",
"(",
"$",
"file",
")",
")",
";",
"$",
"array",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"markdown",
")",
";",
"$",
"data",
"[",
"'url'",
"]",
"=",
"$",
"this",
"->",
"markdownLink",
"(",
"$",
"file",
",",
"'url'",
")",
";",
"$",
"data",
"[",
"'last_modified'",
"]",
"=",
"date",
"(",
"'Y-m-d'",
",",
"Storage",
"::",
"disk",
"(",
"'markdown'",
")",
"->",
"lastModified",
"(",
"$",
"file",
")",
")",
";",
"$",
"posted",
"=",
"Carbon",
"::",
"now",
"(",
")",
"->",
"parse",
"(",
"$",
"data",
"[",
"'last_modified'",
"]",
")",
"->",
"diffForHumans",
"(",
")",
";",
"$",
"data",
"[",
"'time_ago'",
"]",
"=",
"$",
"posted",
";",
"$",
"data",
"[",
"'link'",
"]",
"=",
"$",
"this",
"->",
"markdownLink",
"(",
"$",
"file",
")",
";",
"$",
"data",
"[",
"'title'",
"]",
"=",
"$",
"array",
"[",
"0",
"]",
";",
"$",
"data",
"[",
"'excerpt'",
"]",
"=",
"$",
"array",
"[",
"2",
"]",
";",
"$",
"data",
"[",
"'content'",
"]",
"=",
"str_replace",
"(",
"$",
"data",
"[",
"'title'",
"]",
",",
"''",
",",
"$",
"markdown",
")",
";",
"return",
"$",
"data",
";",
"}"
] |
Takes a markdown and converts it to array
@param string $file
@return array
|
[
"Takes",
"a",
"markdown",
"and",
"converts",
"it",
"to",
"array"
] |
train
|
https://github.com/shawnsandy/ui-pages/blob/11584c12fa3e2b9a5c513f4ec9e2eaf78c206ca8/src/Classes/Markdown.php#L194-L218
|
drupol/valuewrapper
|
src/Type/ArrayType.php
|
ArrayType.hash
|
public function hash(): string
{
if ($string = \json_encode($this->value())) {
return $this->doHash($string);
}
throw new \Exception('Unable to encode the value.');
}
|
php
|
public function hash(): string
{
if ($string = \json_encode($this->value())) {
return $this->doHash($string);
}
throw new \Exception('Unable to encode the value.');
}
|
[
"public",
"function",
"hash",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"string",
"=",
"\\",
"json_encode",
"(",
"$",
"this",
"->",
"value",
"(",
")",
")",
")",
"{",
"return",
"$",
"this",
"->",
"doHash",
"(",
"$",
"string",
")",
";",
"}",
"throw",
"new",
"\\",
"Exception",
"(",
"'Unable to encode the value.'",
")",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/drupol/valuewrapper/blob/49cc07e4d0284718c24ba6e9cf524c1f4226694e/src/Type/ArrayType.php#L25-L32
|
FrenchFrogs/framework
|
src/Filterer/Filterer.php
|
Filterer.setFilters
|
public function setFilters($filters)
{
if (!is_array($filters)) {
$this->clearFilters();
foreach(explode('|', $filters) as $filter) {
// searching for optional params
$params = [];
if (strpos($filter, ':')) {
list($filter, $params) = explode(':', $filter);
$params = (array) explode(',', $params);
}
$this->addFilter($filter, null, ...$params);
}
} else {
$this->filters = $filters;
}
return $this;
}
|
php
|
public function setFilters($filters)
{
if (!is_array($filters)) {
$this->clearFilters();
foreach(explode('|', $filters) as $filter) {
// searching for optional params
$params = [];
if (strpos($filter, ':')) {
list($filter, $params) = explode(':', $filter);
$params = (array) explode(',', $params);
}
$this->addFilter($filter, null, ...$params);
}
} else {
$this->filters = $filters;
}
return $this;
}
|
[
"public",
"function",
"setFilters",
"(",
"$",
"filters",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"filters",
")",
")",
"{",
"$",
"this",
"->",
"clearFilters",
"(",
")",
";",
"foreach",
"(",
"explode",
"(",
"'|'",
",",
"$",
"filters",
")",
"as",
"$",
"filter",
")",
"{",
"// searching for optional params",
"$",
"params",
"=",
"[",
"]",
";",
"if",
"(",
"strpos",
"(",
"$",
"filter",
",",
"':'",
")",
")",
"{",
"list",
"(",
"$",
"filter",
",",
"$",
"params",
")",
"=",
"explode",
"(",
"':'",
",",
"$",
"filter",
")",
";",
"$",
"params",
"=",
"(",
"array",
")",
"explode",
"(",
"','",
",",
"$",
"params",
")",
";",
"}",
"$",
"this",
"->",
"addFilter",
"(",
"$",
"filter",
",",
"null",
",",
"...",
"$",
"params",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"filters",
"=",
"$",
"filters",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Set all filter as an array
@param $filters
@return $this
|
[
"Set",
"all",
"filter",
"as",
"an",
"array"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Filterer/Filterer.php#L43-L64
|
FrenchFrogs/framework
|
src/Filterer/Filterer.php
|
Filterer.addFilter
|
public function addFilter($index, $method = null, ...$params)
{
$this->filters[$index] = [$method, $params];
return $this;
}
|
php
|
public function addFilter($index, $method = null, ...$params)
{
$this->filters[$index] = [$method, $params];
return $this;
}
|
[
"public",
"function",
"addFilter",
"(",
"$",
"index",
",",
"$",
"method",
"=",
"null",
",",
"...",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"filters",
"[",
"$",
"index",
"]",
"=",
"[",
"$",
"method",
",",
"$",
"params",
"]",
";",
"return",
"$",
"this",
";",
"}"
] |
Add a single filter to the filters container
@param $index
@param null $method
@param ...$params
@return $this
|
[
"Add",
"a",
"single",
"filter",
"to",
"the",
"filters",
"container"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Filterer/Filterer.php#L74-L78
|
FrenchFrogs/framework
|
src/Filterer/Filterer.php
|
Filterer.getFilter
|
public function getFilter($index)
{
if (!$this->hasFilter($index)) {
throw new \Exception('Impossible de trouver le filtre : ' . $index);
}
return $this->filters[$index];
}
|
php
|
public function getFilter($index)
{
if (!$this->hasFilter($index)) {
throw new \Exception('Impossible de trouver le filtre : ' . $index);
}
return $this->filters[$index];
}
|
[
"public",
"function",
"getFilter",
"(",
"$",
"index",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasFilter",
"(",
"$",
"index",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Impossible de trouver le filtre : '",
".",
"$",
"index",
")",
";",
"}",
"return",
"$",
"this",
"->",
"filters",
"[",
"$",
"index",
"]",
";",
"}"
] |
Return the filter from the filters container from the filter container
@param $index
@return mixed
@throws \Exception
|
[
"Return",
"the",
"filter",
"from",
"the",
"filters",
"container",
"from",
"the",
"filter",
"container"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Filterer/Filterer.php#L129-L136
|
FrenchFrogs/framework
|
src/Filterer/Filterer.php
|
Filterer.filter
|
public function filter($value)
{
foreach($this->getFilters() as $index => $filter) {
// Extract the params
list($method, $params) = $filter;
// If method is null, we use the index as the method name
$method = is_null($method) ? $index : $method;
// Build the params for the filter
array_unshift($params, $value);
// If it's a anonymous function
if (!is_string($method) && is_callable($method)) {
$value = call_user_func_array($method, $params);
// if it's a local method
} else {
if (!method_exists($this, $method)) {
throw new \Exception('Method "'. $method .'" not found for filter : ' . $index);
}
$value = call_user_func_array([$this, $method], $params);
}
}
return $value;
}
|
php
|
public function filter($value)
{
foreach($this->getFilters() as $index => $filter) {
// Extract the params
list($method, $params) = $filter;
// If method is null, we use the index as the method name
$method = is_null($method) ? $index : $method;
// Build the params for the filter
array_unshift($params, $value);
// If it's a anonymous function
if (!is_string($method) && is_callable($method)) {
$value = call_user_func_array($method, $params);
// if it's a local method
} else {
if (!method_exists($this, $method)) {
throw new \Exception('Method "'. $method .'" not found for filter : ' . $index);
}
$value = call_user_func_array([$this, $method], $params);
}
}
return $value;
}
|
[
"public",
"function",
"filter",
"(",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getFilters",
"(",
")",
"as",
"$",
"index",
"=>",
"$",
"filter",
")",
"{",
"// Extract the params",
"list",
"(",
"$",
"method",
",",
"$",
"params",
")",
"=",
"$",
"filter",
";",
"// If method is null, we use the index as the method name",
"$",
"method",
"=",
"is_null",
"(",
"$",
"method",
")",
"?",
"$",
"index",
":",
"$",
"method",
";",
"// Build the params for the filter",
"array_unshift",
"(",
"$",
"params",
",",
"$",
"value",
")",
";",
"// If it's a anonymous function",
"if",
"(",
"!",
"is_string",
"(",
"$",
"method",
")",
"&&",
"is_callable",
"(",
"$",
"method",
")",
")",
"{",
"$",
"value",
"=",
"call_user_func_array",
"(",
"$",
"method",
",",
"$",
"params",
")",
";",
"// if it's a local method",
"}",
"else",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
",",
"$",
"method",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Method \"'",
".",
"$",
"method",
".",
"'\" not found for filter : '",
".",
"$",
"index",
")",
";",
"}",
"$",
"value",
"=",
"call_user_func_array",
"(",
"[",
"$",
"this",
",",
"$",
"method",
"]",
",",
"$",
"params",
")",
";",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] |
Filter de value
Main method of the class
@param $value
@return mixed
@throws \Exception
|
[
"Filter",
"de",
"value"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Filterer/Filterer.php#L159-L188
|
FrenchFrogs/framework
|
src/Filterer/Filterer.php
|
Filterer.dateFormat
|
public function dateFormat($value, $format = 'd/m/Y')
{
if (!empty($value)) {
// passage de la date en datetime
if (strlen($value) == 10) {
$value .= ' 00:00:00';
}
// gestion d'une date vide
if ($value == '0000-00-00 00:00:00') {
$value = '';
} else {
$date = \DateTime::createFromFormat('Y-m-d H:i:s',$value);
//Check que la value est compatible avec le format
if($date !== false && !array_sum($date->getLastErrors())){
$value = $date->format($format);
}
}
}
return $value;
}
|
php
|
public function dateFormat($value, $format = 'd/m/Y')
{
if (!empty($value)) {
// passage de la date en datetime
if (strlen($value) == 10) {
$value .= ' 00:00:00';
}
// gestion d'une date vide
if ($value == '0000-00-00 00:00:00') {
$value = '';
} else {
$date = \DateTime::createFromFormat('Y-m-d H:i:s',$value);
//Check que la value est compatible avec le format
if($date !== false && !array_sum($date->getLastErrors())){
$value = $date->format($format);
}
}
}
return $value;
}
|
[
"public",
"function",
"dateFormat",
"(",
"$",
"value",
",",
"$",
"format",
"=",
"'d/m/Y'",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"// passage de la date en datetime",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
"==",
"10",
")",
"{",
"$",
"value",
".=",
"' 00:00:00'",
";",
"}",
"// gestion d'une date vide",
"if",
"(",
"$",
"value",
"==",
"'0000-00-00 00:00:00'",
")",
"{",
"$",
"value",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"date",
"=",
"\\",
"DateTime",
"::",
"createFromFormat",
"(",
"'Y-m-d H:i:s'",
",",
"$",
"value",
")",
";",
"//Check que la value est compatible avec le format",
"if",
"(",
"$",
"date",
"!==",
"false",
"&&",
"!",
"array_sum",
"(",
"$",
"date",
"->",
"getLastErrors",
"(",
")",
")",
")",
"{",
"$",
"value",
"=",
"$",
"date",
"->",
"format",
"(",
"$",
"format",
")",
";",
"}",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] |
Format a date
@param $value
@param string $format
@return string
|
[
"Format",
"a",
"date"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Filterer/Filterer.php#L232-L254
|
FrenchFrogs/framework
|
src/Filterer/Filterer.php
|
Filterer.wrap
|
public function wrap($value, $size, $replacement = '...')
{
if (strlen($value) > ($size - strlen($replacement))) {
$value = substr($value, 0, $size) .$replacement;
}
return $value;
}
|
php
|
public function wrap($value, $size, $replacement = '...')
{
if (strlen($value) > ($size - strlen($replacement))) {
$value = substr($value, 0, $size) .$replacement;
}
return $value;
}
|
[
"public",
"function",
"wrap",
"(",
"$",
"value",
",",
"$",
"size",
",",
"$",
"replacement",
"=",
"'...'",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
">",
"(",
"$",
"size",
"-",
"strlen",
"(",
"$",
"replacement",
")",
")",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"$",
"size",
")",
".",
"$",
"replacement",
";",
"}",
"return",
"$",
"value",
";",
"}"
] |
Wrap string
@param $value
@param $size
@param string $replacement
|
[
"Wrap",
"string"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Filterer/Filterer.php#L369-L376
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.addServer
|
public function addServer(int $engine, string $host = "127.0.0.1", int $port = 0): Server
{
$this->servers[] = new Server($engine, $host, $port);
return end($this->servers);
}
|
php
|
public function addServer(int $engine, string $host = "127.0.0.1", int $port = 0): Server
{
$this->servers[] = new Server($engine, $host, $port);
return end($this->servers);
}
|
[
"public",
"function",
"addServer",
"(",
"int",
"$",
"engine",
",",
"string",
"$",
"host",
"=",
"\"127.0.0.1\"",
",",
"int",
"$",
"port",
"=",
"0",
")",
":",
"Server",
"{",
"$",
"this",
"->",
"servers",
"[",
"]",
"=",
"new",
"Server",
"(",
"$",
"engine",
",",
"$",
"host",
",",
"$",
"port",
")",
";",
"return",
"end",
"(",
"$",
"this",
"->",
"servers",
")",
";",
"}"
] |
Add a server to connection queue
Multiple cache servers may be added before connection, if connection fails with first server then Comely
Cache component will try to connect to next server.
@param int $engine
@param string $host
@param int $port
@return Server
@throws ConnectionException
|
[
"Add",
"a",
"server",
"to",
"connection",
"queue"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L84-L88
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.connect
|
public function connect(): void
{
/** @var $server Server */
$attempts = 0;
foreach ($this->servers as $server) {
try {
$attempts++;
if ($server->engine === self::REDIS) {
$engine = new Redis($server);
} elseif ($server->engine === self::MEMCACHED) {
$engine = new Memcached($server);
}
// Reaching here means, connection successful!
break;
} catch (EngineException $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
}
}
// Connection successful?
if (isset($engine) && $engine instanceof EngineInterface) {
$this->engine = $engine;
return;
}
throw new ConnectionException('Failed to connect with cache server(s)', $attempts);
}
|
php
|
public function connect(): void
{
/** @var $server Server */
$attempts = 0;
foreach ($this->servers as $server) {
try {
$attempts++;
if ($server->engine === self::REDIS) {
$engine = new Redis($server);
} elseif ($server->engine === self::MEMCACHED) {
$engine = new Memcached($server);
}
// Reaching here means, connection successful!
break;
} catch (EngineException $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
}
}
// Connection successful?
if (isset($engine) && $engine instanceof EngineInterface) {
$this->engine = $engine;
return;
}
throw new ConnectionException('Failed to connect with cache server(s)', $attempts);
}
|
[
"public",
"function",
"connect",
"(",
")",
":",
"void",
"{",
"/** @var $server Server */",
"$",
"attempts",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"servers",
"as",
"$",
"server",
")",
"{",
"try",
"{",
"$",
"attempts",
"++",
";",
"if",
"(",
"$",
"server",
"->",
"engine",
"===",
"self",
"::",
"REDIS",
")",
"{",
"$",
"engine",
"=",
"new",
"Redis",
"(",
"$",
"server",
")",
";",
"}",
"elseif",
"(",
"$",
"server",
"->",
"engine",
"===",
"self",
"::",
"MEMCACHED",
")",
"{",
"$",
"engine",
"=",
"new",
"Memcached",
"(",
"$",
"server",
")",
";",
"}",
"// Reaching here means, connection successful!",
"break",
";",
"}",
"catch",
"(",
"EngineException",
"$",
"e",
")",
"{",
"trigger_error",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"E_USER_WARNING",
")",
";",
"}",
"}",
"// Connection successful?",
"if",
"(",
"isset",
"(",
"$",
"engine",
")",
"&&",
"$",
"engine",
"instanceof",
"EngineInterface",
")",
"{",
"$",
"this",
"->",
"engine",
"=",
"$",
"engine",
";",
"return",
";",
"}",
"throw",
"new",
"ConnectionException",
"(",
"'Failed to connect with cache server(s)'",
",",
"$",
"attempts",
")",
";",
"}"
] |
Establish connection with cache server(s)
This method will try to establish connection with servers in order they were added. Each failed connection
will trigger an error message (E_USER_WARNING), and if all of the connections fail then a ConnectionException
will be thrown.
@throws ConnectionException
|
[
"Establish",
"connection",
"with",
"cache",
"server",
"(",
"s",
")"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L109-L136
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.disconnect
|
public function disconnect(): void
{
if ($this->engine) {
$this->engine->disconnect();
}
$this->engine = null;
}
|
php
|
public function disconnect(): void
{
if ($this->engine) {
$this->engine->disconnect();
}
$this->engine = null;
}
|
[
"public",
"function",
"disconnect",
"(",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"engine",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"disconnect",
"(",
")",
";",
"}",
"$",
"this",
"->",
"engine",
"=",
"null",
";",
"}"
] |
Disconnect from currently connected cache server/engine
|
[
"Disconnect",
"from",
"currently",
"connected",
"cache",
"server",
"/",
"engine"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L141-L148
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.isConnected
|
public function isConnected(): bool
{
if ($this->engine) {
$connected = $this->engine->isConnected();
if (!$connected) {
$this->engine = null;
}
return $connected;
}
return false;
}
|
php
|
public function isConnected(): bool
{
if ($this->engine) {
$connected = $this->engine->isConnected();
if (!$connected) {
$this->engine = null;
}
return $connected;
}
return false;
}
|
[
"public",
"function",
"isConnected",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"engine",
")",
"{",
"$",
"connected",
"=",
"$",
"this",
"->",
"engine",
"->",
"isConnected",
"(",
")",
";",
"if",
"(",
"!",
"$",
"connected",
")",
"{",
"$",
"this",
"->",
"engine",
"=",
"null",
";",
"}",
"return",
"$",
"connected",
";",
"}",
"return",
"false",
";",
"}"
] |
Check connection status
@return bool
|
[
"Check",
"connection",
"status"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L154-L166
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.ping
|
public function ping(bool $reconnect = false): bool
{
if ($this->engine) {
$ping = $this->engine->ping();
if (!$ping) {
$this->engine = null;
if ($reconnect) {
$this->connect();
}
}
return $ping;
}
return false;
}
|
php
|
public function ping(bool $reconnect = false): bool
{
if ($this->engine) {
$ping = $this->engine->ping();
if (!$ping) {
$this->engine = null;
if ($reconnect) {
$this->connect();
}
}
return $ping;
}
return false;
}
|
[
"public",
"function",
"ping",
"(",
"bool",
"$",
"reconnect",
"=",
"false",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"engine",
")",
"{",
"$",
"ping",
"=",
"$",
"this",
"->",
"engine",
"->",
"ping",
"(",
")",
";",
"if",
"(",
"!",
"$",
"ping",
")",
"{",
"$",
"this",
"->",
"engine",
"=",
"null",
";",
"if",
"(",
"$",
"reconnect",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"}",
"}",
"return",
"$",
"ping",
";",
"}",
"return",
"false",
";",
"}"
] |
Ping Cache Server
This method will not only check the connection status, but also attempt to ping cache server. On failure,
cache component will be disconnected with cache server/engine. Optional $reconnect param. may be passed to
attempt reconnection on failure.
@param bool $reconnect
@return bool
@throws ConnectionException
@throws EngineException
|
[
"Ping",
"Cache",
"Server"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L180-L195
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.set
|
public function set(string $key, $value, int $ttl = 0): bool
{
$this->checkConnection(__METHOD__);
// Get type of value being stored
$valueType = gettype($value);
// Floats are evil, they should be converted to strings
if ($valueType === "double") {
$valueType = "string";
$value = strval($value);
}
// Check value data type and proceed further...
switch ($valueType) {
case "string":
if (strlen($value) >= $this->cacheableLengthFrom) {
$value = $this->encode(new CacheItem($key, $value, $ttl));
}
break;
case "object":
case "array":
$value = $this->encode(new CacheItem($key, $value, $ttl));
break;
case "NULL":
case "boolean":
$value = $this->encode(new CacheItem($key, $value, $ttl));
break;
default:
throw new CacheException(sprintf('Value of type "%s" cannot be stored on cache', $valueType));
}
$store = $this->engine->set($key, $value, $ttl);
if ($store && $this->index) {
$this->index->events()->trigger(Indexing::EVENT_ON_STORE)
->params($key, $valueType)
->fire();
}
return $store;
}
|
php
|
public function set(string $key, $value, int $ttl = 0): bool
{
$this->checkConnection(__METHOD__);
// Get type of value being stored
$valueType = gettype($value);
// Floats are evil, they should be converted to strings
if ($valueType === "double") {
$valueType = "string";
$value = strval($value);
}
// Check value data type and proceed further...
switch ($valueType) {
case "string":
if (strlen($value) >= $this->cacheableLengthFrom) {
$value = $this->encode(new CacheItem($key, $value, $ttl));
}
break;
case "object":
case "array":
$value = $this->encode(new CacheItem($key, $value, $ttl));
break;
case "NULL":
case "boolean":
$value = $this->encode(new CacheItem($key, $value, $ttl));
break;
default:
throw new CacheException(sprintf('Value of type "%s" cannot be stored on cache', $valueType));
}
$store = $this->engine->set($key, $value, $ttl);
if ($store && $this->index) {
$this->index->events()->trigger(Indexing::EVENT_ON_STORE)
->params($key, $valueType)
->fire();
}
return $store;
}
|
[
"public",
"function",
"set",
"(",
"string",
"$",
"key",
",",
"$",
"value",
",",
"int",
"$",
"ttl",
"=",
"0",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"// Get type of value being stored",
"$",
"valueType",
"=",
"gettype",
"(",
"$",
"value",
")",
";",
"// Floats are evil, they should be converted to strings",
"if",
"(",
"$",
"valueType",
"===",
"\"double\"",
")",
"{",
"$",
"valueType",
"=",
"\"string\"",
";",
"$",
"value",
"=",
"strval",
"(",
"$",
"value",
")",
";",
"}",
"// Check value data type and proceed further...",
"switch",
"(",
"$",
"valueType",
")",
"{",
"case",
"\"string\"",
":",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
">=",
"$",
"this",
"->",
"cacheableLengthFrom",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"encode",
"(",
"new",
"CacheItem",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"ttl",
")",
")",
";",
"}",
"break",
";",
"case",
"\"object\"",
":",
"case",
"\"array\"",
":",
"$",
"value",
"=",
"$",
"this",
"->",
"encode",
"(",
"new",
"CacheItem",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"ttl",
")",
")",
";",
"break",
";",
"case",
"\"NULL\"",
":",
"case",
"\"boolean\"",
":",
"$",
"value",
"=",
"$",
"this",
"->",
"encode",
"(",
"new",
"CacheItem",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"ttl",
")",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"CacheException",
"(",
"sprintf",
"(",
"'Value of type \"%s\" cannot be stored on cache'",
",",
"$",
"valueType",
")",
")",
";",
"}",
"$",
"store",
"=",
"$",
"this",
"->",
"engine",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"ttl",
")",
";",
"if",
"(",
"$",
"store",
"&&",
"$",
"this",
"->",
"index",
")",
"{",
"$",
"this",
"->",
"index",
"->",
"events",
"(",
")",
"->",
"trigger",
"(",
"Indexing",
"::",
"EVENT_ON_STORE",
")",
"->",
"params",
"(",
"$",
"key",
",",
"$",
"valueType",
")",
"->",
"fire",
"(",
")",
";",
"}",
"return",
"$",
"store",
";",
"}"
] |
Store a key/value on cache engine/server
Long strings, objects, arrays, NULL and booleans are first encoded as CacheItem and then stored serialized.
@param string $key
@param $value
@param int $ttl
@return bool
@throws CacheException
@throws EngineException
|
[
"Store",
"a",
"key",
"/",
"value",
"on",
"cache",
"engine",
"/",
"server"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L209-L249
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.get
|
public function get(string $key, bool $returnCacheable = false)
{
$this->checkConnection(__METHOD__);
$value = $this->engine->get($key);
if (is_string($value)) {
$value = trim($value); // trim
if (strlen($value) >= $this->cacheableLengthFrom) {
if (substr($value, 0, $this->cacheableIdLength) === $this->cacheableId) {
$value = $this->decode($key, $value);
if (!$returnCacheable) {
$value = $value->yield();
}
}
} elseif (preg_match('/^\-?[0-9]+$/', $value)) {
$value = intval($value); // Convert to integers
}
}
return $value;
}
|
php
|
public function get(string $key, bool $returnCacheable = false)
{
$this->checkConnection(__METHOD__);
$value = $this->engine->get($key);
if (is_string($value)) {
$value = trim($value); // trim
if (strlen($value) >= $this->cacheableLengthFrom) {
if (substr($value, 0, $this->cacheableIdLength) === $this->cacheableId) {
$value = $this->decode($key, $value);
if (!$returnCacheable) {
$value = $value->yield();
}
}
} elseif (preg_match('/^\-?[0-9]+$/', $value)) {
$value = intval($value); // Convert to integers
}
}
return $value;
}
|
[
"public",
"function",
"get",
"(",
"string",
"$",
"key",
",",
"bool",
"$",
"returnCacheable",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"engine",
"->",
"get",
"(",
"$",
"key",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"// trim",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
">=",
"$",
"this",
"->",
"cacheableLengthFrom",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"$",
"this",
"->",
"cacheableIdLength",
")",
"===",
"$",
"this",
"->",
"cacheableId",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"decode",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"if",
"(",
"!",
"$",
"returnCacheable",
")",
"{",
"$",
"value",
"=",
"$",
"value",
"->",
"yield",
"(",
")",
";",
"}",
"}",
"}",
"elseif",
"(",
"preg_match",
"(",
"'/^\\-?[0-9]+$/'",
",",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"intval",
"(",
"$",
"value",
")",
";",
"// Convert to integers",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] |
Get value for provided key from cache engine/server
This method will return NULL if key doesn't exist on cache server. An exception is thrown if there was an
error communicating with cache engine. If value is stored after encoding as CacheItem/CacheableInterface object
then the actual stored value will be returned, optionally param. $returnCacheable may be passed as TRUE
to get instance of CacheableInterface itself.
@param string $key
@param bool $returnCacheable
@return CacheableInterface|mixed
@throws CacheException
@throws EngineException
|
[
"Get",
"value",
"for",
"provided",
"key",
"from",
"cache",
"engine",
"/",
"server"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L265-L285
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.has
|
public function has(string $key): bool
{
$this->checkConnection(__METHOD__);
return $this->engine->has($key);
}
|
php
|
public function has(string $key): bool
{
$this->checkConnection(__METHOD__);
return $this->engine->has($key);
}
|
[
"public",
"function",
"has",
"(",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"return",
"$",
"this",
"->",
"engine",
"->",
"has",
"(",
"$",
"key",
")",
";",
"}"
] |
Checks if a data exists on cache server corresponding to provided key
@param string $key
@return bool
@throws CacheException
@throws EngineException
|
[
"Checks",
"if",
"a",
"data",
"exists",
"on",
"cache",
"server",
"corresponding",
"to",
"provided",
"key"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L295-L299
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.delete
|
public function delete(string $key): bool
{
$this->checkConnection(__METHOD__);
$delete = $this->engine->delete($key);
if ($delete && $this->index) {
$this->index->events()
->trigger(Indexing::EVENT_ON_DELETE)
->params($key)
->fire();
}
return $delete;
}
|
php
|
public function delete(string $key): bool
{
$this->checkConnection(__METHOD__);
$delete = $this->engine->delete($key);
if ($delete && $this->index) {
$this->index->events()
->trigger(Indexing::EVENT_ON_DELETE)
->params($key)
->fire();
}
return $delete;
}
|
[
"public",
"function",
"delete",
"(",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"$",
"delete",
"=",
"$",
"this",
"->",
"engine",
"->",
"delete",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"delete",
"&&",
"$",
"this",
"->",
"index",
")",
"{",
"$",
"this",
"->",
"index",
"->",
"events",
"(",
")",
"->",
"trigger",
"(",
"Indexing",
"::",
"EVENT_ON_DELETE",
")",
"->",
"params",
"(",
"$",
"key",
")",
"->",
"fire",
"(",
")",
";",
"}",
"return",
"$",
"delete",
";",
"}"
] |
Delete an stored item with provided key on cache server
@param string $key
@return bool
@throws CacheException
@throws EngineException
|
[
"Delete",
"an",
"stored",
"item",
"with",
"provided",
"key",
"on",
"cache",
"server"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L309-L321
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.flush
|
public function flush(): bool
{
$this->checkConnection(__METHOD__);
$flush = $this->engine->flush();
if ($flush && $this->index) {
$this->index->events()->trigger(Indexing::EVENT_ON_FLUSH)
->fire();
}
return $flush;
}
|
php
|
public function flush(): bool
{
$this->checkConnection(__METHOD__);
$flush = $this->engine->flush();
if ($flush && $this->index) {
$this->index->events()->trigger(Indexing::EVENT_ON_FLUSH)
->fire();
}
return $flush;
}
|
[
"public",
"function",
"flush",
"(",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"$",
"flush",
"=",
"$",
"this",
"->",
"engine",
"->",
"flush",
"(",
")",
";",
"if",
"(",
"$",
"flush",
"&&",
"$",
"this",
"->",
"index",
")",
"{",
"$",
"this",
"->",
"index",
"->",
"events",
"(",
")",
"->",
"trigger",
"(",
"Indexing",
"::",
"EVENT_ON_FLUSH",
")",
"->",
"fire",
"(",
")",
";",
"}",
"return",
"$",
"flush",
";",
"}"
] |
Flushes all stored data from cache server
@return bool
@throws CacheException
@throws EngineException
|
[
"Flushes",
"all",
"stored",
"data",
"from",
"cache",
"server"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L330-L340
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.countUp
|
public function countUp(string $key, int $inc = 1): int
{
$this->checkConnection(__METHOD__);
return $this->engine->countUp($key, $inc);
}
|
php
|
public function countUp(string $key, int $inc = 1): int
{
$this->checkConnection(__METHOD__);
return $this->engine->countUp($key, $inc);
}
|
[
"public",
"function",
"countUp",
"(",
"string",
"$",
"key",
",",
"int",
"$",
"inc",
"=",
"1",
")",
":",
"int",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"return",
"$",
"this",
"->",
"engine",
"->",
"countUp",
"(",
"$",
"key",
",",
"$",
"inc",
")",
";",
"}"
] |
Increase stored integer value
If key doesn't already exist, a new key will be created with value 0 before increment
@param string $key
@param int $inc
@return int
@throws CacheException
@throws EngineException
|
[
"Increase",
"stored",
"integer",
"value",
"If",
"key",
"doesn",
"t",
"already",
"exist",
"a",
"new",
"key",
"will",
"be",
"created",
"with",
"value",
"0",
"before",
"increment"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L352-L356
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.countDown
|
public function countDown(string $key, int $dec = 1): int
{
$this->checkConnection(__METHOD__);
return $this->engine->countDown($key, $dec);
}
|
php
|
public function countDown(string $key, int $dec = 1): int
{
$this->checkConnection(__METHOD__);
return $this->engine->countDown($key, $dec);
}
|
[
"public",
"function",
"countDown",
"(",
"string",
"$",
"key",
",",
"int",
"$",
"dec",
"=",
"1",
")",
":",
"int",
"{",
"$",
"this",
"->",
"checkConnection",
"(",
"__METHOD__",
")",
";",
"return",
"$",
"this",
"->",
"engine",
"->",
"countDown",
"(",
"$",
"key",
",",
"$",
"dec",
")",
";",
"}"
] |
Decrease stored integer value
If key doesn't already exist, a new key will be created with value 0 before decrement
@param string $key
@param int $dec
@return int
@throws CacheException
@throws EngineException
|
[
"Decrease",
"stored",
"integer",
"value",
"If",
"key",
"doesn",
"t",
"already",
"exist",
"a",
"new",
"key",
"will",
"be",
"created",
"with",
"value",
"0",
"before",
"decrement"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L368-L372
|
comelyio/comely
|
src/Comely/IO/Cache/Cache.php
|
Cache.setCacheableIdentifier
|
public function setCacheableIdentifier(string $id = null, int $length = null): self
{
if ($id) {
if (!preg_match('/^[a-zA-Z0-9\_\-\~\.]{8,32}$/', $id)) {
throw new CacheException('Invalid value passed to "setCacheableIdentifier" method');
}
$this->cacheableId = $id;
$this->cacheableIdLength = strlen($id);
}
if ($length) {
if ($length < 100 || $length <= $this->cacheableIdLength) {
throw new CacheException('Length of encoded Cacheable objects must start from at least 100');
}
$this->cacheableLengthFrom = $length;
}
return $this;
}
|
php
|
public function setCacheableIdentifier(string $id = null, int $length = null): self
{
if ($id) {
if (!preg_match('/^[a-zA-Z0-9\_\-\~\.]{8,32}$/', $id)) {
throw new CacheException('Invalid value passed to "setCacheableIdentifier" method');
}
$this->cacheableId = $id;
$this->cacheableIdLength = strlen($id);
}
if ($length) {
if ($length < 100 || $length <= $this->cacheableIdLength) {
throw new CacheException('Length of encoded Cacheable objects must start from at least 100');
}
$this->cacheableLengthFrom = $length;
}
return $this;
}
|
[
"public",
"function",
"setCacheableIdentifier",
"(",
"string",
"$",
"id",
"=",
"null",
",",
"int",
"$",
"length",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/^[a-zA-Z0-9\\_\\-\\~\\.]{8,32}$/'",
",",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"CacheException",
"(",
"'Invalid value passed to \"setCacheableIdentifier\" method'",
")",
";",
"}",
"$",
"this",
"->",
"cacheableId",
"=",
"$",
"id",
";",
"$",
"this",
"->",
"cacheableIdLength",
"=",
"strlen",
"(",
"$",
"id",
")",
";",
"}",
"if",
"(",
"$",
"length",
")",
"{",
"if",
"(",
"$",
"length",
"<",
"100",
"||",
"$",
"length",
"<=",
"$",
"this",
"->",
"cacheableIdLength",
")",
"{",
"throw",
"new",
"CacheException",
"(",
"'Length of encoded Cacheable objects must start from at least 100'",
")",
";",
"}",
"$",
"this",
"->",
"cacheableLengthFrom",
"=",
"$",
"length",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Set custom identifier for objects extending CacheableInterface
@param string|null $id
@param int|null $length
@return Cache
@throws CacheException
|
[
"Set",
"custom",
"identifier",
"for",
"objects",
"extending",
"CacheableInterface"
] |
train
|
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Cache/Cache.php#L431-L451
|
yishixincheng/Xl_WeApp_SDK
|
src/Service/PayService.php
|
PayService.orderQuery
|
public function orderQuery($params,$timeOut=6){
$url='https://api.mch.weixin.qq.com/pay/orderquery';
$inputObj=new WxPayParam();
$inputObj->setValues($params); //置入参数
if(!$inputObj->isKeySet("transaction_id")&&!$inputObj->isKeySet("out_trade_no")){
throw new \Exception("订单查询接口中,out_trade_no、transaction_id至少填一个!");
}
$inputObj->setValueByKey("appid",Config::getAppId());
$inputObj->setValueByKey("mch_id",Config::getMchid());
$inputObj->setValueByKey("nonce_str",static::getNonceStr()); //随机字符串
//签名
$inputObj->SetSign();
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response=static::postXmlCurl($xml,$url,false,$timeOut);
$result=WxPayResult::Init($response);
//上报数据
$this->reportCostTime($url,$startTimeStamp,$result);
return $result;
}
|
php
|
public function orderQuery($params,$timeOut=6){
$url='https://api.mch.weixin.qq.com/pay/orderquery';
$inputObj=new WxPayParam();
$inputObj->setValues($params); //置入参数
if(!$inputObj->isKeySet("transaction_id")&&!$inputObj->isKeySet("out_trade_no")){
throw new \Exception("订单查询接口中,out_trade_no、transaction_id至少填一个!");
}
$inputObj->setValueByKey("appid",Config::getAppId());
$inputObj->setValueByKey("mch_id",Config::getMchid());
$inputObj->setValueByKey("nonce_str",static::getNonceStr()); //随机字符串
//签名
$inputObj->SetSign();
$xml = $inputObj->ToXml();
$startTimeStamp = self::getMillisecond();//请求开始时间
$response=static::postXmlCurl($xml,$url,false,$timeOut);
$result=WxPayResult::Init($response);
//上报数据
$this->reportCostTime($url,$startTimeStamp,$result);
return $result;
}
|
[
"public",
"function",
"orderQuery",
"(",
"$",
"params",
",",
"$",
"timeOut",
"=",
"6",
")",
"{",
"$",
"url",
"=",
"'https://api.mch.weixin.qq.com/pay/orderquery'",
";",
"$",
"inputObj",
"=",
"new",
"WxPayParam",
"(",
")",
";",
"$",
"inputObj",
"->",
"setValues",
"(",
"$",
"params",
")",
";",
"//置入参数",
"if",
"(",
"!",
"$",
"inputObj",
"->",
"isKeySet",
"(",
"\"transaction_id\"",
")",
"&&",
"!",
"$",
"inputObj",
"->",
"isKeySet",
"(",
"\"out_trade_no\"",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"订单查询接口中,out_trade_no、transaction_id至少填一个!\");",
"",
"",
"}",
"$",
"inputObj",
"->",
"setValueByKey",
"(",
"\"appid\"",
",",
"Config",
"::",
"getAppId",
"(",
")",
")",
";",
"$",
"inputObj",
"->",
"setValueByKey",
"(",
"\"mch_id\"",
",",
"Config",
"::",
"getMchid",
"(",
")",
")",
";",
"$",
"inputObj",
"->",
"setValueByKey",
"(",
"\"nonce_str\"",
",",
"static",
"::",
"getNonceStr",
"(",
")",
")",
";",
"//随机字符串",
"//签名",
"$",
"inputObj",
"->",
"SetSign",
"(",
")",
";",
"$",
"xml",
"=",
"$",
"inputObj",
"->",
"ToXml",
"(",
")",
";",
"$",
"startTimeStamp",
"=",
"self",
"::",
"getMillisecond",
"(",
")",
";",
"//请求开始时间",
"$",
"response",
"=",
"static",
"::",
"postXmlCurl",
"(",
"$",
"xml",
",",
"$",
"url",
",",
"false",
",",
"$",
"timeOut",
")",
";",
"$",
"result",
"=",
"WxPayResult",
"::",
"Init",
"(",
"$",
"response",
")",
";",
"//上报数据",
"$",
"this",
"->",
"reportCostTime",
"(",
"$",
"url",
",",
"$",
"startTimeStamp",
",",
"$",
"result",
")",
";",
"return",
"$",
"result",
";",
"}"
] |
订单查询
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_2
|
[
"订单查询",
"https",
":",
"//",
"pay",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki",
"/",
"doc",
"/",
"api",
"/",
"wxa",
"/",
"wxa_api",
".",
"php?chapter",
"=",
"9_2"
] |
train
|
https://github.com/yishixincheng/Xl_WeApp_SDK/blob/26e58154e2aceccd6ffb92c4ed2b1c5a0b6414da/src/Service/PayService.php#L75-L102
|
yishixincheng/Xl_WeApp_SDK
|
src/Service/PayService.php
|
PayService.postXmlCurl
|
private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//如果有配置代理这里就设置代理
if(Config::getCURL_PROXY_HOST() != "0.0.0.0" && Config::getCURL_PROXY_PORT() != 0){
curl_setopt($ch,CURLOPT_PROXY, Config::getCURL_PROXY_HOST());
curl_setopt($ch,CURLOPT_PROXYPORT, Config::getCURL_PROXY_PORT());
}
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if($useCert == true){
//设置证书
//使用证书:cert 与 key 分别属于两个.pem文件
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, Config::getSSLCERT_PATH());
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, Config::getSSLKEY_PATH());
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new \Exception("curl出错,错误码:$error");
}
}
|
php
|
private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//如果有配置代理这里就设置代理
if(Config::getCURL_PROXY_HOST() != "0.0.0.0" && Config::getCURL_PROXY_PORT() != 0){
curl_setopt($ch,CURLOPT_PROXY, Config::getCURL_PROXY_HOST());
curl_setopt($ch,CURLOPT_PROXYPORT, Config::getCURL_PROXY_PORT());
}
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if($useCert == true){
//设置证书
//使用证书:cert 与 key 分别属于两个.pem文件
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, Config::getSSLCERT_PATH());
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, Config::getSSLKEY_PATH());
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new \Exception("curl出错,错误码:$error");
}
}
|
[
"private",
"static",
"function",
"postXmlCurl",
"(",
"$",
"xml",
",",
"$",
"url",
",",
"$",
"useCert",
"=",
"false",
",",
"$",
"second",
"=",
"30",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"//设置超时",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_TIMEOUT",
",",
"$",
"second",
")",
";",
"//如果有配置代理这里就设置代理",
"if",
"(",
"Config",
"::",
"getCURL_PROXY_HOST",
"(",
")",
"!=",
"\"0.0.0.0\"",
"&&",
"Config",
"::",
"getCURL_PROXY_PORT",
"(",
")",
"!=",
"0",
")",
"{",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_PROXY",
",",
"Config",
"::",
"getCURL_PROXY_HOST",
"(",
")",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_PROXYPORT",
",",
"Config",
"::",
"getCURL_PROXY_PORT",
"(",
")",
")",
";",
"}",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL",
",",
"$",
"url",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSL_VERIFYPEER",
",",
"TRUE",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSL_VERIFYHOST",
",",
"2",
")",
";",
"//严格校验",
"//设置header",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_HEADER",
",",
"FALSE",
")",
";",
"//要求结果为字符串且输出到屏幕上",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_RETURNTRANSFER",
",",
"TRUE",
")",
";",
"if",
"(",
"$",
"useCert",
"==",
"true",
")",
"{",
"//设置证书",
"//使用证书:cert 与 key 分别属于两个.pem文件",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSLCERTTYPE",
",",
"'PEM'",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSLCERT",
",",
"Config",
"::",
"getSSLCERT_PATH",
"(",
")",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSLKEYTYPE",
",",
"'PEM'",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSLKEY",
",",
"Config",
"::",
"getSSLKEY_PATH",
"(",
")",
")",
";",
"}",
"//post提交方式",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POST",
",",
"TRUE",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POSTFIELDS",
",",
"$",
"xml",
")",
";",
"//运行curl",
"$",
"data",
"=",
"curl_exec",
"(",
"$",
"ch",
")",
";",
"//返回结果",
"if",
"(",
"$",
"data",
")",
"{",
"curl_close",
"(",
"$",
"ch",
")",
";",
"return",
"$",
"data",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"curl_errno",
"(",
"$",
"ch",
")",
";",
"curl_close",
"(",
"$",
"ch",
")",
";",
"throw",
"new",
"\\",
"Exception",
"(",
"\"curl出错,错误码:$error\");",
"",
"",
"}",
"}"
] |
以post方式提交xml到对应的接口url
@param string $xml 需要post的xml数据
@param string $url url
@param bool $useCert 是否需要证书,默认不需要
@param int $second url执行超时时间,默认30s
@throws WxPayException
|
[
"以post方式提交xml到对应的接口url"
] |
train
|
https://github.com/yishixincheng/Xl_WeApp_SDK/blob/26e58154e2aceccd6ffb92c4ed2b1c5a0b6414da/src/Service/PayService.php#L347-L388
|
braincrafted/arrayquery
|
src/Braincrafted/ArrayQuery/QueryBuilder.php
|
QueryBuilder.getSelectEvaluation
|
protected function getSelectEvaluation($selectEvaluation = null)
{
if (null !== $selectEvaluation && false === ($selectEvaluation instanceof SelectEvaluation)) {
throw new \InvalidArgumentException('Argument "selectEvaluation" must be an instance of SelectEvaluation.');
}
if (null === $selectEvaluation) {
$selectEvaluation = new SelectEvaluation;
}
foreach (FilterFactory::getFilters() as $filter) {
$selectEvaluation->addFilter($filter);
}
return $selectEvaluation;
}
|
php
|
protected function getSelectEvaluation($selectEvaluation = null)
{
if (null !== $selectEvaluation && false === ($selectEvaluation instanceof SelectEvaluation)) {
throw new \InvalidArgumentException('Argument "selectEvaluation" must be an instance of SelectEvaluation.');
}
if (null === $selectEvaluation) {
$selectEvaluation = new SelectEvaluation;
}
foreach (FilterFactory::getFilters() as $filter) {
$selectEvaluation->addFilter($filter);
}
return $selectEvaluation;
}
|
[
"protected",
"function",
"getSelectEvaluation",
"(",
"$",
"selectEvaluation",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"selectEvaluation",
"&&",
"false",
"===",
"(",
"$",
"selectEvaluation",
"instanceof",
"SelectEvaluation",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Argument \"selectEvaluation\" must be an instance of SelectEvaluation.'",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"selectEvaluation",
")",
"{",
"$",
"selectEvaluation",
"=",
"new",
"SelectEvaluation",
";",
"}",
"foreach",
"(",
"FilterFactory",
"::",
"getFilters",
"(",
")",
"as",
"$",
"filter",
")",
"{",
"$",
"selectEvaluation",
"->",
"addFilter",
"(",
"$",
"filter",
")",
";",
"}",
"return",
"$",
"selectEvaluation",
";",
"}"
] |
@param SelectEvaluation $selectEvaluation
@return SelectEvaluation
|
[
"@param",
"SelectEvaluation",
"$selectEvaluation"
] |
train
|
https://github.com/braincrafted/arrayquery/blob/8b0c44ee76cea796589422f52e2f7130676b9bd1/src/Braincrafted/ArrayQuery/QueryBuilder.php#L56-L70
|
braincrafted/arrayquery
|
src/Braincrafted/ArrayQuery/QueryBuilder.php
|
QueryBuilder.getWhereEvaluation
|
protected function getWhereEvaluation($whereEvaluation = null)
{
if (null !== $whereEvaluation && false === ($whereEvaluation instanceof WhereEvaluation)) {
throw new \InvalidArgumentException('Argument "whereEvaluation" must be an instance of WhereEvaluation.');
}
if (null === $whereEvaluation) {
$whereEvaluation = new WhereEvaluation;
}
foreach (OperatorFactory::getOperators() as $operator) {
$whereEvaluation->addOperator($operator);
}
foreach (FilterFactory::getFilters() as $filter) {
$whereEvaluation->addFilter($filter);
}
return $whereEvaluation;
}
|
php
|
protected function getWhereEvaluation($whereEvaluation = null)
{
if (null !== $whereEvaluation && false === ($whereEvaluation instanceof WhereEvaluation)) {
throw new \InvalidArgumentException('Argument "whereEvaluation" must be an instance of WhereEvaluation.');
}
if (null === $whereEvaluation) {
$whereEvaluation = new WhereEvaluation;
}
foreach (OperatorFactory::getOperators() as $operator) {
$whereEvaluation->addOperator($operator);
}
foreach (FilterFactory::getFilters() as $filter) {
$whereEvaluation->addFilter($filter);
}
return $whereEvaluation;
}
|
[
"protected",
"function",
"getWhereEvaluation",
"(",
"$",
"whereEvaluation",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"whereEvaluation",
"&&",
"false",
"===",
"(",
"$",
"whereEvaluation",
"instanceof",
"WhereEvaluation",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Argument \"whereEvaluation\" must be an instance of WhereEvaluation.'",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"whereEvaluation",
")",
"{",
"$",
"whereEvaluation",
"=",
"new",
"WhereEvaluation",
";",
"}",
"foreach",
"(",
"OperatorFactory",
"::",
"getOperators",
"(",
")",
"as",
"$",
"operator",
")",
"{",
"$",
"whereEvaluation",
"->",
"addOperator",
"(",
"$",
"operator",
")",
";",
"}",
"foreach",
"(",
"FilterFactory",
"::",
"getFilters",
"(",
")",
"as",
"$",
"filter",
")",
"{",
"$",
"whereEvaluation",
"->",
"addFilter",
"(",
"$",
"filter",
")",
";",
"}",
"return",
"$",
"whereEvaluation",
";",
"}"
] |
@param WhereEvaluation $whereEvaluation
@return WhereEvaluation
|
[
"@param",
"WhereEvaluation",
"$whereEvaluation"
] |
train
|
https://github.com/braincrafted/arrayquery/blob/8b0c44ee76cea796589422f52e2f7130676b9bd1/src/Braincrafted/ArrayQuery/QueryBuilder.php#L77-L94
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.decodeJson
|
private function decodeJson(string $serialized)
{
$objectsAsArray = json_decode($serialized, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidJson(json_last_error_msg());
}
return $objectsAsArray;
}
|
php
|
private function decodeJson(string $serialized)
{
$objectsAsArray = json_decode($serialized, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidJson(json_last_error_msg());
}
return $objectsAsArray;
}
|
[
"private",
"function",
"decodeJson",
"(",
"string",
"$",
"serialized",
")",
"{",
"$",
"objectsAsArray",
"=",
"json_decode",
"(",
"$",
"serialized",
",",
"true",
")",
";",
"if",
"(",
"json_last_error",
"(",
")",
"!==",
"JSON_ERROR_NONE",
")",
"{",
"throw",
"new",
"InvalidJson",
"(",
"json_last_error_msg",
"(",
")",
")",
";",
"}",
"return",
"$",
"objectsAsArray",
";",
"}"
] |
@param string $serialized
@return mixed
@throws InvalidJson
|
[
"@param",
"string",
"$serialized"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L42-L51
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.deserialize
|
public function deserialize(string $serialized, ClassName $className = null)
{
$objectsAsArray = $this->decodeJson($serialized);
if ($className !== null) {
return $this->setObjectForClass($className, $objectsAsArray);
}
return $this->setObject($objectsAsArray);
}
|
php
|
public function deserialize(string $serialized, ClassName $className = null)
{
$objectsAsArray = $this->decodeJson($serialized);
if ($className !== null) {
return $this->setObjectForClass($className, $objectsAsArray);
}
return $this->setObject($objectsAsArray);
}
|
[
"public",
"function",
"deserialize",
"(",
"string",
"$",
"serialized",
",",
"ClassName",
"$",
"className",
"=",
"null",
")",
"{",
"$",
"objectsAsArray",
"=",
"$",
"this",
"->",
"decodeJson",
"(",
"$",
"serialized",
")",
";",
"if",
"(",
"$",
"className",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"setObjectForClass",
"(",
"$",
"className",
",",
"$",
"objectsAsArray",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setObject",
"(",
"$",
"objectsAsArray",
")",
";",
"}"
] |
Deserialize string with class as the root object
@param string $serialized
@param ClassName $className
@return object|object[]
@throws InvalidJson
@throws UndefinedIdentifierAttribute
@throws MissingIdentifierAttribute
|
[
"Deserialize",
"string",
"with",
"class",
"as",
"the",
"root",
"object"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L64-L73
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.deserializeCollection
|
public function deserializeCollection(string $serialized, ClassName $className)
{
$objectsAsArray = $this->decodeJson($serialized);
$objects = [];
foreach ($objectsAsArray as $attribute => $object) {
$objects[$attribute] = $this->setObjectForClass($className, $object);
}
return $objects;
}
|
php
|
public function deserializeCollection(string $serialized, ClassName $className)
{
$objectsAsArray = $this->decodeJson($serialized);
$objects = [];
foreach ($objectsAsArray as $attribute => $object) {
$objects[$attribute] = $this->setObjectForClass($className, $object);
}
return $objects;
}
|
[
"public",
"function",
"deserializeCollection",
"(",
"string",
"$",
"serialized",
",",
"ClassName",
"$",
"className",
")",
"{",
"$",
"objectsAsArray",
"=",
"$",
"this",
"->",
"decodeJson",
"(",
"$",
"serialized",
")",
";",
"$",
"objects",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"objectsAsArray",
"as",
"$",
"attribute",
"=>",
"$",
"object",
")",
"{",
"$",
"objects",
"[",
"$",
"attribute",
"]",
"=",
"$",
"this",
"->",
"setObjectForClass",
"(",
"$",
"className",
",",
"$",
"object",
")",
";",
"}",
"return",
"$",
"objects",
";",
"}"
] |
Deserialize string with class as the root object
@param string $serialized
@param ClassName $className
@return object[]
@throws InvalidJson
@throws UndefinedIdentifierAttribute
@throws MissingIdentifierAttribute
|
[
"Deserialize",
"string",
"with",
"class",
"as",
"the",
"root",
"object"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L86-L96
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.setObject
|
private function setObject(array $data)
{
$identifierAttribute = $this->configuration->getIdentifierAttribute();
if ($identifierAttribute === null) {
throw new UndefinedIdentifierAttribute();
}
// We found an identifier attribute, $data is a json object
if (isset($data[$identifierAttribute]) === true) {
return $this->setObjectForObjectData($identifierAttribute, $data);
}
// We don't found an identifier attribute, $data is a collection
return $this->setObjectForCollectionData($data);
}
|
php
|
private function setObject(array $data)
{
$identifierAttribute = $this->configuration->getIdentifierAttribute();
if ($identifierAttribute === null) {
throw new UndefinedIdentifierAttribute();
}
// We found an identifier attribute, $data is a json object
if (isset($data[$identifierAttribute]) === true) {
return $this->setObjectForObjectData($identifierAttribute, $data);
}
// We don't found an identifier attribute, $data is a collection
return $this->setObjectForCollectionData($data);
}
|
[
"private",
"function",
"setObject",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"identifierAttribute",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getIdentifierAttribute",
"(",
")",
";",
"if",
"(",
"$",
"identifierAttribute",
"===",
"null",
")",
"{",
"throw",
"new",
"UndefinedIdentifierAttribute",
"(",
")",
";",
"}",
"// We found an identifier attribute, $data is a json object",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"$",
"identifierAttribute",
"]",
")",
"===",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"setObjectForObjectData",
"(",
"$",
"identifierAttribute",
",",
"$",
"data",
")",
";",
"}",
"// We don't found an identifier attribute, $data is a collection",
"return",
"$",
"this",
"->",
"setObjectForCollectionData",
"(",
"$",
"data",
")",
";",
"}"
] |
Create class object with data
@param mixed[] $data
@return object|object[]
@throws UndefinedIdentifierAttribute
@throws MissingIdentifierAttribute
|
[
"Create",
"class",
"object",
"with",
"data"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L107-L122
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.setObjectForObjectData
|
private function setObjectForObjectData(string $identifierAttribute, array $data)
{
$configurationObject = $this->configuration
->getConfigurationObjectForIdentifier($data[$identifierAttribute]);
$className = $configurationObject->getClassName();
$fqdnClass = $className->getValue();
$object = new $fqdnClass();
foreach ($data as $attribute => $value) {
if ($attribute === $identifierAttribute) {
continue;
}
$type = $configurationObject->getTypeForAttribute($attribute);
$this->processDeserializeForType($type, $object, $value);
}
return $object;
}
|
php
|
private function setObjectForObjectData(string $identifierAttribute, array $data)
{
$configurationObject = $this->configuration
->getConfigurationObjectForIdentifier($data[$identifierAttribute]);
$className = $configurationObject->getClassName();
$fqdnClass = $className->getValue();
$object = new $fqdnClass();
foreach ($data as $attribute => $value) {
if ($attribute === $identifierAttribute) {
continue;
}
$type = $configurationObject->getTypeForAttribute($attribute);
$this->processDeserializeForType($type, $object, $value);
}
return $object;
}
|
[
"private",
"function",
"setObjectForObjectData",
"(",
"string",
"$",
"identifierAttribute",
",",
"array",
"$",
"data",
")",
"{",
"$",
"configurationObject",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getConfigurationObjectForIdentifier",
"(",
"$",
"data",
"[",
"$",
"identifierAttribute",
"]",
")",
";",
"$",
"className",
"=",
"$",
"configurationObject",
"->",
"getClassName",
"(",
")",
";",
"$",
"fqdnClass",
"=",
"$",
"className",
"->",
"getValue",
"(",
")",
";",
"$",
"object",
"=",
"new",
"$",
"fqdnClass",
"(",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"attribute",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"attribute",
"===",
"$",
"identifierAttribute",
")",
"{",
"continue",
";",
"}",
"$",
"type",
"=",
"$",
"configurationObject",
"->",
"getTypeForAttribute",
"(",
"$",
"attribute",
")",
";",
"$",
"this",
"->",
"processDeserializeForType",
"(",
"$",
"type",
",",
"$",
"object",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"object",
";",
"}"
] |
@param string $identifierAttribute
@param array $data
@return mixed
|
[
"@param",
"string",
"$identifierAttribute",
"@param",
"array",
"$data"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L130-L148
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.setObjectForCollectionData
|
private function setObjectForCollectionData(array $data)
{
$objects = [];
foreach ($data as $attribute => $object) {
if (is_array($object) === false) {
throw new MissingIdentifierAttribute();
}
$objects[$attribute] = $this->setObject($object);
}
return $objects;
}
|
php
|
private function setObjectForCollectionData(array $data)
{
$objects = [];
foreach ($data as $attribute => $object) {
if (is_array($object) === false) {
throw new MissingIdentifierAttribute();
}
$objects[$attribute] = $this->setObject($object);
}
return $objects;
}
|
[
"private",
"function",
"setObjectForCollectionData",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"objects",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"attribute",
"=>",
"$",
"object",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"object",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"MissingIdentifierAttribute",
"(",
")",
";",
"}",
"$",
"objects",
"[",
"$",
"attribute",
"]",
"=",
"$",
"this",
"->",
"setObject",
"(",
"$",
"object",
")",
";",
"}",
"return",
"$",
"objects",
";",
"}"
] |
@param mixed[] $data
@return object[]
@throws MissingIdentifierAttribute
@throws UndefinedIdentifierAttribute
|
[
"@param",
"mixed",
"[]",
"$data"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L158-L170
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.setObjectForClass
|
private function setObjectForClass(ClassName $className, array $data)
{
$fqdnClass = $className->getValue();
$object = new $fqdnClass();
foreach ($data as $attribute => $value) {
$configurationObject = $this->configuration->getConfigurationObjectForClass($className);
$type = $configurationObject->getTypeForAttribute($attribute);
$this->processDeserializeForType($type, $object, $value);
}
return $object;
}
|
php
|
private function setObjectForClass(ClassName $className, array $data)
{
$fqdnClass = $className->getValue();
$object = new $fqdnClass();
foreach ($data as $attribute => $value) {
$configurationObject = $this->configuration->getConfigurationObjectForClass($className);
$type = $configurationObject->getTypeForAttribute($attribute);
$this->processDeserializeForType($type, $object, $value);
}
return $object;
}
|
[
"private",
"function",
"setObjectForClass",
"(",
"ClassName",
"$",
"className",
",",
"array",
"$",
"data",
")",
"{",
"$",
"fqdnClass",
"=",
"$",
"className",
"->",
"getValue",
"(",
")",
";",
"$",
"object",
"=",
"new",
"$",
"fqdnClass",
"(",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"attribute",
"=>",
"$",
"value",
")",
"{",
"$",
"configurationObject",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getConfigurationObjectForClass",
"(",
"$",
"className",
")",
";",
"$",
"type",
"=",
"$",
"configurationObject",
"->",
"getTypeForAttribute",
"(",
"$",
"attribute",
")",
";",
"$",
"this",
"->",
"processDeserializeForType",
"(",
"$",
"type",
",",
"$",
"object",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"object",
";",
"}"
] |
Create $className object with data
@param ClassName $className
@param mixed[] $data
@return object|object[]
|
[
"Create",
"$className",
"object",
"with",
"data"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L180-L193
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.processDeserializeTypeMethod
|
private function processDeserializeTypeMethod(Type\Method $method, $object, $value): self
{
$object->{$method->setter()}($value);
return $this;
}
|
php
|
private function processDeserializeTypeMethod(Type\Method $method, $object, $value): self
{
$object->{$method->setter()}($value);
return $this;
}
|
[
"private",
"function",
"processDeserializeTypeMethod",
"(",
"Type",
"\\",
"Method",
"$",
"method",
",",
"$",
"object",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"object",
"->",
"{",
"$",
"method",
"->",
"setter",
"(",
")",
"}",
"(",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param Type\Method $method
@param object $object
@param mixed $value
@return Deserialize
|
[
"@param",
"Type",
"\\",
"Method",
"$method",
"@param",
"object",
"$object",
"@param",
"mixed",
"$value"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L224-L229
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.processDeserializeTypeObject
|
private function processDeserializeTypeObject(Type\Object $objectType, $object, $value): self
{
$object->{$objectType->setter()}($this->setObjectForClass($objectType->className(), $value));
return $this;
}
|
php
|
private function processDeserializeTypeObject(Type\Object $objectType, $object, $value): self
{
$object->{$objectType->setter()}($this->setObjectForClass($objectType->className(), $value));
return $this;
}
|
[
"private",
"function",
"processDeserializeTypeObject",
"(",
"Type",
"\\",
"Object",
"$",
"objectType",
",",
"$",
"object",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"object",
"->",
"{",
"$",
"objectType",
"->",
"setter",
"(",
")",
"}",
"(",
"$",
"this",
"->",
"setObjectForClass",
"(",
"$",
"objectType",
"->",
"className",
"(",
")",
",",
"$",
"value",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param Type\Object $objectType
@param object $object
@param mixed $value
@return Deserialize
|
[
"@param",
"Type",
"\\",
"Object",
"$objectType",
"@param",
"object",
"$object",
"@param",
"mixed",
"$value"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L238-L243
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.processDeserializeTypeCollectionObject
|
private function processDeserializeTypeCollectionObject(Type\Collection\Object $objectType, $object, array $values)
{
$objects = [];
foreach ($values as $key => $objectFromValue) {
$objects[$key] = $this->setObjectForClass($objectType->className(), $objectFromValue);
}
$object->{$objectType->setter()}($objects);
return $this;
}
|
php
|
private function processDeserializeTypeCollectionObject(Type\Collection\Object $objectType, $object, array $values)
{
$objects = [];
foreach ($values as $key => $objectFromValue) {
$objects[$key] = $this->setObjectForClass($objectType->className(), $objectFromValue);
}
$object->{$objectType->setter()}($objects);
return $this;
}
|
[
"private",
"function",
"processDeserializeTypeCollectionObject",
"(",
"Type",
"\\",
"Collection",
"\\",
"Object",
"$",
"objectType",
",",
"$",
"object",
",",
"array",
"$",
"values",
")",
"{",
"$",
"objects",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"key",
"=>",
"$",
"objectFromValue",
")",
"{",
"$",
"objects",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"setObjectForClass",
"(",
"$",
"objectType",
"->",
"className",
"(",
")",
",",
"$",
"objectFromValue",
")",
";",
"}",
"$",
"object",
"->",
"{",
"$",
"objectType",
"->",
"setter",
"(",
")",
"}",
"(",
"$",
"objects",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param Type\Collection\Object $objectType
@param object $object
@param array $values
@return Deserialize
|
[
"@param",
"Type",
"\\",
"Collection",
"\\",
"Object",
"$objectType",
"@param",
"object",
"$object",
"@param",
"array",
"$values"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L252-L262
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.processDeserializeTypeIdentifiedObject
|
private function processDeserializeTypeIdentifiedObject(Type\IdentifiedObject $objectType, $object, $value): self
{
$identifierAttribute = $this->configuration->getIdentifierAttribute();
if (isset($value[$identifierAttribute]) === false) {
return $this;
}
$configurationObject = $this->configuration->getConfigurationObjectForIdentifier($value[$identifierAttribute]);
if ($configurationObject instanceof Blackhole) {
return $this;
}
$object->{$objectType->setter()}($this->setObjectForClass($configurationObject->getClassName(), $value));
return $this;
}
|
php
|
private function processDeserializeTypeIdentifiedObject(Type\IdentifiedObject $objectType, $object, $value): self
{
$identifierAttribute = $this->configuration->getIdentifierAttribute();
if (isset($value[$identifierAttribute]) === false) {
return $this;
}
$configurationObject = $this->configuration->getConfigurationObjectForIdentifier($value[$identifierAttribute]);
if ($configurationObject instanceof Blackhole) {
return $this;
}
$object->{$objectType->setter()}($this->setObjectForClass($configurationObject->getClassName(), $value));
return $this;
}
|
[
"private",
"function",
"processDeserializeTypeIdentifiedObject",
"(",
"Type",
"\\",
"IdentifiedObject",
"$",
"objectType",
",",
"$",
"object",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"identifierAttribute",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getIdentifierAttribute",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"value",
"[",
"$",
"identifierAttribute",
"]",
")",
"===",
"false",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"configurationObject",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getConfigurationObjectForIdentifier",
"(",
"$",
"value",
"[",
"$",
"identifierAttribute",
"]",
")",
";",
"if",
"(",
"$",
"configurationObject",
"instanceof",
"Blackhole",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"object",
"->",
"{",
"$",
"objectType",
"->",
"setter",
"(",
")",
"}",
"(",
"$",
"this",
"->",
"setObjectForClass",
"(",
"$",
"configurationObject",
"->",
"getClassName",
"(",
")",
",",
"$",
"value",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param Type\IdentifiedObject $objectType
@param object $object
@param mixed $value
@return Deserialize
|
[
"@param",
"Type",
"\\",
"IdentifiedObject",
"$objectType",
"@param",
"object",
"$object",
"@param",
"mixed",
"$value"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L271-L288
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.processDeserializeTypeCollectionIdentifiedObject
|
private function processDeserializeTypeCollectionIdentifiedObject(
Type\Collection\IdentifiedObject $objectType,
$object,
array $values
): self {
$identifierAttribute = $this->configuration->getIdentifierAttribute();
$objects = [];
foreach ($values as $key => $objectFromValue) {
if (isset($objectFromValue[$identifierAttribute]) === false) {
continue;
}
$configurationObject =
$this->configuration->getConfigurationObjectForIdentifier($objectFromValue[$identifierAttribute]);
if ($configurationObject instanceof Blackhole) {
continue;
}
$objects[$key] = $this->setObjectForClass($configurationObject->getClassName(), $objectFromValue);
}
$object->{$objectType->setter()}($objects);
return $this;
}
|
php
|
private function processDeserializeTypeCollectionIdentifiedObject(
Type\Collection\IdentifiedObject $objectType,
$object,
array $values
): self {
$identifierAttribute = $this->configuration->getIdentifierAttribute();
$objects = [];
foreach ($values as $key => $objectFromValue) {
if (isset($objectFromValue[$identifierAttribute]) === false) {
continue;
}
$configurationObject =
$this->configuration->getConfigurationObjectForIdentifier($objectFromValue[$identifierAttribute]);
if ($configurationObject instanceof Blackhole) {
continue;
}
$objects[$key] = $this->setObjectForClass($configurationObject->getClassName(), $objectFromValue);
}
$object->{$objectType->setter()}($objects);
return $this;
}
|
[
"private",
"function",
"processDeserializeTypeCollectionIdentifiedObject",
"(",
"Type",
"\\",
"Collection",
"\\",
"IdentifiedObject",
"$",
"objectType",
",",
"$",
"object",
",",
"array",
"$",
"values",
")",
":",
"self",
"{",
"$",
"identifierAttribute",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getIdentifierAttribute",
"(",
")",
";",
"$",
"objects",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"key",
"=>",
"$",
"objectFromValue",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"objectFromValue",
"[",
"$",
"identifierAttribute",
"]",
")",
"===",
"false",
")",
"{",
"continue",
";",
"}",
"$",
"configurationObject",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getConfigurationObjectForIdentifier",
"(",
"$",
"objectFromValue",
"[",
"$",
"identifierAttribute",
"]",
")",
";",
"if",
"(",
"$",
"configurationObject",
"instanceof",
"Blackhole",
")",
"{",
"continue",
";",
"}",
"$",
"objects",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"setObjectForClass",
"(",
"$",
"configurationObject",
"->",
"getClassName",
"(",
")",
",",
"$",
"objectFromValue",
")",
";",
"}",
"$",
"object",
"->",
"{",
"$",
"objectType",
"->",
"setter",
"(",
")",
"}",
"(",
"$",
"objects",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param Type\Collection\IdentifiedObject $objectType
@param object $object
@param array $values
@return Deserialize
|
[
"@param",
"Type",
"\\",
"Collection",
"\\",
"IdentifiedObject",
"$objectType",
"@param",
"object",
"$object",
"@param",
"array",
"$values"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L297-L323
|
blackprism/serializer
|
src/Blackprism/Serializer/Json/Deserialize.php
|
Deserialize.processDeserializeTypeHandler
|
private function processDeserializeTypeHandler(Type\Handler $handler, $object, $value): self
{
$handler->deserializer()->deserialize($object, $value);
return $this;
}
|
php
|
private function processDeserializeTypeHandler(Type\Handler $handler, $object, $value): self
{
$handler->deserializer()->deserialize($object, $value);
return $this;
}
|
[
"private",
"function",
"processDeserializeTypeHandler",
"(",
"Type",
"\\",
"Handler",
"$",
"handler",
",",
"$",
"object",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"handler",
"->",
"deserializer",
"(",
")",
"->",
"deserialize",
"(",
"$",
"object",
",",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param Type\Handler $handler
@param object $object
@param mixed $value
@return Deserialize
|
[
"@param",
"Type",
"\\",
"Handler",
"$handler",
"@param",
"object",
"$object",
"@param",
"mixed",
"$value"
] |
train
|
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Json/Deserialize.php#L332-L337
|
FrenchFrogs/framework
|
src/Html/Element/Button.php
|
Button.icon
|
public function icon($icon, $is_icon_only = true)
{
$this->setIcon($icon);
($is_icon_only) ? $this->enableIconOnly() : $this->disableIconOnly();
return $this;
}
|
php
|
public function icon($icon, $is_icon_only = true)
{
$this->setIcon($icon);
($is_icon_only) ? $this->enableIconOnly() : $this->disableIconOnly();
return $this;
}
|
[
"public",
"function",
"icon",
"(",
"$",
"icon",
",",
"$",
"is_icon_only",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"setIcon",
"(",
"$",
"icon",
")",
";",
"(",
"$",
"is_icon_only",
")",
"?",
"$",
"this",
"->",
"enableIconOnly",
"(",
")",
":",
"$",
"this",
"->",
"disableIconOnly",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
Fast setting for icon
@param $icon
@param bool|true $is_icon_only
@return $this
|
[
"Fast",
"setting",
"for",
"icon"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Html/Element/Button.php#L48-L53
|
phpmob/twig-modify-bundle
|
DependencyInjection/PhpMobTwigModifyExtension.php
|
PhpMobTwigModifyExtension.load
|
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('phpmob_twig_modify.enabled', $config['enabled']);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
if ($config['cache_adapter']) {
$definition = $container->getDefinition('phpmob_twig_modify.modifier');
$definition->replaceArgument(0, new Reference($config['cache_adapter']));
}
foreach ($config['modifiers'] as $key => $options) {
$definition->addMethodCall('addType', [$key, $options]);
}
}
|
php
|
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('phpmob_twig_modify.enabled', $config['enabled']);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
if ($config['cache_adapter']) {
$definition = $container->getDefinition('phpmob_twig_modify.modifier');
$definition->replaceArgument(0, new Reference($config['cache_adapter']));
}
foreach ($config['modifiers'] as $key => $options) {
$definition->addMethodCall('addType', [$key, $options]);
}
}
|
[
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"configuration",
"=",
"new",
"Configuration",
"(",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"processConfiguration",
"(",
"$",
"configuration",
",",
"$",
"configs",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'phpmob_twig_modify.enabled'",
",",
"$",
"config",
"[",
"'enabled'",
"]",
")",
";",
"$",
"loader",
"=",
"new",
"Loader",
"\\",
"XmlFileLoader",
"(",
"$",
"container",
",",
"new",
"FileLocator",
"(",
"__DIR__",
".",
"'/../Resources/config'",
")",
")",
";",
"$",
"loader",
"->",
"load",
"(",
"'services.xml'",
")",
";",
"if",
"(",
"$",
"config",
"[",
"'cache_adapter'",
"]",
")",
"{",
"$",
"definition",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"'phpmob_twig_modify.modifier'",
")",
";",
"$",
"definition",
"->",
"replaceArgument",
"(",
"0",
",",
"new",
"Reference",
"(",
"$",
"config",
"[",
"'cache_adapter'",
"]",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"config",
"[",
"'modifiers'",
"]",
"as",
"$",
"key",
"=>",
"$",
"options",
")",
"{",
"$",
"definition",
"->",
"addMethodCall",
"(",
"'addType'",
",",
"[",
"$",
"key",
",",
"$",
"options",
"]",
")",
";",
"}",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/phpmob/twig-modify-bundle/blob/30b70ca3ea7b902f2f29c8457cd4f8da45b1d29e/DependencyInjection/PhpMobTwigModifyExtension.php#L36-L54
|
yosmanyga/resource
|
src/Yosmanyga/Resource/Reader/Iterator/InMemoryReader.php
|
InMemoryReader.open
|
public function open(Resource $resource)
{
$this->data = $resource->getMetadata('data');
if (!is_array($this->data)) {
throw new \InvalidArgumentException('Resource "data" metadata is not an array');
}
}
|
php
|
public function open(Resource $resource)
{
$this->data = $resource->getMetadata('data');
if (!is_array($this->data)) {
throw new \InvalidArgumentException('Resource "data" metadata is not an array');
}
}
|
[
"public",
"function",
"open",
"(",
"Resource",
"$",
"resource",
")",
"{",
"$",
"this",
"->",
"data",
"=",
"$",
"resource",
"->",
"getMetadata",
"(",
"'data'",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Resource \"data\" metadata is not an array'",
")",
";",
"}",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Reader/Iterator/InMemoryReader.php#L38-L45
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.