repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
list | docstring
stringlengths 3
47.2k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.prepareNormalSql
|
private function prepareNormalSql(array $searchCriteria, string $classname, string $andOr, int $fKey): string
{
$sql = '';
$textFields = $this->getTextFields($classname);
list($searchField, $operator, $searchValues) = $searchCriteria;
$operator = $this->operators[$operator];
if (trim($searchValues) !== '') {
if ($searchValues == '%%') {
$sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' IS NULL';
$sql .= ' OR ' . $classname . '.' . $searchField . ' = ""';
if ($this->model->$searchField === 0) {
$sql .= ' OR ' . $classname . '.' . $searchField . ' = 0';
}
$sql .= ')';
} elseif ($searchValues == '$$') {
$sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' IS NOT NULL';
$sql .= ' OR ' . $classname . '.' . $searchField . ' != ""';
if ($this->model->$searchField === 0) {
$sql .= ' OR ' . $classname . '.' . $searchField . ' != 0';
}
$sql .= ')';
} else {
if (strpos($searchValues, '|')) {
$searchValues = explode('|', $searchValues);
} else {
$searchValues = [$searchValues];
}
foreach ($searchValues as $vKey => $value) {
if ((in_array($searchField, $textFields)
&& preg_match('#^%[^%]+%|%[^%]+|[^%]+%$#i', $value))
|| $value == '%%'
) {
$operator = 'LIKE';
}
if (!$vKey) {
$sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' ' . $operator . ' :f' . $searchField . $fKey . $vKey;
} else {
$sql .= ' OR ' . $classname . '.' . $searchField . ' ' . $operator . ' :f' . $searchField . $fKey . $vKey;
}
$this->bindParamsKeys[] = 'f' . $searchField . $fKey . $vKey;
$this->bindParamsValues[] = $value;
}
$sql .= ')';
}
}
return $sql;
}
|
php
|
private function prepareNormalSql(array $searchCriteria, string $classname, string $andOr, int $fKey): string
{
$sql = '';
$textFields = $this->getTextFields($classname);
list($searchField, $operator, $searchValues) = $searchCriteria;
$operator = $this->operators[$operator];
if (trim($searchValues) !== '') {
if ($searchValues == '%%') {
$sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' IS NULL';
$sql .= ' OR ' . $classname . '.' . $searchField . ' = ""';
if ($this->model->$searchField === 0) {
$sql .= ' OR ' . $classname . '.' . $searchField . ' = 0';
}
$sql .= ')';
} elseif ($searchValues == '$$') {
$sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' IS NOT NULL';
$sql .= ' OR ' . $classname . '.' . $searchField . ' != ""';
if ($this->model->$searchField === 0) {
$sql .= ' OR ' . $classname . '.' . $searchField . ' != 0';
}
$sql .= ')';
} else {
if (strpos($searchValues, '|')) {
$searchValues = explode('|', $searchValues);
} else {
$searchValues = [$searchValues];
}
foreach ($searchValues as $vKey => $value) {
if ((in_array($searchField, $textFields)
&& preg_match('#^%[^%]+%|%[^%]+|[^%]+%$#i', $value))
|| $value == '%%'
) {
$operator = 'LIKE';
}
if (!$vKey) {
$sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' ' . $operator . ' :f' . $searchField . $fKey . $vKey;
} else {
$sql .= ' OR ' . $classname . '.' . $searchField . ' ' . $operator . ' :f' . $searchField . $fKey . $vKey;
}
$this->bindParamsKeys[] = 'f' . $searchField . $fKey . $vKey;
$this->bindParamsValues[] = $value;
}
$sql .= ')';
}
}
return $sql;
}
|
[
"private",
"function",
"prepareNormalSql",
"(",
"array",
"$",
"searchCriteria",
",",
"string",
"$",
"classname",
",",
"string",
"$",
"andOr",
",",
"int",
"$",
"fKey",
")",
":",
"string",
"{",
"$",
"sql",
"=",
"''",
";",
"$",
"textFields",
"=",
"$",
"this",
"->",
"getTextFields",
"(",
"$",
"classname",
")",
";",
"list",
"(",
"$",
"searchField",
",",
"$",
"operator",
",",
"$",
"searchValues",
")",
"=",
"$",
"searchCriteria",
";",
"$",
"operator",
"=",
"$",
"this",
"->",
"operators",
"[",
"$",
"operator",
"]",
";",
"if",
"(",
"trim",
"(",
"$",
"searchValues",
")",
"!==",
"''",
")",
"{",
"if",
"(",
"$",
"searchValues",
"==",
"'%%'",
")",
"{",
"$",
"sql",
".=",
"' '",
".",
"$",
"andOr",
".",
"' ('",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' IS NULL'",
";",
"$",
"sql",
".=",
"' OR '",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' = \"\"'",
";",
"if",
"(",
"$",
"this",
"->",
"model",
"->",
"$",
"searchField",
"===",
"0",
")",
"{",
"$",
"sql",
".=",
"' OR '",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' = 0'",
";",
"}",
"$",
"sql",
".=",
"')'",
";",
"}",
"elseif",
"(",
"$",
"searchValues",
"==",
"'$$'",
")",
"{",
"$",
"sql",
".=",
"' '",
".",
"$",
"andOr",
".",
"' ('",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' IS NOT NULL'",
";",
"$",
"sql",
".=",
"' OR '",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' != \"\"'",
";",
"if",
"(",
"$",
"this",
"->",
"model",
"->",
"$",
"searchField",
"===",
"0",
")",
"{",
"$",
"sql",
".=",
"' OR '",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' != 0'",
";",
"}",
"$",
"sql",
".=",
"')'",
";",
"}",
"else",
"{",
"if",
"(",
"strpos",
"(",
"$",
"searchValues",
",",
"'|'",
")",
")",
"{",
"$",
"searchValues",
"=",
"explode",
"(",
"'|'",
",",
"$",
"searchValues",
")",
";",
"}",
"else",
"{",
"$",
"searchValues",
"=",
"[",
"$",
"searchValues",
"]",
";",
"}",
"foreach",
"(",
"$",
"searchValues",
"as",
"$",
"vKey",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"(",
"in_array",
"(",
"$",
"searchField",
",",
"$",
"textFields",
")",
"&&",
"preg_match",
"(",
"'#^%[^%]+%|%[^%]+|[^%]+%$#i'",
",",
"$",
"value",
")",
")",
"||",
"$",
"value",
"==",
"'%%'",
")",
"{",
"$",
"operator",
"=",
"'LIKE'",
";",
"}",
"if",
"(",
"!",
"$",
"vKey",
")",
"{",
"$",
"sql",
".=",
"' '",
".",
"$",
"andOr",
".",
"' ('",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' '",
".",
"$",
"operator",
".",
"' :f'",
".",
"$",
"searchField",
".",
"$",
"fKey",
".",
"$",
"vKey",
";",
"}",
"else",
"{",
"$",
"sql",
".=",
"' OR '",
".",
"$",
"classname",
".",
"'.'",
".",
"$",
"searchField",
".",
"' '",
".",
"$",
"operator",
".",
"' :f'",
".",
"$",
"searchField",
".",
"$",
"fKey",
".",
"$",
"vKey",
";",
"}",
"$",
"this",
"->",
"bindParamsKeys",
"[",
"]",
"=",
"'f'",
".",
"$",
"searchField",
".",
"$",
"fKey",
".",
"$",
"vKey",
";",
"$",
"this",
"->",
"bindParamsValues",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"$",
"sql",
".=",
"')'",
";",
"}",
"}",
"return",
"$",
"sql",
";",
"}"
] |
Prepare the SQL for a normal search.
@param array $searchCriteria
@param string $classname
@param string $andOr
@param int $fKey
@return string
|
[
"Prepare",
"the",
"SQL",
"for",
"a",
"normal",
"search",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L362-L418
|
train
|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.prepareCustomSql
|
private function prepareCustomSql(array $searchCriteria, Model $modules, string $classname, string $andOr, int $fKey): string
{
$sql = '';
list($searchField, $operator, $searchValue) = $searchCriteria;
$operator = $this->operators[$operator];
if (trim($searchValue) !== '') {
$customFields = CustomFields::findFirst([
'modules_id = ?0 AND name = ?1',
'bind' => [$modules->id, $searchField],
]);
$customFieldValue = $classname . '.value';
if ($customFields->type->name == 'number') {
$customFieldValue = 'CAST(' . $customFieldValue . ' AS INT)';
}
$sql .= ' AND ' . $classname . '.custom_fields_id = :cfi' . $searchField;
$this->bindParamsKeys[] = 'cfi' . $searchField;
$this->bindParamsValues[] = $customFields->id;
if ($searchValue == '%%') {
$sql .= ' ' . $andOr . ' (' . $classname . '.value IS NULL OR ' . $classname . '.value = "")';
} elseif ($searchValue == '$$') {
$sql .= ' ' . $andOr . ' (' . $classname . '.value IS NOT NULL OR ' . $classname . '.value != "")';
} else {
if (strpos($searchValue, '|')) {
$searchValue = explode('|', $searchValue);
} else {
$searchValue = [$searchValue];
}
foreach ($searchValue as $vKey => $value) {
if (preg_match('#^%[^%]+%|%[^%]+|[^%]+%$#i', $value)) {
$operator = 'LIKE';
}
if (!$vKey) {
$sql .= ' ' . $andOr . ' (' . $customFieldValue . ' ' . $operator . ' :cfv' . $searchField . $fKey . $vKey;
} else {
$sql .= ' OR ' . $customFieldValue . ' ' . $operator . ' :cfv' . $searchField . $fKey . $vKey;
}
$this->bindParamsKeys[] = 'cfv' . $searchField . $fKey . $vKey;
$this->bindParamsValues[] = $value;
}
$sql .= ')';
}
}
return $sql;
}
|
php
|
private function prepareCustomSql(array $searchCriteria, Model $modules, string $classname, string $andOr, int $fKey): string
{
$sql = '';
list($searchField, $operator, $searchValue) = $searchCriteria;
$operator = $this->operators[$operator];
if (trim($searchValue) !== '') {
$customFields = CustomFields::findFirst([
'modules_id = ?0 AND name = ?1',
'bind' => [$modules->id, $searchField],
]);
$customFieldValue = $classname . '.value';
if ($customFields->type->name == 'number') {
$customFieldValue = 'CAST(' . $customFieldValue . ' AS INT)';
}
$sql .= ' AND ' . $classname . '.custom_fields_id = :cfi' . $searchField;
$this->bindParamsKeys[] = 'cfi' . $searchField;
$this->bindParamsValues[] = $customFields->id;
if ($searchValue == '%%') {
$sql .= ' ' . $andOr . ' (' . $classname . '.value IS NULL OR ' . $classname . '.value = "")';
} elseif ($searchValue == '$$') {
$sql .= ' ' . $andOr . ' (' . $classname . '.value IS NOT NULL OR ' . $classname . '.value != "")';
} else {
if (strpos($searchValue, '|')) {
$searchValue = explode('|', $searchValue);
} else {
$searchValue = [$searchValue];
}
foreach ($searchValue as $vKey => $value) {
if (preg_match('#^%[^%]+%|%[^%]+|[^%]+%$#i', $value)) {
$operator = 'LIKE';
}
if (!$vKey) {
$sql .= ' ' . $andOr . ' (' . $customFieldValue . ' ' . $operator . ' :cfv' . $searchField . $fKey . $vKey;
} else {
$sql .= ' OR ' . $customFieldValue . ' ' . $operator . ' :cfv' . $searchField . $fKey . $vKey;
}
$this->bindParamsKeys[] = 'cfv' . $searchField . $fKey . $vKey;
$this->bindParamsValues[] = $value;
}
$sql .= ')';
}
}
return $sql;
}
|
[
"private",
"function",
"prepareCustomSql",
"(",
"array",
"$",
"searchCriteria",
",",
"Model",
"$",
"modules",
",",
"string",
"$",
"classname",
",",
"string",
"$",
"andOr",
",",
"int",
"$",
"fKey",
")",
":",
"string",
"{",
"$",
"sql",
"=",
"''",
";",
"list",
"(",
"$",
"searchField",
",",
"$",
"operator",
",",
"$",
"searchValue",
")",
"=",
"$",
"searchCriteria",
";",
"$",
"operator",
"=",
"$",
"this",
"->",
"operators",
"[",
"$",
"operator",
"]",
";",
"if",
"(",
"trim",
"(",
"$",
"searchValue",
")",
"!==",
"''",
")",
"{",
"$",
"customFields",
"=",
"CustomFields",
"::",
"findFirst",
"(",
"[",
"'modules_id = ?0 AND name = ?1'",
",",
"'bind'",
"=>",
"[",
"$",
"modules",
"->",
"id",
",",
"$",
"searchField",
"]",
",",
"]",
")",
";",
"$",
"customFieldValue",
"=",
"$",
"classname",
".",
"'.value'",
";",
"if",
"(",
"$",
"customFields",
"->",
"type",
"->",
"name",
"==",
"'number'",
")",
"{",
"$",
"customFieldValue",
"=",
"'CAST('",
".",
"$",
"customFieldValue",
".",
"' AS INT)'",
";",
"}",
"$",
"sql",
".=",
"' AND '",
".",
"$",
"classname",
".",
"'.custom_fields_id = :cfi'",
".",
"$",
"searchField",
";",
"$",
"this",
"->",
"bindParamsKeys",
"[",
"]",
"=",
"'cfi'",
".",
"$",
"searchField",
";",
"$",
"this",
"->",
"bindParamsValues",
"[",
"]",
"=",
"$",
"customFields",
"->",
"id",
";",
"if",
"(",
"$",
"searchValue",
"==",
"'%%'",
")",
"{",
"$",
"sql",
".=",
"' '",
".",
"$",
"andOr",
".",
"' ('",
".",
"$",
"classname",
".",
"'.value IS NULL OR '",
".",
"$",
"classname",
".",
"'.value = \"\")'",
";",
"}",
"elseif",
"(",
"$",
"searchValue",
"==",
"'$$'",
")",
"{",
"$",
"sql",
".=",
"' '",
".",
"$",
"andOr",
".",
"' ('",
".",
"$",
"classname",
".",
"'.value IS NOT NULL OR '",
".",
"$",
"classname",
".",
"'.value != \"\")'",
";",
"}",
"else",
"{",
"if",
"(",
"strpos",
"(",
"$",
"searchValue",
",",
"'|'",
")",
")",
"{",
"$",
"searchValue",
"=",
"explode",
"(",
"'|'",
",",
"$",
"searchValue",
")",
";",
"}",
"else",
"{",
"$",
"searchValue",
"=",
"[",
"$",
"searchValue",
"]",
";",
"}",
"foreach",
"(",
"$",
"searchValue",
"as",
"$",
"vKey",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'#^%[^%]+%|%[^%]+|[^%]+%$#i'",
",",
"$",
"value",
")",
")",
"{",
"$",
"operator",
"=",
"'LIKE'",
";",
"}",
"if",
"(",
"!",
"$",
"vKey",
")",
"{",
"$",
"sql",
".=",
"' '",
".",
"$",
"andOr",
".",
"' ('",
".",
"$",
"customFieldValue",
".",
"' '",
".",
"$",
"operator",
".",
"' :cfv'",
".",
"$",
"searchField",
".",
"$",
"fKey",
".",
"$",
"vKey",
";",
"}",
"else",
"{",
"$",
"sql",
".=",
"' OR '",
".",
"$",
"customFieldValue",
".",
"' '",
".",
"$",
"operator",
".",
"' :cfv'",
".",
"$",
"searchField",
".",
"$",
"fKey",
".",
"$",
"vKey",
";",
"}",
"$",
"this",
"->",
"bindParamsKeys",
"[",
"]",
"=",
"'cfv'",
".",
"$",
"searchField",
".",
"$",
"fKey",
".",
"$",
"vKey",
";",
"$",
"this",
"->",
"bindParamsValues",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"$",
"sql",
".=",
"')'",
";",
"}",
"}",
"return",
"$",
"sql",
";",
"}"
] |
Prepare the SQL for a custom fields search.
@param array $searchCriteria
@param Model $modules
@param string $classname
@param string $andOr
@param int $fKey
@return string
|
[
"Prepare",
"the",
"SQL",
"for",
"a",
"custom",
"fields",
"search",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L498-L551
|
train
|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.prepareParams
|
protected function prepareParams(array $unparsed): void
{
$this->relationSearchFields = array_key_exists('rparams', $unparsed) ? $this->parseRelationParameters($unparsed['rparams']) : [];
$this->customSearchFields = array_key_exists('cparams', $unparsed) ? $this->parseSearchParameters($unparsed['cparams'])['mapped'] : [];
$this->normalSearchFields = array_key_exists('params', $unparsed) ? $this->parseSearchParameters($unparsed['params'])['mapped'] : [];
}
|
php
|
protected function prepareParams(array $unparsed): void
{
$this->relationSearchFields = array_key_exists('rparams', $unparsed) ? $this->parseRelationParameters($unparsed['rparams']) : [];
$this->customSearchFields = array_key_exists('cparams', $unparsed) ? $this->parseSearchParameters($unparsed['cparams'])['mapped'] : [];
$this->normalSearchFields = array_key_exists('params', $unparsed) ? $this->parseSearchParameters($unparsed['params'])['mapped'] : [];
}
|
[
"protected",
"function",
"prepareParams",
"(",
"array",
"$",
"unparsed",
")",
":",
"void",
"{",
"$",
"this",
"->",
"relationSearchFields",
"=",
"array_key_exists",
"(",
"'rparams'",
",",
"$",
"unparsed",
")",
"?",
"$",
"this",
"->",
"parseRelationParameters",
"(",
"$",
"unparsed",
"[",
"'rparams'",
"]",
")",
":",
"[",
"]",
";",
"$",
"this",
"->",
"customSearchFields",
"=",
"array_key_exists",
"(",
"'cparams'",
",",
"$",
"unparsed",
")",
"?",
"$",
"this",
"->",
"parseSearchParameters",
"(",
"$",
"unparsed",
"[",
"'cparams'",
"]",
")",
"[",
"'mapped'",
"]",
":",
"[",
"]",
";",
"$",
"this",
"->",
"normalSearchFields",
"=",
"array_key_exists",
"(",
"'params'",
",",
"$",
"unparsed",
")",
"?",
"$",
"this",
"->",
"parseSearchParameters",
"(",
"$",
"unparsed",
"[",
"'params'",
"]",
")",
"[",
"'mapped'",
"]",
":",
"[",
"]",
";",
"}"
] |
Preparse the parameters to be used in the search
@return void
|
[
"Preparse",
"the",
"parameters",
"to",
"be",
"used",
"in",
"the",
"search"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L558-L563
|
train
|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.parseRelationParameters
|
protected function parseRelationParameters(array $unparsed): array
{
$parseRelationParameters = [];
$modelNamespace = \Phalcon\Di::getDefault()->getConfig()->namespace->models;
foreach ($unparsed as $model => $query) {
$modelName = str_replace(' ', '', ucwords(str_replace('_', ' ', $model)));
$modelName = $modelNamespace . '\\' . $modelName;
if (!class_exists($modelName)) {
throw new \Exception('Related model does not exist.');
}
$parseRelationParameters[$modelName] = $this->parseSearchParameters($query)['mapped'];
}
return $parseRelationParameters;
}
|
php
|
protected function parseRelationParameters(array $unparsed): array
{
$parseRelationParameters = [];
$modelNamespace = \Phalcon\Di::getDefault()->getConfig()->namespace->models;
foreach ($unparsed as $model => $query) {
$modelName = str_replace(' ', '', ucwords(str_replace('_', ' ', $model)));
$modelName = $modelNamespace . '\\' . $modelName;
if (!class_exists($modelName)) {
throw new \Exception('Related model does not exist.');
}
$parseRelationParameters[$modelName] = $this->parseSearchParameters($query)['mapped'];
}
return $parseRelationParameters;
}
|
[
"protected",
"function",
"parseRelationParameters",
"(",
"array",
"$",
"unparsed",
")",
":",
"array",
"{",
"$",
"parseRelationParameters",
"=",
"[",
"]",
";",
"$",
"modelNamespace",
"=",
"\\",
"Phalcon",
"\\",
"Di",
"::",
"getDefault",
"(",
")",
"->",
"getConfig",
"(",
")",
"->",
"namespace",
"->",
"models",
";",
"foreach",
"(",
"$",
"unparsed",
"as",
"$",
"model",
"=>",
"$",
"query",
")",
"{",
"$",
"modelName",
"=",
"str_replace",
"(",
"' '",
",",
"''",
",",
"ucwords",
"(",
"str_replace",
"(",
"'_'",
",",
"' '",
",",
"$",
"model",
")",
")",
")",
";",
"$",
"modelName",
"=",
"$",
"modelNamespace",
".",
"'\\\\'",
".",
"$",
"modelName",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"modelName",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Related model does not exist.'",
")",
";",
"}",
"$",
"parseRelationParameters",
"[",
"$",
"modelName",
"]",
"=",
"$",
"this",
"->",
"parseSearchParameters",
"(",
"$",
"query",
")",
"[",
"'mapped'",
"]",
";",
"}",
"return",
"$",
"parseRelationParameters",
";",
"}"
] |
Parse relationship query parameters
@param array $unparsed
@return array
|
[
"Parse",
"relationship",
"query",
"parameters"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L572-L589
|
train
|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.getTextFields
|
private function getTextFields($table): array
{
$columnsData = $this->model->getReadConnection()->describeColumns($table);
$textFields = [];
foreach ($columnsData as $column) {
switch ($column->getType()) {
case \Phalcon\Db\Column::TYPE_VARCHAR:
case \Phalcon\Db\Column::TYPE_TEXT:
$textFields[] = $column->getName();
break;
}
}
return $textFields;
}
|
php
|
private function getTextFields($table): array
{
$columnsData = $this->model->getReadConnection()->describeColumns($table);
$textFields = [];
foreach ($columnsData as $column) {
switch ($column->getType()) {
case \Phalcon\Db\Column::TYPE_VARCHAR:
case \Phalcon\Db\Column::TYPE_TEXT:
$textFields[] = $column->getName();
break;
}
}
return $textFields;
}
|
[
"private",
"function",
"getTextFields",
"(",
"$",
"table",
")",
":",
"array",
"{",
"$",
"columnsData",
"=",
"$",
"this",
"->",
"model",
"->",
"getReadConnection",
"(",
")",
"->",
"describeColumns",
"(",
"$",
"table",
")",
";",
"$",
"textFields",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columnsData",
"as",
"$",
"column",
")",
"{",
"switch",
"(",
"$",
"column",
"->",
"getType",
"(",
")",
")",
"{",
"case",
"\\",
"Phalcon",
"\\",
"Db",
"\\",
"Column",
"::",
"TYPE_VARCHAR",
":",
"case",
"\\",
"Phalcon",
"\\",
"Db",
"\\",
"Column",
"::",
"TYPE_TEXT",
":",
"$",
"textFields",
"[",
"]",
"=",
"$",
"column",
"->",
"getName",
"(",
")",
";",
"break",
";",
"}",
"}",
"return",
"$",
"textFields",
";",
"}"
] |
get the text field from this model database
so we can do like search
@param string $table
@return array
|
[
"get",
"the",
"text",
"field",
"from",
"this",
"model",
"database",
"so",
"we",
"can",
"do",
"like",
"search"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L647-L662
|
train
|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.appendAdditionalParams
|
public function appendAdditionalParams(): void
{
if (!empty($this->additionalSearchFields)) {
$this->normalSearchFields = array_merge_recursive($this->normalSearchFields, $this->additionalSearchFields);
}
if (!empty($this->additionalCustomSearchFields)) {
$this->customSearchFields = array_merge_recursive($this->customSearchFields, $this->additionalCustomSearchFields);
}
if (!empty($this->additionalRelationSearchFields)) {
$this->relationSearchFields = array_merge_recursive($this->relationSearchFields, $this->additionalRelationSearchFields);
}
}
|
php
|
public function appendAdditionalParams(): void
{
if (!empty($this->additionalSearchFields)) {
$this->normalSearchFields = array_merge_recursive($this->normalSearchFields, $this->additionalSearchFields);
}
if (!empty($this->additionalCustomSearchFields)) {
$this->customSearchFields = array_merge_recursive($this->customSearchFields, $this->additionalCustomSearchFields);
}
if (!empty($this->additionalRelationSearchFields)) {
$this->relationSearchFields = array_merge_recursive($this->relationSearchFields, $this->additionalRelationSearchFields);
}
}
|
[
"public",
"function",
"appendAdditionalParams",
"(",
")",
":",
"void",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"additionalSearchFields",
")",
")",
"{",
"$",
"this",
"->",
"normalSearchFields",
"=",
"array_merge_recursive",
"(",
"$",
"this",
"->",
"normalSearchFields",
",",
"$",
"this",
"->",
"additionalSearchFields",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"additionalCustomSearchFields",
")",
")",
"{",
"$",
"this",
"->",
"customSearchFields",
"=",
"array_merge_recursive",
"(",
"$",
"this",
"->",
"customSearchFields",
",",
"$",
"this",
"->",
"additionalCustomSearchFields",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"additionalRelationSearchFields",
")",
")",
"{",
"$",
"this",
"->",
"relationSearchFields",
"=",
"array_merge_recursive",
"(",
"$",
"this",
"->",
"relationSearchFields",
",",
"$",
"this",
"->",
"additionalRelationSearchFields",
")",
";",
"}",
"}"
] |
Append any defined additional parameters
@return void
|
[
"Append",
"any",
"defined",
"additional",
"parameters"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L669-L682
|
train
|
bakaphp/http
|
src/QueryParserCustomFields.php
|
QueryParserCustomFields.parseColumns
|
protected function parseColumns(string $columns): void
{
// Split the columns string into individual columns
$columns = explode(',', $columns);
foreach ($columns as &$column) {
if (strpos($column, '.') === false) {
$column = "{$this->model->getSource()}.{$column}";
} else {
$as = str_replace('.', '_', $column);
$column = "{$column} {$as}";
}
}
$this->columns = implode(', ', $columns);
}
|
php
|
protected function parseColumns(string $columns): void
{
// Split the columns string into individual columns
$columns = explode(',', $columns);
foreach ($columns as &$column) {
if (strpos($column, '.') === false) {
$column = "{$this->model->getSource()}.{$column}";
} else {
$as = str_replace('.', '_', $column);
$column = "{$column} {$as}";
}
}
$this->columns = implode(', ', $columns);
}
|
[
"protected",
"function",
"parseColumns",
"(",
"string",
"$",
"columns",
")",
":",
"void",
"{",
"// Split the columns string into individual columns",
"$",
"columns",
"=",
"explode",
"(",
"','",
",",
"$",
"columns",
")",
";",
"foreach",
"(",
"$",
"columns",
"as",
"&",
"$",
"column",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"column",
",",
"'.'",
")",
"===",
"false",
")",
"{",
"$",
"column",
"=",
"\"{$this->model->getSource()}.{$column}\"",
";",
"}",
"else",
"{",
"$",
"as",
"=",
"str_replace",
"(",
"'.'",
",",
"'_'",
",",
"$",
"column",
")",
";",
"$",
"column",
"=",
"\"{$column} {$as}\"",
";",
"}",
"}",
"$",
"this",
"->",
"columns",
"=",
"implode",
"(",
"', '",
",",
"$",
"columns",
")",
";",
"}"
] |
Parse the requested columns to be returned.
@param string $columns
@return void
|
[
"Parse",
"the",
"requested",
"columns",
"to",
"be",
"returned",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/QueryParserCustomFields.php#L727-L742
|
train
|
bakaphp/http
|
src/Rest/CrudExtendedController.php
|
CrudExtendedController.delete
|
public function delete($id): Response
{
if ($objectInfo = $this->model->findFirst($id)) {
if ($this->softDelete == 1) {
$objectInfo->softDelete();
} else {
$objectInfo->delete();
}
return $this->response(['Delete Successfully']);
} else {
throw new Exception('Record not found');
}
}
|
php
|
public function delete($id): Response
{
if ($objectInfo = $this->model->findFirst($id)) {
if ($this->softDelete == 1) {
$objectInfo->softDelete();
} else {
$objectInfo->delete();
}
return $this->response(['Delete Successfully']);
} else {
throw new Exception('Record not found');
}
}
|
[
"public",
"function",
"delete",
"(",
"$",
"id",
")",
":",
"Response",
"{",
"if",
"(",
"$",
"objectInfo",
"=",
"$",
"this",
"->",
"model",
"->",
"findFirst",
"(",
"$",
"id",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"softDelete",
"==",
"1",
")",
"{",
"$",
"objectInfo",
"->",
"softDelete",
"(",
")",
";",
"}",
"else",
"{",
"$",
"objectInfo",
"->",
"delete",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"response",
"(",
"[",
"'Delete Successfully'",
"]",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"'Record not found'",
")",
";",
"}",
"}"
] |
delete a new Entry
@method DELETE
@url /v1/data/{id}
@return \Phalcon\Http\Response
|
[
"delete",
"a",
"new",
"Entry"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/CrudExtendedController.php#L202-L215
|
train
|
bakaphp/http
|
src/Rest/CrudCustomFieldsController.php
|
CrudCustomFieldsController.index
|
public function index($id = null): Response
{
if ($id != null) {
return $this->getById($id);
}
//parse the rquest
$parse = new QueryParserCustomFields($this->request->getQuery(), $this->model);
$parse->appendParams($this->additionalSearchFields);
$parse->appendCustomParams($this->additionalCustomSearchFields);
$parse->appendRelationParams($this->additionalRelationSearchFields);
$params = $parse->request();
$results = (new SimpleRecords(null, $this->model, $this->model->getReadConnection()->query($params['sql'], $params['bind'])));
$count = $this->model->getReadConnection()->query($params['countSql'], $params['bind'])->fetch(\PDO::FETCH_OBJ)->total;
$relationships = false;
// Relationships, but we have to change it to sparo full implementation
if ($this->request->hasQuery('relationships')) {
$relationships = $this->request->getQuery('relationships', 'string');
}
//navigate los records
$newResult = [];
foreach ($results as $key => $record) {
//field the object
foreach ($record->getAllCustomFields() as $key => $value) {
$record->{$key} = $value;
}
$newResult[] = !$relationships ? $record->toFullArray() : QueryParserCustomFields::parseRelationShips($relationships, $record);
}
unset($results);
//this means the want the response in a vuejs format
if ($this->request->hasQuery('format')) {
$limit = (int)$this->request->getQuery('limit', 'int', 25);
$newResult = [
'data' => $newResult,
'limit' => $limit,
'page' => $this->request->getQuery('page', 'int', 1),
'total_pages' => ceil($count / $limit)
];
}
return $this->response($newResult);
}
|
php
|
public function index($id = null): Response
{
if ($id != null) {
return $this->getById($id);
}
//parse the rquest
$parse = new QueryParserCustomFields($this->request->getQuery(), $this->model);
$parse->appendParams($this->additionalSearchFields);
$parse->appendCustomParams($this->additionalCustomSearchFields);
$parse->appendRelationParams($this->additionalRelationSearchFields);
$params = $parse->request();
$results = (new SimpleRecords(null, $this->model, $this->model->getReadConnection()->query($params['sql'], $params['bind'])));
$count = $this->model->getReadConnection()->query($params['countSql'], $params['bind'])->fetch(\PDO::FETCH_OBJ)->total;
$relationships = false;
// Relationships, but we have to change it to sparo full implementation
if ($this->request->hasQuery('relationships')) {
$relationships = $this->request->getQuery('relationships', 'string');
}
//navigate los records
$newResult = [];
foreach ($results as $key => $record) {
//field the object
foreach ($record->getAllCustomFields() as $key => $value) {
$record->{$key} = $value;
}
$newResult[] = !$relationships ? $record->toFullArray() : QueryParserCustomFields::parseRelationShips($relationships, $record);
}
unset($results);
//this means the want the response in a vuejs format
if ($this->request->hasQuery('format')) {
$limit = (int)$this->request->getQuery('limit', 'int', 25);
$newResult = [
'data' => $newResult,
'limit' => $limit,
'page' => $this->request->getQuery('page', 'int', 1),
'total_pages' => ceil($count / $limit)
];
}
return $this->response($newResult);
}
|
[
"public",
"function",
"index",
"(",
"$",
"id",
"=",
"null",
")",
":",
"Response",
"{",
"if",
"(",
"$",
"id",
"!=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getById",
"(",
"$",
"id",
")",
";",
"}",
"//parse the rquest",
"$",
"parse",
"=",
"new",
"QueryParserCustomFields",
"(",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
")",
",",
"$",
"this",
"->",
"model",
")",
";",
"$",
"parse",
"->",
"appendParams",
"(",
"$",
"this",
"->",
"additionalSearchFields",
")",
";",
"$",
"parse",
"->",
"appendCustomParams",
"(",
"$",
"this",
"->",
"additionalCustomSearchFields",
")",
";",
"$",
"parse",
"->",
"appendRelationParams",
"(",
"$",
"this",
"->",
"additionalRelationSearchFields",
")",
";",
"$",
"params",
"=",
"$",
"parse",
"->",
"request",
"(",
")",
";",
"$",
"results",
"=",
"(",
"new",
"SimpleRecords",
"(",
"null",
",",
"$",
"this",
"->",
"model",
",",
"$",
"this",
"->",
"model",
"->",
"getReadConnection",
"(",
")",
"->",
"query",
"(",
"$",
"params",
"[",
"'sql'",
"]",
",",
"$",
"params",
"[",
"'bind'",
"]",
")",
")",
")",
";",
"$",
"count",
"=",
"$",
"this",
"->",
"model",
"->",
"getReadConnection",
"(",
")",
"->",
"query",
"(",
"$",
"params",
"[",
"'countSql'",
"]",
",",
"$",
"params",
"[",
"'bind'",
"]",
")",
"->",
"fetch",
"(",
"\\",
"PDO",
"::",
"FETCH_OBJ",
")",
"->",
"total",
";",
"$",
"relationships",
"=",
"false",
";",
"// Relationships, but we have to change it to sparo full implementation",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"hasQuery",
"(",
"'relationships'",
")",
")",
"{",
"$",
"relationships",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'relationships'",
",",
"'string'",
")",
";",
"}",
"//navigate los records",
"$",
"newResult",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"results",
"as",
"$",
"key",
"=>",
"$",
"record",
")",
"{",
"//field the object",
"foreach",
"(",
"$",
"record",
"->",
"getAllCustomFields",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"record",
"->",
"{",
"$",
"key",
"}",
"=",
"$",
"value",
";",
"}",
"$",
"newResult",
"[",
"]",
"=",
"!",
"$",
"relationships",
"?",
"$",
"record",
"->",
"toFullArray",
"(",
")",
":",
"QueryParserCustomFields",
"::",
"parseRelationShips",
"(",
"$",
"relationships",
",",
"$",
"record",
")",
";",
"}",
"unset",
"(",
"$",
"results",
")",
";",
"//this means the want the response in a vuejs format",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"hasQuery",
"(",
"'format'",
")",
")",
"{",
"$",
"limit",
"=",
"(",
"int",
")",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'limit'",
",",
"'int'",
",",
"25",
")",
";",
"$",
"newResult",
"=",
"[",
"'data'",
"=>",
"$",
"newResult",
",",
"'limit'",
"=>",
"$",
"limit",
",",
"'page'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'page'",
",",
"'int'",
",",
"1",
")",
",",
"'total_pages'",
"=>",
"ceil",
"(",
"$",
"count",
"/",
"$",
"limit",
")",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"response",
"(",
"$",
"newResult",
")",
";",
"}"
] |
List items.
@method GET
url /v1/controller
@param mixed $id
@return \Phalcon\Http\Response
|
[
"List",
"items",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/CrudCustomFieldsController.php#L25-L73
|
train
|
bakaphp/http
|
src/Rest/CrudCustomFieldsController.php
|
CrudCustomFieldsController.getById
|
public function getById($id): Response
{
//find the info
$record = $this->model->findFirst($id);
if (!is_object($record)) {
throw new UnprocessableEntityHttpException('Record not found');
}
$relationships = false;
//get relationship
if ($this->request->hasQuery('relationships')) {
$relationships = $this->request->getQuery('relationships', 'string');
}
$result = !$relationships ? $record->toFullArray() : QueryParserCustomFields::parseRelationShips($relationships, $record);
return $this->response($result);
}
|
php
|
public function getById($id): Response
{
//find the info
$record = $this->model->findFirst($id);
if (!is_object($record)) {
throw new UnprocessableEntityHttpException('Record not found');
}
$relationships = false;
//get relationship
if ($this->request->hasQuery('relationships')) {
$relationships = $this->request->getQuery('relationships', 'string');
}
$result = !$relationships ? $record->toFullArray() : QueryParserCustomFields::parseRelationShips($relationships, $record);
return $this->response($result);
}
|
[
"public",
"function",
"getById",
"(",
"$",
"id",
")",
":",
"Response",
"{",
"//find the info",
"$",
"record",
"=",
"$",
"this",
"->",
"model",
"->",
"findFirst",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"is_object",
"(",
"$",
"record",
")",
")",
"{",
"throw",
"new",
"UnprocessableEntityHttpException",
"(",
"'Record not found'",
")",
";",
"}",
"$",
"relationships",
"=",
"false",
";",
"//get relationship",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"hasQuery",
"(",
"'relationships'",
")",
")",
"{",
"$",
"relationships",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'relationships'",
",",
"'string'",
")",
";",
"}",
"$",
"result",
"=",
"!",
"$",
"relationships",
"?",
"$",
"record",
"->",
"toFullArray",
"(",
")",
":",
"QueryParserCustomFields",
"::",
"parseRelationShips",
"(",
"$",
"relationships",
",",
"$",
"record",
")",
";",
"return",
"$",
"this",
"->",
"response",
"(",
"$",
"result",
")",
";",
"}"
] |
Get item.
@method GET
url /v1/controller/{id}
@param mixed $id
@return \Phalcon\Http\Response
@throws \Exception
|
[
"Get",
"item",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/CrudCustomFieldsController.php#L86-L105
|
train
|
bakaphp/http
|
src/Rest/CrudCustomFieldsController.php
|
CrudCustomFieldsController.create
|
public function create(): Response
{
$request = $this->request->getPost();
if (empty($request)) {
$request = $this->request->getJsonRawBody(true);
}
//we need even if empty the custome fields
if (empty($request)) {
throw new Exception('No valie info sent');
}
//set the custom fields to update
$this->model->setCustomFields($request);
//try to save all the fields we allow
if ($this->model->save($request, $this->createFields)) {
return $this->getById($this->model->id);
} else {
//if not thorw exception
throw new Exception($this->model->getMessages()[0]);
}
}
|
php
|
public function create(): Response
{
$request = $this->request->getPost();
if (empty($request)) {
$request = $this->request->getJsonRawBody(true);
}
//we need even if empty the custome fields
if (empty($request)) {
throw new Exception('No valie info sent');
}
//set the custom fields to update
$this->model->setCustomFields($request);
//try to save all the fields we allow
if ($this->model->save($request, $this->createFields)) {
return $this->getById($this->model->id);
} else {
//if not thorw exception
throw new Exception($this->model->getMessages()[0]);
}
}
|
[
"public",
"function",
"create",
"(",
")",
":",
"Response",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request",
"->",
"getPost",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"request",
")",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request",
"->",
"getJsonRawBody",
"(",
"true",
")",
";",
"}",
"//we need even if empty the custome fields",
"if",
"(",
"empty",
"(",
"$",
"request",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'No valie info sent'",
")",
";",
"}",
"//set the custom fields to update",
"$",
"this",
"->",
"model",
"->",
"setCustomFields",
"(",
"$",
"request",
")",
";",
"//try to save all the fields we allow",
"if",
"(",
"$",
"this",
"->",
"model",
"->",
"save",
"(",
"$",
"request",
",",
"$",
"this",
"->",
"createFields",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getById",
"(",
"$",
"this",
"->",
"model",
"->",
"id",
")",
";",
"}",
"else",
"{",
"//if not thorw exception",
"throw",
"new",
"Exception",
"(",
"$",
"this",
"->",
"model",
"->",
"getMessages",
"(",
")",
"[",
"0",
"]",
")",
";",
"}",
"}"
] |
Add a new item.
@method POST
url /v1/controller
@return \Phalcon\Http\Response
@throws \Exception
|
[
"Add",
"a",
"new",
"item",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/CrudCustomFieldsController.php#L116-L139
|
train
|
bakaphp/http
|
src/Rest/SdkTrait.php
|
SdkTrait.transporterAction
|
public function transporterAction(): Response
{
// Get all router params
$routeParams = $this->router->getParams();
// Confirm that an API version has been configured
if (!array_key_exists('version', $routeParams)) {
return $this->response->setJsonContent([
'error' => 'You must specify an API version in your configuration.',
])->send();
}
// Confirm that the API version matches with the configuration.
if ($routeParams['version'] != $this->apiVersion) {
return $this->response->setJsonContent([
'error' => 'The specified API version is different from your configuration.',
])->send();
}
// Get real API URL
$apiUrl = getenv('EXT_API_URL') . str_replace('api/', '', $this->router->getRewriteUri());
// Execute the request, providing the URL, the request method and the data.
$response = $this->makeRequest($apiUrl, $this->request->getMethod(), $this->getData(), $this->apiHeaders);
//set status code so we can get 404
if ($response->getStatusCode()) {
$this->response->setStatusCode($response->getStatusCode());
}
//Set all the response headers
foreach ($response->getHeaders() as $header => $value) {
// Set the response headers based on the response headers of the API.
if (is_array($value)) {
$value = current($value);
}
$this->response->setHeader($header, $value);
}
return $this->response->setContent($response->getBody());
}
|
php
|
public function transporterAction(): Response
{
// Get all router params
$routeParams = $this->router->getParams();
// Confirm that an API version has been configured
if (!array_key_exists('version', $routeParams)) {
return $this->response->setJsonContent([
'error' => 'You must specify an API version in your configuration.',
])->send();
}
// Confirm that the API version matches with the configuration.
if ($routeParams['version'] != $this->apiVersion) {
return $this->response->setJsonContent([
'error' => 'The specified API version is different from your configuration.',
])->send();
}
// Get real API URL
$apiUrl = getenv('EXT_API_URL') . str_replace('api/', '', $this->router->getRewriteUri());
// Execute the request, providing the URL, the request method and the data.
$response = $this->makeRequest($apiUrl, $this->request->getMethod(), $this->getData(), $this->apiHeaders);
//set status code so we can get 404
if ($response->getStatusCode()) {
$this->response->setStatusCode($response->getStatusCode());
}
//Set all the response headers
foreach ($response->getHeaders() as $header => $value) {
// Set the response headers based on the response headers of the API.
if (is_array($value)) {
$value = current($value);
}
$this->response->setHeader($header, $value);
}
return $this->response->setContent($response->getBody());
}
|
[
"public",
"function",
"transporterAction",
"(",
")",
":",
"Response",
"{",
"// Get all router params",
"$",
"routeParams",
"=",
"$",
"this",
"->",
"router",
"->",
"getParams",
"(",
")",
";",
"// Confirm that an API version has been configured",
"if",
"(",
"!",
"array_key_exists",
"(",
"'version'",
",",
"$",
"routeParams",
")",
")",
"{",
"return",
"$",
"this",
"->",
"response",
"->",
"setJsonContent",
"(",
"[",
"'error'",
"=>",
"'You must specify an API version in your configuration.'",
",",
"]",
")",
"->",
"send",
"(",
")",
";",
"}",
"// Confirm that the API version matches with the configuration.",
"if",
"(",
"$",
"routeParams",
"[",
"'version'",
"]",
"!=",
"$",
"this",
"->",
"apiVersion",
")",
"{",
"return",
"$",
"this",
"->",
"response",
"->",
"setJsonContent",
"(",
"[",
"'error'",
"=>",
"'The specified API version is different from your configuration.'",
",",
"]",
")",
"->",
"send",
"(",
")",
";",
"}",
"// Get real API URL",
"$",
"apiUrl",
"=",
"getenv",
"(",
"'EXT_API_URL'",
")",
".",
"str_replace",
"(",
"'api/'",
",",
"''",
",",
"$",
"this",
"->",
"router",
"->",
"getRewriteUri",
"(",
")",
")",
";",
"// Execute the request, providing the URL, the request method and the data.",
"$",
"response",
"=",
"$",
"this",
"->",
"makeRequest",
"(",
"$",
"apiUrl",
",",
"$",
"this",
"->",
"request",
"->",
"getMethod",
"(",
")",
",",
"$",
"this",
"->",
"getData",
"(",
")",
",",
"$",
"this",
"->",
"apiHeaders",
")",
";",
"//set status code so we can get 404",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
"{",
"$",
"this",
"->",
"response",
"->",
"setStatusCode",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
";",
"}",
"//Set all the response headers",
"foreach",
"(",
"$",
"response",
"->",
"getHeaders",
"(",
")",
"as",
"$",
"header",
"=>",
"$",
"value",
")",
"{",
"// Set the response headers based on the response headers of the API.",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"current",
"(",
"$",
"value",
")",
";",
"}",
"$",
"this",
"->",
"response",
"->",
"setHeader",
"(",
"$",
"header",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"this",
"->",
"response",
"->",
"setContent",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"}"
] |
Function tasked with delegating API requests to the configured API
@todo Verify headers being received from the API response before returning the request response.
@return \Phalcon\Http\Response
|
[
"Function",
"tasked",
"with",
"delegating",
"API",
"requests",
"to",
"the",
"configured",
"API"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/SdkTrait.php#L85-L126
|
train
|
bakaphp/http
|
src/Rest/SdkTrait.php
|
SdkTrait.makeRequest
|
public function makeRequest($url, $method = 'GET', $data = [], $headers = [])
{
//we cant send to the API the array with get GET, JSON, form_params parameters
//the API doesnt get it taht way, guzzle sends it directly
//so we extract it
$rawData = count(array_keys($data)) > 0 ? $data[array_keys($data)[0]] : [];
$client = (new ClientSecurity($this->apiPublicKey, $this->apiPrivateKey, $rawData, $headers))->getGuzzle();
$parse = function ($error) {
if ($error->hasResponse()) {
return $error->getResponse();
}
return json_decode($error->getMessage());
};
try {
return $client->request($method, $url, $data);
} catch (\GuzzleHttp\Exception\BadResponseException $error) {
return $parse($error);
} catch (\GuzzleHttp\Exception\ClientException $error) {
return $parse($error);
} catch (\GuzzleHttp\Exception\ConnectException $error) {
return $parse($error);
} catch (\GuzzleHttp\Exception\RequestException $error) {
return $parse($error);
}
}
|
php
|
public function makeRequest($url, $method = 'GET', $data = [], $headers = [])
{
//we cant send to the API the array with get GET, JSON, form_params parameters
//the API doesnt get it taht way, guzzle sends it directly
//so we extract it
$rawData = count(array_keys($data)) > 0 ? $data[array_keys($data)[0]] : [];
$client = (new ClientSecurity($this->apiPublicKey, $this->apiPrivateKey, $rawData, $headers))->getGuzzle();
$parse = function ($error) {
if ($error->hasResponse()) {
return $error->getResponse();
}
return json_decode($error->getMessage());
};
try {
return $client->request($method, $url, $data);
} catch (\GuzzleHttp\Exception\BadResponseException $error) {
return $parse($error);
} catch (\GuzzleHttp\Exception\ClientException $error) {
return $parse($error);
} catch (\GuzzleHttp\Exception\ConnectException $error) {
return $parse($error);
} catch (\GuzzleHttp\Exception\RequestException $error) {
return $parse($error);
}
}
|
[
"public",
"function",
"makeRequest",
"(",
"$",
"url",
",",
"$",
"method",
"=",
"'GET'",
",",
"$",
"data",
"=",
"[",
"]",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"//we cant send to the API the array with get GET, JSON, form_params parameters",
"//the API doesnt get it taht way, guzzle sends it directly",
"//so we extract it",
"$",
"rawData",
"=",
"count",
"(",
"array_keys",
"(",
"$",
"data",
")",
")",
">",
"0",
"?",
"$",
"data",
"[",
"array_keys",
"(",
"$",
"data",
")",
"[",
"0",
"]",
"]",
":",
"[",
"]",
";",
"$",
"client",
"=",
"(",
"new",
"ClientSecurity",
"(",
"$",
"this",
"->",
"apiPublicKey",
",",
"$",
"this",
"->",
"apiPrivateKey",
",",
"$",
"rawData",
",",
"$",
"headers",
")",
")",
"->",
"getGuzzle",
"(",
")",
";",
"$",
"parse",
"=",
"function",
"(",
"$",
"error",
")",
"{",
"if",
"(",
"$",
"error",
"->",
"hasResponse",
"(",
")",
")",
"{",
"return",
"$",
"error",
"->",
"getResponse",
"(",
")",
";",
"}",
"return",
"json_decode",
"(",
"$",
"error",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
";",
"try",
"{",
"return",
"$",
"client",
"->",
"request",
"(",
"$",
"method",
",",
"$",
"url",
",",
"$",
"data",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"BadResponseException",
"$",
"error",
")",
"{",
"return",
"$",
"parse",
"(",
"$",
"error",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"ClientException",
"$",
"error",
")",
"{",
"return",
"$",
"parse",
"(",
"$",
"error",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"ConnectException",
"$",
"error",
")",
"{",
"return",
"$",
"parse",
"(",
"$",
"error",
")",
";",
"}",
"catch",
"(",
"\\",
"GuzzleHttp",
"\\",
"Exception",
"\\",
"RequestException",
"$",
"error",
")",
"{",
"return",
"$",
"parse",
"(",
"$",
"error",
")",
";",
"}",
"}"
] |
Function that executes the request to the configured API
@param string $method - The request method
@param string $url - The request URL
@param array $data - The form data
@return JSON
|
[
"Function",
"that",
"executes",
"the",
"request",
"to",
"the",
"configured",
"API"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/SdkTrait.php#L137-L166
|
train
|
bakaphp/http
|
src/Rest/SdkTrait.php
|
SdkTrait.getData
|
public function getData(): array
{
$uploads = [];
//if the user is trying to upload a image
if ($this->request->hasFiles()) {
foreach ($this->request->getUploadedFiles() as $file) {
$uploads[] = [
'name' => $file->getKey(),
'filename' => $file->getName(),
'contents' => file_get_contents($file->getTempName()),
];
}
$parseUpload = function ($request) use (&$uploads) {
foreach ($request as $key => $value) {
if (is_array($value)) {
foreach ($value as $f => $v) {
$uploads[] = ['name' => $key . '[' . $f . ']', 'contents' => $v];
}
} else {
$uploads[] = ['name' => $key, 'contents' => $value];
}
}
};
}
switch ($this->request->getMethod()) {
case 'GET':
$queryParams = $this->request->getQuery();
unset($queryParams['_url']);
return ['query' => $queryParams];
break;
case 'POST':
if (!$uploads) {
//if we dont get post send the raw
if (count($this->request->getPost()) > 0) {
return ['form_params' => $this->request->getPost()];
} elseif ($this->request->getJsonRawBody()) {
return ['json' => json_decode($this->request->getRawBody(), true)];
}
//why did we get here?
return ['form_params' => $this->request->getPost()];
} else {
$parseUpload($this->request->getPost());
return ['multipart' => $uploads];
}
break;
case 'PUT':
if (!$uploads) {
//if we get put send it with the normal put, else send json
if (count($this->request->getPut()) > 0) {
return ['form_params' => $this->request->getPut()];
} elseif ($this->request->getJsonRawBody()) {
return ['json' => json_decode($this->request->getRawBody(), true)];
}
//why did we get here?
return ['form_params' => $this->request->getPut()];
} else {
$parseUpload($this->request->getPut());
return ['multipart' => $uploads];
}
break;
default:
return [];
break;
}
}
|
php
|
public function getData(): array
{
$uploads = [];
//if the user is trying to upload a image
if ($this->request->hasFiles()) {
foreach ($this->request->getUploadedFiles() as $file) {
$uploads[] = [
'name' => $file->getKey(),
'filename' => $file->getName(),
'contents' => file_get_contents($file->getTempName()),
];
}
$parseUpload = function ($request) use (&$uploads) {
foreach ($request as $key => $value) {
if (is_array($value)) {
foreach ($value as $f => $v) {
$uploads[] = ['name' => $key . '[' . $f . ']', 'contents' => $v];
}
} else {
$uploads[] = ['name' => $key, 'contents' => $value];
}
}
};
}
switch ($this->request->getMethod()) {
case 'GET':
$queryParams = $this->request->getQuery();
unset($queryParams['_url']);
return ['query' => $queryParams];
break;
case 'POST':
if (!$uploads) {
//if we dont get post send the raw
if (count($this->request->getPost()) > 0) {
return ['form_params' => $this->request->getPost()];
} elseif ($this->request->getJsonRawBody()) {
return ['json' => json_decode($this->request->getRawBody(), true)];
}
//why did we get here?
return ['form_params' => $this->request->getPost()];
} else {
$parseUpload($this->request->getPost());
return ['multipart' => $uploads];
}
break;
case 'PUT':
if (!$uploads) {
//if we get put send it with the normal put, else send json
if (count($this->request->getPut()) > 0) {
return ['form_params' => $this->request->getPut()];
} elseif ($this->request->getJsonRawBody()) {
return ['json' => json_decode($this->request->getRawBody(), true)];
}
//why did we get here?
return ['form_params' => $this->request->getPut()];
} else {
$parseUpload($this->request->getPut());
return ['multipart' => $uploads];
}
break;
default:
return [];
break;
}
}
|
[
"public",
"function",
"getData",
"(",
")",
":",
"array",
"{",
"$",
"uploads",
"=",
"[",
"]",
";",
"//if the user is trying to upload a image",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"hasFiles",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"request",
"->",
"getUploadedFiles",
"(",
")",
"as",
"$",
"file",
")",
"{",
"$",
"uploads",
"[",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"file",
"->",
"getKey",
"(",
")",
",",
"'filename'",
"=>",
"$",
"file",
"->",
"getName",
"(",
")",
",",
"'contents'",
"=>",
"file_get_contents",
"(",
"$",
"file",
"->",
"getTempName",
"(",
")",
")",
",",
"]",
";",
"}",
"$",
"parseUpload",
"=",
"function",
"(",
"$",
"request",
")",
"use",
"(",
"&",
"$",
"uploads",
")",
"{",
"foreach",
"(",
"$",
"request",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"foreach",
"(",
"$",
"value",
"as",
"$",
"f",
"=>",
"$",
"v",
")",
"{",
"$",
"uploads",
"[",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"key",
".",
"'['",
".",
"$",
"f",
".",
"']'",
",",
"'contents'",
"=>",
"$",
"v",
"]",
";",
"}",
"}",
"else",
"{",
"$",
"uploads",
"[",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"key",
",",
"'contents'",
"=>",
"$",
"value",
"]",
";",
"}",
"}",
"}",
";",
"}",
"switch",
"(",
"$",
"this",
"->",
"request",
"->",
"getMethod",
"(",
")",
")",
"{",
"case",
"'GET'",
":",
"$",
"queryParams",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
")",
";",
"unset",
"(",
"$",
"queryParams",
"[",
"'_url'",
"]",
")",
";",
"return",
"[",
"'query'",
"=>",
"$",
"queryParams",
"]",
";",
"break",
";",
"case",
"'POST'",
":",
"if",
"(",
"!",
"$",
"uploads",
")",
"{",
"//if we dont get post send the raw",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"request",
"->",
"getPost",
"(",
")",
")",
">",
"0",
")",
"{",
"return",
"[",
"'form_params'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getPost",
"(",
")",
"]",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"request",
"->",
"getJsonRawBody",
"(",
")",
")",
"{",
"return",
"[",
"'json'",
"=>",
"json_decode",
"(",
"$",
"this",
"->",
"request",
"->",
"getRawBody",
"(",
")",
",",
"true",
")",
"]",
";",
"}",
"//why did we get here?",
"return",
"[",
"'form_params'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getPost",
"(",
")",
"]",
";",
"}",
"else",
"{",
"$",
"parseUpload",
"(",
"$",
"this",
"->",
"request",
"->",
"getPost",
"(",
")",
")",
";",
"return",
"[",
"'multipart'",
"=>",
"$",
"uploads",
"]",
";",
"}",
"break",
";",
"case",
"'PUT'",
":",
"if",
"(",
"!",
"$",
"uploads",
")",
"{",
"//if we get put send it with the normal put, else send json",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"request",
"->",
"getPut",
"(",
")",
")",
">",
"0",
")",
"{",
"return",
"[",
"'form_params'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getPut",
"(",
")",
"]",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"request",
"->",
"getJsonRawBody",
"(",
")",
")",
"{",
"return",
"[",
"'json'",
"=>",
"json_decode",
"(",
"$",
"this",
"->",
"request",
"->",
"getRawBody",
"(",
")",
",",
"true",
")",
"]",
";",
"}",
"//why did we get here?",
"return",
"[",
"'form_params'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getPut",
"(",
")",
"]",
";",
"}",
"else",
"{",
"$",
"parseUpload",
"(",
"$",
"this",
"->",
"request",
"->",
"getPut",
"(",
")",
")",
";",
"return",
"[",
"'multipart'",
"=>",
"$",
"uploads",
"]",
";",
"}",
"break",
";",
"default",
":",
"return",
"[",
"]",
";",
"break",
";",
"}",
"}"
] |
Function that obtains the data as per the request type.
@return array
|
[
"Function",
"that",
"obtains",
"the",
"data",
"as",
"per",
"the",
"request",
"type",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/SdkTrait.php#L173-L242
|
train
|
bakaphp/http
|
src/Rest/CrudController.php
|
CrudController.index
|
public function index($id = null)
{
// Support for resource/identifier/resource
if ($id != null) {
return $this->getById($id);
}
//parse the rquest
$parse = new QueryParser($this->request->getQuery());
$params = $parse->request();
$results = $this->model->find($params);
if ($this->request->hasQuery('relationships')) {
$relationships = $this->request->getQuery('relationships', 'string');
$results = QueryParser::parseRelationShips($relationships, $results);
}
//this means the want the response in a vuejs format
if ($this->request->hasQuery('format')) {
unset($params['limit'], $params['offset']);
$results = [
'data' => $results,
'limit' => $this->request->getQuery('limit', 'int'),
'page' => $this->request->getQuery('page', 'int'),
'total_pages' => ceil($this->model->count($params) / $this->request->getQuery('limit', 'int')),
];
}
return $this->response($results);
}
|
php
|
public function index($id = null)
{
// Support for resource/identifier/resource
if ($id != null) {
return $this->getById($id);
}
//parse the rquest
$parse = new QueryParser($this->request->getQuery());
$params = $parse->request();
$results = $this->model->find($params);
if ($this->request->hasQuery('relationships')) {
$relationships = $this->request->getQuery('relationships', 'string');
$results = QueryParser::parseRelationShips($relationships, $results);
}
//this means the want the response in a vuejs format
if ($this->request->hasQuery('format')) {
unset($params['limit'], $params['offset']);
$results = [
'data' => $results,
'limit' => $this->request->getQuery('limit', 'int'),
'page' => $this->request->getQuery('page', 'int'),
'total_pages' => ceil($this->model->count($params) / $this->request->getQuery('limit', 'int')),
];
}
return $this->response($results);
}
|
[
"public",
"function",
"index",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"// Support for resource/identifier/resource",
"if",
"(",
"$",
"id",
"!=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getById",
"(",
"$",
"id",
")",
";",
"}",
"//parse the rquest",
"$",
"parse",
"=",
"new",
"QueryParser",
"(",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
")",
")",
";",
"$",
"params",
"=",
"$",
"parse",
"->",
"request",
"(",
")",
";",
"$",
"results",
"=",
"$",
"this",
"->",
"model",
"->",
"find",
"(",
"$",
"params",
")",
";",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"hasQuery",
"(",
"'relationships'",
")",
")",
"{",
"$",
"relationships",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'relationships'",
",",
"'string'",
")",
";",
"$",
"results",
"=",
"QueryParser",
"::",
"parseRelationShips",
"(",
"$",
"relationships",
",",
"$",
"results",
")",
";",
"}",
"//this means the want the response in a vuejs format",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"hasQuery",
"(",
"'format'",
")",
")",
"{",
"unset",
"(",
"$",
"params",
"[",
"'limit'",
"]",
",",
"$",
"params",
"[",
"'offset'",
"]",
")",
";",
"$",
"results",
"=",
"[",
"'data'",
"=>",
"$",
"results",
",",
"'limit'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'limit'",
",",
"'int'",
")",
",",
"'page'",
"=>",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'page'",
",",
"'int'",
")",
",",
"'total_pages'",
"=>",
"ceil",
"(",
"$",
"this",
"->",
"model",
"->",
"count",
"(",
"$",
"params",
")",
"/",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'limit'",
",",
"'int'",
")",
")",
",",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"response",
"(",
"$",
"results",
")",
";",
"}"
] |
List of business
@method GET
@url /v1/business
@todo add security to query strings with bidn params
@return Phalcon\Http\Response
|
[
"List",
"of",
"business"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/CrudController.php#L51-L83
|
train
|
bakaphp/http
|
src/RouterCollection.php
|
RouterCollection.mount
|
public function mount(): void
{
if (count($this->collections) > 0) {
foreach ($this->collections as $collection) {
$micro = new MicroCollection();
// Set the main handler. ie. a controller instance
$micro->setHandler($collection['className'], true);
// Set a common prefix for all routes
if ($this->prefix) {
$micro->setPrefix($this->prefix);
}
// Use the method 'index' in PostsController
$micro->{$collection['method']}($collection['pattern'], $collection['function']);
$this->application->mount($micro);
}
}
return;
}
|
php
|
public function mount(): void
{
if (count($this->collections) > 0) {
foreach ($this->collections as $collection) {
$micro = new MicroCollection();
// Set the main handler. ie. a controller instance
$micro->setHandler($collection['className'], true);
// Set a common prefix for all routes
if ($this->prefix) {
$micro->setPrefix($this->prefix);
}
// Use the method 'index' in PostsController
$micro->{$collection['method']}($collection['pattern'], $collection['function']);
$this->application->mount($micro);
}
}
return;
}
|
[
"public",
"function",
"mount",
"(",
")",
":",
"void",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"collections",
")",
">",
"0",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"collections",
"as",
"$",
"collection",
")",
"{",
"$",
"micro",
"=",
"new",
"MicroCollection",
"(",
")",
";",
"// Set the main handler. ie. a controller instance",
"$",
"micro",
"->",
"setHandler",
"(",
"$",
"collection",
"[",
"'className'",
"]",
",",
"true",
")",
";",
"// Set a common prefix for all routes",
"if",
"(",
"$",
"this",
"->",
"prefix",
")",
"{",
"$",
"micro",
"->",
"setPrefix",
"(",
"$",
"this",
"->",
"prefix",
")",
";",
"}",
"// Use the method 'index' in PostsController",
"$",
"micro",
"->",
"{",
"$",
"collection",
"[",
"'method'",
"]",
"}",
"(",
"$",
"collection",
"[",
"'pattern'",
"]",
",",
"$",
"collection",
"[",
"'function'",
"]",
")",
";",
"$",
"this",
"->",
"application",
"->",
"mount",
"(",
"$",
"micro",
")",
";",
"}",
"}",
"return",
";",
"}"
] |
Mount the collection to the micro app router.
@return void
|
[
"Mount",
"the",
"collection",
"to",
"the",
"micro",
"app",
"router",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/RouterCollection.php#L69-L90
|
train
|
bakaphp/http
|
src/RouterCollection.php
|
RouterCollection.call
|
private function call(string $method, string $pattern, string $className, string $function, array $options = []): void
{
if (empty($className) || empty($function)) {
throw new Exception('Missing params, we need 2 parameters');
}
$route = [
'method' => $method,
'pattern' => $pattern,
'className' => $className,
'function' => $function,
];
$this->collections[] = $route;
if (array_key_exists('options', $options)) {
$this->setOptions($route, $options);
}
return;
}
|
php
|
private function call(string $method, string $pattern, string $className, string $function, array $options = []): void
{
if (empty($className) || empty($function)) {
throw new Exception('Missing params, we need 2 parameters');
}
$route = [
'method' => $method,
'pattern' => $pattern,
'className' => $className,
'function' => $function,
];
$this->collections[] = $route;
if (array_key_exists('options', $options)) {
$this->setOptions($route, $options);
}
return;
}
|
[
"private",
"function",
"call",
"(",
"string",
"$",
"method",
",",
"string",
"$",
"pattern",
",",
"string",
"$",
"className",
",",
"string",
"$",
"function",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"className",
")",
"||",
"empty",
"(",
"$",
"function",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Missing params, we need 2 parameters'",
")",
";",
"}",
"$",
"route",
"=",
"[",
"'method'",
"=>",
"$",
"method",
",",
"'pattern'",
"=>",
"$",
"pattern",
",",
"'className'",
"=>",
"$",
"className",
",",
"'function'",
"=>",
"$",
"function",
",",
"]",
";",
"$",
"this",
"->",
"collections",
"[",
"]",
"=",
"$",
"route",
";",
"if",
"(",
"array_key_exists",
"(",
"'options'",
",",
"$",
"options",
")",
")",
"{",
"$",
"this",
"->",
"setOptions",
"(",
"$",
"route",
",",
"$",
"options",
")",
";",
"}",
"return",
";",
"}"
] |
Add the call function to the collection array.
@param string $method
@param string $pattern
@param string $className
@param string $function
@return void
|
[
"Add",
"the",
"call",
"function",
"to",
"the",
"collection",
"array",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/RouterCollection.php#L101-L120
|
train
|
bakaphp/http
|
src/RouterCollection.php
|
RouterCollection.setOptions
|
private function setOptions(array $route, array $options): void
{
if (array_key_exists('jwt', $options['options'])) {
//only add if we want to ignore this url
if (!$options['options']['jwt']) {
self::$hasJwtOptionsSetup = true;
//we group them by method and hash the pattern to make it a faster lookup
self::$jwt[strtoupper($route['method'])][md5($this->prefix . $route['pattern'])] = $this->prefix . $route['pattern'];
}
}
}
|
php
|
private function setOptions(array $route, array $options): void
{
if (array_key_exists('jwt', $options['options'])) {
//only add if we want to ignore this url
if (!$options['options']['jwt']) {
self::$hasJwtOptionsSetup = true;
//we group them by method and hash the pattern to make it a faster lookup
self::$jwt[strtoupper($route['method'])][md5($this->prefix . $route['pattern'])] = $this->prefix . $route['pattern'];
}
}
}
|
[
"private",
"function",
"setOptions",
"(",
"array",
"$",
"route",
",",
"array",
"$",
"options",
")",
":",
"void",
"{",
"if",
"(",
"array_key_exists",
"(",
"'jwt'",
",",
"$",
"options",
"[",
"'options'",
"]",
")",
")",
"{",
"//only add if we want to ignore this url",
"if",
"(",
"!",
"$",
"options",
"[",
"'options'",
"]",
"[",
"'jwt'",
"]",
")",
"{",
"self",
"::",
"$",
"hasJwtOptionsSetup",
"=",
"true",
";",
"//we group them by method and hash the pattern to make it a faster lookup",
"self",
"::",
"$",
"jwt",
"[",
"strtoupper",
"(",
"$",
"route",
"[",
"'method'",
"]",
")",
"]",
"[",
"md5",
"(",
"$",
"this",
"->",
"prefix",
".",
"$",
"route",
"[",
"'pattern'",
"]",
")",
"]",
"=",
"$",
"this",
"->",
"prefix",
".",
"$",
"route",
"[",
"'pattern'",
"]",
";",
"}",
"}",
"}"
] |
Set routers options JWT.
@todo add Middleware that the router will call
@param array $route
@param array $options
@return void
|
[
"Set",
"routers",
"options",
"JWT",
"."
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/RouterCollection.php#L130-L140
|
train
|
bakaphp/http
|
src/Rest/BaseController.php
|
BaseController.response
|
public function response($content, int $statusCode = 200, string $statusMessage = 'OK'): Response
{
$response = [
'statusCode' => $statusCode,
'statusMessage' => $statusMessage,
'content' => $content,
];
if ($this->config->application->debug->logRequest) {
$this->log->addInfo('RESPONSE', $response);
}
// Create a response since it's an ajax
//in order to use the current response instead of having to create a new object , this is needed for swoole servers
$response = $this->response ?? new Response();
$response->setStatusCode($statusCode, $statusMessage);
$response->setContentType('application/vnd.api+json', 'UTF-8');
$response->setJsonContent($content);
return $response;
}
|
php
|
public function response($content, int $statusCode = 200, string $statusMessage = 'OK'): Response
{
$response = [
'statusCode' => $statusCode,
'statusMessage' => $statusMessage,
'content' => $content,
];
if ($this->config->application->debug->logRequest) {
$this->log->addInfo('RESPONSE', $response);
}
// Create a response since it's an ajax
//in order to use the current response instead of having to create a new object , this is needed for swoole servers
$response = $this->response ?? new Response();
$response->setStatusCode($statusCode, $statusMessage);
$response->setContentType('application/vnd.api+json', 'UTF-8');
$response->setJsonContent($content);
return $response;
}
|
[
"public",
"function",
"response",
"(",
"$",
"content",
",",
"int",
"$",
"statusCode",
"=",
"200",
",",
"string",
"$",
"statusMessage",
"=",
"'OK'",
")",
":",
"Response",
"{",
"$",
"response",
"=",
"[",
"'statusCode'",
"=>",
"$",
"statusCode",
",",
"'statusMessage'",
"=>",
"$",
"statusMessage",
",",
"'content'",
"=>",
"$",
"content",
",",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"application",
"->",
"debug",
"->",
"logRequest",
")",
"{",
"$",
"this",
"->",
"log",
"->",
"addInfo",
"(",
"'RESPONSE'",
",",
"$",
"response",
")",
";",
"}",
"// Create a response since it's an ajax",
"//in order to use the current response instead of having to create a new object , this is needed for swoole servers",
"$",
"response",
"=",
"$",
"this",
"->",
"response",
"??",
"new",
"Response",
"(",
")",
";",
"$",
"response",
"->",
"setStatusCode",
"(",
"$",
"statusCode",
",",
"$",
"statusMessage",
")",
";",
"$",
"response",
"->",
"setContentType",
"(",
"'application/vnd.api+json'",
",",
"'UTF-8'",
")",
";",
"$",
"response",
"->",
"setJsonContent",
"(",
"$",
"content",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Set JSON response for AJAX, API request
@param mixed $content
@param integer $statusCode
@param string $statusMessage
@return \Phalcon\Http\Response
|
[
"Set",
"JSON",
"response",
"for",
"AJAX",
"API",
"request"
] |
e99d7e1408066c4b30450455c32adb810ce41e49
|
https://github.com/bakaphp/http/blob/e99d7e1408066c4b30450455c32adb810ce41e49/src/Rest/BaseController.php#L22-L42
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Guesser/PropelORMFieldGuesser.php
|
PropelORMFieldGuesser.getModelPrimaryKeyName
|
public function getModelPrimaryKeyName($class = null)
{
$pks = $this->getMetadatas($class)->getPrimaryKeyColumns();
if (count($pks) == 1) {
return $pks[0]->getPhpName();
}
throw new \LogicException('No valid primary keys found');
}
|
php
|
public function getModelPrimaryKeyName($class = null)
{
$pks = $this->getMetadatas($class)->getPrimaryKeyColumns();
if (count($pks) == 1) {
return $pks[0]->getPhpName();
}
throw new \LogicException('No valid primary keys found');
}
|
[
"public",
"function",
"getModelPrimaryKeyName",
"(",
"$",
"class",
"=",
"null",
")",
"{",
"$",
"pks",
"=",
"$",
"this",
"->",
"getMetadatas",
"(",
"$",
"class",
")",
"->",
"getPrimaryKeyColumns",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"pks",
")",
"==",
"1",
")",
"{",
"return",
"$",
"pks",
"[",
"0",
"]",
"->",
"getPhpName",
"(",
")",
";",
"}",
"throw",
"new",
"\\",
"LogicException",
"(",
"'No valid primary keys found'",
")",
";",
"}"
] |
Find the pk name
|
[
"Find",
"the",
"pk",
"name"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Guesser/PropelORMFieldGuesser.php#L252-L261
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Builder/Generator.php
|
Generator.addBuilder
|
public function addBuilder(BuilderInterface $builder)
{
parent::addBuilder($builder);
$builder->setVariables(
$this->mergeParameters(
$this->getFromYaml('params', array()),
$this->getFromYaml(sprintf('builders.%s.params', $builder->getYamlKey()), array())
)
);
$builder->setColumnClass($this->getColumnClass());
}
|
php
|
public function addBuilder(BuilderInterface $builder)
{
parent::addBuilder($builder);
$builder->setVariables(
$this->mergeParameters(
$this->getFromYaml('params', array()),
$this->getFromYaml(sprintf('builders.%s.params', $builder->getYamlKey()), array())
)
);
$builder->setColumnClass($this->getColumnClass());
}
|
[
"public",
"function",
"addBuilder",
"(",
"BuilderInterface",
"$",
"builder",
")",
"{",
"parent",
"::",
"addBuilder",
"(",
"$",
"builder",
")",
";",
"$",
"builder",
"->",
"setVariables",
"(",
"$",
"this",
"->",
"mergeParameters",
"(",
"$",
"this",
"->",
"getFromYaml",
"(",
"'params'",
",",
"array",
"(",
")",
")",
",",
"$",
"this",
"->",
"getFromYaml",
"(",
"sprintf",
"(",
"'builders.%s.params'",
",",
"$",
"builder",
"->",
"getYamlKey",
"(",
")",
")",
",",
"array",
"(",
")",
")",
")",
")",
";",
"$",
"builder",
"->",
"setColumnClass",
"(",
"$",
"this",
"->",
"getColumnClass",
"(",
")",
")",
";",
"}"
] |
Add a builder
@param BuilderInterface $builder
|
[
"Add",
"a",
"builder"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Builder/Generator.php#L59-L70
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Builder/Generator.php
|
Generator.recursiveReplace
|
protected function recursiveReplace($base, $replacement)
{
$replace_values_recursive = function (array $array, array $order) use (&$replace_values_recursive) {
$array = array_replace($order, array_replace($array, $order));
foreach ($array as $key => &$value) {
if (is_array($value)) {
$value = (array_key_exists($key, $order) && is_array($order[$key]))
? $replace_values_recursive($value, $order[$key])
: $value
;
}
}
return $array;
};
return $replace_values_recursive($base, $replacement);
}
|
php
|
protected function recursiveReplace($base, $replacement)
{
$replace_values_recursive = function (array $array, array $order) use (&$replace_values_recursive) {
$array = array_replace($order, array_replace($array, $order));
foreach ($array as $key => &$value) {
if (is_array($value)) {
$value = (array_key_exists($key, $order) && is_array($order[$key]))
? $replace_values_recursive($value, $order[$key])
: $value
;
}
}
return $array;
};
return $replace_values_recursive($base, $replacement);
}
|
[
"protected",
"function",
"recursiveReplace",
"(",
"$",
"base",
",",
"$",
"replacement",
")",
"{",
"$",
"replace_values_recursive",
"=",
"function",
"(",
"array",
"$",
"array",
",",
"array",
"$",
"order",
")",
"use",
"(",
"&",
"$",
"replace_values_recursive",
")",
"{",
"$",
"array",
"=",
"array_replace",
"(",
"$",
"order",
",",
"array_replace",
"(",
"$",
"array",
",",
"$",
"order",
")",
")",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"&",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"order",
")",
"&&",
"is_array",
"(",
"$",
"order",
"[",
"$",
"key",
"]",
")",
")",
"?",
"$",
"replace_values_recursive",
"(",
"$",
"value",
",",
"$",
"order",
"[",
"$",
"key",
"]",
")",
":",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"array",
";",
"}",
";",
"return",
"$",
"replace_values_recursive",
"(",
"$",
"base",
",",
"$",
"replacement",
")",
";",
"}"
] |
Recursively replaces Base array values with Replacement array values
while keeping indexes of Replacement array
@param array $base Base array
@param array $replacement Replacement array
|
[
"Recursively",
"replaces",
"Base",
"array",
"values",
"with",
"Replacement",
"array",
"values",
"while",
"keeping",
"indexes",
"of",
"Replacement",
"array"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Builder/Generator.php#L172-L189
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Builder/Admin/BaseBuilder.php
|
BaseBuilder.getDisplayAsColumns
|
protected function getDisplayAsColumns()
{
$display = $this->getVariable('display');
// tabs
if (null == $display || 0 == sizeof($display)) {
$tabs = $this->getVariable('tabs');
if (null != $tabs || 0 < sizeof($tabs)) {
$display = array();
foreach ($tabs as $tab) {
$display = array_merge($display, $tab);
}
}
}
if (null == $display || 0 == sizeof($display)) {
return $this->getAllFields();
}
if (isset($display[0])) {
return $display;
}
//there is fieldsets
$return = array();
foreach ($display as $fieldset => $rows_or_fields) {
foreach ($rows_or_fields as $fields) {
if (is_array($fields)) { //It s a row
$return = array_merge($return, $fields);
} else {
$return[$fields] = $fields;
}
}
}
return $return;
}
|
php
|
protected function getDisplayAsColumns()
{
$display = $this->getVariable('display');
// tabs
if (null == $display || 0 == sizeof($display)) {
$tabs = $this->getVariable('tabs');
if (null != $tabs || 0 < sizeof($tabs)) {
$display = array();
foreach ($tabs as $tab) {
$display = array_merge($display, $tab);
}
}
}
if (null == $display || 0 == sizeof($display)) {
return $this->getAllFields();
}
if (isset($display[0])) {
return $display;
}
//there is fieldsets
$return = array();
foreach ($display as $fieldset => $rows_or_fields) {
foreach ($rows_or_fields as $fields) {
if (is_array($fields)) { //It s a row
$return = array_merge($return, $fields);
} else {
$return[$fields] = $fields;
}
}
}
return $return;
}
|
[
"protected",
"function",
"getDisplayAsColumns",
"(",
")",
"{",
"$",
"display",
"=",
"$",
"this",
"->",
"getVariable",
"(",
"'display'",
")",
";",
"// tabs",
"if",
"(",
"null",
"==",
"$",
"display",
"||",
"0",
"==",
"sizeof",
"(",
"$",
"display",
")",
")",
"{",
"$",
"tabs",
"=",
"$",
"this",
"->",
"getVariable",
"(",
"'tabs'",
")",
";",
"if",
"(",
"null",
"!=",
"$",
"tabs",
"||",
"0",
"<",
"sizeof",
"(",
"$",
"tabs",
")",
")",
"{",
"$",
"display",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"tabs",
"as",
"$",
"tab",
")",
"{",
"$",
"display",
"=",
"array_merge",
"(",
"$",
"display",
",",
"$",
"tab",
")",
";",
"}",
"}",
"}",
"if",
"(",
"null",
"==",
"$",
"display",
"||",
"0",
"==",
"sizeof",
"(",
"$",
"display",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getAllFields",
"(",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"display",
"[",
"0",
"]",
")",
")",
"{",
"return",
"$",
"display",
";",
"}",
"//there is fieldsets",
"$",
"return",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"display",
"as",
"$",
"fieldset",
"=>",
"$",
"rows_or_fields",
")",
"{",
"foreach",
"(",
"$",
"rows_or_fields",
"as",
"$",
"fields",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fields",
")",
")",
"{",
"//It s a row",
"$",
"return",
"=",
"array_merge",
"(",
"$",
"return",
",",
"$",
"fields",
")",
";",
"}",
"else",
"{",
"$",
"return",
"[",
"$",
"fields",
"]",
"=",
"$",
"fields",
";",
"}",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] |
Extract from the displays arrays of fieldset to keep only columns
@return array
|
[
"Extract",
"from",
"the",
"displays",
"arrays",
"of",
"fieldset",
"to",
"keep",
"only",
"columns"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Builder/Admin/BaseBuilder.php#L143-L182
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Builder/Admin/BaseBuilder.php
|
BaseBuilder.parseStringWithTwig
|
public function parseStringWithTwig($template, $options = array())
{
$loader = new \Twig_Loader_String();
$twig = new \Twig_Environment(
$loader,
array(
'autoescape' => false,
'strict_variables' => true,
'debug' => true,
'cache' => $this->getGenerator()->getTempDir(),
)
);
$this->addTwigExtensions($twig, $loader);
$this->addTwigFilters($twig);
$template = $twig->loadTemplate($template);
return $template->render($options);
}
|
php
|
public function parseStringWithTwig($template, $options = array())
{
$loader = new \Twig_Loader_String();
$twig = new \Twig_Environment(
$loader,
array(
'autoescape' => false,
'strict_variables' => true,
'debug' => true,
'cache' => $this->getGenerator()->getTempDir(),
)
);
$this->addTwigExtensions($twig, $loader);
$this->addTwigFilters($twig);
$template = $twig->loadTemplate($template);
return $template->render($options);
}
|
[
"public",
"function",
"parseStringWithTwig",
"(",
"$",
"template",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"loader",
"=",
"new",
"\\",
"Twig_Loader_String",
"(",
")",
";",
"$",
"twig",
"=",
"new",
"\\",
"Twig_Environment",
"(",
"$",
"loader",
",",
"array",
"(",
"'autoescape'",
"=>",
"false",
",",
"'strict_variables'",
"=>",
"true",
",",
"'debug'",
"=>",
"true",
",",
"'cache'",
"=>",
"$",
"this",
"->",
"getGenerator",
"(",
")",
"->",
"getTempDir",
"(",
")",
",",
")",
")",
";",
"$",
"this",
"->",
"addTwigExtensions",
"(",
"$",
"twig",
",",
"$",
"loader",
")",
";",
"$",
"this",
"->",
"addTwigFilters",
"(",
"$",
"twig",
")",
";",
"$",
"template",
"=",
"$",
"twig",
"->",
"loadTemplate",
"(",
"$",
"template",
")",
";",
"return",
"$",
"template",
"->",
"render",
"(",
"$",
"options",
")",
";",
"}"
] |
Parse a little template with twig for yaml options
From @sescandell: is this function still used????
|
[
"Parse",
"a",
"little",
"template",
"with",
"twig",
"for",
"yaml",
"options",
"From"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Builder/Admin/BaseBuilder.php#L399-L417
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Builder/Admin/BaseBuilder.php
|
BaseBuilder.getStylesheets
|
public function getStylesheets()
{
$parse_stylesheets = function ($params, $stylesheets) {
foreach ($params as $css) {
if (is_string($css)) {
$css = array(
'path' => $css,
'media' => 'all',
);
}
$stylesheets[] = $css;
}
return $stylesheets;
};
// From config.yml
$stylesheets = $parse_stylesheets(
$this->getGenerator()->getContainer()
->getParameter('admingenerator.stylesheets', array()), array()
);
// From generator.yml
$stylesheets = $parse_stylesheets(
$this->getVariable('stylesheets', array()), $stylesheets
);
return $stylesheets;
}
|
php
|
public function getStylesheets()
{
$parse_stylesheets = function ($params, $stylesheets) {
foreach ($params as $css) {
if (is_string($css)) {
$css = array(
'path' => $css,
'media' => 'all',
);
}
$stylesheets[] = $css;
}
return $stylesheets;
};
// From config.yml
$stylesheets = $parse_stylesheets(
$this->getGenerator()->getContainer()
->getParameter('admingenerator.stylesheets', array()), array()
);
// From generator.yml
$stylesheets = $parse_stylesheets(
$this->getVariable('stylesheets', array()), $stylesheets
);
return $stylesheets;
}
|
[
"public",
"function",
"getStylesheets",
"(",
")",
"{",
"$",
"parse_stylesheets",
"=",
"function",
"(",
"$",
"params",
",",
"$",
"stylesheets",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"css",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"css",
")",
")",
"{",
"$",
"css",
"=",
"array",
"(",
"'path'",
"=>",
"$",
"css",
",",
"'media'",
"=>",
"'all'",
",",
")",
";",
"}",
"$",
"stylesheets",
"[",
"]",
"=",
"$",
"css",
";",
"}",
"return",
"$",
"stylesheets",
";",
"}",
";",
"// From config.yml",
"$",
"stylesheets",
"=",
"$",
"parse_stylesheets",
"(",
"$",
"this",
"->",
"getGenerator",
"(",
")",
"->",
"getContainer",
"(",
")",
"->",
"getParameter",
"(",
"'admingenerator.stylesheets'",
",",
"array",
"(",
")",
")",
",",
"array",
"(",
")",
")",
";",
"// From generator.yml",
"$",
"stylesheets",
"=",
"$",
"parse_stylesheets",
"(",
"$",
"this",
"->",
"getVariable",
"(",
"'stylesheets'",
",",
"array",
"(",
")",
")",
",",
"$",
"stylesheets",
")",
";",
"return",
"$",
"stylesheets",
";",
"}"
] |
Allow to add complementary strylesheets
param:
stylesheets:
- path/css.css
- { path: path/css.css, media: all }
@return array
|
[
"Allow",
"to",
"add",
"complementary",
"strylesheets"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Builder/Admin/BaseBuilder.php#L479-L508
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Builder/Admin/BaseBuilder.php
|
BaseBuilder.getJavascripts
|
public function getJavascripts()
{
$self = $this;
$parse_javascripts = function ($params, $javascripts) use ($self) {
foreach ($params as $js) {
if (is_string($js)) {
$js = array(
'path' => $js,
);
} elseif (isset($js['route'])) {
$js = array(
'path' => $self->getGenerator()
->getContainer()
->get('router')
->generate($js['route'], $js['routeparams'])
);
}
$javascripts[] = $js;
}
return $javascripts;
};
// From config.yml
$javascripts = $parse_javascripts(
$this->getGenerator()->getContainer()
->getParameter('admingenerator.javascripts', array()), array()
);
// From generator.yml
$javascripts = $parse_javascripts(
$this->getVariable('javascripts', array()), $javascripts
);
return $javascripts;
}
|
php
|
public function getJavascripts()
{
$self = $this;
$parse_javascripts = function ($params, $javascripts) use ($self) {
foreach ($params as $js) {
if (is_string($js)) {
$js = array(
'path' => $js,
);
} elseif (isset($js['route'])) {
$js = array(
'path' => $self->getGenerator()
->getContainer()
->get('router')
->generate($js['route'], $js['routeparams'])
);
}
$javascripts[] = $js;
}
return $javascripts;
};
// From config.yml
$javascripts = $parse_javascripts(
$this->getGenerator()->getContainer()
->getParameter('admingenerator.javascripts', array()), array()
);
// From generator.yml
$javascripts = $parse_javascripts(
$this->getVariable('javascripts', array()), $javascripts
);
return $javascripts;
}
|
[
"public",
"function",
"getJavascripts",
"(",
")",
"{",
"$",
"self",
"=",
"$",
"this",
";",
"$",
"parse_javascripts",
"=",
"function",
"(",
"$",
"params",
",",
"$",
"javascripts",
")",
"use",
"(",
"$",
"self",
")",
"{",
"foreach",
"(",
"$",
"params",
"as",
"$",
"js",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"js",
")",
")",
"{",
"$",
"js",
"=",
"array",
"(",
"'path'",
"=>",
"$",
"js",
",",
")",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"js",
"[",
"'route'",
"]",
")",
")",
"{",
"$",
"js",
"=",
"array",
"(",
"'path'",
"=>",
"$",
"self",
"->",
"getGenerator",
"(",
")",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'router'",
")",
"->",
"generate",
"(",
"$",
"js",
"[",
"'route'",
"]",
",",
"$",
"js",
"[",
"'routeparams'",
"]",
")",
")",
";",
"}",
"$",
"javascripts",
"[",
"]",
"=",
"$",
"js",
";",
"}",
"return",
"$",
"javascripts",
";",
"}",
";",
"// From config.yml",
"$",
"javascripts",
"=",
"$",
"parse_javascripts",
"(",
"$",
"this",
"->",
"getGenerator",
"(",
")",
"->",
"getContainer",
"(",
")",
"->",
"getParameter",
"(",
"'admingenerator.javascripts'",
",",
"array",
"(",
")",
")",
",",
"array",
"(",
")",
")",
";",
"// From generator.yml",
"$",
"javascripts",
"=",
"$",
"parse_javascripts",
"(",
"$",
"this",
"->",
"getVariable",
"(",
"'javascripts'",
",",
"array",
"(",
")",
")",
",",
"$",
"javascripts",
")",
";",
"return",
"$",
"javascripts",
";",
"}"
] |
Allow to add complementary javascripts
param:
javascripts:
- path/js.js
- { path: path/js.js }
- { route: my_route, routeparams: {} }
@return array
|
[
"Allow",
"to",
"add",
"complementary",
"javascripts"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Builder/Admin/BaseBuilder.php#L522-L559
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Generator/Generator.php
|
Generator.needToOverwrite
|
public function needToOverwrite(AdminGenerator $generator)
{
if ($this->container->getParameter('admingenerator.overwrite_if_exists')) {
return true;
}
$cacheDir = $this->getCachePath($generator->getFromYaml('params.namespace_prefix'), $generator->getFromYaml('params.bundle_name'));
if (!is_dir($cacheDir)) {
return true;
}
$fileInfo = new \SplFileInfo($this->getGeneratorYml());
$finder = new Finder();
$files = $finder->files()
->date('< '.date('Y-m-d H:i:s',$fileInfo->getMTime()))
->in($cacheDir)
->count();
if ($files > 0) {
return true;
}
$finder = new Finder();
foreach ($finder->files()->in($cacheDir) as $file) {
if (false !== strpos(file_get_contents($file), 'AdmingeneratorEmptyBuilderClass')) {
return true;
}
}
return false;
}
|
php
|
public function needToOverwrite(AdminGenerator $generator)
{
if ($this->container->getParameter('admingenerator.overwrite_if_exists')) {
return true;
}
$cacheDir = $this->getCachePath($generator->getFromYaml('params.namespace_prefix'), $generator->getFromYaml('params.bundle_name'));
if (!is_dir($cacheDir)) {
return true;
}
$fileInfo = new \SplFileInfo($this->getGeneratorYml());
$finder = new Finder();
$files = $finder->files()
->date('< '.date('Y-m-d H:i:s',$fileInfo->getMTime()))
->in($cacheDir)
->count();
if ($files > 0) {
return true;
}
$finder = new Finder();
foreach ($finder->files()->in($cacheDir) as $file) {
if (false !== strpos(file_get_contents($file), 'AdmingeneratorEmptyBuilderClass')) {
return true;
}
}
return false;
}
|
[
"public",
"function",
"needToOverwrite",
"(",
"AdminGenerator",
"$",
"generator",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'admingenerator.overwrite_if_exists'",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"cacheDir",
"=",
"$",
"this",
"->",
"getCachePath",
"(",
"$",
"generator",
"->",
"getFromYaml",
"(",
"'params.namespace_prefix'",
")",
",",
"$",
"generator",
"->",
"getFromYaml",
"(",
"'params.bundle_name'",
")",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"cacheDir",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"fileInfo",
"=",
"new",
"\\",
"SplFileInfo",
"(",
"$",
"this",
"->",
"getGeneratorYml",
"(",
")",
")",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"files",
"=",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
"date",
"(",
"'< '",
".",
"date",
"(",
"'Y-m-d H:i:s'",
",",
"$",
"fileInfo",
"->",
"getMTime",
"(",
")",
")",
")",
"->",
"in",
"(",
"$",
"cacheDir",
")",
"->",
"count",
"(",
")",
";",
"if",
"(",
"$",
"files",
">",
"0",
")",
"{",
"return",
"true",
";",
"}",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"foreach",
"(",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
"in",
"(",
"$",
"cacheDir",
")",
"as",
"$",
"file",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"file_get_contents",
"(",
"$",
"file",
")",
",",
"'AdmingeneratorEmptyBuilderClass'",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Check if we have to build file
|
[
"Check",
"if",
"we",
"have",
"to",
"build",
"file"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Generator/Generator.php#L137-L169
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
DependencyInjection/AdmingeneratorGeneratorExtension.php
|
AdmingeneratorGeneratorExtension.prepend
|
public function prepend(ContainerBuilder $container)
{
$config = array('twig' => array(
'template' => 'AdmingeneratorGeneratorBundle:KnpMenu:knp_menu_trans.html.twig'
));
foreach ($container->getExtensions() as $name => $extension) {
switch ($name) {
case 'knp_menu':
$container->prependExtensionConfig($name, $config);
break;
}
}
}
|
php
|
public function prepend(ContainerBuilder $container)
{
$config = array('twig' => array(
'template' => 'AdmingeneratorGeneratorBundle:KnpMenu:knp_menu_trans.html.twig'
));
foreach ($container->getExtensions() as $name => $extension) {
switch ($name) {
case 'knp_menu':
$container->prependExtensionConfig($name, $config);
break;
}
}
}
|
[
"public",
"function",
"prepend",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"config",
"=",
"array",
"(",
"'twig'",
"=>",
"array",
"(",
"'template'",
"=>",
"'AdmingeneratorGeneratorBundle:KnpMenu:knp_menu_trans.html.twig'",
")",
")",
";",
"foreach",
"(",
"$",
"container",
"->",
"getExtensions",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"extension",
")",
"{",
"switch",
"(",
"$",
"name",
")",
"{",
"case",
"'knp_menu'",
":",
"$",
"container",
"->",
"prependExtensionConfig",
"(",
"$",
"name",
",",
"$",
"config",
")",
";",
"break",
";",
"}",
"}",
"}"
] |
Prepend KnpMenuBundle config
|
[
"Prepend",
"KnpMenuBundle",
"config"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/DependencyInjection/AdmingeneratorGeneratorExtension.php#L20-L33
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Twig/Extension/EchoExtension.php
|
EchoExtension.wrap
|
public function wrap($str, $wrap)
{
return (is_string($str) && $str !== '') ? $wrap.$str.$wrap : $str;
}
|
php
|
public function wrap($str, $wrap)
{
return (is_string($str) && $str !== '') ? $wrap.$str.$wrap : $str;
}
|
[
"public",
"function",
"wrap",
"(",
"$",
"str",
",",
"$",
"wrap",
")",
"{",
"return",
"(",
"is_string",
"(",
"$",
"str",
")",
"&&",
"$",
"str",
"!==",
"''",
")",
"?",
"$",
"wrap",
".",
"$",
"str",
".",
"$",
"wrap",
":",
"$",
"str",
";",
"}"
] |
Wrap string around with given string only if string is not empty
@param string $str
@param string $wrap
@return string
|
[
"Wrap",
"string",
"around",
"with",
"given",
"string",
"only",
"if",
"string",
"is",
"not",
"empty"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Twig/Extension/EchoExtension.php#L186-L189
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Twig/Extension/EchoExtension.php
|
EchoExtension.char
|
public function char()
{
$str = '';
foreach (func_get_args() as $char) {
if (is_int($char)) {
$str .= chr($char);
}
}
return $str;
}
|
php
|
public function char()
{
$str = '';
foreach (func_get_args() as $char) {
if (is_int($char)) {
$str .= chr($char);
}
}
return $str;
}
|
[
"public",
"function",
"char",
"(",
")",
"{",
"$",
"str",
"=",
"''",
";",
"foreach",
"(",
"func_get_args",
"(",
")",
"as",
"$",
"char",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"char",
")",
")",
"{",
"$",
"str",
".=",
"chr",
"(",
"$",
"char",
")",
";",
"}",
"}",
"return",
"$",
"str",
";",
"}"
] |
Get characters by code
Note: if the code is higher than 256, it will return the code mod 256.
For example: chr(321)=A because A=65(256)
@param integer Any number of integer codes
@return string
|
[
"Get",
"characters",
"by",
"code"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Twig/Extension/EchoExtension.php#L205-L216
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Twig/Extension/EchoExtension.php
|
EchoExtension.getParameterBag
|
private function getParameterBag($subject)
{
// Backwards compability - replace twig tags with parameters
$pattern_bc = '/\{\{\s(?<param>[a-zA-Z0-9.]+)\s\}\}+/';
if (preg_match_all($pattern_bc, $subject, $match_params)) {
$string = preg_filter($pattern_bc, '%\1%', $subject);
$param = array();
foreach ($match_params['param'] as $value) {
$param[$value] = $value;
}
return array(
'string' => $string,
'params' => $param
);
}
# Feature - read key/value syntax parameters
$pattern_string = '/^(?<string>[^|]+)(?<parameter_bag>\|\{(\s?%[a-zA-Z0-9.]+%:\s[a-zA-Z0-9.]+,?\s?)+\s?\}\|)\s*$/';
$pattern_params = '/(?>(?<=(\|\{\s|.,\s))%(?<key>[a-zA-Z0-9.]+)%:\s(?<value>[a-zA-Z0-9.]+)(?=(,\s.|\s\}\|)))+/';
if (preg_match($pattern_string, $subject, $match_string)) {
$string = $match_string['string'];
$parameter_bag = $match_string['parameter_bag'];
$param = array();
preg_match_all($pattern_params, $parameter_bag, $match_params, PREG_SET_ORDER);
foreach ($match_params as $match) {
$param[$match['key']] = $match['value'];
}
return array(
'string' => $string,
'params' => $param
);
}
# Feature - read abbreviated syntax parameters
$abbreviated_pattern_string = '/^(?<string>[^|]+)(?<parameter_bag>\|\{(\s?[a-zA-Z0-9.]+,?\s?)+\s?\}\|)\s*$/';
$abbreviated_pattern_params = '/(?>(?<=(\|\{\s|.,\s))(?<param>[a-zA-Z0-9.]+)(?=(,\s.|\s\}\|)))+?/';
if (preg_match($abbreviated_pattern_string, $subject, $match_string)) {
$string = $match_string['string'];
$parameter_bag = $match_string['parameter_bag'];
$param = array();
preg_match_all($abbreviated_pattern_params, $parameter_bag, $match_params);
foreach ($match_params['param'] as $value) {
$param[$value] = $value;
}
return array(
'string' => $string,
'params' => $param
);
}
// If subject does not match any pattern, return false
return false;
}
|
php
|
private function getParameterBag($subject)
{
// Backwards compability - replace twig tags with parameters
$pattern_bc = '/\{\{\s(?<param>[a-zA-Z0-9.]+)\s\}\}+/';
if (preg_match_all($pattern_bc, $subject, $match_params)) {
$string = preg_filter($pattern_bc, '%\1%', $subject);
$param = array();
foreach ($match_params['param'] as $value) {
$param[$value] = $value;
}
return array(
'string' => $string,
'params' => $param
);
}
# Feature - read key/value syntax parameters
$pattern_string = '/^(?<string>[^|]+)(?<parameter_bag>\|\{(\s?%[a-zA-Z0-9.]+%:\s[a-zA-Z0-9.]+,?\s?)+\s?\}\|)\s*$/';
$pattern_params = '/(?>(?<=(\|\{\s|.,\s))%(?<key>[a-zA-Z0-9.]+)%:\s(?<value>[a-zA-Z0-9.]+)(?=(,\s.|\s\}\|)))+/';
if (preg_match($pattern_string, $subject, $match_string)) {
$string = $match_string['string'];
$parameter_bag = $match_string['parameter_bag'];
$param = array();
preg_match_all($pattern_params, $parameter_bag, $match_params, PREG_SET_ORDER);
foreach ($match_params as $match) {
$param[$match['key']] = $match['value'];
}
return array(
'string' => $string,
'params' => $param
);
}
# Feature - read abbreviated syntax parameters
$abbreviated_pattern_string = '/^(?<string>[^|]+)(?<parameter_bag>\|\{(\s?[a-zA-Z0-9.]+,?\s?)+\s?\}\|)\s*$/';
$abbreviated_pattern_params = '/(?>(?<=(\|\{\s|.,\s))(?<param>[a-zA-Z0-9.]+)(?=(,\s.|\s\}\|)))+?/';
if (preg_match($abbreviated_pattern_string, $subject, $match_string)) {
$string = $match_string['string'];
$parameter_bag = $match_string['parameter_bag'];
$param = array();
preg_match_all($abbreviated_pattern_params, $parameter_bag, $match_params);
foreach ($match_params['param'] as $value) {
$param[$value] = $value;
}
return array(
'string' => $string,
'params' => $param
);
}
// If subject does not match any pattern, return false
return false;
}
|
[
"private",
"function",
"getParameterBag",
"(",
"$",
"subject",
")",
"{",
"// Backwards compability - replace twig tags with parameters",
"$",
"pattern_bc",
"=",
"'/\\{\\{\\s(?<param>[a-zA-Z0-9.]+)\\s\\}\\}+/'",
";",
"if",
"(",
"preg_match_all",
"(",
"$",
"pattern_bc",
",",
"$",
"subject",
",",
"$",
"match_params",
")",
")",
"{",
"$",
"string",
"=",
"preg_filter",
"(",
"$",
"pattern_bc",
",",
"'%\\1%'",
",",
"$",
"subject",
")",
";",
"$",
"param",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"match_params",
"[",
"'param'",
"]",
"as",
"$",
"value",
")",
"{",
"$",
"param",
"[",
"$",
"value",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"array",
"(",
"'string'",
"=>",
"$",
"string",
",",
"'params'",
"=>",
"$",
"param",
")",
";",
"}",
"# Feature - read key/value syntax parameters",
"$",
"pattern_string",
"=",
"'/^(?<string>[^|]+)(?<parameter_bag>\\|\\{(\\s?%[a-zA-Z0-9.]+%:\\s[a-zA-Z0-9.]+,?\\s?)+\\s?\\}\\|)\\s*$/'",
";",
"$",
"pattern_params",
"=",
"'/(?>(?<=(\\|\\{\\s|.,\\s))%(?<key>[a-zA-Z0-9.]+)%:\\s(?<value>[a-zA-Z0-9.]+)(?=(,\\s.|\\s\\}\\|)))+/'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"pattern_string",
",",
"$",
"subject",
",",
"$",
"match_string",
")",
")",
"{",
"$",
"string",
"=",
"$",
"match_string",
"[",
"'string'",
"]",
";",
"$",
"parameter_bag",
"=",
"$",
"match_string",
"[",
"'parameter_bag'",
"]",
";",
"$",
"param",
"=",
"array",
"(",
")",
";",
"preg_match_all",
"(",
"$",
"pattern_params",
",",
"$",
"parameter_bag",
",",
"$",
"match_params",
",",
"PREG_SET_ORDER",
")",
";",
"foreach",
"(",
"$",
"match_params",
"as",
"$",
"match",
")",
"{",
"$",
"param",
"[",
"$",
"match",
"[",
"'key'",
"]",
"]",
"=",
"$",
"match",
"[",
"'value'",
"]",
";",
"}",
"return",
"array",
"(",
"'string'",
"=>",
"$",
"string",
",",
"'params'",
"=>",
"$",
"param",
")",
";",
"}",
"# Feature - read abbreviated syntax parameters",
"$",
"abbreviated_pattern_string",
"=",
"'/^(?<string>[^|]+)(?<parameter_bag>\\|\\{(\\s?[a-zA-Z0-9.]+,?\\s?)+\\s?\\}\\|)\\s*$/'",
";",
"$",
"abbreviated_pattern_params",
"=",
"'/(?>(?<=(\\|\\{\\s|.,\\s))(?<param>[a-zA-Z0-9.]+)(?=(,\\s.|\\s\\}\\|)))+?/'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"abbreviated_pattern_string",
",",
"$",
"subject",
",",
"$",
"match_string",
")",
")",
"{",
"$",
"string",
"=",
"$",
"match_string",
"[",
"'string'",
"]",
";",
"$",
"parameter_bag",
"=",
"$",
"match_string",
"[",
"'parameter_bag'",
"]",
";",
"$",
"param",
"=",
"array",
"(",
")",
";",
"preg_match_all",
"(",
"$",
"abbreviated_pattern_params",
",",
"$",
"parameter_bag",
",",
"$",
"match_params",
")",
";",
"foreach",
"(",
"$",
"match_params",
"[",
"'param'",
"]",
"as",
"$",
"value",
")",
"{",
"$",
"param",
"[",
"$",
"value",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"array",
"(",
"'string'",
"=>",
"$",
"string",
",",
"'params'",
"=>",
"$",
"param",
")",
";",
"}",
"// If subject does not match any pattern, return false",
"return",
"false",
";",
"}"
] |
Reads parameters from subject and removes parameter bag from string.
@return array
[string] -> string for echo trans
[params] -> parameters for echo trans
@return false if subject did not match any of following patterns
##############################
Backwards compability pattern:
replaces twig tags {{ parameter_name }} with parameters.
example: You're editing {{ Book.title }} written by {{ Book.author.name }}!
results in:
string -> You're editing %Book.title% written by %Book.author.name%!
params ->
[Book.title] -> Book.title
[Book.author.name] -> Book.author.name
###################################
Feature - key-value syntax pattern:
|{ %param_key%: param_value, %param_key2%: param_value2, %param_key3%: param_value3 }|
where param_key and param_value consist of any number a-z, A-Z, 0-9 or . (dot) characters
example: You're editing %book% written by %author%!|{ %book%: Book.title, %author%: Book.author.name }|
results in:
string -> You're editing %book% written by %author%!
params ->
[book] -> Book.title
[author] -> Book.author.name
example: book.edit.title|{ %book%: Book.title, %author%: Book.author.name }| *
results in:
string -> book.edit.title
params ->
[book] -> Book.title
[author] -> Book.author.name
###################################
Feature - abbreviated syntax pattern:
|{ param_value, param_value2, param_value3 }|
where param_value consists of any number a-z, A-Z, 0-9 or . (dot) characters
example: You're editing %Book.title% written by %Book.author.name%!|{ Book.title, Book.author.name }|
results in:
string -> You're editing %Book.title% written by %Book.author.name%!
params ->
[Book.title] -> Book.title
[Book.author.name] -> Book.author.name
example: book.edit.title|{ Book.title, Book.author.name }|
results in:
string -> book.edit.title
params ->
[Book.title] -> Book.title
[Book.author.name] -> Book.author.name
|
[
"Reads",
"parameters",
"from",
"subject",
"and",
"removes",
"parameter",
"bag",
"from",
"string",
"."
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Twig/Extension/EchoExtension.php#L280-L343
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Menu/AdmingeneratorMenuBuilder.php
|
AdmingeneratorMenuBuilder.addHeader
|
protected function addHeader(ItemInterface $menu, $label)
{
$item = $menu->addChild($label);
$item->setAttribute('class', 'dropdown-header');
$item->setExtra('translation_domain', $this->translation_domain);
return $item;
}
|
php
|
protected function addHeader(ItemInterface $menu, $label)
{
$item = $menu->addChild($label);
$item->setAttribute('class', 'dropdown-header');
$item->setExtra('translation_domain', $this->translation_domain);
return $item;
}
|
[
"protected",
"function",
"addHeader",
"(",
"ItemInterface",
"$",
"menu",
",",
"$",
"label",
")",
"{",
"$",
"item",
"=",
"$",
"menu",
"->",
"addChild",
"(",
"$",
"label",
")",
";",
"$",
"item",
"->",
"setAttribute",
"(",
"'class'",
",",
"'dropdown-header'",
")",
";",
"$",
"item",
"->",
"setExtra",
"(",
"'translation_domain'",
",",
"$",
"this",
"->",
"translation_domain",
")",
";",
"return",
"$",
"item",
";",
"}"
] |
Creates header element and adds it to menu
@param \Knp\Menu\ItemInterface $menu
@param string $label Header label
@return ItemInterface Header element
|
[
"Creates",
"header",
"element",
"and",
"adds",
"it",
"to",
"menu"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Menu/AdmingeneratorMenuBuilder.php#L21-L28
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Menu/AdmingeneratorMenuBuilder.php
|
AdmingeneratorMenuBuilder.addDivider
|
protected function addDivider(ItemInterface $menu)
{
do {
$name = 'divider'.mt_rand();
} while (in_array($name, $this->dividers));
$this->dividers[] = $name;
$item = $menu->addChild($name, array());
$item->setLabel('');
$item->setAttribute('class', 'divider');
return $item;
}
|
php
|
protected function addDivider(ItemInterface $menu)
{
do {
$name = 'divider'.mt_rand();
} while (in_array($name, $this->dividers));
$this->dividers[] = $name;
$item = $menu->addChild($name, array());
$item->setLabel('');
$item->setAttribute('class', 'divider');
return $item;
}
|
[
"protected",
"function",
"addDivider",
"(",
"ItemInterface",
"$",
"menu",
")",
"{",
"do",
"{",
"$",
"name",
"=",
"'divider'",
".",
"mt_rand",
"(",
")",
";",
"}",
"while",
"(",
"in_array",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"dividers",
")",
")",
";",
"$",
"this",
"->",
"dividers",
"[",
"]",
"=",
"$",
"name",
";",
"$",
"item",
"=",
"$",
"menu",
"->",
"addChild",
"(",
"$",
"name",
",",
"array",
"(",
")",
")",
";",
"$",
"item",
"->",
"setLabel",
"(",
"''",
")",
";",
"$",
"item",
"->",
"setAttribute",
"(",
"'class'",
",",
"'divider'",
")",
";",
"return",
"$",
"item",
";",
"}"
] |
Creates divider element and adds it to menu
@param \Knp\Menu\ItemInterface $menu
@return ItemInterface Divider element
|
[
"Creates",
"divider",
"element",
"and",
"adds",
"it",
"to",
"menu"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Menu/AdmingeneratorMenuBuilder.php#L96-L109
|
train
|
symfony2admingenerator/AdmingeneratorGeneratorBundle
|
Generator/Action.php
|
Action.setCondition
|
public function setCondition(array $condition)
{
if (!isset($condition['function'])) {
return false;
}
$this->conditional_function = $condition['function'];
if (isset($condition['parameters'])) {
$this->conditional_parameters = (array) $condition['parameters'];
}
if (isset($condition['inverse'])) {
$this->conditional_inverse = (boolean) $condition['inverse'];
}
}
|
php
|
public function setCondition(array $condition)
{
if (!isset($condition['function'])) {
return false;
}
$this->conditional_function = $condition['function'];
if (isset($condition['parameters'])) {
$this->conditional_parameters = (array) $condition['parameters'];
}
if (isset($condition['inverse'])) {
$this->conditional_inverse = (boolean) $condition['inverse'];
}
}
|
[
"public",
"function",
"setCondition",
"(",
"array",
"$",
"condition",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"condition",
"[",
"'function'",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"conditional_function",
"=",
"$",
"condition",
"[",
"'function'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"condition",
"[",
"'parameters'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"conditional_parameters",
"=",
"(",
"array",
")",
"$",
"condition",
"[",
"'parameters'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"condition",
"[",
"'inverse'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"conditional_inverse",
"=",
"(",
"boolean",
")",
"$",
"condition",
"[",
"'inverse'",
"]",
";",
"}",
"}"
] |
To be removed
@deprecated use credentials instead and SecurityFunction annotation
from JMS\DiExtraBundle
|
[
"To",
"be",
"removed"
] |
58008ec61746da9e6829d0e9b94b8f39589a623f
|
https://github.com/symfony2admingenerator/AdmingeneratorGeneratorBundle/blob/58008ec61746da9e6829d0e9b94b8f39589a623f/Generator/Action.php#L195-L210
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseCacheUtil.php
|
DatabaseCacheUtil.keyExists
|
public function keyExists(string $key): bool
{
$result = $this->database->prepare('SELECT * FROM tl_db_cache WHERE cacheKey = ?')->execute($key);
return $result->numRows > 0;
}
|
php
|
public function keyExists(string $key): bool
{
$result = $this->database->prepare('SELECT * FROM tl_db_cache WHERE cacheKey = ?')->execute($key);
return $result->numRows > 0;
}
|
[
"public",
"function",
"keyExists",
"(",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"database",
"->",
"prepare",
"(",
"'SELECT * FROM tl_db_cache WHERE cacheKey = ?'",
")",
"->",
"execute",
"(",
"$",
"key",
")",
";",
"return",
"$",
"result",
"->",
"numRows",
">",
"0",
";",
"}"
] |
Check for a given cache key.
@param string $key
@return bool
|
[
"Check",
"for",
"a",
"given",
"cache",
"key",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseCacheUtil.php#L49-L54
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseCacheUtil.php
|
DatabaseCacheUtil.cacheValue
|
public function cacheValue(string $key, $value)
{
if (!Config::get('activateDbCache')) {
return false;
}
if ($this->getValue($key)) {
throw new \Exception('Duplicate entry in tl_db_cache for key '.$key);
}
$now = time();
$this->database->prepare('INSERT INTO tl_db_cache (tstamp, expiration, cacheKey, cacheValue) VALUES (?, ?, ?, ?)')->execute(
$now,
$now + $this->container->get('huh.utils.date')->getTimePeriodInSeconds(
StringUtil::deserialize(Config::get('dbCacheMaxTime'), true)
),
$key,
$value
);
return true;
}
|
php
|
public function cacheValue(string $key, $value)
{
if (!Config::get('activateDbCache')) {
return false;
}
if ($this->getValue($key)) {
throw new \Exception('Duplicate entry in tl_db_cache for key '.$key);
}
$now = time();
$this->database->prepare('INSERT INTO tl_db_cache (tstamp, expiration, cacheKey, cacheValue) VALUES (?, ?, ?, ?)')->execute(
$now,
$now + $this->container->get('huh.utils.date')->getTimePeriodInSeconds(
StringUtil::deserialize(Config::get('dbCacheMaxTime'), true)
),
$key,
$value
);
return true;
}
|
[
"public",
"function",
"cacheValue",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"Config",
"::",
"get",
"(",
"'activateDbCache'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"getValue",
"(",
"$",
"key",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Duplicate entry in tl_db_cache for key '",
".",
"$",
"key",
")",
";",
"}",
"$",
"now",
"=",
"time",
"(",
")",
";",
"$",
"this",
"->",
"database",
"->",
"prepare",
"(",
"'INSERT INTO tl_db_cache (tstamp, expiration, cacheKey, cacheValue) VALUES (?, ?, ?, ?)'",
")",
"->",
"execute",
"(",
"$",
"now",
",",
"$",
"now",
"+",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.date'",
")",
"->",
"getTimePeriodInSeconds",
"(",
"StringUtil",
"::",
"deserialize",
"(",
"Config",
"::",
"get",
"(",
"'dbCacheMaxTime'",
")",
",",
"true",
")",
")",
",",
"$",
"key",
",",
"$",
"value",
")",
";",
"return",
"true",
";",
"}"
] |
Store a given value to cache.
@param string $key
@param $value
@throws \Exception
@return bool
|
[
"Store",
"a",
"given",
"value",
"to",
"cache",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseCacheUtil.php#L91-L113
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Twig/FileExtension.php
|
FileExtension.getFileData
|
public function getFileData($file, array $data = [], array $jsonSerializeOptions = []): array
{
if (null === ($fileObj = $this->container->get('huh.utils.file')->getFileFromUuid($file))) {
return [];
}
$fileData = $this->container->get('huh.utils.class')->jsonSerialize($fileObj, $data, array_merge_recursive($jsonSerializeOptions, ['ignoreMethods' => true]));
foreach (static::FILE_OBJECT_PROPERTIES as $property) {
$fileData[$property] = $fileObj->{$property};
}
return $fileData;
}
|
php
|
public function getFileData($file, array $data = [], array $jsonSerializeOptions = []): array
{
if (null === ($fileObj = $this->container->get('huh.utils.file')->getFileFromUuid($file))) {
return [];
}
$fileData = $this->container->get('huh.utils.class')->jsonSerialize($fileObj, $data, array_merge_recursive($jsonSerializeOptions, ['ignoreMethods' => true]));
foreach (static::FILE_OBJECT_PROPERTIES as $property) {
$fileData[$property] = $fileObj->{$property};
}
return $fileData;
}
|
[
"public",
"function",
"getFileData",
"(",
"$",
"file",
",",
"array",
"$",
"data",
"=",
"[",
"]",
",",
"array",
"$",
"jsonSerializeOptions",
"=",
"[",
"]",
")",
":",
"array",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"fileObj",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.file'",
")",
"->",
"getFileFromUuid",
"(",
"$",
"file",
")",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"fileData",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.class'",
")",
"->",
"jsonSerialize",
"(",
"$",
"fileObj",
",",
"$",
"data",
",",
"array_merge_recursive",
"(",
"$",
"jsonSerializeOptions",
",",
"[",
"'ignoreMethods'",
"=>",
"true",
"]",
")",
")",
";",
"foreach",
"(",
"static",
"::",
"FILE_OBJECT_PROPERTIES",
"as",
"$",
"property",
")",
"{",
"$",
"fileData",
"[",
"$",
"property",
"]",
"=",
"$",
"fileObj",
"->",
"{",
"$",
"property",
"}",
";",
"}",
"return",
"$",
"fileData",
";",
"}"
] |
Get file data based on given uuid.
@param mixed $file File uuid
@param array $data Add file data here
@param array $jsonSerializeOptions Options for the object to array transformation
@throws \ReflectionException
@return array File data
|
[
"Get",
"file",
"data",
"based",
"on",
"given",
"uuid",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Twig/FileExtension.php#L86-L99
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Twig/FileExtension.php
|
FileExtension.getFilePath
|
public function getFilePath($file): string
{
if (null === ($fileObj = $this->container->get('huh.utils.file')->getFileFromUuid($file))) {
return '';
}
return $fileObj->path;
}
|
php
|
public function getFilePath($file): string
{
if (null === ($fileObj = $this->container->get('huh.utils.file')->getFileFromUuid($file))) {
return '';
}
return $fileObj->path;
}
|
[
"public",
"function",
"getFilePath",
"(",
"$",
"file",
")",
":",
"string",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"fileObj",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.file'",
")",
"->",
"getFileFromUuid",
"(",
"$",
"file",
")",
")",
")",
"{",
"return",
"''",
";",
"}",
"return",
"$",
"fileObj",
"->",
"path",
";",
"}"
] |
Get file path based on given uuid.
@param mixed $file File uuid
@return string File path
|
[
"Get",
"file",
"path",
"based",
"on",
"given",
"uuid",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Twig/FileExtension.php#L108-L115
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Driver/DC_Table_Utils.php
|
DC_Table_Utils.createFromModel
|
public static function createFromModel(Model $model)
{
$table = $model->getTable();
$dc = new static($table);
$dc->strTable = $model->getTable();
$dc->activeRecord = $model;
$dc->intId = $model->id;
return $dc;
}
|
php
|
public static function createFromModel(Model $model)
{
$table = $model->getTable();
$dc = new static($table);
$dc->strTable = $model->getTable();
$dc->activeRecord = $model;
$dc->intId = $model->id;
return $dc;
}
|
[
"public",
"static",
"function",
"createFromModel",
"(",
"Model",
"$",
"model",
")",
"{",
"$",
"table",
"=",
"$",
"model",
"->",
"getTable",
"(",
")",
";",
"$",
"dc",
"=",
"new",
"static",
"(",
"$",
"table",
")",
";",
"$",
"dc",
"->",
"strTable",
"=",
"$",
"model",
"->",
"getTable",
"(",
")",
";",
"$",
"dc",
"->",
"activeRecord",
"=",
"$",
"model",
";",
"$",
"dc",
"->",
"intId",
"=",
"$",
"model",
"->",
"id",
";",
"return",
"$",
"dc",
";",
"}"
] |
Create a DataContainer instance from a given Model.
@param Model $model
@return static
|
[
"Create",
"a",
"DataContainer",
"instance",
"from",
"a",
"given",
"Model",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Driver/DC_Table_Utils.php#L145-L156
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Driver/DC_Table_Utils.php
|
DC_Table_Utils.createFromModelData
|
public static function createFromModelData(array $modelData, string $table, string $field = null)
{
$dc = new static($table);
$dc->strTable = $table;
$dc->activeRecord = null;
if (isset($modelData['id']) && $modelData['id'] > 0) {
$dc->activeRecord = System::getContainer()->get('huh.utils.model')->findModelInstanceByPk($table, $modelData['id']);
$dc->intId = $modelData['id'];
}
if ($field) {
$dc->strField = $field;
}
return $dc;
}
|
php
|
public static function createFromModelData(array $modelData, string $table, string $field = null)
{
$dc = new static($table);
$dc->strTable = $table;
$dc->activeRecord = null;
if (isset($modelData['id']) && $modelData['id'] > 0) {
$dc->activeRecord = System::getContainer()->get('huh.utils.model')->findModelInstanceByPk($table, $modelData['id']);
$dc->intId = $modelData['id'];
}
if ($field) {
$dc->strField = $field;
}
return $dc;
}
|
[
"public",
"static",
"function",
"createFromModelData",
"(",
"array",
"$",
"modelData",
",",
"string",
"$",
"table",
",",
"string",
"$",
"field",
"=",
"null",
")",
"{",
"$",
"dc",
"=",
"new",
"static",
"(",
"$",
"table",
")",
";",
"$",
"dc",
"->",
"strTable",
"=",
"$",
"table",
";",
"$",
"dc",
"->",
"activeRecord",
"=",
"null",
";",
"if",
"(",
"isset",
"(",
"$",
"modelData",
"[",
"'id'",
"]",
")",
"&&",
"$",
"modelData",
"[",
"'id'",
"]",
">",
"0",
")",
"{",
"$",
"dc",
"->",
"activeRecord",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.model'",
")",
"->",
"findModelInstanceByPk",
"(",
"$",
"table",
",",
"$",
"modelData",
"[",
"'id'",
"]",
")",
";",
"$",
"dc",
"->",
"intId",
"=",
"$",
"modelData",
"[",
"'id'",
"]",
";",
"}",
"if",
"(",
"$",
"field",
")",
"{",
"$",
"dc",
"->",
"strField",
"=",
"$",
"field",
";",
"}",
"return",
"$",
"dc",
";",
"}"
] |
Create a DataContainer instance from given model data.
@param Model $model
@param string $table
@param string $field
@return static
|
[
"Create",
"a",
"DataContainer",
"instance",
"from",
"given",
"model",
"data",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Driver/DC_Table_Utils.php#L167-L184
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Dca/DcaUtil.php
|
DcaUtil.getEditLink
|
public function getEditLink(string $module, int $id, string $label = null): string
{
$url = $this->container->get('huh.utils.url')->getCurrentUrl([
'skipParams' => true,
]);
if (!$id) {
return '';
}
$label = sprintf(StringUtil::specialchars($label ?: $GLOBALS['TL_LANG']['tl_content']['editalias'][1]), $id);
return sprintf(
' <a href="'.$url.'?do=%s&act=edit&id=%s&rt=%s" title="%s" style="padding-left: 5px; padding-top: 2px; display: inline-block;">%s</a>',
$module,
$id,
$this->container->get('security.csrf.token_manager')->getToken($this->container->getParameter('contao.csrf_token_name'))->getValue(),
$label,
Image::getHtml('alias.svg', $label, 'style="vertical-align:top"')
);
}
|
php
|
public function getEditLink(string $module, int $id, string $label = null): string
{
$url = $this->container->get('huh.utils.url')->getCurrentUrl([
'skipParams' => true,
]);
if (!$id) {
return '';
}
$label = sprintf(StringUtil::specialchars($label ?: $GLOBALS['TL_LANG']['tl_content']['editalias'][1]), $id);
return sprintf(
' <a href="'.$url.'?do=%s&act=edit&id=%s&rt=%s" title="%s" style="padding-left: 5px; padding-top: 2px; display: inline-block;">%s</a>',
$module,
$id,
$this->container->get('security.csrf.token_manager')->getToken($this->container->getParameter('contao.csrf_token_name'))->getValue(),
$label,
Image::getHtml('alias.svg', $label, 'style="vertical-align:top"')
);
}
|
[
"public",
"function",
"getEditLink",
"(",
"string",
"$",
"module",
",",
"int",
"$",
"id",
",",
"string",
"$",
"label",
"=",
"null",
")",
":",
"string",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.url'",
")",
"->",
"getCurrentUrl",
"(",
"[",
"'skipParams'",
"=>",
"true",
",",
"]",
")",
";",
"if",
"(",
"!",
"$",
"id",
")",
"{",
"return",
"''",
";",
"}",
"$",
"label",
"=",
"sprintf",
"(",
"StringUtil",
"::",
"specialchars",
"(",
"$",
"label",
"?",
":",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"'tl_content'",
"]",
"[",
"'editalias'",
"]",
"[",
"1",
"]",
")",
",",
"$",
"id",
")",
";",
"return",
"sprintf",
"(",
"' <a href=\"'",
".",
"$",
"url",
".",
"'?do=%s&act=edit&id=%s&rt=%s\" title=\"%s\" style=\"padding-left: 5px; padding-top: 2px; display: inline-block;\">%s</a>'",
",",
"$",
"module",
",",
"$",
"id",
",",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'security.csrf.token_manager'",
")",
"->",
"getToken",
"(",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'contao.csrf_token_name'",
")",
")",
"->",
"getValue",
"(",
")",
",",
"$",
"label",
",",
"Image",
"::",
"getHtml",
"(",
"'alias.svg'",
",",
"$",
"label",
",",
"'style=\"vertical-align:top\"'",
")",
")",
";",
"}"
] |
Get a contao backend modal edit link.
@param string $module Name of the module
@param int $id Id of the entity
@param string|null $label The label text
@return string The edit link
|
[
"Get",
"a",
"contao",
"backend",
"modal",
"edit",
"link",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Dca/DcaUtil.php#L59-L79
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Dca/DcaUtil.php
|
DcaUtil.setDateAdded
|
public function setDateAdded(DataContainer $dc)
{
$modelUtil = $this->container->get('huh.utils.model');
if (null === $dc || null === ($model = $modelUtil->findModelInstanceByPk($dc->table, $dc->id)) || $model->dateAdded > 0) {
return null;
}
$this->framework->createInstance(Database::class)->prepare("UPDATE $dc->table SET dateAdded=? WHERE id=? AND dateAdded = 0")->execute(time(), $dc->id);
}
|
php
|
public function setDateAdded(DataContainer $dc)
{
$modelUtil = $this->container->get('huh.utils.model');
if (null === $dc || null === ($model = $modelUtil->findModelInstanceByPk($dc->table, $dc->id)) || $model->dateAdded > 0) {
return null;
}
$this->framework->createInstance(Database::class)->prepare("UPDATE $dc->table SET dateAdded=? WHERE id=? AND dateAdded = 0")->execute(time(), $dc->id);
}
|
[
"public",
"function",
"setDateAdded",
"(",
"DataContainer",
"$",
"dc",
")",
"{",
"$",
"modelUtil",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.model'",
")",
";",
"if",
"(",
"null",
"===",
"$",
"dc",
"||",
"null",
"===",
"(",
"$",
"model",
"=",
"$",
"modelUtil",
"->",
"findModelInstanceByPk",
"(",
"$",
"dc",
"->",
"table",
",",
"$",
"dc",
"->",
"id",
")",
")",
"||",
"$",
"model",
"->",
"dateAdded",
">",
"0",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"framework",
"->",
"createInstance",
"(",
"Database",
"::",
"class",
")",
"->",
"prepare",
"(",
"\"UPDATE $dc->table SET dateAdded=? WHERE id=? AND dateAdded = 0\"",
")",
"->",
"execute",
"(",
"time",
"(",
")",
",",
"$",
"dc",
"->",
"id",
")",
";",
"}"
] |
Sets the current date as the date added -> usually used on submit.
@param DataContainer $dc
|
[
"Sets",
"the",
"current",
"date",
"as",
"the",
"date",
"added",
"-",
">",
"usually",
"used",
"on",
"submit",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Dca/DcaUtil.php#L252-L261
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Dca/DcaUtil.php
|
DcaUtil.getFields
|
public function getFields(string $table, array $options = []): array
{
$fields = [];
if (!$table) {
return $fields;
}
Controller::loadDataContainer($table);
System::loadLanguageFile($table);
if (!isset($GLOBALS['TL_DCA'][$table]['fields'])) {
return $fields;
}
foreach ($GLOBALS['TL_DCA'][$table]['fields'] as $name => $data) {
// restrict to certain input types
if (isset($options['inputTypes']) && \is_array($options['inputTypes']) && !empty($options['inputTypes']) && !\in_array($data['inputType'], $options['inputTypes'])) {
continue;
}
// restrict to certain dca eval
if (isset($options['evalConditions']) && \is_array($options['evalConditions']) && !empty($options['evalConditions'])) {
foreach ($options['evalConditions'] as $key => $value) {
if ($data['eval'][$key] !== $value) {
continue 2;
}
}
}
if (isset($options['localizeLabels']) && !$options['localizeLabels']) {
$fields[$name] = $name;
} else {
$label = $name;
if (isset($data['label'][0]) && $data['label'][0]) {
$label .= ' <span style="display: inline; color:#999; padding-left:3px">['.$data['label'][0].']</span>';
}
$fields[$name] = $label;
}
}
if (!isset($options['skipSorting']) || !$options['skipSorting']) {
asort($fields);
}
return $fields;
}
|
php
|
public function getFields(string $table, array $options = []): array
{
$fields = [];
if (!$table) {
return $fields;
}
Controller::loadDataContainer($table);
System::loadLanguageFile($table);
if (!isset($GLOBALS['TL_DCA'][$table]['fields'])) {
return $fields;
}
foreach ($GLOBALS['TL_DCA'][$table]['fields'] as $name => $data) {
// restrict to certain input types
if (isset($options['inputTypes']) && \is_array($options['inputTypes']) && !empty($options['inputTypes']) && !\in_array($data['inputType'], $options['inputTypes'])) {
continue;
}
// restrict to certain dca eval
if (isset($options['evalConditions']) && \is_array($options['evalConditions']) && !empty($options['evalConditions'])) {
foreach ($options['evalConditions'] as $key => $value) {
if ($data['eval'][$key] !== $value) {
continue 2;
}
}
}
if (isset($options['localizeLabels']) && !$options['localizeLabels']) {
$fields[$name] = $name;
} else {
$label = $name;
if (isset($data['label'][0]) && $data['label'][0]) {
$label .= ' <span style="display: inline; color:#999; padding-left:3px">['.$data['label'][0].']</span>';
}
$fields[$name] = $label;
}
}
if (!isset($options['skipSorting']) || !$options['skipSorting']) {
asort($fields);
}
return $fields;
}
|
[
"public",
"function",
"getFields",
"(",
"string",
"$",
"table",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"fields",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"table",
")",
"{",
"return",
"$",
"fields",
";",
"}",
"Controller",
"::",
"loadDataContainer",
"(",
"$",
"table",
")",
";",
"System",
"::",
"loadLanguageFile",
"(",
"$",
"table",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'fields'",
"]",
")",
")",
"{",
"return",
"$",
"fields",
";",
"}",
"foreach",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'fields'",
"]",
"as",
"$",
"name",
"=>",
"$",
"data",
")",
"{",
"// restrict to certain input types",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'inputTypes'",
"]",
")",
"&&",
"\\",
"is_array",
"(",
"$",
"options",
"[",
"'inputTypes'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"options",
"[",
"'inputTypes'",
"]",
")",
"&&",
"!",
"\\",
"in_array",
"(",
"$",
"data",
"[",
"'inputType'",
"]",
",",
"$",
"options",
"[",
"'inputTypes'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"// restrict to certain dca eval",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'evalConditions'",
"]",
")",
"&&",
"\\",
"is_array",
"(",
"$",
"options",
"[",
"'evalConditions'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"options",
"[",
"'evalConditions'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"options",
"[",
"'evalConditions'",
"]",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"data",
"[",
"'eval'",
"]",
"[",
"$",
"key",
"]",
"!==",
"$",
"value",
")",
"{",
"continue",
"2",
";",
"}",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'localizeLabels'",
"]",
")",
"&&",
"!",
"$",
"options",
"[",
"'localizeLabels'",
"]",
")",
"{",
"$",
"fields",
"[",
"$",
"name",
"]",
"=",
"$",
"name",
";",
"}",
"else",
"{",
"$",
"label",
"=",
"$",
"name",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'label'",
"]",
"[",
"0",
"]",
")",
"&&",
"$",
"data",
"[",
"'label'",
"]",
"[",
"0",
"]",
")",
"{",
"$",
"label",
".=",
"' <span style=\"display: inline; color:#999; padding-left:3px\">['",
".",
"$",
"data",
"[",
"'label'",
"]",
"[",
"0",
"]",
".",
"']</span>'",
";",
"}",
"$",
"fields",
"[",
"$",
"name",
"]",
"=",
"$",
"label",
";",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'skipSorting'",
"]",
")",
"||",
"!",
"$",
"options",
"[",
"'skipSorting'",
"]",
")",
"{",
"asort",
"(",
"$",
"fields",
")",
";",
"}",
"return",
"$",
"fields",
";",
"}"
] |
Returns a list of fields as an option array for dca fields.
Possible options:
- array inputTypes Restrict to certain input types
- array evalConditions restrict to certain dca eval
- bool localizeLabels
- bool skipSorting
@param string $table
@param array $options
@return array
|
[
"Returns",
"a",
"list",
"of",
"fields",
"as",
"an",
"option",
"array",
"for",
"dca",
"fields",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Dca/DcaUtil.php#L294-L342
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Dca/DcaUtil.php
|
DcaUtil.addAliasToDca
|
public function addAliasToDca(string $dca, $generateAliasCallback, string $paletteField, array $palettes = ['default'])
{
Controller::loadDataContainer($dca);
$arrDca = &$GLOBALS['TL_DCA'][$dca];
// add to palettes
foreach ($palettes as $strPalette) {
$arrDca['palettes'][$strPalette] = str_replace($paletteField.',', $paletteField.',alias,', $arrDca['palettes'][$strPalette]);
}
// add field
$arrDca['fields']['alias'] = [
'label' => &$GLOBALS['TL_LANG']['MSC']['alias'],
'exclude' => true,
'search' => true,
'inputType' => 'text',
'eval' => ['rgxp' => 'alias', 'unique' => true, 'maxlength' => 128, 'tl_class' => 'w50'],
'save_callback' => [$generateAliasCallback],
'sql' => "varchar(128) COLLATE utf8_bin NOT NULL default ''",
];
}
|
php
|
public function addAliasToDca(string $dca, $generateAliasCallback, string $paletteField, array $palettes = ['default'])
{
Controller::loadDataContainer($dca);
$arrDca = &$GLOBALS['TL_DCA'][$dca];
// add to palettes
foreach ($palettes as $strPalette) {
$arrDca['palettes'][$strPalette] = str_replace($paletteField.',', $paletteField.',alias,', $arrDca['palettes'][$strPalette]);
}
// add field
$arrDca['fields']['alias'] = [
'label' => &$GLOBALS['TL_LANG']['MSC']['alias'],
'exclude' => true,
'search' => true,
'inputType' => 'text',
'eval' => ['rgxp' => 'alias', 'unique' => true, 'maxlength' => 128, 'tl_class' => 'w50'],
'save_callback' => [$generateAliasCallback],
'sql' => "varchar(128) COLLATE utf8_bin NOT NULL default ''",
];
}
|
[
"public",
"function",
"addAliasToDca",
"(",
"string",
"$",
"dca",
",",
"$",
"generateAliasCallback",
",",
"string",
"$",
"paletteField",
",",
"array",
"$",
"palettes",
"=",
"[",
"'default'",
"]",
")",
"{",
"Controller",
"::",
"loadDataContainer",
"(",
"$",
"dca",
")",
";",
"$",
"arrDca",
"=",
"&",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"dca",
"]",
";",
"// add to palettes",
"foreach",
"(",
"$",
"palettes",
"as",
"$",
"strPalette",
")",
"{",
"$",
"arrDca",
"[",
"'palettes'",
"]",
"[",
"$",
"strPalette",
"]",
"=",
"str_replace",
"(",
"$",
"paletteField",
".",
"','",
",",
"$",
"paletteField",
".",
"',alias,'",
",",
"$",
"arrDca",
"[",
"'palettes'",
"]",
"[",
"$",
"strPalette",
"]",
")",
";",
"}",
"// add field",
"$",
"arrDca",
"[",
"'fields'",
"]",
"[",
"'alias'",
"]",
"=",
"[",
"'label'",
"=>",
"&",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"'MSC'",
"]",
"[",
"'alias'",
"]",
",",
"'exclude'",
"=>",
"true",
",",
"'search'",
"=>",
"true",
",",
"'inputType'",
"=>",
"'text'",
",",
"'eval'",
"=>",
"[",
"'rgxp'",
"=>",
"'alias'",
",",
"'unique'",
"=>",
"true",
",",
"'maxlength'",
"=>",
"128",
",",
"'tl_class'",
"=>",
"'w50'",
"]",
",",
"'save_callback'",
"=>",
"[",
"$",
"generateAliasCallback",
"]",
",",
"'sql'",
"=>",
"\"varchar(128) COLLATE utf8_bin NOT NULL default ''\"",
",",
"]",
";",
"}"
] |
Adds an alias field to the dca and to the desired palettes.
@param $dca
@param $generateAliasCallback mixed The callback to call for generating the alias
@param $paletteField String The field after which to insert the alias field in the palettes
@param array $palettes The palettes in which to insert the field
|
[
"Adds",
"an",
"alias",
"field",
"to",
"the",
"dca",
"and",
"to",
"the",
"desired",
"palettes",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Dca/DcaUtil.php#L719-L740
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Dca/DcaUtil.php
|
DcaUtil.loadDc
|
public function loadDc(string $table)
{
if (!isset($GLOBALS['TL_DCA'][$table]) || null === $GLOBALS['TL_DCA'][$table]) {
/** @var Controller $controller */
$controller = $this->framework->getAdapter(Controller::class);
$controller->loadDataContainer($table);
}
}
|
php
|
public function loadDc(string $table)
{
if (!isset($GLOBALS['TL_DCA'][$table]) || null === $GLOBALS['TL_DCA'][$table]) {
/** @var Controller $controller */
$controller = $this->framework->getAdapter(Controller::class);
$controller->loadDataContainer($table);
}
}
|
[
"public",
"function",
"loadDc",
"(",
"string",
"$",
"table",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
")",
"||",
"null",
"===",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
")",
"{",
"/** @var Controller $controller */",
"$",
"controller",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Controller",
"::",
"class",
")",
";",
"$",
"controller",
"->",
"loadDataContainer",
"(",
"$",
"table",
")",
";",
"}",
"}"
] |
Load a data container in a testable way.
@param string $table
|
[
"Load",
"a",
"data",
"container",
"in",
"a",
"testable",
"way",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Dca/DcaUtil.php#L761-L769
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Dca/DcaUtil.php
|
DcaUtil.loadLanguageFile
|
public function loadLanguageFile(string $table)
{
if (!isset($GLOBALS['TL_LANG'][$table]) || null === $GLOBALS['TL_LANG'][$table]) {
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($table);
}
}
|
php
|
public function loadLanguageFile(string $table)
{
if (!isset($GLOBALS['TL_LANG'][$table]) || null === $GLOBALS['TL_LANG'][$table]) {
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($table);
}
}
|
[
"public",
"function",
"loadLanguageFile",
"(",
"string",
"$",
"table",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"$",
"table",
"]",
")",
"||",
"null",
"===",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"$",
"table",
"]",
")",
"{",
"/** @var System $system */",
"$",
"system",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"System",
"::",
"class",
")",
";",
"$",
"system",
"->",
"loadLanguageFile",
"(",
"$",
"table",
")",
";",
"}",
"}"
] |
Load a language file in a testable way.
@param string $table
|
[
"Load",
"a",
"language",
"file",
"in",
"a",
"testable",
"way",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Dca/DcaUtil.php#L776-L784
|
train
|
heimrichhannot/contao-utils-bundle
|
src/File/FileUtil.php
|
FileUtil.getFileList
|
public function getFileList($dir, $baseUrl, $protectedBaseUrl = null)
{
$results = [];
if (is_dir($dir)) {
if ($handler = opendir($dir)) {
while (false !== ($file = readdir($handler))) {
if ('.' == substr($file, 0, 1)) {
continue;
}
$fileArray = [];
$fileArray['filename'] = htmlentities($file);
if ($protectedBaseUrl) {
$fileArray['absUrl'] =
$protectedBaseUrl.(empty($_GET) ? '?' : '&').'file='.str_replace('//', '', $baseUrl.'/'.$file);
} else {
$fileArray['absUrl'] = str_replace('\\', '/', str_replace('//', '', $baseUrl.'/'.$file));
}
$fileArray['path'] = str_replace($fileArray['filename'], '', $fileArray['absUrl']);
$fileArray['filesize'] =
$this->formatSizeUnits(filesize(str_replace('\\', '/', str_replace('//', '', $dir.'/'.$file))), true);
$results[] = $fileArray;
}
closedir($handler);
}
}
$this->container->get('huh.utils.array')->aasort($results, 'filename');
return $results;
}
|
php
|
public function getFileList($dir, $baseUrl, $protectedBaseUrl = null)
{
$results = [];
if (is_dir($dir)) {
if ($handler = opendir($dir)) {
while (false !== ($file = readdir($handler))) {
if ('.' == substr($file, 0, 1)) {
continue;
}
$fileArray = [];
$fileArray['filename'] = htmlentities($file);
if ($protectedBaseUrl) {
$fileArray['absUrl'] =
$protectedBaseUrl.(empty($_GET) ? '?' : '&').'file='.str_replace('//', '', $baseUrl.'/'.$file);
} else {
$fileArray['absUrl'] = str_replace('\\', '/', str_replace('//', '', $baseUrl.'/'.$file));
}
$fileArray['path'] = str_replace($fileArray['filename'], '', $fileArray['absUrl']);
$fileArray['filesize'] =
$this->formatSizeUnits(filesize(str_replace('\\', '/', str_replace('//', '', $dir.'/'.$file))), true);
$results[] = $fileArray;
}
closedir($handler);
}
}
$this->container->get('huh.utils.array')->aasort($results, 'filename');
return $results;
}
|
[
"public",
"function",
"getFileList",
"(",
"$",
"dir",
",",
"$",
"baseUrl",
",",
"$",
"protectedBaseUrl",
"=",
"null",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"if",
"(",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"if",
"(",
"$",
"handler",
"=",
"opendir",
"(",
"$",
"dir",
")",
")",
"{",
"while",
"(",
"false",
"!==",
"(",
"$",
"file",
"=",
"readdir",
"(",
"$",
"handler",
")",
")",
")",
"{",
"if",
"(",
"'.'",
"==",
"substr",
"(",
"$",
"file",
",",
"0",
",",
"1",
")",
")",
"{",
"continue",
";",
"}",
"$",
"fileArray",
"=",
"[",
"]",
";",
"$",
"fileArray",
"[",
"'filename'",
"]",
"=",
"htmlentities",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"protectedBaseUrl",
")",
"{",
"$",
"fileArray",
"[",
"'absUrl'",
"]",
"=",
"$",
"protectedBaseUrl",
".",
"(",
"empty",
"(",
"$",
"_GET",
")",
"?",
"'?'",
":",
"'&'",
")",
".",
"'file='",
".",
"str_replace",
"(",
"'//'",
",",
"''",
",",
"$",
"baseUrl",
".",
"'/'",
".",
"$",
"file",
")",
";",
"}",
"else",
"{",
"$",
"fileArray",
"[",
"'absUrl'",
"]",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"str_replace",
"(",
"'//'",
",",
"''",
",",
"$",
"baseUrl",
".",
"'/'",
".",
"$",
"file",
")",
")",
";",
"}",
"$",
"fileArray",
"[",
"'path'",
"]",
"=",
"str_replace",
"(",
"$",
"fileArray",
"[",
"'filename'",
"]",
",",
"''",
",",
"$",
"fileArray",
"[",
"'absUrl'",
"]",
")",
";",
"$",
"fileArray",
"[",
"'filesize'",
"]",
"=",
"$",
"this",
"->",
"formatSizeUnits",
"(",
"filesize",
"(",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"str_replace",
"(",
"'//'",
",",
"''",
",",
"$",
"dir",
".",
"'/'",
".",
"$",
"file",
")",
")",
")",
",",
"true",
")",
";",
"$",
"results",
"[",
"]",
"=",
"$",
"fileArray",
";",
"}",
"closedir",
"(",
"$",
"handler",
")",
";",
"}",
"}",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.array'",
")",
"->",
"aasort",
"(",
"$",
"results",
",",
"'filename'",
")",
";",
"return",
"$",
"results",
";",
"}"
] |
Returns the file list for a given directory.
@param string $dir - the absolute local path to the directory (e.g. /dir/mydir)
@param string $baseUrl - the relative uri (e.g. /tl_files/mydir)
@param string $protectedBaseUrl - domain + request uri -> absUrl will be domain + request uri + ?file=$baseUrl/filename.ext
@return array file list containing file objects
|
[
"Returns",
"the",
"file",
"list",
"for",
"a",
"given",
"directory",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/File/FileUtil.php#L107-L142
|
train
|
heimrichhannot/contao-utils-bundle
|
src/File/FileUtil.php
|
FileUtil.addUniqueIdToFilename
|
public function addUniqueIdToFilename($fileName, $prefix = null, $moreEntropy = true)
{
$file = new File($fileName);
$directory = ltrim(str_replace($this->container->getParameter('kernel.project_dir'), '', $file->dirname), '/');
return ($directory ? $directory.'/' : '').$file->filename.uniqid($prefix, $moreEntropy).($file->extension ? '.'
.$file->extension : '');
}
|
php
|
public function addUniqueIdToFilename($fileName, $prefix = null, $moreEntropy = true)
{
$file = new File($fileName);
$directory = ltrim(str_replace($this->container->getParameter('kernel.project_dir'), '', $file->dirname), '/');
return ($directory ? $directory.'/' : '').$file->filename.uniqid($prefix, $moreEntropy).($file->extension ? '.'
.$file->extension : '');
}
|
[
"public",
"function",
"addUniqueIdToFilename",
"(",
"$",
"fileName",
",",
"$",
"prefix",
"=",
"null",
",",
"$",
"moreEntropy",
"=",
"true",
")",
"{",
"$",
"file",
"=",
"new",
"File",
"(",
"$",
"fileName",
")",
";",
"$",
"directory",
"=",
"ltrim",
"(",
"str_replace",
"(",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'kernel.project_dir'",
")",
",",
"''",
",",
"$",
"file",
"->",
"dirname",
")",
",",
"'/'",
")",
";",
"return",
"(",
"$",
"directory",
"?",
"$",
"directory",
".",
"'/'",
":",
"''",
")",
".",
"$",
"file",
"->",
"filename",
".",
"uniqid",
"(",
"$",
"prefix",
",",
"$",
"moreEntropy",
")",
".",
"(",
"$",
"file",
"->",
"extension",
"?",
"'.'",
".",
"$",
"file",
"->",
"extension",
":",
"''",
")",
";",
"}"
] |
Add a unique identifier to a file name.
@param string $fileName The file name, can be with or without path
@param string $prefix add a prefix to the unique identifier, with an empty prefix, the returned string will be 13 characters long
@param bool $moreEntropy if set to TRUE, will add additional entropy (using the combined linear congruential generator) at the end of the
return value, which increases the likelihood that the result will be unique
@return string Filename with timestamp based unique identifier
|
[
"Add",
"a",
"unique",
"identifier",
"to",
"a",
"file",
"name",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/File/FileUtil.php#L250-L258
|
train
|
heimrichhannot/contao-utils-bundle
|
src/File/FileUtil.php
|
FileUtil.getFolderFromDca
|
public function getFolderFromDca($folder, DataContainer $dc = null)
{
// upload folder
if (\is_array($folder) && null !== $dc) {
$callback = $folder;
$folder = System::importStatic($callback[0])->{$callback[1]}($dc);
} elseif (\is_callable($folder) && null !== $dc) {
$method = $folder;
$folder = $method($dc);
} elseif (\is_string($folder)) {
if (false !== strpos($folder, '../')) {
throw new \Exception("Invalid target path $folder");
}
}
if ($folder instanceof File) {
$folder = $folder->value;
} elseif ($folder instanceof FilesModel) {
$folder = $folder->path;
}
if (Validator::isUuid($folder)) {
$folderObj = $this->getFolderFromUuid($folder);
$folder = $folderObj->value;
}
return $folder;
}
|
php
|
public function getFolderFromDca($folder, DataContainer $dc = null)
{
// upload folder
if (\is_array($folder) && null !== $dc) {
$callback = $folder;
$folder = System::importStatic($callback[0])->{$callback[1]}($dc);
} elseif (\is_callable($folder) && null !== $dc) {
$method = $folder;
$folder = $method($dc);
} elseif (\is_string($folder)) {
if (false !== strpos($folder, '../')) {
throw new \Exception("Invalid target path $folder");
}
}
if ($folder instanceof File) {
$folder = $folder->value;
} elseif ($folder instanceof FilesModel) {
$folder = $folder->path;
}
if (Validator::isUuid($folder)) {
$folderObj = $this->getFolderFromUuid($folder);
$folder = $folderObj->value;
}
return $folder;
}
|
[
"public",
"function",
"getFolderFromDca",
"(",
"$",
"folder",
",",
"DataContainer",
"$",
"dc",
"=",
"null",
")",
"{",
"// upload folder",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"folder",
")",
"&&",
"null",
"!==",
"$",
"dc",
")",
"{",
"$",
"callback",
"=",
"$",
"folder",
";",
"$",
"folder",
"=",
"System",
"::",
"importStatic",
"(",
"$",
"callback",
"[",
"0",
"]",
")",
"->",
"{",
"$",
"callback",
"[",
"1",
"]",
"}",
"(",
"$",
"dc",
")",
";",
"}",
"elseif",
"(",
"\\",
"is_callable",
"(",
"$",
"folder",
")",
"&&",
"null",
"!==",
"$",
"dc",
")",
"{",
"$",
"method",
"=",
"$",
"folder",
";",
"$",
"folder",
"=",
"$",
"method",
"(",
"$",
"dc",
")",
";",
"}",
"elseif",
"(",
"\\",
"is_string",
"(",
"$",
"folder",
")",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"folder",
",",
"'../'",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Invalid target path $folder\"",
")",
";",
"}",
"}",
"if",
"(",
"$",
"folder",
"instanceof",
"File",
")",
"{",
"$",
"folder",
"=",
"$",
"folder",
"->",
"value",
";",
"}",
"elseif",
"(",
"$",
"folder",
"instanceof",
"FilesModel",
")",
"{",
"$",
"folder",
"=",
"$",
"folder",
"->",
"path",
";",
"}",
"if",
"(",
"Validator",
"::",
"isUuid",
"(",
"$",
"folder",
")",
")",
"{",
"$",
"folderObj",
"=",
"$",
"this",
"->",
"getFolderFromUuid",
"(",
"$",
"folder",
")",
";",
"$",
"folder",
"=",
"$",
"folderObj",
"->",
"value",
";",
"}",
"return",
"$",
"folder",
";",
"}"
] |
Get real folder from datacontainer attribute.
@param mixed $folder The folder as uuid, function, callback array('CLASS', 'method') or string (files/...)
@param DataContainer|null $dc Optional \DataContainer, required for function and callback
@throws \Exception If ../ is part of the path
@return mixed|null The folder path or null
|
[
"Get",
"real",
"folder",
"from",
"datacontainer",
"attribute",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/File/FileUtil.php#L310-L337
|
train
|
heimrichhannot/contao-utils-bundle
|
src/File/FileUtil.php
|
FileUtil.getPreviewFromPdf
|
public function getPreviewFromPdf(FilesModel $file, int $page = 0): FilesModel
{
$strippedName = str_replace('.'.$file->extension, '', $file->name);
$previewFileName = 'preview-'.$strippedName.'.'.static::FILE_UTIL_CONVERT_FILE_TYPE;
$folder = str_replace($file->name, '', $file->path);
$target = $folder.\DIRECTORY_SEPARATOR.$previewFileName;
// ghostscript
/** @var Transcoder $transcoder */
$transcoder = $this->framework->getAdapter(Transcoder::class)->create();
$transcoder->toImage($file->path, $target);
// get all created images
$folderFiles = scandir($folder);
$pdfPreviewFiles = [];
$needle = '/preview-'.$strippedName.'*\.'.static::FILE_UTIL_CONVERT_FILE_TYPE.'/';
foreach ($folderFiles as $file) {
if (!preg_match($needle, $file)) {
continue;
}
$pdfPreviewFiles[] = $file;
}
$preview = null;
foreach ($pdfPreviewFiles as $key => $value) {
if ($page != $key && file_exists($value)) {
unlink($value);
continue;
}
$preview = $value;
}
if (null === ($previewFile = $this->framework->getAdapter(FilesModel::class)->findByPath($preview))) {
$previewFile = $this->framework->getAdapter(Dbafs::class)->addResource($folder.\DIRECTORY_SEPARATOR.$preview);
}
return $previewFile;
}
|
php
|
public function getPreviewFromPdf(FilesModel $file, int $page = 0): FilesModel
{
$strippedName = str_replace('.'.$file->extension, '', $file->name);
$previewFileName = 'preview-'.$strippedName.'.'.static::FILE_UTIL_CONVERT_FILE_TYPE;
$folder = str_replace($file->name, '', $file->path);
$target = $folder.\DIRECTORY_SEPARATOR.$previewFileName;
// ghostscript
/** @var Transcoder $transcoder */
$transcoder = $this->framework->getAdapter(Transcoder::class)->create();
$transcoder->toImage($file->path, $target);
// get all created images
$folderFiles = scandir($folder);
$pdfPreviewFiles = [];
$needle = '/preview-'.$strippedName.'*\.'.static::FILE_UTIL_CONVERT_FILE_TYPE.'/';
foreach ($folderFiles as $file) {
if (!preg_match($needle, $file)) {
continue;
}
$pdfPreviewFiles[] = $file;
}
$preview = null;
foreach ($pdfPreviewFiles as $key => $value) {
if ($page != $key && file_exists($value)) {
unlink($value);
continue;
}
$preview = $value;
}
if (null === ($previewFile = $this->framework->getAdapter(FilesModel::class)->findByPath($preview))) {
$previewFile = $this->framework->getAdapter(Dbafs::class)->addResource($folder.\DIRECTORY_SEPARATOR.$preview);
}
return $previewFile;
}
|
[
"public",
"function",
"getPreviewFromPdf",
"(",
"FilesModel",
"$",
"file",
",",
"int",
"$",
"page",
"=",
"0",
")",
":",
"FilesModel",
"{",
"$",
"strippedName",
"=",
"str_replace",
"(",
"'.'",
".",
"$",
"file",
"->",
"extension",
",",
"''",
",",
"$",
"file",
"->",
"name",
")",
";",
"$",
"previewFileName",
"=",
"'preview-'",
".",
"$",
"strippedName",
".",
"'.'",
".",
"static",
"::",
"FILE_UTIL_CONVERT_FILE_TYPE",
";",
"$",
"folder",
"=",
"str_replace",
"(",
"$",
"file",
"->",
"name",
",",
"''",
",",
"$",
"file",
"->",
"path",
")",
";",
"$",
"target",
"=",
"$",
"folder",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"$",
"previewFileName",
";",
"// ghostscript",
"/** @var Transcoder $transcoder */",
"$",
"transcoder",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Transcoder",
"::",
"class",
")",
"->",
"create",
"(",
")",
";",
"$",
"transcoder",
"->",
"toImage",
"(",
"$",
"file",
"->",
"path",
",",
"$",
"target",
")",
";",
"// get all created images",
"$",
"folderFiles",
"=",
"scandir",
"(",
"$",
"folder",
")",
";",
"$",
"pdfPreviewFiles",
"=",
"[",
"]",
";",
"$",
"needle",
"=",
"'/preview-'",
".",
"$",
"strippedName",
".",
"'*\\.'",
".",
"static",
"::",
"FILE_UTIL_CONVERT_FILE_TYPE",
".",
"'/'",
";",
"foreach",
"(",
"$",
"folderFiles",
"as",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"$",
"needle",
",",
"$",
"file",
")",
")",
"{",
"continue",
";",
"}",
"$",
"pdfPreviewFiles",
"[",
"]",
"=",
"$",
"file",
";",
"}",
"$",
"preview",
"=",
"null",
";",
"foreach",
"(",
"$",
"pdfPreviewFiles",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"page",
"!=",
"$",
"key",
"&&",
"file_exists",
"(",
"$",
"value",
")",
")",
"{",
"unlink",
"(",
"$",
"value",
")",
";",
"continue",
";",
"}",
"$",
"preview",
"=",
"$",
"value",
";",
"}",
"if",
"(",
"null",
"===",
"(",
"$",
"previewFile",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"FilesModel",
"::",
"class",
")",
"->",
"findByPath",
"(",
"$",
"preview",
")",
")",
")",
"{",
"$",
"previewFile",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Dbafs",
"::",
"class",
")",
"->",
"addResource",
"(",
"$",
"folder",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"$",
"preview",
")",
";",
"}",
"return",
"$",
"previewFile",
";",
"}"
] |
convert pdf to png and return a preview file
delete the other png files.
@param FilesModel $file
@param int $page
@deprecated Dublicate to PdfPreview util
@return FilesModel
|
[
"convert",
"pdf",
"to",
"png",
"and",
"return",
"a",
"preview",
"file",
"delete",
"the",
"other",
"png",
"files",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/File/FileUtil.php#L379-L421
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Salutation/SalutationUtil.php
|
SalutationUtil.createNameByFields
|
public function createNameByFields(string $language, array $data)
{
if ($language) {
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile('default', $language, true);
}
$name = '';
if ($data['firstname']) {
$name = $data['firstname'].($data['lastname'] ? ' '.$data['lastname'] : '');
} elseif ($data['lastname']) {
$name = $data['lastname'];
}
if ($name && $data['academicTitle']) {
$name = $data['academicTitle'].' '.$name;
}
if ($name && $data['additionalTitle']) {
$name = $data['additionalTitle'].' '.$name;
}
if ($data['lastname'] && $data['gender'] && ('en' != $language || !$data['academicTitle'])) {
$gender = $GLOBALS['TL_LANG']['MSC']['haste_plus']['gender'.('female' == $data['gender'] ? 'Female' : 'Male')];
$name = $gender.' '.$name;
}
if ($language) {
$system->loadLanguageFile('default', $GLOBALS['TL_LANGUAGE'], true);
}
return $name;
}
|
php
|
public function createNameByFields(string $language, array $data)
{
if ($language) {
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile('default', $language, true);
}
$name = '';
if ($data['firstname']) {
$name = $data['firstname'].($data['lastname'] ? ' '.$data['lastname'] : '');
} elseif ($data['lastname']) {
$name = $data['lastname'];
}
if ($name && $data['academicTitle']) {
$name = $data['academicTitle'].' '.$name;
}
if ($name && $data['additionalTitle']) {
$name = $data['additionalTitle'].' '.$name;
}
if ($data['lastname'] && $data['gender'] && ('en' != $language || !$data['academicTitle'])) {
$gender = $GLOBALS['TL_LANG']['MSC']['haste_plus']['gender'.('female' == $data['gender'] ? 'Female' : 'Male')];
$name = $gender.' '.$name;
}
if ($language) {
$system->loadLanguageFile('default', $GLOBALS['TL_LANGUAGE'], true);
}
return $name;
}
|
[
"public",
"function",
"createNameByFields",
"(",
"string",
"$",
"language",
",",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"language",
")",
"{",
"/** @var System $system */",
"$",
"system",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"System",
"::",
"class",
")",
";",
"$",
"system",
"->",
"loadLanguageFile",
"(",
"'default'",
",",
"$",
"language",
",",
"true",
")",
";",
"}",
"$",
"name",
"=",
"''",
";",
"if",
"(",
"$",
"data",
"[",
"'firstname'",
"]",
")",
"{",
"$",
"name",
"=",
"$",
"data",
"[",
"'firstname'",
"]",
".",
"(",
"$",
"data",
"[",
"'lastname'",
"]",
"?",
"' '",
".",
"$",
"data",
"[",
"'lastname'",
"]",
":",
"''",
")",
";",
"}",
"elseif",
"(",
"$",
"data",
"[",
"'lastname'",
"]",
")",
"{",
"$",
"name",
"=",
"$",
"data",
"[",
"'lastname'",
"]",
";",
"}",
"if",
"(",
"$",
"name",
"&&",
"$",
"data",
"[",
"'academicTitle'",
"]",
")",
"{",
"$",
"name",
"=",
"$",
"data",
"[",
"'academicTitle'",
"]",
".",
"' '",
".",
"$",
"name",
";",
"}",
"if",
"(",
"$",
"name",
"&&",
"$",
"data",
"[",
"'additionalTitle'",
"]",
")",
"{",
"$",
"name",
"=",
"$",
"data",
"[",
"'additionalTitle'",
"]",
".",
"' '",
".",
"$",
"name",
";",
"}",
"if",
"(",
"$",
"data",
"[",
"'lastname'",
"]",
"&&",
"$",
"data",
"[",
"'gender'",
"]",
"&&",
"(",
"'en'",
"!=",
"$",
"language",
"||",
"!",
"$",
"data",
"[",
"'academicTitle'",
"]",
")",
")",
"{",
"$",
"gender",
"=",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"'MSC'",
"]",
"[",
"'haste_plus'",
"]",
"[",
"'gender'",
".",
"(",
"'female'",
"==",
"$",
"data",
"[",
"'gender'",
"]",
"?",
"'Female'",
":",
"'Male'",
")",
"]",
";",
"$",
"name",
"=",
"$",
"gender",
".",
"' '",
".",
"$",
"name",
";",
"}",
"if",
"(",
"$",
"language",
")",
"{",
"$",
"system",
"->",
"loadLanguageFile",
"(",
"'default'",
",",
"$",
"GLOBALS",
"[",
"'TL_LANGUAGE'",
"]",
",",
"true",
")",
";",
"}",
"return",
"$",
"name",
";",
"}"
] |
Creates complete names by inserting an array of the person's data.
Supported field names: firstname, lastname, academicTitle, additionalTitle, gender
If some of the fields shouldn't go into the processed name, just leave them out of $arrData
@param array $data
|
[
"Creates",
"complete",
"names",
"by",
"inserting",
"an",
"array",
"of",
"the",
"person",
"s",
"data",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Salutation/SalutationUtil.php#L35-L71
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Database/DatabaseUtil.php
|
DatabaseUtil.processInPieces
|
public function processInPieces(string $countQuery, string $query, $callback = null, string $key = null, int $bulkSize = 5000)
{
/** @var Database $database */
$database = $this->framework->createInstance(Database::class);
$total = $database->execute($countQuery);
if ($total->total < 1) {
return false;
}
$bulkSize = (int) $bulkSize;
$totalCount = $total->total;
$cycles = $totalCount / $bulkSize;
for ($i = 0; $i <= $cycles; ++$i) {
$result = $database->prepare($query)->limit($bulkSize, $i * $bulkSize)->execute();
if ($result->numRows < 1) {
return false;
}
if (\is_callable($callback)) {
$return = [];
while (false !== ($row = $result->fetchAssoc())) {
if ($key) {
if (isset($row[$key])) {
$return[$row[$key]] = $row;
}
continue;
}
$return[] = $row;
}
\call_user_func_array($callback, [$return]);
}
}
return $totalCount;
}
|
php
|
public function processInPieces(string $countQuery, string $query, $callback = null, string $key = null, int $bulkSize = 5000)
{
/** @var Database $database */
$database = $this->framework->createInstance(Database::class);
$total = $database->execute($countQuery);
if ($total->total < 1) {
return false;
}
$bulkSize = (int) $bulkSize;
$totalCount = $total->total;
$cycles = $totalCount / $bulkSize;
for ($i = 0; $i <= $cycles; ++$i) {
$result = $database->prepare($query)->limit($bulkSize, $i * $bulkSize)->execute();
if ($result->numRows < 1) {
return false;
}
if (\is_callable($callback)) {
$return = [];
while (false !== ($row = $result->fetchAssoc())) {
if ($key) {
if (isset($row[$key])) {
$return[$row[$key]] = $row;
}
continue;
}
$return[] = $row;
}
\call_user_func_array($callback, [$return]);
}
}
return $totalCount;
}
|
[
"public",
"function",
"processInPieces",
"(",
"string",
"$",
"countQuery",
",",
"string",
"$",
"query",
",",
"$",
"callback",
"=",
"null",
",",
"string",
"$",
"key",
"=",
"null",
",",
"int",
"$",
"bulkSize",
"=",
"5000",
")",
"{",
"/** @var Database $database */",
"$",
"database",
"=",
"$",
"this",
"->",
"framework",
"->",
"createInstance",
"(",
"Database",
"::",
"class",
")",
";",
"$",
"total",
"=",
"$",
"database",
"->",
"execute",
"(",
"$",
"countQuery",
")",
";",
"if",
"(",
"$",
"total",
"->",
"total",
"<",
"1",
")",
"{",
"return",
"false",
";",
"}",
"$",
"bulkSize",
"=",
"(",
"int",
")",
"$",
"bulkSize",
";",
"$",
"totalCount",
"=",
"$",
"total",
"->",
"total",
";",
"$",
"cycles",
"=",
"$",
"totalCount",
"/",
"$",
"bulkSize",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<=",
"$",
"cycles",
";",
"++",
"$",
"i",
")",
"{",
"$",
"result",
"=",
"$",
"database",
"->",
"prepare",
"(",
"$",
"query",
")",
"->",
"limit",
"(",
"$",
"bulkSize",
",",
"$",
"i",
"*",
"$",
"bulkSize",
")",
"->",
"execute",
"(",
")",
";",
"if",
"(",
"$",
"result",
"->",
"numRows",
"<",
"1",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"\\",
"is_callable",
"(",
"$",
"callback",
")",
")",
"{",
"$",
"return",
"=",
"[",
"]",
";",
"while",
"(",
"false",
"!==",
"(",
"$",
"row",
"=",
"$",
"result",
"->",
"fetchAssoc",
"(",
")",
")",
")",
"{",
"if",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"row",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"return",
"[",
"$",
"row",
"[",
"$",
"key",
"]",
"]",
"=",
"$",
"row",
";",
"}",
"continue",
";",
"}",
"$",
"return",
"[",
"]",
"=",
"$",
"row",
";",
"}",
"\\",
"call_user_func_array",
"(",
"$",
"callback",
",",
"[",
"$",
"return",
"]",
")",
";",
"}",
"}",
"return",
"$",
"totalCount",
";",
"}"
] |
Process a query in pieces, run callback within each cycle.
@param string $countQuery The query that count the total rows, must contain "Select COUNT(*) as total"
@param string $query The query, with the rows that should be iterated over
@param callable $callback A callback that should be triggered after each cycle, contains $arrRows of current cycle
@param string $key The key of the value that should be set as key identifier for the returned result array entries
@param int $bulkSize The bulk size
@return bool|int False if nothing to do, otherwise return the total number of processes entities
|
[
"Process",
"a",
"query",
"in",
"pieces",
"run",
"callback",
"within",
"each",
"cycle",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Database/DatabaseUtil.php#L108-L149
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Database/DatabaseUtil.php
|
DatabaseUtil.createWhereForSerializedBlob
|
public function createWhereForSerializedBlob(string $field, array $values, string $connective = self::SQL_CONDITION_OR)
{
$where = null;
$returnValues = [];
if (!\in_array($connective, [self::SQL_CONDITION_OR, self::SQL_CONDITION_AND])) {
throw new \Exception('Unknown sql junctor');
}
foreach ($values as $val) {
if (null !== $where) {
$where .= " $connective ";
}
$where .= self::SQL_CONDITION_AND == $connective ? '(' : '';
$where .= "$field REGEXP (?)";
$where .= self::SQL_CONDITION_AND == $connective ? ')' : '';
$returnValues[] = "':\"$val\"'";
}
return ["($where)", $returnValues];
}
|
php
|
public function createWhereForSerializedBlob(string $field, array $values, string $connective = self::SQL_CONDITION_OR)
{
$where = null;
$returnValues = [];
if (!\in_array($connective, [self::SQL_CONDITION_OR, self::SQL_CONDITION_AND])) {
throw new \Exception('Unknown sql junctor');
}
foreach ($values as $val) {
if (null !== $where) {
$where .= " $connective ";
}
$where .= self::SQL_CONDITION_AND == $connective ? '(' : '';
$where .= "$field REGEXP (?)";
$where .= self::SQL_CONDITION_AND == $connective ? ')' : '';
$returnValues[] = "':\"$val\"'";
}
return ["($where)", $returnValues];
}
|
[
"public",
"function",
"createWhereForSerializedBlob",
"(",
"string",
"$",
"field",
",",
"array",
"$",
"values",
",",
"string",
"$",
"connective",
"=",
"self",
"::",
"SQL_CONDITION_OR",
")",
"{",
"$",
"where",
"=",
"null",
";",
"$",
"returnValues",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"connective",
",",
"[",
"self",
"::",
"SQL_CONDITION_OR",
",",
"self",
"::",
"SQL_CONDITION_AND",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Unknown sql junctor'",
")",
";",
"}",
"foreach",
"(",
"$",
"values",
"as",
"$",
"val",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"where",
")",
"{",
"$",
"where",
".=",
"\" $connective \"",
";",
"}",
"$",
"where",
".=",
"self",
"::",
"SQL_CONDITION_AND",
"==",
"$",
"connective",
"?",
"'('",
":",
"''",
";",
"$",
"where",
".=",
"\"$field REGEXP (?)\"",
";",
"$",
"where",
".=",
"self",
"::",
"SQL_CONDITION_AND",
"==",
"$",
"connective",
"?",
"')'",
":",
"''",
";",
"$",
"returnValues",
"[",
"]",
"=",
"\"':\\\"$val\\\"'\"",
";",
"}",
"return",
"[",
"\"($where)\"",
",",
"$",
"returnValues",
"]",
";",
"}"
] |
Create a where condition for a field that contains a serialized blob.
@param string $field The field the condition should be checked against accordances
@param array $values The values array to check the field against
@param string $connective SQL_CONDITION_OR | SQL_CONDITION_AND
@return array
|
[
"Create",
"a",
"where",
"condition",
"for",
"a",
"field",
"that",
"contains",
"a",
"serialized",
"blob",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Database/DatabaseUtil.php#L322-L346
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Template/TemplateUtil.php
|
TemplateUtil.getAllTemplates
|
public function getAllTemplates()
{
$strCacheDir = $this->container->getParameter('kernel.cache_dir');
// Try to load from cache
if (file_exists($strCacheDir.'/contao/config/twig-templates.php')) {
self::$twigFiles = include $strCacheDir.'/contao/config/twig-templates.php';
return self::$twigFiles;
}
$bundles = $this->kernel->getBundles();
if (\is_array($bundles)) {
foreach (array_reverse($bundles) as $key => $value) {
$path = $this->kernel->locateResource("@$key");
$dir = rtrim($path, '/').'/Resources/views';
if (!is_dir($dir)) {
continue;
}
$finder = new Finder();
$twigKey = preg_replace('/Bundle$/', '', $key);
foreach ($finder->in($dir)->files()->name('*.twig') as $file) {
/** @var SplFileInfo $file */
$name = $file->getBasename();
$legacyName = false !== strpos($name, 'html.twig') ? $file->getBasename('.html.twig') : $name;
if (isset(self::$twigFiles[$name])) {
continue;
}
self::$twigFiles[$name] = "@$twigKey/".$file->getRelativePathname();
if ($legacyName !== $name) {
self::$twigFiles[$legacyName] = self::$twigFiles[$name];
}
}
}
}
foreach ($this->container->get('contao.resource_finder')->findIn('templates')->name('*.twig') as $file) {
$name = $file->getBasename();
$legacyName = false !== strpos($name, 'html.twig') ? $file->getBasename('.html.twig') : $name;
/* @var SplFileInfo $file */
self::$twigFiles[$name] = $file->getRealPath();
if ($legacyName !== $name) {
self::$twigFiles[$legacyName] = self::$twigFiles[$name];
}
}
// add root templates
$rootTemplates = $this->findTemplates($this->containerUtil->getProjectDir().'/templates/');
if (\is_array($rootTemplates)) {
foreach ($rootTemplates as $file) {
$name = basename($file);
$legacyName = false !== strpos($name, 'html.twig') ? basename($file, '.html.twig') : $name;
self::$twigFiles[$name] = $file;
if ($legacyName !== $name) {
self::$twigFiles[$legacyName] = self::$twigFiles[$name];
}
}
}
return self::$twigFiles;
}
|
php
|
public function getAllTemplates()
{
$strCacheDir = $this->container->getParameter('kernel.cache_dir');
// Try to load from cache
if (file_exists($strCacheDir.'/contao/config/twig-templates.php')) {
self::$twigFiles = include $strCacheDir.'/contao/config/twig-templates.php';
return self::$twigFiles;
}
$bundles = $this->kernel->getBundles();
if (\is_array($bundles)) {
foreach (array_reverse($bundles) as $key => $value) {
$path = $this->kernel->locateResource("@$key");
$dir = rtrim($path, '/').'/Resources/views';
if (!is_dir($dir)) {
continue;
}
$finder = new Finder();
$twigKey = preg_replace('/Bundle$/', '', $key);
foreach ($finder->in($dir)->files()->name('*.twig') as $file) {
/** @var SplFileInfo $file */
$name = $file->getBasename();
$legacyName = false !== strpos($name, 'html.twig') ? $file->getBasename('.html.twig') : $name;
if (isset(self::$twigFiles[$name])) {
continue;
}
self::$twigFiles[$name] = "@$twigKey/".$file->getRelativePathname();
if ($legacyName !== $name) {
self::$twigFiles[$legacyName] = self::$twigFiles[$name];
}
}
}
}
foreach ($this->container->get('contao.resource_finder')->findIn('templates')->name('*.twig') as $file) {
$name = $file->getBasename();
$legacyName = false !== strpos($name, 'html.twig') ? $file->getBasename('.html.twig') : $name;
/* @var SplFileInfo $file */
self::$twigFiles[$name] = $file->getRealPath();
if ($legacyName !== $name) {
self::$twigFiles[$legacyName] = self::$twigFiles[$name];
}
}
// add root templates
$rootTemplates = $this->findTemplates($this->containerUtil->getProjectDir().'/templates/');
if (\is_array($rootTemplates)) {
foreach ($rootTemplates as $file) {
$name = basename($file);
$legacyName = false !== strpos($name, 'html.twig') ? basename($file, '.html.twig') : $name;
self::$twigFiles[$name] = $file;
if ($legacyName !== $name) {
self::$twigFiles[$legacyName] = self::$twigFiles[$name];
}
}
}
return self::$twigFiles;
}
|
[
"public",
"function",
"getAllTemplates",
"(",
")",
"{",
"$",
"strCacheDir",
"=",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'kernel.cache_dir'",
")",
";",
"// Try to load from cache",
"if",
"(",
"file_exists",
"(",
"$",
"strCacheDir",
".",
"'/contao/config/twig-templates.php'",
")",
")",
"{",
"self",
"::",
"$",
"twigFiles",
"=",
"include",
"$",
"strCacheDir",
".",
"'/contao/config/twig-templates.php'",
";",
"return",
"self",
"::",
"$",
"twigFiles",
";",
"}",
"$",
"bundles",
"=",
"$",
"this",
"->",
"kernel",
"->",
"getBundles",
"(",
")",
";",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"bundles",
")",
")",
"{",
"foreach",
"(",
"array_reverse",
"(",
"$",
"bundles",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"kernel",
"->",
"locateResource",
"(",
"\"@$key\"",
")",
";",
"$",
"dir",
"=",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
")",
".",
"'/Resources/views'",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"continue",
";",
"}",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"twigKey",
"=",
"preg_replace",
"(",
"'/Bundle$/'",
",",
"''",
",",
"$",
"key",
")",
";",
"foreach",
"(",
"$",
"finder",
"->",
"in",
"(",
"$",
"dir",
")",
"->",
"files",
"(",
")",
"->",
"name",
"(",
"'*.twig'",
")",
"as",
"$",
"file",
")",
"{",
"/** @var SplFileInfo $file */",
"$",
"name",
"=",
"$",
"file",
"->",
"getBasename",
"(",
")",
";",
"$",
"legacyName",
"=",
"false",
"!==",
"strpos",
"(",
"$",
"name",
",",
"'html.twig'",
")",
"?",
"$",
"file",
"->",
"getBasename",
"(",
"'.html.twig'",
")",
":",
"$",
"name",
";",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
")",
")",
"{",
"continue",
";",
"}",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
"=",
"\"@$twigKey/\"",
".",
"$",
"file",
"->",
"getRelativePathname",
"(",
")",
";",
"if",
"(",
"$",
"legacyName",
"!==",
"$",
"name",
")",
"{",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"legacyName",
"]",
"=",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
";",
"}",
"}",
"}",
"}",
"foreach",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'contao.resource_finder'",
")",
"->",
"findIn",
"(",
"'templates'",
")",
"->",
"name",
"(",
"'*.twig'",
")",
"as",
"$",
"file",
")",
"{",
"$",
"name",
"=",
"$",
"file",
"->",
"getBasename",
"(",
")",
";",
"$",
"legacyName",
"=",
"false",
"!==",
"strpos",
"(",
"$",
"name",
",",
"'html.twig'",
")",
"?",
"$",
"file",
"->",
"getBasename",
"(",
"'.html.twig'",
")",
":",
"$",
"name",
";",
"/* @var SplFileInfo $file */",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
"=",
"$",
"file",
"->",
"getRealPath",
"(",
")",
";",
"if",
"(",
"$",
"legacyName",
"!==",
"$",
"name",
")",
"{",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"legacyName",
"]",
"=",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
";",
"}",
"}",
"// add root templates",
"$",
"rootTemplates",
"=",
"$",
"this",
"->",
"findTemplates",
"(",
"$",
"this",
"->",
"containerUtil",
"->",
"getProjectDir",
"(",
")",
".",
"'/templates/'",
")",
";",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"rootTemplates",
")",
")",
"{",
"foreach",
"(",
"$",
"rootTemplates",
"as",
"$",
"file",
")",
"{",
"$",
"name",
"=",
"basename",
"(",
"$",
"file",
")",
";",
"$",
"legacyName",
"=",
"false",
"!==",
"strpos",
"(",
"$",
"name",
",",
"'html.twig'",
")",
"?",
"basename",
"(",
"$",
"file",
",",
"'.html.twig'",
")",
":",
"$",
"name",
";",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
"=",
"$",
"file",
";",
"if",
"(",
"$",
"legacyName",
"!==",
"$",
"name",
")",
"{",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"legacyName",
"]",
"=",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
";",
"}",
"}",
"}",
"return",
"self",
"::",
"$",
"twigFiles",
";",
"}"
] |
Get a list of all available templates.
|
[
"Get",
"a",
"list",
"of",
"all",
"available",
"templates",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Template/TemplateUtil.php#L60-L132
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Template/TemplateUtil.php
|
TemplateUtil.getTemplate
|
public function getTemplate(string $name, string $format = 'twig'): string
{
// Check for a theme folder
if ($this->containerUtil->isFrontend()) {
/* @var PageModel $objPage */
global $objPage;
if ('' != $objPage->templateGroup) {
if (\Validator::isInsecurePath($objPage->templateGroup)) {
throw new \RuntimeException('Invalid path '.$objPage->templateGroup);
}
$templates = $this->findTemplates($this->containerUtil->getProjectDir().'/'.$objPage->templateGroup, $name, $format);
if (!empty($templates)) {
return reset($templates);
}
}
}
if (!isset(self::$twigFiles[$name])) {
throw new \Twig_Error_Loader(sprintf('Unable to find template "%s".', $name));
}
return self::$twigFiles[$name];
}
|
php
|
public function getTemplate(string $name, string $format = 'twig'): string
{
// Check for a theme folder
if ($this->containerUtil->isFrontend()) {
/* @var PageModel $objPage */
global $objPage;
if ('' != $objPage->templateGroup) {
if (\Validator::isInsecurePath($objPage->templateGroup)) {
throw new \RuntimeException('Invalid path '.$objPage->templateGroup);
}
$templates = $this->findTemplates($this->containerUtil->getProjectDir().'/'.$objPage->templateGroup, $name, $format);
if (!empty($templates)) {
return reset($templates);
}
}
}
if (!isset(self::$twigFiles[$name])) {
throw new \Twig_Error_Loader(sprintf('Unable to find template "%s".', $name));
}
return self::$twigFiles[$name];
}
|
[
"public",
"function",
"getTemplate",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"format",
"=",
"'twig'",
")",
":",
"string",
"{",
"// Check for a theme folder",
"if",
"(",
"$",
"this",
"->",
"containerUtil",
"->",
"isFrontend",
"(",
")",
")",
"{",
"/* @var PageModel $objPage */",
"global",
"$",
"objPage",
";",
"if",
"(",
"''",
"!=",
"$",
"objPage",
"->",
"templateGroup",
")",
"{",
"if",
"(",
"\\",
"Validator",
"::",
"isInsecurePath",
"(",
"$",
"objPage",
"->",
"templateGroup",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Invalid path '",
".",
"$",
"objPage",
"->",
"templateGroup",
")",
";",
"}",
"$",
"templates",
"=",
"$",
"this",
"->",
"findTemplates",
"(",
"$",
"this",
"->",
"containerUtil",
"->",
"getProjectDir",
"(",
")",
".",
"'/'",
".",
"$",
"objPage",
"->",
"templateGroup",
",",
"$",
"name",
",",
"$",
"format",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"templates",
")",
")",
"{",
"return",
"reset",
"(",
"$",
"templates",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Twig_Error_Loader",
"(",
"sprintf",
"(",
"'Unable to find template \"%s\".'",
",",
"$",
"name",
")",
")",
";",
"}",
"return",
"self",
"::",
"$",
"twigFiles",
"[",
"$",
"name",
"]",
";",
"}"
] |
Find a particular template file and return its path.
@param string $name The name of the template
@param string $format The file extension
@throws \InvalidArgumentException If $strFormat is unknown
@throws \RuntimeException If the template group folder is insecure
@throws \Twig_Error_Loader
@return string The path to the template file
|
[
"Find",
"a",
"particular",
"template",
"file",
"and",
"return",
"its",
"path",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Template/TemplateUtil.php#L267-L292
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Template/TemplateUtil.php
|
TemplateUtil.findTemplates
|
public function findTemplates(string $path, string $pattern = null, string $format = 'twig')
{
// Use glob() if possible
if (false === strpos($path, '/**/') && (\defined('GLOB_BRACE') || false === strpos($path, '{'))) {
$templates = glob(rtrim($path, '/').'/*.{'.$format.'}', \defined('GLOB_BRACE') ? GLOB_BRACE : 0);
return null === $pattern ? $templates : preg_grep('$'.$pattern.'$', $templates);
}
$pattern = rtrim($path, '/').(null === $pattern ? '' : $pattern).'/*.{'.$format.'}';
$finder = new Finder();
$regex = Glob::toRegex($pattern);
// All files in the given template folder
$filesIterator = $finder->files()->followLinks()->sortByName()->in(\dirname($pattern));
// Match the actual regex and filter the files
$filesIterator = $filesIterator->filter(
function (\SplFileInfo $info) use ($regex) {
$path = $info->getPathname();
return preg_match($regex, $path) && $info->isFile();
}
);
$files = iterator_to_array($filesIterator);
return array_keys($files);
}
|
php
|
public function findTemplates(string $path, string $pattern = null, string $format = 'twig')
{
// Use glob() if possible
if (false === strpos($path, '/**/') && (\defined('GLOB_BRACE') || false === strpos($path, '{'))) {
$templates = glob(rtrim($path, '/').'/*.{'.$format.'}', \defined('GLOB_BRACE') ? GLOB_BRACE : 0);
return null === $pattern ? $templates : preg_grep('$'.$pattern.'$', $templates);
}
$pattern = rtrim($path, '/').(null === $pattern ? '' : $pattern).'/*.{'.$format.'}';
$finder = new Finder();
$regex = Glob::toRegex($pattern);
// All files in the given template folder
$filesIterator = $finder->files()->followLinks()->sortByName()->in(\dirname($pattern));
// Match the actual regex and filter the files
$filesIterator = $filesIterator->filter(
function (\SplFileInfo $info) use ($regex) {
$path = $info->getPathname();
return preg_match($regex, $path) && $info->isFile();
}
);
$files = iterator_to_array($filesIterator);
return array_keys($files);
}
|
[
"public",
"function",
"findTemplates",
"(",
"string",
"$",
"path",
",",
"string",
"$",
"pattern",
"=",
"null",
",",
"string",
"$",
"format",
"=",
"'twig'",
")",
"{",
"// Use glob() if possible",
"if",
"(",
"false",
"===",
"strpos",
"(",
"$",
"path",
",",
"'/**/'",
")",
"&&",
"(",
"\\",
"defined",
"(",
"'GLOB_BRACE'",
")",
"||",
"false",
"===",
"strpos",
"(",
"$",
"path",
",",
"'{'",
")",
")",
")",
"{",
"$",
"templates",
"=",
"glob",
"(",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
")",
".",
"'/*.{'",
".",
"$",
"format",
".",
"'}'",
",",
"\\",
"defined",
"(",
"'GLOB_BRACE'",
")",
"?",
"GLOB_BRACE",
":",
"0",
")",
";",
"return",
"null",
"===",
"$",
"pattern",
"?",
"$",
"templates",
":",
"preg_grep",
"(",
"'$'",
".",
"$",
"pattern",
".",
"'$'",
",",
"$",
"templates",
")",
";",
"}",
"$",
"pattern",
"=",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
")",
".",
"(",
"null",
"===",
"$",
"pattern",
"?",
"''",
":",
"$",
"pattern",
")",
".",
"'/*.{'",
".",
"$",
"format",
".",
"'}'",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"regex",
"=",
"Glob",
"::",
"toRegex",
"(",
"$",
"pattern",
")",
";",
"// All files in the given template folder",
"$",
"filesIterator",
"=",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
"followLinks",
"(",
")",
"->",
"sortByName",
"(",
")",
"->",
"in",
"(",
"\\",
"dirname",
"(",
"$",
"pattern",
")",
")",
";",
"// Match the actual regex and filter the files",
"$",
"filesIterator",
"=",
"$",
"filesIterator",
"->",
"filter",
"(",
"function",
"(",
"\\",
"SplFileInfo",
"$",
"info",
")",
"use",
"(",
"$",
"regex",
")",
"{",
"$",
"path",
"=",
"$",
"info",
"->",
"getPathname",
"(",
")",
";",
"return",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"path",
")",
"&&",
"$",
"info",
"->",
"isFile",
"(",
")",
";",
"}",
")",
";",
"$",
"files",
"=",
"iterator_to_array",
"(",
"$",
"filesIterator",
")",
";",
"return",
"array_keys",
"(",
"$",
"files",
")",
";",
"}"
] |
Return the files matching a GLOB pattern.
@param string $path
@param string $pattern
@param string $format
@return array
|
[
"Return",
"the",
"files",
"matching",
"a",
"GLOB",
"pattern",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Template/TemplateUtil.php#L303-L332
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Template/TemplateUtil.php
|
TemplateUtil.isTemplatePartEmpty
|
public function isTemplatePartEmpty($template = null)
{
if (!\is_string($template)) {
return true;
}
return empty($this->removeTemplateComment($template));
}
|
php
|
public function isTemplatePartEmpty($template = null)
{
if (!\is_string($template)) {
return true;
}
return empty($this->removeTemplateComment($template));
}
|
[
"public",
"function",
"isTemplatePartEmpty",
"(",
"$",
"template",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"\\",
"is_string",
"(",
"$",
"template",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"empty",
"(",
"$",
"this",
"->",
"removeTemplateComment",
"(",
"$",
"template",
")",
")",
";",
"}"
] |
Return true, if the template part is empty.
Template comments from debug and white spaces are treated as empty.
Datatypes other than string (typical null) are also treated as empty.
@param string $template
@return bool
|
[
"Return",
"true",
"if",
"the",
"template",
"part",
"is",
"empty",
".",
"Template",
"comments",
"from",
"debug",
"and",
"white",
"spaces",
"are",
"treated",
"as",
"empty",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Template/TemplateUtil.php#L363-L370
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Template/TemplateUtil.php
|
TemplateUtil.renderTwigTemplate
|
public function renderTwigTemplate(string $name, array $context = [])
{
$event = $this->container->get('event_dispatcher')->dispatch(
RenderTwigTemplateEvent::NAME,
new RenderTwigTemplateEvent(
$name, $context
)
);
$buffer = $this->container->get('twig')->render(
$this->getTemplate($event->getTemplate()),
$event->getContext()
);
return $buffer;
}
|
php
|
public function renderTwigTemplate(string $name, array $context = [])
{
$event = $this->container->get('event_dispatcher')->dispatch(
RenderTwigTemplateEvent::NAME,
new RenderTwigTemplateEvent(
$name, $context
)
);
$buffer = $this->container->get('twig')->render(
$this->getTemplate($event->getTemplate()),
$event->getContext()
);
return $buffer;
}
|
[
"public",
"function",
"renderTwigTemplate",
"(",
"string",
"$",
"name",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"event",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'event_dispatcher'",
")",
"->",
"dispatch",
"(",
"RenderTwigTemplateEvent",
"::",
"NAME",
",",
"new",
"RenderTwigTemplateEvent",
"(",
"$",
"name",
",",
"$",
"context",
")",
")",
";",
"$",
"buffer",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'twig'",
")",
"->",
"render",
"(",
"$",
"this",
"->",
"getTemplate",
"(",
"$",
"event",
"->",
"getTemplate",
"(",
")",
")",
",",
"$",
"event",
"->",
"getContext",
"(",
")",
")",
";",
"return",
"$",
"buffer",
";",
"}"
] |
Renders a twig template with data.
@param string $name The twig template name
@param array $context The twig template context data
@throws \Psr\Cache\InvalidArgumentException
@throws \Twig_Error_Loader
@throws \Twig_Error_Runtime
@throws \Twig_Error_Syntax
@return string
|
[
"Renders",
"a",
"twig",
"template",
"with",
"data",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Template/TemplateUtil.php#L392-L407
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Template/TemplateUtil.php
|
TemplateUtil.getBundleTemplate
|
public function getBundleTemplate(string $name, string $format = 'html.twig'): string
{
$templatePath = $name;
$bundles = $this->kernel->getBundles();
// if file from Controller::getTemplate() does not exist, search template in bundle views directory and return twig bundle path
if (\is_array($bundles) && '.twig' === substr($format, -5)) {
$pattern = $name.'.'.$format;
foreach (array_reverse($bundles) as $key => $value) {
$path = $this->kernel->locateResource("@$key");
$finder = new Finder();
$finder->in($path);
$finder->files()->name($pattern);
$twigKey = preg_replace('/Bundle$/', '', $key);
foreach ($finder as $val) {
$explodurl = explode('Resources'.\DIRECTORY_SEPARATOR.'views'.\DIRECTORY_SEPARATOR, $val->getRelativePathname());
$string = end($explodurl);
$templatePath = "@$twigKey/$string";
break 2;
}
}
}
return $templatePath;
}
|
php
|
public function getBundleTemplate(string $name, string $format = 'html.twig'): string
{
$templatePath = $name;
$bundles = $this->kernel->getBundles();
// if file from Controller::getTemplate() does not exist, search template in bundle views directory and return twig bundle path
if (\is_array($bundles) && '.twig' === substr($format, -5)) {
$pattern = $name.'.'.$format;
foreach (array_reverse($bundles) as $key => $value) {
$path = $this->kernel->locateResource("@$key");
$finder = new Finder();
$finder->in($path);
$finder->files()->name($pattern);
$twigKey = preg_replace('/Bundle$/', '', $key);
foreach ($finder as $val) {
$explodurl = explode('Resources'.\DIRECTORY_SEPARATOR.'views'.\DIRECTORY_SEPARATOR, $val->getRelativePathname());
$string = end($explodurl);
$templatePath = "@$twigKey/$string";
break 2;
}
}
}
return $templatePath;
}
|
[
"public",
"function",
"getBundleTemplate",
"(",
"string",
"$",
"name",
",",
"string",
"$",
"format",
"=",
"'html.twig'",
")",
":",
"string",
"{",
"$",
"templatePath",
"=",
"$",
"name",
";",
"$",
"bundles",
"=",
"$",
"this",
"->",
"kernel",
"->",
"getBundles",
"(",
")",
";",
"// if file from Controller::getTemplate() does not exist, search template in bundle views directory and return twig bundle path",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"bundles",
")",
"&&",
"'.twig'",
"===",
"substr",
"(",
"$",
"format",
",",
"-",
"5",
")",
")",
"{",
"$",
"pattern",
"=",
"$",
"name",
".",
"'.'",
".",
"$",
"format",
";",
"foreach",
"(",
"array_reverse",
"(",
"$",
"bundles",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"kernel",
"->",
"locateResource",
"(",
"\"@$key\"",
")",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"finder",
"->",
"in",
"(",
"$",
"path",
")",
";",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
"name",
"(",
"$",
"pattern",
")",
";",
"$",
"twigKey",
"=",
"preg_replace",
"(",
"'/Bundle$/'",
",",
"''",
",",
"$",
"key",
")",
";",
"foreach",
"(",
"$",
"finder",
"as",
"$",
"val",
")",
"{",
"$",
"explodurl",
"=",
"explode",
"(",
"'Resources'",
".",
"\\",
"DIRECTORY_SEPARATOR",
".",
"'views'",
".",
"\\",
"DIRECTORY_SEPARATOR",
",",
"$",
"val",
"->",
"getRelativePathname",
"(",
")",
")",
";",
"$",
"string",
"=",
"end",
"(",
"$",
"explodurl",
")",
";",
"$",
"templatePath",
"=",
"\"@$twigKey/$string\"",
";",
"break",
"2",
";",
"}",
"}",
"}",
"return",
"$",
"templatePath",
";",
"}"
] |
Find a particular template file within all bundles and return its path.
@param string $name The name of the template
@param string $format The file extension
@throws \InvalidArgumentException If $strFormat is unknown
@throws \RuntimeException If the template group folder is insecure
@return string The path to the template file
|
[
"Find",
"a",
"particular",
"template",
"file",
"within",
"all",
"bundles",
"and",
"return",
"its",
"path",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Template/TemplateUtil.php#L420-L447
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Form/FormUtil.php
|
FormUtil.getWidgetFromAttributes
|
public function getWidgetFromAttributes(string $name, array $data, $value = null, string $dbName = '', string $table = '', DataContainer $dc = null, string $mode = ''): ? Widget
{
if ('' === $mode) {
$mode = System::getContainer()->get('huh.utils.container')->isFrontend() ? 'FE' : 'BE';
}
if ('hidden' === $data['inputType']) {
$mode = 'FE';
}
$mode = strtoupper($mode);
$mode = \in_array($mode, ['FE', 'BE']) ? $mode : 'FE';
$class = 'FE' === $mode ? $GLOBALS['TL_FFL'][$data['inputType']] : $GLOBALS['BE_FFL'][$data['inputType']];
/** @var $widget Widget */
$widget = $this->framework->getAdapter(Widget::class);
if (empty($class) || !class_exists($class)) {
return null;
}
return new $class($widget->getAttributesFromDca($data, $name, $value, $dbName, $table, $dc));
}
|
php
|
public function getWidgetFromAttributes(string $name, array $data, $value = null, string $dbName = '', string $table = '', DataContainer $dc = null, string $mode = ''): ? Widget
{
if ('' === $mode) {
$mode = System::getContainer()->get('huh.utils.container')->isFrontend() ? 'FE' : 'BE';
}
if ('hidden' === $data['inputType']) {
$mode = 'FE';
}
$mode = strtoupper($mode);
$mode = \in_array($mode, ['FE', 'BE']) ? $mode : 'FE';
$class = 'FE' === $mode ? $GLOBALS['TL_FFL'][$data['inputType']] : $GLOBALS['BE_FFL'][$data['inputType']];
/** @var $widget Widget */
$widget = $this->framework->getAdapter(Widget::class);
if (empty($class) || !class_exists($class)) {
return null;
}
return new $class($widget->getAttributesFromDca($data, $name, $value, $dbName, $table, $dc));
}
|
[
"public",
"function",
"getWidgetFromAttributes",
"(",
"string",
"$",
"name",
",",
"array",
"$",
"data",
",",
"$",
"value",
"=",
"null",
",",
"string",
"$",
"dbName",
"=",
"''",
",",
"string",
"$",
"table",
"=",
"''",
",",
"DataContainer",
"$",
"dc",
"=",
"null",
",",
"string",
"$",
"mode",
"=",
"''",
")",
":",
"?",
"Widget",
"{",
"if",
"(",
"''",
"===",
"$",
"mode",
")",
"{",
"$",
"mode",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.container'",
")",
"->",
"isFrontend",
"(",
")",
"?",
"'FE'",
":",
"'BE'",
";",
"}",
"if",
"(",
"'hidden'",
"===",
"$",
"data",
"[",
"'inputType'",
"]",
")",
"{",
"$",
"mode",
"=",
"'FE'",
";",
"}",
"$",
"mode",
"=",
"strtoupper",
"(",
"$",
"mode",
")",
";",
"$",
"mode",
"=",
"\\",
"in_array",
"(",
"$",
"mode",
",",
"[",
"'FE'",
",",
"'BE'",
"]",
")",
"?",
"$",
"mode",
":",
"'FE'",
";",
"$",
"class",
"=",
"'FE'",
"===",
"$",
"mode",
"?",
"$",
"GLOBALS",
"[",
"'TL_FFL'",
"]",
"[",
"$",
"data",
"[",
"'inputType'",
"]",
"]",
":",
"$",
"GLOBALS",
"[",
"'BE_FFL'",
"]",
"[",
"$",
"data",
"[",
"'inputType'",
"]",
"]",
";",
"/** @var $widget Widget */",
"$",
"widget",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Widget",
"::",
"class",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"class",
")",
"||",
"!",
"class_exists",
"(",
"$",
"class",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"$",
"class",
"(",
"$",
"widget",
"->",
"getAttributesFromDca",
"(",
"$",
"data",
",",
"$",
"name",
",",
"$",
"value",
",",
"$",
"dbName",
",",
"$",
"table",
",",
"$",
"dc",
")",
")",
";",
"}"
] |
Get a new widget instance based on given attributes from a Data Container array.
@param string $name The field name in the form
@param array $data The field configuration array
@param mixed $value The field value
@param string $dbName The field name in the database
@param string $table The table name in the database
@param DataContainer|null $dc An optional DataContainer object
@param string $mode The contao mode, use FE or BE to get proper widget/form type
@return Widget|null The new widget based on given attributes
|
[
"Get",
"a",
"new",
"widget",
"instance",
"based",
"on",
"given",
"attributes",
"from",
"a",
"Data",
"Container",
"array",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Form/FormUtil.php#L60-L81
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Routing/RoutingUtil.php
|
RoutingUtil.generateBackendRoute
|
public function generateBackendRoute(array $params = [], $addToken = true, $addReferer = true)
{
if ($addToken) {
// >= contao 4.6.8 uses contao.csrf.token_manager service to validate token
if (System::getContainer()->has('contao.csrf.token_manager')) {
$params['rt'] = System::getContainer()->get('contao.csrf.token_manager')->getToken($this->token)->getValue();
} else {
$params['rt'] = System::getContainer()->get('security.csrf.token_manager')->getToken($this->token)->getValue();
}
}
if ($addReferer) {
$params['ref'] = $this->request->getCurrentRequest()->get('_contao_referer_id');
}
return $this->router->generate('contao_backend', $params);
}
|
php
|
public function generateBackendRoute(array $params = [], $addToken = true, $addReferer = true)
{
if ($addToken) {
// >= contao 4.6.8 uses contao.csrf.token_manager service to validate token
if (System::getContainer()->has('contao.csrf.token_manager')) {
$params['rt'] = System::getContainer()->get('contao.csrf.token_manager')->getToken($this->token)->getValue();
} else {
$params['rt'] = System::getContainer()->get('security.csrf.token_manager')->getToken($this->token)->getValue();
}
}
if ($addReferer) {
$params['ref'] = $this->request->getCurrentRequest()->get('_contao_referer_id');
}
return $this->router->generate('contao_backend', $params);
}
|
[
"public",
"function",
"generateBackendRoute",
"(",
"array",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"addToken",
"=",
"true",
",",
"$",
"addReferer",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"addToken",
")",
"{",
"// >= contao 4.6.8 uses contao.csrf.token_manager service to validate token",
"if",
"(",
"System",
"::",
"getContainer",
"(",
")",
"->",
"has",
"(",
"'contao.csrf.token_manager'",
")",
")",
"{",
"$",
"params",
"[",
"'rt'",
"]",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'contao.csrf.token_manager'",
")",
"->",
"getToken",
"(",
"$",
"this",
"->",
"token",
")",
"->",
"getValue",
"(",
")",
";",
"}",
"else",
"{",
"$",
"params",
"[",
"'rt'",
"]",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'security.csrf.token_manager'",
")",
"->",
"getToken",
"(",
"$",
"this",
"->",
"token",
")",
"->",
"getValue",
"(",
")",
";",
"}",
"}",
"if",
"(",
"$",
"addReferer",
")",
"{",
"$",
"params",
"[",
"'ref'",
"]",
"=",
"$",
"this",
"->",
"request",
"->",
"getCurrentRequest",
"(",
")",
"->",
"get",
"(",
"'_contao_referer_id'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"router",
"->",
"generate",
"(",
"'contao_backend'",
",",
"$",
"params",
")",
";",
"}"
] |
Generate a backend route with token and referer.
@param array $params Url-Parameters
@param bool $addToken
@param bool $addReferer
@return string The backend route url
|
[
"Generate",
"a",
"backend",
"route",
"with",
"token",
"and",
"referer",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Routing/RoutingUtil.php#L53-L69
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.loadDataContainer
|
public function loadDataContainer($table)
{
if (!$this->database->tableExists($table)) {
return;
}
if (!isset($GLOBALS['TL_DCA'][$table]) || !isset($GLOBALS['TL_DCA'][$table]['config']['treeCache']) || !\is_array($GLOBALS['TL_DCA'][$table]['config']['treeCache'])) {
return;
}
$configurations = $GLOBALS['TL_DCA'][$table]['config']['treeCache'];
foreach ($configurations as $key => $config) {
$this->addConfigToTreeCache($table, $key, $config);
}
}
|
php
|
public function loadDataContainer($table)
{
if (!$this->database->tableExists($table)) {
return;
}
if (!isset($GLOBALS['TL_DCA'][$table]) || !isset($GLOBALS['TL_DCA'][$table]['config']['treeCache']) || !\is_array($GLOBALS['TL_DCA'][$table]['config']['treeCache'])) {
return;
}
$configurations = $GLOBALS['TL_DCA'][$table]['config']['treeCache'];
foreach ($configurations as $key => $config) {
$this->addConfigToTreeCache($table, $key, $config);
}
}
|
[
"public",
"function",
"loadDataContainer",
"(",
"$",
"table",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"database",
"->",
"tableExists",
"(",
"$",
"table",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'treeCache'",
"]",
")",
"||",
"!",
"\\",
"is_array",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'treeCache'",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"configurations",
"=",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'treeCache'",
"]",
";",
"foreach",
"(",
"$",
"configurations",
"as",
"$",
"key",
"=>",
"$",
"config",
")",
"{",
"$",
"this",
"->",
"addConfigToTreeCache",
"(",
"$",
"table",
",",
"$",
"key",
",",
"$",
"config",
")",
";",
"}",
"}"
] |
Generate tree cache.
|
[
"Generate",
"tree",
"cache",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L65-L80
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.getChildRecords
|
public function getChildRecords(string $table, array $ids = [], $maxLevels = null, string $key = 'id', array $children = [], int $level = 0): array
{
if (null === ($tree = $this->getTreeCache($table, $key))) {
return $this->database->getChildRecords($ids, $table);
}
foreach ($ids as $i => $id) {
if (!isset($tree[$id]) || !\is_array($tree[$id])) {
continue;
}
$children = array_merge($children, $tree[$id]);
if (1 === $maxLevels) {
continue;
}
if ($maxLevels > 0 && $level > $maxLevels) {
return [];
}
if (!empty($nested = self::getChildRecords($table, $tree[$id], $maxLevels, $key, $children, ++$level))) {
$children = $nested;
} else {
$depth = 0;
}
}
return $children;
}
|
php
|
public function getChildRecords(string $table, array $ids = [], $maxLevels = null, string $key = 'id', array $children = [], int $level = 0): array
{
if (null === ($tree = $this->getTreeCache($table, $key))) {
return $this->database->getChildRecords($ids, $table);
}
foreach ($ids as $i => $id) {
if (!isset($tree[$id]) || !\is_array($tree[$id])) {
continue;
}
$children = array_merge($children, $tree[$id]);
if (1 === $maxLevels) {
continue;
}
if ($maxLevels > 0 && $level > $maxLevels) {
return [];
}
if (!empty($nested = self::getChildRecords($table, $tree[$id], $maxLevels, $key, $children, ++$level))) {
$children = $nested;
} else {
$depth = 0;
}
}
return $children;
}
|
[
"public",
"function",
"getChildRecords",
"(",
"string",
"$",
"table",
",",
"array",
"$",
"ids",
"=",
"[",
"]",
",",
"$",
"maxLevels",
"=",
"null",
",",
"string",
"$",
"key",
"=",
"'id'",
",",
"array",
"$",
"children",
"=",
"[",
"]",
",",
"int",
"$",
"level",
"=",
"0",
")",
":",
"array",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"tree",
"=",
"$",
"this",
"->",
"getTreeCache",
"(",
"$",
"table",
",",
"$",
"key",
")",
")",
")",
"{",
"return",
"$",
"this",
"->",
"database",
"->",
"getChildRecords",
"(",
"$",
"ids",
",",
"$",
"table",
")",
";",
"}",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"i",
"=>",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"tree",
"[",
"$",
"id",
"]",
")",
"||",
"!",
"\\",
"is_array",
"(",
"$",
"tree",
"[",
"$",
"id",
"]",
")",
")",
"{",
"continue",
";",
"}",
"$",
"children",
"=",
"array_merge",
"(",
"$",
"children",
",",
"$",
"tree",
"[",
"$",
"id",
"]",
")",
";",
"if",
"(",
"1",
"===",
"$",
"maxLevels",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"maxLevels",
">",
"0",
"&&",
"$",
"level",
">",
"$",
"maxLevels",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"nested",
"=",
"self",
"::",
"getChildRecords",
"(",
"$",
"table",
",",
"$",
"tree",
"[",
"$",
"id",
"]",
",",
"$",
"maxLevels",
",",
"$",
"key",
",",
"$",
"children",
",",
"++",
"$",
"level",
")",
")",
")",
"{",
"$",
"children",
"=",
"$",
"nested",
";",
"}",
"else",
"{",
"$",
"depth",
"=",
"0",
";",
"}",
"}",
"return",
"$",
"children",
";",
"}"
] |
Get all child records for given parent entities.
@param string $table The database table
@param array $ids The parent entity ids
@param int $maxLevels The max stop level
@param string Custom index key (default: primary key from model)
@param array $children Internal children return array
@param int $level Internal depth attribute
@return array An array containing all children for given parent entities
|
[
"Get",
"all",
"child",
"records",
"for",
"given",
"parent",
"entities",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L114-L143
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.getParentRecords
|
public function getParentRecords(string $table, int $id, $maxLevels = null, string $key = 'id', array $parents = [], int $level = 0): array
{
if (null === ($tree = $this->getTreeCache($table, $key))) {
return $this->database->getParentRecords($id, $table);
}
if (isset($tree[$id]) && 0 === $level) {
$parents[] = $id;
}
foreach ($tree as $pid => $ids) {
if (!\in_array($id, $ids)) {
continue;
}
$parents[] = $pid;
if (1 === $maxLevels) {
continue;
}
if ($maxLevels > 0 && $level > $maxLevels) {
return [];
}
if (!empty($nested = self::getParentRecords($table, $pid, $maxLevels, $key, $parents, ++$level))) {
$parents = $nested;
} else {
$level = 0;
}
}
return $parents;
}
|
php
|
public function getParentRecords(string $table, int $id, $maxLevels = null, string $key = 'id', array $parents = [], int $level = 0): array
{
if (null === ($tree = $this->getTreeCache($table, $key))) {
return $this->database->getParentRecords($id, $table);
}
if (isset($tree[$id]) && 0 === $level) {
$parents[] = $id;
}
foreach ($tree as $pid => $ids) {
if (!\in_array($id, $ids)) {
continue;
}
$parents[] = $pid;
if (1 === $maxLevels) {
continue;
}
if ($maxLevels > 0 && $level > $maxLevels) {
return [];
}
if (!empty($nested = self::getParentRecords($table, $pid, $maxLevels, $key, $parents, ++$level))) {
$parents = $nested;
} else {
$level = 0;
}
}
return $parents;
}
|
[
"public",
"function",
"getParentRecords",
"(",
"string",
"$",
"table",
",",
"int",
"$",
"id",
",",
"$",
"maxLevels",
"=",
"null",
",",
"string",
"$",
"key",
"=",
"'id'",
",",
"array",
"$",
"parents",
"=",
"[",
"]",
",",
"int",
"$",
"level",
"=",
"0",
")",
":",
"array",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"tree",
"=",
"$",
"this",
"->",
"getTreeCache",
"(",
"$",
"table",
",",
"$",
"key",
")",
")",
")",
"{",
"return",
"$",
"this",
"->",
"database",
"->",
"getParentRecords",
"(",
"$",
"id",
",",
"$",
"table",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"tree",
"[",
"$",
"id",
"]",
")",
"&&",
"0",
"===",
"$",
"level",
")",
"{",
"$",
"parents",
"[",
"]",
"=",
"$",
"id",
";",
"}",
"foreach",
"(",
"$",
"tree",
"as",
"$",
"pid",
"=>",
"$",
"ids",
")",
"{",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"id",
",",
"$",
"ids",
")",
")",
"{",
"continue",
";",
"}",
"$",
"parents",
"[",
"]",
"=",
"$",
"pid",
";",
"if",
"(",
"1",
"===",
"$",
"maxLevels",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"maxLevels",
">",
"0",
"&&",
"$",
"level",
">",
"$",
"maxLevels",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"nested",
"=",
"self",
"::",
"getParentRecords",
"(",
"$",
"table",
",",
"$",
"pid",
",",
"$",
"maxLevels",
",",
"$",
"key",
",",
"$",
"parents",
",",
"++",
"$",
"level",
")",
")",
")",
"{",
"$",
"parents",
"=",
"$",
"nested",
";",
"}",
"else",
"{",
"$",
"level",
"=",
"0",
";",
"}",
"}",
"return",
"$",
"parents",
";",
"}"
] |
Get all parent records for given child entity.
@param string $table The database table
@param int $id The current entity id
@param int $maxLevels The max stop level
@param string Custom index key (default: primary key from model)
@param array $parents Internal children return array
@param int $level Internal depth attribute
@return array An array containing all children for given parent entities
|
[
"Get",
"all",
"parent",
"records",
"for",
"given",
"child",
"entity",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L157-L190
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.getTreeCache
|
public function getTreeCache($table, $key): ?array
{
$filename = $table.'_'.$key.'.php';
if (file_exists($this->cacheDir.'/'.$filename)) {
self::$cache[$table.'_'.$key] = (include $this->cacheDir.'/'.$filename);
}
return self::$cache[$table.'_'.$key] ?? null;
}
|
php
|
public function getTreeCache($table, $key): ?array
{
$filename = $table.'_'.$key.'.php';
if (file_exists($this->cacheDir.'/'.$filename)) {
self::$cache[$table.'_'.$key] = (include $this->cacheDir.'/'.$filename);
}
return self::$cache[$table.'_'.$key] ?? null;
}
|
[
"public",
"function",
"getTreeCache",
"(",
"$",
"table",
",",
"$",
"key",
")",
":",
"?",
"array",
"{",
"$",
"filename",
"=",
"$",
"table",
".",
"'_'",
".",
"$",
"key",
".",
"'.php'",
";",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"cacheDir",
".",
"'/'",
".",
"$",
"filename",
")",
")",
"{",
"self",
"::",
"$",
"cache",
"[",
"$",
"table",
".",
"'_'",
".",
"$",
"key",
"]",
"=",
"(",
"include",
"$",
"this",
"->",
"cacheDir",
".",
"'/'",
".",
"$",
"filename",
")",
";",
"}",
"return",
"self",
"::",
"$",
"cache",
"[",
"$",
"table",
".",
"'_'",
".",
"$",
"key",
"]",
"??",
"null",
";",
"}"
] |
Get the tree cache for a given table and key.
@param string $table The database table
@param string Custom index key (default: primary key from model)
@return array|null
|
[
"Get",
"the",
"tree",
"cache",
"for",
"a",
"given",
"table",
"and",
"key",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L200-L209
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.generateCacheTree
|
public function generateCacheTree(string $table, array $ids = [], string $key = 'id', array $config = [], $return = []): array
{
foreach ($ids as $id) {
if (null === ($children = $this->modelUtil->findModelInstancesBy($table, ['pid = ?'], $id, $config['options']))) {
$return[$id] = [];
continue;
}
while ($children->next()) {
$return[$children->pid][$children->{$key}] = $children->{$key};
$return = $this->generateCacheTree($table, [$children->{$key}], $key, $config, $return);
}
}
return $return;
}
|
php
|
public function generateCacheTree(string $table, array $ids = [], string $key = 'id', array $config = [], $return = []): array
{
foreach ($ids as $id) {
if (null === ($children = $this->modelUtil->findModelInstancesBy($table, ['pid = ?'], $id, $config['options']))) {
$return[$id] = [];
continue;
}
while ($children->next()) {
$return[$children->pid][$children->{$key}] = $children->{$key};
$return = $this->generateCacheTree($table, [$children->{$key}], $key, $config, $return);
}
}
return $return;
}
|
[
"public",
"function",
"generateCacheTree",
"(",
"string",
"$",
"table",
",",
"array",
"$",
"ids",
"=",
"[",
"]",
",",
"string",
"$",
"key",
"=",
"'id'",
",",
"array",
"$",
"config",
"=",
"[",
"]",
",",
"$",
"return",
"=",
"[",
"]",
")",
":",
"array",
"{",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"id",
")",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"children",
"=",
"$",
"this",
"->",
"modelUtil",
"->",
"findModelInstancesBy",
"(",
"$",
"table",
",",
"[",
"'pid = ?'",
"]",
",",
"$",
"id",
",",
"$",
"config",
"[",
"'options'",
"]",
")",
")",
")",
"{",
"$",
"return",
"[",
"$",
"id",
"]",
"=",
"[",
"]",
";",
"continue",
";",
"}",
"while",
"(",
"$",
"children",
"->",
"next",
"(",
")",
")",
"{",
"$",
"return",
"[",
"$",
"children",
"->",
"pid",
"]",
"[",
"$",
"children",
"->",
"{",
"$",
"key",
"}",
"]",
"=",
"$",
"children",
"->",
"{",
"$",
"key",
"}",
";",
"$",
"return",
"=",
"$",
"this",
"->",
"generateCacheTree",
"(",
"$",
"table",
",",
"[",
"$",
"children",
"->",
"{",
"$",
"key",
"}",
"]",
",",
"$",
"key",
",",
"$",
"config",
",",
"$",
"return",
")",
";",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] |
Generate the flat cache tree.
@param string $table The database table
@param string $key Custom index key (default: primary key from model)
@param array $ids Root identifiers (parent ids)
@param array $config Tree config
@param array $return Internal return array
@return array The flat cache tree
|
[
"Generate",
"the",
"flat",
"cache",
"tree",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L222-L238
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.generateAllCacheTree
|
public function generateAllCacheTree($cacheDir)
{
$this->cacheDir = $cacheDir;
$tables = $this->database->listTables();
foreach ($tables as $table) {
// trigger loadDataContainer TL_HOOK
System::getContainer()->get('huh.utils.dca')->loadDc($table);
}
}
|
php
|
public function generateAllCacheTree($cacheDir)
{
$this->cacheDir = $cacheDir;
$tables = $this->database->listTables();
foreach ($tables as $table) {
// trigger loadDataContainer TL_HOOK
System::getContainer()->get('huh.utils.dca')->loadDc($table);
}
}
|
[
"public",
"function",
"generateAllCacheTree",
"(",
"$",
"cacheDir",
")",
"{",
"$",
"this",
"->",
"cacheDir",
"=",
"$",
"cacheDir",
";",
"$",
"tables",
"=",
"$",
"this",
"->",
"database",
"->",
"listTables",
"(",
")",
";",
"foreach",
"(",
"$",
"tables",
"as",
"$",
"table",
")",
"{",
"// trigger loadDataContainer TL_HOOK",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.dca'",
")",
"->",
"loadDc",
"(",
"$",
"table",
")",
";",
"}",
"}"
] |
Generate all cache trees.
@param $cacheDir
|
[
"Generate",
"all",
"cache",
"trees",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L245-L255
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/DatabaseTreeCache.php
|
DatabaseTreeCache.registerDcaToCacheTree
|
public function registerDcaToCacheTree(string $table, array $columns = [], array $values = [], array $options = [], string $key = 'id')
{
System::getContainer()->get('huh.utils.dca')->loadDc($table);
if (!isset($GLOBALS['TL_DCA'][$table])) {
return false;
}
$GLOBALS['TL_DCA'][$table]['config']['treeCache'][$key] = [
'columns' => $columns,
'values' => $values,
'options' => $options,
'key' => $key,
];
$GLOBALS['TL_DCA'][$table]['config']['ondelete_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
$GLOBALS['TL_DCA'][$table]['config']['oncut_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
$GLOBALS['TL_DCA'][$table]['config']['onsubmit_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
$GLOBALS['TL_DCA'][$table]['config']['onrestore_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
return true;
}
|
php
|
public function registerDcaToCacheTree(string $table, array $columns = [], array $values = [], array $options = [], string $key = 'id')
{
System::getContainer()->get('huh.utils.dca')->loadDc($table);
if (!isset($GLOBALS['TL_DCA'][$table])) {
return false;
}
$GLOBALS['TL_DCA'][$table]['config']['treeCache'][$key] = [
'columns' => $columns,
'values' => $values,
'options' => $options,
'key' => $key,
];
$GLOBALS['TL_DCA'][$table]['config']['ondelete_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
$GLOBALS['TL_DCA'][$table]['config']['oncut_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
$GLOBALS['TL_DCA'][$table]['config']['onsubmit_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
$GLOBALS['TL_DCA'][$table]['config']['onrestore_callback']['huh.utils.cache.database_tree'] = ['huh.utils.cache.database_tree', 'purgeCacheTree'];
return true;
}
|
[
"public",
"function",
"registerDcaToCacheTree",
"(",
"string",
"$",
"table",
",",
"array",
"$",
"columns",
"=",
"[",
"]",
",",
"array",
"$",
"values",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"string",
"$",
"key",
"=",
"'id'",
")",
"{",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.dca'",
")",
"->",
"loadDc",
"(",
"$",
"table",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'treeCache'",
"]",
"[",
"$",
"key",
"]",
"=",
"[",
"'columns'",
"=>",
"$",
"columns",
",",
"'values'",
"=>",
"$",
"values",
",",
"'options'",
"=>",
"$",
"options",
",",
"'key'",
"=>",
"$",
"key",
",",
"]",
";",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'ondelete_callback'",
"]",
"[",
"'huh.utils.cache.database_tree'",
"]",
"=",
"[",
"'huh.utils.cache.database_tree'",
",",
"'purgeCacheTree'",
"]",
";",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'oncut_callback'",
"]",
"[",
"'huh.utils.cache.database_tree'",
"]",
"=",
"[",
"'huh.utils.cache.database_tree'",
",",
"'purgeCacheTree'",
"]",
";",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'onsubmit_callback'",
"]",
"[",
"'huh.utils.cache.database_tree'",
"]",
"=",
"[",
"'huh.utils.cache.database_tree'",
",",
"'purgeCacheTree'",
"]",
";",
"$",
"GLOBALS",
"[",
"'TL_DCA'",
"]",
"[",
"$",
"table",
"]",
"[",
"'config'",
"]",
"[",
"'onrestore_callback'",
"]",
"[",
"'huh.utils.cache.database_tree'",
"]",
"=",
"[",
"'huh.utils.cache.database_tree'",
",",
"'purgeCacheTree'",
"]",
";",
"return",
"true",
";",
"}"
] |
Register a dca to the tree cache.
@param string $table (The dca table)
@param array $columns Parent sql filter columns (e.g. `tl_page.type`)
@param array $values Parent sql filter values (e.g. `root` for `tl_page.type`)
@param array $options SQL Options for sorting
@param string Custom index key (default: primary key from model)
@return bool Acknowledge state if register succeeded
|
[
"Register",
"a",
"dca",
"to",
"the",
"tree",
"cache",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/DatabaseTreeCache.php#L268-L289
|
train
|
heimrichhannot/contao-utils-bundle
|
src/String/StringUtil.php
|
StringUtil.convertToInlineCss
|
public function convertToInlineCss(string $text, string $cssText = null)
{
// apply the css inliner
$objCssInliner = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles();
return $objCssInliner->convert($text, $cssText);
}
|
php
|
public function convertToInlineCss(string $text, string $cssText = null)
{
// apply the css inliner
$objCssInliner = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles();
return $objCssInliner->convert($text, $cssText);
}
|
[
"public",
"function",
"convertToInlineCss",
"(",
"string",
"$",
"text",
",",
"string",
"$",
"cssText",
"=",
"null",
")",
"{",
"// apply the css inliner",
"$",
"objCssInliner",
"=",
"new",
"\\",
"TijsVerkoyen",
"\\",
"CssToInlineStyles",
"\\",
"CssToInlineStyles",
"(",
")",
";",
"return",
"$",
"objCssInliner",
"->",
"convert",
"(",
"$",
"text",
",",
"$",
"cssText",
")",
";",
"}"
] |
Convert css into inline styles.
@param string $text
@param array $cssText the css as text (no paths allowed atm)
@return string
|
[
"Convert",
"css",
"into",
"inline",
"styles",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/String/StringUtil.php#L317-L323
|
train
|
heimrichhannot/contao-utils-bundle
|
src/String/StringUtil.php
|
StringUtil.html2Text
|
public function html2Text(string $html, array $options = [])
{
$html = str_replace("\n", '', $html); // remove white spaces from html
$html = str_replace('</p>', '<br /></p>', $html); // interpret paragrah as block element
$html = str_replace('</div>', '<br /></div>', $html); // interpret div as block element
return \Soundasleep\Html2Text::convert($html, $options);
}
|
php
|
public function html2Text(string $html, array $options = [])
{
$html = str_replace("\n", '', $html); // remove white spaces from html
$html = str_replace('</p>', '<br /></p>', $html); // interpret paragrah as block element
$html = str_replace('</div>', '<br /></div>', $html); // interpret div as block element
return \Soundasleep\Html2Text::convert($html, $options);
}
|
[
"public",
"function",
"html2Text",
"(",
"string",
"$",
"html",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"html",
"=",
"str_replace",
"(",
"\"\\n\"",
",",
"''",
",",
"$",
"html",
")",
";",
"// remove white spaces from html",
"$",
"html",
"=",
"str_replace",
"(",
"'</p>'",
",",
"'<br /></p>'",
",",
"$",
"html",
")",
";",
"// interpret paragrah as block element",
"$",
"html",
"=",
"str_replace",
"(",
"'</div>'",
",",
"'<br /></div>'",
",",
"$",
"html",
")",
";",
"// interpret div as block element",
"return",
"\\",
"Soundasleep",
"\\",
"Html2Text",
"::",
"convert",
"(",
"$",
"html",
",",
"$",
"options",
")",
";",
"}"
] |
Converts html to text.
@param string $html
@param array $options
@throws \Soundasleep\Html2TextException
@return string
|
[
"Converts",
"html",
"to",
"text",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/String/StringUtil.php#L335-L342
|
train
|
heimrichhannot/contao-utils-bundle
|
src/String/StringUtil.php
|
StringUtil.ensureLineBreaks
|
public function ensureLineBreaks(string $buffer, string $language = 'en'): string
{
switch ($language) {
case 'cs':
// in czech language, one-syllable words should not stand alone at the end (use instead of whitespace)
$buffer = preg_replace('/(\s\w{1})(\s)/', '$1 ', $buffer);
break;
}
return $buffer;
}
|
php
|
public function ensureLineBreaks(string $buffer, string $language = 'en'): string
{
switch ($language) {
case 'cs':
// in czech language, one-syllable words should not stand alone at the end (use instead of whitespace)
$buffer = preg_replace('/(\s\w{1})(\s)/', '$1 ', $buffer);
break;
}
return $buffer;
}
|
[
"public",
"function",
"ensureLineBreaks",
"(",
"string",
"$",
"buffer",
",",
"string",
"$",
"language",
"=",
"'en'",
")",
":",
"string",
"{",
"switch",
"(",
"$",
"language",
")",
"{",
"case",
"'cs'",
":",
"// in czech language, one-syllable words should not stand alone at the end (use instead of whitespace)",
"$",
"buffer",
"=",
"preg_replace",
"(",
"'/(\\s\\w{1})(\\s)/'",
",",
"'$1 '",
",",
"$",
"buffer",
")",
";",
"break",
";",
"}",
"return",
"$",
"buffer",
";",
"}"
] |
Ensure line breaks for several languages.
@param string $buffer
@param string $language
@return string
|
[
"Ensure",
"line",
"breaks",
"for",
"several",
"languages",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/String/StringUtil.php#L365-L376
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Request/CurlRequestUtil.php
|
CurlRequestUtil.request
|
public function request(string $url, array $requestHeaders = [], $returnResponseHeaders = false)
{
$handle = $this->createCurlHandle($url);
if ($proxy = Config::get('hpProxy')) {
$handle->setOption(CURLOPT_PROXY, $proxy);
}
if (!empty($requestHeaders)) {
$handle->setOption(CURLOPT_HTTPHEADER, $this->prepareHeaders($requestHeaders));
}
if ($returnResponseHeaders) {
$handle->setOption(CURLOPT_HEADER, true);
}
$response = $handle->execute();
$statusCode = $handle->getInfo(CURLINFO_HTTP_CODE);
$handle->close();
if ($response && $returnResponseHeaders) {
return $this->splitResponseHeaderAndBody($response, $statusCode);
}
return $response;
}
|
php
|
public function request(string $url, array $requestHeaders = [], $returnResponseHeaders = false)
{
$handle = $this->createCurlHandle($url);
if ($proxy = Config::get('hpProxy')) {
$handle->setOption(CURLOPT_PROXY, $proxy);
}
if (!empty($requestHeaders)) {
$handle->setOption(CURLOPT_HTTPHEADER, $this->prepareHeaders($requestHeaders));
}
if ($returnResponseHeaders) {
$handle->setOption(CURLOPT_HEADER, true);
}
$response = $handle->execute();
$statusCode = $handle->getInfo(CURLINFO_HTTP_CODE);
$handle->close();
if ($response && $returnResponseHeaders) {
return $this->splitResponseHeaderAndBody($response, $statusCode);
}
return $response;
}
|
[
"public",
"function",
"request",
"(",
"string",
"$",
"url",
",",
"array",
"$",
"requestHeaders",
"=",
"[",
"]",
",",
"$",
"returnResponseHeaders",
"=",
"false",
")",
"{",
"$",
"handle",
"=",
"$",
"this",
"->",
"createCurlHandle",
"(",
"$",
"url",
")",
";",
"if",
"(",
"$",
"proxy",
"=",
"Config",
"::",
"get",
"(",
"'hpProxy'",
")",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_PROXY",
",",
"$",
"proxy",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"requestHeaders",
")",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_HTTPHEADER",
",",
"$",
"this",
"->",
"prepareHeaders",
"(",
"$",
"requestHeaders",
")",
")",
";",
"}",
"if",
"(",
"$",
"returnResponseHeaders",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_HEADER",
",",
"true",
")",
";",
"}",
"$",
"response",
"=",
"$",
"handle",
"->",
"execute",
"(",
")",
";",
"$",
"statusCode",
"=",
"$",
"handle",
"->",
"getInfo",
"(",
"CURLINFO_HTTP_CODE",
")",
";",
"$",
"handle",
"->",
"close",
"(",
")",
";",
"if",
"(",
"$",
"response",
"&&",
"$",
"returnResponseHeaders",
")",
"{",
"return",
"$",
"this",
"->",
"splitResponseHeaderAndBody",
"(",
"$",
"response",
",",
"$",
"statusCode",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] |
Executes a curl request while taking.
@param $url
@param array $requestHeaders
@param bool $returnResponseHeaders
@return array|mixed
|
[
"Executes",
"a",
"curl",
"request",
"while",
"taking",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Request/CurlRequestUtil.php#L90-L115
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Request/CurlRequestUtil.php
|
CurlRequestUtil.postRequest
|
public function postRequest(string $url, array $requestHeaders = [], array $postFields = [], bool $returnResponseHeaders = false)
{
$handle = $this->createCurlHandle($url);
if (Config::get('hpProxy')) {
$handle->setOption(CURLOPT_PROXY, Config::get('hpProxy'));
}
if ($returnResponseHeaders) {
$handle->setOption(CURLOPT_HEADER, true);
}
if (!empty($requestHeaders)) {
$handle->setOption(CURLOPT_HTTPHEADER, $this->prepareHeaders($requestHeaders));
}
if (!empty($postFields)) {
$handle->setOption(CURLOPT_POST, true);
$handle->setOption(CURLOPT_POSTFIELDS, http_build_query($postFields));
}
$response = $handle->execute();
$statusCode = $handle->getInfo(CURLINFO_HTTP_CODE);
$handle->close();
if ($response && $returnResponseHeaders) {
return $this->splitResponseHeaderAndBody($response, $statusCode);
}
return $response;
}
|
php
|
public function postRequest(string $url, array $requestHeaders = [], array $postFields = [], bool $returnResponseHeaders = false)
{
$handle = $this->createCurlHandle($url);
if (Config::get('hpProxy')) {
$handle->setOption(CURLOPT_PROXY, Config::get('hpProxy'));
}
if ($returnResponseHeaders) {
$handle->setOption(CURLOPT_HEADER, true);
}
if (!empty($requestHeaders)) {
$handle->setOption(CURLOPT_HTTPHEADER, $this->prepareHeaders($requestHeaders));
}
if (!empty($postFields)) {
$handle->setOption(CURLOPT_POST, true);
$handle->setOption(CURLOPT_POSTFIELDS, http_build_query($postFields));
}
$response = $handle->execute();
$statusCode = $handle->getInfo(CURLINFO_HTTP_CODE);
$handle->close();
if ($response && $returnResponseHeaders) {
return $this->splitResponseHeaderAndBody($response, $statusCode);
}
return $response;
}
|
[
"public",
"function",
"postRequest",
"(",
"string",
"$",
"url",
",",
"array",
"$",
"requestHeaders",
"=",
"[",
"]",
",",
"array",
"$",
"postFields",
"=",
"[",
"]",
",",
"bool",
"$",
"returnResponseHeaders",
"=",
"false",
")",
"{",
"$",
"handle",
"=",
"$",
"this",
"->",
"createCurlHandle",
"(",
"$",
"url",
")",
";",
"if",
"(",
"Config",
"::",
"get",
"(",
"'hpProxy'",
")",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_PROXY",
",",
"Config",
"::",
"get",
"(",
"'hpProxy'",
")",
")",
";",
"}",
"if",
"(",
"$",
"returnResponseHeaders",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_HEADER",
",",
"true",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"requestHeaders",
")",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_HTTPHEADER",
",",
"$",
"this",
"->",
"prepareHeaders",
"(",
"$",
"requestHeaders",
")",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"postFields",
")",
")",
"{",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_POST",
",",
"true",
")",
";",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_POSTFIELDS",
",",
"http_build_query",
"(",
"$",
"postFields",
")",
")",
";",
"}",
"$",
"response",
"=",
"$",
"handle",
"->",
"execute",
"(",
")",
";",
"$",
"statusCode",
"=",
"$",
"handle",
"->",
"getInfo",
"(",
"CURLINFO_HTTP_CODE",
")",
";",
"$",
"handle",
"->",
"close",
"(",
")",
";",
"if",
"(",
"$",
"response",
"&&",
"$",
"returnResponseHeaders",
")",
"{",
"return",
"$",
"this",
"->",
"splitResponseHeaderAndBody",
"(",
"$",
"response",
",",
"$",
"statusCode",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] |
Create a curl post request.
@param string $url
@param array $requestHeaders
@param array $postFields
@param bool $returnResponseHeaders
@return array|mixed
|
[
"Create",
"a",
"curl",
"post",
"request",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Request/CurlRequestUtil.php#L127-L158
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Request/CurlRequestUtil.php
|
CurlRequestUtil.recursiveGetRequest
|
public function recursiveGetRequest(int $maxRecursionCount, callable $callback, string $url, array $requestHeaders = [], bool $returnResponseHeaders = false)
{
$i = 0;
$terminate = false;
$result = null;
while ($i++ < $maxRecursionCount && !$terminate) {
$result = $this->request($url, $requestHeaders, $returnResponseHeaders);
$terminate = $callback($result, $url, $requestHeaders, $returnResponseHeaders, $maxRecursionCount, $i);
}
return $result;
}
|
php
|
public function recursiveGetRequest(int $maxRecursionCount, callable $callback, string $url, array $requestHeaders = [], bool $returnResponseHeaders = false)
{
$i = 0;
$terminate = false;
$result = null;
while ($i++ < $maxRecursionCount && !$terminate) {
$result = $this->request($url, $requestHeaders, $returnResponseHeaders);
$terminate = $callback($result, $url, $requestHeaders, $returnResponseHeaders, $maxRecursionCount, $i);
}
return $result;
}
|
[
"public",
"function",
"recursiveGetRequest",
"(",
"int",
"$",
"maxRecursionCount",
",",
"callable",
"$",
"callback",
",",
"string",
"$",
"url",
",",
"array",
"$",
"requestHeaders",
"=",
"[",
"]",
",",
"bool",
"$",
"returnResponseHeaders",
"=",
"false",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"terminate",
"=",
"false",
";",
"$",
"result",
"=",
"null",
";",
"while",
"(",
"$",
"i",
"++",
"<",
"$",
"maxRecursionCount",
"&&",
"!",
"$",
"terminate",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"request",
"(",
"$",
"url",
",",
"$",
"requestHeaders",
",",
"$",
"returnResponseHeaders",
")",
";",
"$",
"terminate",
"=",
"$",
"callback",
"(",
"$",
"result",
",",
"$",
"url",
",",
"$",
"requestHeaders",
",",
"$",
"returnResponseHeaders",
",",
"$",
"maxRecursionCount",
",",
"$",
"i",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
Recursivly send get request and terminates if termination condition is given or max request count is reached.
@param int $maxRecursionCount
@param callable $callback Termination condition callback. Return true to terminate.
@param string $url
@param array $requestHeaders
@param bool $returnResponseHeaders
@return array|mixed|null
|
[
"Recursivly",
"send",
"get",
"request",
"and",
"terminates",
"if",
"termination",
"condition",
"is",
"given",
"or",
"max",
"request",
"count",
"is",
"reached",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Request/CurlRequestUtil.php#L171-L184
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Request/CurlRequestUtil.php
|
CurlRequestUtil.recursivePostRequest
|
public function recursivePostRequest(int $maxRecursionCount, callable $callback, string $url, array $requestHeaders = [], array $post = [], bool $returnResponseHeaders = false)
{
$i = 0;
$terminate = false;
$result = null;
while ($i++ < $maxRecursionCount && !$terminate) {
$result = $this->postRequest($url, $requestHeaders, $post, $returnResponseHeaders);
$terminate = $callback($result, $url, $requestHeaders, $post, $returnResponseHeaders, $maxRecursionCount, $i);
}
return $result;
}
|
php
|
public function recursivePostRequest(int $maxRecursionCount, callable $callback, string $url, array $requestHeaders = [], array $post = [], bool $returnResponseHeaders = false)
{
$i = 0;
$terminate = false;
$result = null;
while ($i++ < $maxRecursionCount && !$terminate) {
$result = $this->postRequest($url, $requestHeaders, $post, $returnResponseHeaders);
$terminate = $callback($result, $url, $requestHeaders, $post, $returnResponseHeaders, $maxRecursionCount, $i);
}
return $result;
}
|
[
"public",
"function",
"recursivePostRequest",
"(",
"int",
"$",
"maxRecursionCount",
",",
"callable",
"$",
"callback",
",",
"string",
"$",
"url",
",",
"array",
"$",
"requestHeaders",
"=",
"[",
"]",
",",
"array",
"$",
"post",
"=",
"[",
"]",
",",
"bool",
"$",
"returnResponseHeaders",
"=",
"false",
")",
"{",
"$",
"i",
"=",
"0",
";",
"$",
"terminate",
"=",
"false",
";",
"$",
"result",
"=",
"null",
";",
"while",
"(",
"$",
"i",
"++",
"<",
"$",
"maxRecursionCount",
"&&",
"!",
"$",
"terminate",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"postRequest",
"(",
"$",
"url",
",",
"$",
"requestHeaders",
",",
"$",
"post",
",",
"$",
"returnResponseHeaders",
")",
";",
"$",
"terminate",
"=",
"$",
"callback",
"(",
"$",
"result",
",",
"$",
"url",
",",
"$",
"requestHeaders",
",",
"$",
"post",
",",
"$",
"returnResponseHeaders",
",",
"$",
"maxRecursionCount",
",",
"$",
"i",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
Recursivly send post request and terminates if termination condition is given or max request count is reached.
@param int $maxRecursionCount
@param callable $callback
@param string $url
@param array $requestHeaders
@param array $post
@param bool $returnResponseHeaders
@return array|mixed|null
|
[
"Recursivly",
"send",
"post",
"request",
"and",
"terminates",
"if",
"termination",
"condition",
"is",
"given",
"or",
"max",
"request",
"count",
"is",
"reached",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Request/CurlRequestUtil.php#L198-L211
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Request/CurlRequestUtil.php
|
CurlRequestUtil.createCurlHandle
|
public function createCurlHandle($url)
{
$handle = $this->handle ?: new CurlRequest();
$handle->init($url);
$handle->setOption(CURLOPT_RETURNTRANSFER, true);
$handle->setOption(CURLOPT_TIMEOUT, 10);
return $handle;
}
|
php
|
public function createCurlHandle($url)
{
$handle = $this->handle ?: new CurlRequest();
$handle->init($url);
$handle->setOption(CURLOPT_RETURNTRANSFER, true);
$handle->setOption(CURLOPT_TIMEOUT, 10);
return $handle;
}
|
[
"public",
"function",
"createCurlHandle",
"(",
"$",
"url",
")",
"{",
"$",
"handle",
"=",
"$",
"this",
"->",
"handle",
"?",
":",
"new",
"CurlRequest",
"(",
")",
";",
"$",
"handle",
"->",
"init",
"(",
"$",
"url",
")",
";",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_RETURNTRANSFER",
",",
"true",
")",
";",
"$",
"handle",
"->",
"setOption",
"(",
"CURLOPT_TIMEOUT",
",",
"10",
")",
";",
"return",
"$",
"handle",
";",
"}"
] |
Create the curl handle.
@param $url
@return CurlRequest
|
[
"Create",
"the",
"curl",
"handle",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Request/CurlRequestUtil.php#L285-L293
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Request/CurlRequestUtil.php
|
CurlRequestUtil.prepareHeaders
|
protected function prepareHeaders(array $headers)
{
$preparedHeaders = [];
foreach ($headers as $strName => $varValue) {
$preparedHeaders[] = $strName.': '.$varValue;
}
return $preparedHeaders;
}
|
php
|
protected function prepareHeaders(array $headers)
{
$preparedHeaders = [];
foreach ($headers as $strName => $varValue) {
$preparedHeaders[] = $strName.': '.$varValue;
}
return $preparedHeaders;
}
|
[
"protected",
"function",
"prepareHeaders",
"(",
"array",
"$",
"headers",
")",
"{",
"$",
"preparedHeaders",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"strName",
"=>",
"$",
"varValue",
")",
"{",
"$",
"preparedHeaders",
"[",
"]",
"=",
"$",
"strName",
".",
"': '",
".",
"$",
"varValue",
";",
"}",
"return",
"$",
"preparedHeaders",
";",
"}"
] |
Prepare headers for curl handle.
@param array $headers
@return array
|
[
"Prepare",
"headers",
"for",
"curl",
"handle",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Request/CurlRequestUtil.php#L302-L311
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Image/ImageUtil.php
|
ImageUtil.getPixelValue
|
public function getPixelValue(string $size)
{
$value = preg_replace('/[^0-9.-]+/', '', $size);
$unit = preg_replace('/[^acehimnprtvwx%]/', '', $size);
// Convert 16px = 1em = 2ex = 12pt = 1pc = 1/6in = 2.54/6cm = 25.4/6mm = 100%
switch ($unit) {
case '':
case 'px':
return (int) round($value);
break;
case 'em':
return (int) round($value * 16);
break;
case 'ex':
return (int) round($value * 16 / 2);
break;
case 'pt':
return (int) round($value * 16 / 12);
break;
case 'pc':
return (int) round($value * 16);
break;
case 'in':
return (int) round($value * 16 * 6);
break;
case 'cm':
return (int) round($value * 16 / (2.54 / 6));
break;
case 'mm':
return (int) round($value * 16 / (25.4 / 6));
break;
case '%':
return (int) round($value * 16 / 100);
break;
}
return 0;
}
|
php
|
public function getPixelValue(string $size)
{
$value = preg_replace('/[^0-9.-]+/', '', $size);
$unit = preg_replace('/[^acehimnprtvwx%]/', '', $size);
// Convert 16px = 1em = 2ex = 12pt = 1pc = 1/6in = 2.54/6cm = 25.4/6mm = 100%
switch ($unit) {
case '':
case 'px':
return (int) round($value);
break;
case 'em':
return (int) round($value * 16);
break;
case 'ex':
return (int) round($value * 16 / 2);
break;
case 'pt':
return (int) round($value * 16 / 12);
break;
case 'pc':
return (int) round($value * 16);
break;
case 'in':
return (int) round($value * 16 * 6);
break;
case 'cm':
return (int) round($value * 16 / (2.54 / 6));
break;
case 'mm':
return (int) round($value * 16 / (25.4 / 6));
break;
case '%':
return (int) round($value * 16 / 100);
break;
}
return 0;
}
|
[
"public",
"function",
"getPixelValue",
"(",
"string",
"$",
"size",
")",
"{",
"$",
"value",
"=",
"preg_replace",
"(",
"'/[^0-9.-]+/'",
",",
"''",
",",
"$",
"size",
")",
";",
"$",
"unit",
"=",
"preg_replace",
"(",
"'/[^acehimnprtvwx%]/'",
",",
"''",
",",
"$",
"size",
")",
";",
"// Convert 16px = 1em = 2ex = 12pt = 1pc = 1/6in = 2.54/6cm = 25.4/6mm = 100%",
"switch",
"(",
"$",
"unit",
")",
"{",
"case",
"''",
":",
"case",
"'px'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
")",
";",
"break",
";",
"case",
"'em'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
")",
";",
"break",
";",
"case",
"'ex'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
"/",
"2",
")",
";",
"break",
";",
"case",
"'pt'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
"/",
"12",
")",
";",
"break",
";",
"case",
"'pc'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
")",
";",
"break",
";",
"case",
"'in'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
"*",
"6",
")",
";",
"break",
";",
"case",
"'cm'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
"/",
"(",
"2.54",
"/",
"6",
")",
")",
";",
"break",
";",
"case",
"'mm'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
"/",
"(",
"25.4",
"/",
"6",
")",
")",
";",
"break",
";",
"case",
"'%'",
":",
"return",
"(",
"int",
")",
"round",
"(",
"$",
"value",
"*",
"16",
"/",
"100",
")",
";",
"break",
";",
"}",
"return",
"0",
";",
"}"
] |
Convert sizes like 2em, 10cm or 12pt to pixels.
@param string $size The size string
@return int The pixel value
|
[
"Convert",
"sizes",
"like",
"2em",
"10cm",
"or",
"12pt",
"to",
"pixels",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Image/ImageUtil.php#L302-L357
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Url/UrlUtil.php
|
UrlUtil.isNewVisitor
|
public function isNewVisitor(): bool
{
$referer = System::getContainer()->get('request_stack')->getCurrentRequest()->headers->get('referer');
$schemeAndHttpHost = System::getContainer()->get('request_stack')->getCurrentRequest()->getSchemeAndHttpHost();
return null === $referer || false === preg_match('$^'.$schemeAndHttpHost.'$i', $referer);
}
|
php
|
public function isNewVisitor(): bool
{
$referer = System::getContainer()->get('request_stack')->getCurrentRequest()->headers->get('referer');
$schemeAndHttpHost = System::getContainer()->get('request_stack')->getCurrentRequest()->getSchemeAndHttpHost();
return null === $referer || false === preg_match('$^'.$schemeAndHttpHost.'$i', $referer);
}
|
[
"public",
"function",
"isNewVisitor",
"(",
")",
":",
"bool",
"{",
"$",
"referer",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'request_stack'",
")",
"->",
"getCurrentRequest",
"(",
")",
"->",
"headers",
"->",
"get",
"(",
"'referer'",
")",
";",
"$",
"schemeAndHttpHost",
"=",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'request_stack'",
")",
"->",
"getCurrentRequest",
"(",
")",
"->",
"getSchemeAndHttpHost",
"(",
")",
";",
"return",
"null",
"===",
"$",
"referer",
"||",
"false",
"===",
"preg_match",
"(",
"'$^'",
".",
"$",
"schemeAndHttpHost",
".",
"'$i'",
",",
"$",
"referer",
")",
";",
"}"
] |
Detect if user already visited our domain before.
@return bool
|
[
"Detect",
"if",
"user",
"already",
"visited",
"our",
"domain",
"before",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Url/UrlUtil.php#L36-L42
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Url/UrlUtil.php
|
UrlUtil.getCurrentUrl
|
public function getCurrentUrl(array $options)
{
$url = Environment::get('url');
if (isset($options['skipParams']) && $options['skipParams']) {
$url .= parse_url(Environment::get('uri'), PHP_URL_PATH);
} else {
$url .= Environment::get('requestUri');
}
return $url;
}
|
php
|
public function getCurrentUrl(array $options)
{
$url = Environment::get('url');
if (isset($options['skipParams']) && $options['skipParams']) {
$url .= parse_url(Environment::get('uri'), PHP_URL_PATH);
} else {
$url .= Environment::get('requestUri');
}
return $url;
}
|
[
"public",
"function",
"getCurrentUrl",
"(",
"array",
"$",
"options",
")",
"{",
"$",
"url",
"=",
"Environment",
"::",
"get",
"(",
"'url'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'skipParams'",
"]",
")",
"&&",
"$",
"options",
"[",
"'skipParams'",
"]",
")",
"{",
"$",
"url",
".=",
"parse_url",
"(",
"Environment",
"::",
"get",
"(",
"'uri'",
")",
",",
"PHP_URL_PATH",
")",
";",
"}",
"else",
"{",
"$",
"url",
".=",
"Environment",
"::",
"get",
"(",
"'requestUri'",
")",
";",
"}",
"return",
"$",
"url",
";",
"}"
] |
Return the current url with requestUri.
Options:
* skipParams: boolean
@param array $options
@return string
|
[
"Return",
"the",
"current",
"url",
"with",
"requestUri",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Url/UrlUtil.php#L55-L66
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Url/UrlUtil.php
|
UrlUtil.addQueryString
|
public function addQueryString($query, $url = null)
{
$queryString = '';
$url = static::prepareUrl($url);
$query = trim(ampersand($query, false), '&');
$explodedUrl = explode('?', $url, 2);
if (2 === \count($explodedUrl)) {
list($script, $queryString) = $explodedUrl;
} else {
list($script) = $explodedUrl;
}
parse_str($queryString, $queries);
$queries = array_filter($queries);
unset($queries['language']);
$href = '';
if (!empty($queries)) {
parse_str($query, $new);
$href = '?'.http_build_query(array_merge($queries, $new), '', '&');
} elseif (!empty($query)) {
$href = '?'.$query;
}
return $script.$href;
}
|
php
|
public function addQueryString($query, $url = null)
{
$queryString = '';
$url = static::prepareUrl($url);
$query = trim(ampersand($query, false), '&');
$explodedUrl = explode('?', $url, 2);
if (2 === \count($explodedUrl)) {
list($script, $queryString) = $explodedUrl;
} else {
list($script) = $explodedUrl;
}
parse_str($queryString, $queries);
$queries = array_filter($queries);
unset($queries['language']);
$href = '';
if (!empty($queries)) {
parse_str($query, $new);
$href = '?'.http_build_query(array_merge($queries, $new), '', '&');
} elseif (!empty($query)) {
$href = '?'.$query;
}
return $script.$href;
}
|
[
"public",
"function",
"addQueryString",
"(",
"$",
"query",
",",
"$",
"url",
"=",
"null",
")",
"{",
"$",
"queryString",
"=",
"''",
";",
"$",
"url",
"=",
"static",
"::",
"prepareUrl",
"(",
"$",
"url",
")",
";",
"$",
"query",
"=",
"trim",
"(",
"ampersand",
"(",
"$",
"query",
",",
"false",
")",
",",
"'&'",
")",
";",
"$",
"explodedUrl",
"=",
"explode",
"(",
"'?'",
",",
"$",
"url",
",",
"2",
")",
";",
"if",
"(",
"2",
"===",
"\\",
"count",
"(",
"$",
"explodedUrl",
")",
")",
"{",
"list",
"(",
"$",
"script",
",",
"$",
"queryString",
")",
"=",
"$",
"explodedUrl",
";",
"}",
"else",
"{",
"list",
"(",
"$",
"script",
")",
"=",
"$",
"explodedUrl",
";",
"}",
"parse_str",
"(",
"$",
"queryString",
",",
"$",
"queries",
")",
";",
"$",
"queries",
"=",
"array_filter",
"(",
"$",
"queries",
")",
";",
"unset",
"(",
"$",
"queries",
"[",
"'language'",
"]",
")",
";",
"$",
"href",
"=",
"''",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"queries",
")",
")",
"{",
"parse_str",
"(",
"$",
"query",
",",
"$",
"new",
")",
";",
"$",
"href",
"=",
"'?'",
".",
"http_build_query",
"(",
"array_merge",
"(",
"$",
"queries",
",",
"$",
"new",
")",
",",
"''",
",",
"'&'",
")",
";",
"}",
"elseif",
"(",
"!",
"empty",
"(",
"$",
"query",
")",
")",
"{",
"$",
"href",
"=",
"'?'",
".",
"$",
"query",
";",
"}",
"return",
"$",
"script",
".",
"$",
"href",
";",
"}"
] |
Add a query string to the given URI string or page ID.
@param string $query
@param mixed $url
@throws \InvalidArgumentException
@return string
|
[
"Add",
"a",
"query",
"string",
"to",
"the",
"given",
"URI",
"string",
"or",
"page",
"ID",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Url/UrlUtil.php#L78-L107
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Url/UrlUtil.php
|
UrlUtil.removeQueryString
|
public function removeQueryString(array $params, $url = null)
{
$strUrl = static::prepareUrl($url);
if (empty($params)) {
return $strUrl;
}
$explodedUrl = explode('?', $strUrl, 2);
if (2 === \count($explodedUrl)) {
list($script, $queryString) = $explodedUrl;
} else {
list($script) = $explodedUrl;
return $script;
}
parse_str($queryString, $queries);
$queries = array_filter($queries);
$queries = array_diff_key($queries, array_flip($params));
$href = '';
if (!empty($queries)) {
$href .= '?'.http_build_query($queries, '', '&');
}
return $script.$href;
}
|
php
|
public function removeQueryString(array $params, $url = null)
{
$strUrl = static::prepareUrl($url);
if (empty($params)) {
return $strUrl;
}
$explodedUrl = explode('?', $strUrl, 2);
if (2 === \count($explodedUrl)) {
list($script, $queryString) = $explodedUrl;
} else {
list($script) = $explodedUrl;
return $script;
}
parse_str($queryString, $queries);
$queries = array_filter($queries);
$queries = array_diff_key($queries, array_flip($params));
$href = '';
if (!empty($queries)) {
$href .= '?'.http_build_query($queries, '', '&');
}
return $script.$href;
}
|
[
"public",
"function",
"removeQueryString",
"(",
"array",
"$",
"params",
",",
"$",
"url",
"=",
"null",
")",
"{",
"$",
"strUrl",
"=",
"static",
"::",
"prepareUrl",
"(",
"$",
"url",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"params",
")",
")",
"{",
"return",
"$",
"strUrl",
";",
"}",
"$",
"explodedUrl",
"=",
"explode",
"(",
"'?'",
",",
"$",
"strUrl",
",",
"2",
")",
";",
"if",
"(",
"2",
"===",
"\\",
"count",
"(",
"$",
"explodedUrl",
")",
")",
"{",
"list",
"(",
"$",
"script",
",",
"$",
"queryString",
")",
"=",
"$",
"explodedUrl",
";",
"}",
"else",
"{",
"list",
"(",
"$",
"script",
")",
"=",
"$",
"explodedUrl",
";",
"return",
"$",
"script",
";",
"}",
"parse_str",
"(",
"$",
"queryString",
",",
"$",
"queries",
")",
";",
"$",
"queries",
"=",
"array_filter",
"(",
"$",
"queries",
")",
";",
"$",
"queries",
"=",
"array_diff_key",
"(",
"$",
"queries",
",",
"array_flip",
"(",
"$",
"params",
")",
")",
";",
"$",
"href",
"=",
"''",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"queries",
")",
")",
"{",
"$",
"href",
".=",
"'?'",
".",
"http_build_query",
"(",
"$",
"queries",
",",
"''",
",",
"'&'",
")",
";",
"}",
"return",
"$",
"script",
".",
"$",
"href",
";",
"}"
] |
Remove query parameters from the current URL.
@param array $params
@param string|int|null $url
@return string
|
[
"Remove",
"query",
"parameters",
"from",
"the",
"current",
"URL",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Url/UrlUtil.php#L117-L147
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Url/UrlUtil.php
|
UrlUtil.addURIScheme
|
public function addURIScheme(string $url = '', string $protocol = 'http'): string
{
$scheme = $protocol.'://';
if ('' !== $url && false === System::getContainer()->get('huh.utils.string')->startsWith($url, $protocol)) {
$url = $scheme.$url;
}
return $url;
}
|
php
|
public function addURIScheme(string $url = '', string $protocol = 'http'): string
{
$scheme = $protocol.'://';
if ('' !== $url && false === System::getContainer()->get('huh.utils.string')->startsWith($url, $protocol)) {
$url = $scheme.$url;
}
return $url;
}
|
[
"public",
"function",
"addURIScheme",
"(",
"string",
"$",
"url",
"=",
"''",
",",
"string",
"$",
"protocol",
"=",
"'http'",
")",
":",
"string",
"{",
"$",
"scheme",
"=",
"$",
"protocol",
".",
"'://'",
";",
"if",
"(",
"''",
"!==",
"$",
"url",
"&&",
"false",
"===",
"System",
"::",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'huh.utils.string'",
")",
"->",
"startsWith",
"(",
"$",
"url",
",",
"$",
"protocol",
")",
")",
"{",
"$",
"url",
"=",
"$",
"scheme",
".",
"$",
"url",
";",
"}",
"return",
"$",
"url",
";",
"}"
] |
Add a url scheme to a given url.
@param string $url
@param string $protocol
@return string
|
[
"Add",
"a",
"url",
"scheme",
"to",
"a",
"given",
"url",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Url/UrlUtil.php#L268-L277
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Url/UrlUtil.php
|
UrlUtil.prepareUrl
|
protected function prepareUrl($url)
{
if (null === $url) {
$url = Environment::get('requestUri');
} elseif (is_numeric($url)) {
if (null === ($jumpTo = $this->framework->getAdapter(PageModel::class)->findByPk($url))) {
throw new \InvalidArgumentException('Given page id does not exist.');
}
$url = $this->framework->getAdapter(Controller::class)->generateFrontendUrl($jumpTo->row());
list(, $queryString) = explode('?', Environment::get('request'), 2);
if ('' != $queryString) {
$url .= '?'.$queryString;
}
}
$url = ampersand($url, false);
return $url;
}
|
php
|
protected function prepareUrl($url)
{
if (null === $url) {
$url = Environment::get('requestUri');
} elseif (is_numeric($url)) {
if (null === ($jumpTo = $this->framework->getAdapter(PageModel::class)->findByPk($url))) {
throw new \InvalidArgumentException('Given page id does not exist.');
}
$url = $this->framework->getAdapter(Controller::class)->generateFrontendUrl($jumpTo->row());
list(, $queryString) = explode('?', Environment::get('request'), 2);
if ('' != $queryString) {
$url .= '?'.$queryString;
}
}
$url = ampersand($url, false);
return $url;
}
|
[
"protected",
"function",
"prepareUrl",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"url",
")",
"{",
"$",
"url",
"=",
"Environment",
"::",
"get",
"(",
"'requestUri'",
")",
";",
"}",
"elseif",
"(",
"is_numeric",
"(",
"$",
"url",
")",
")",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"jumpTo",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"PageModel",
"::",
"class",
")",
"->",
"findByPk",
"(",
"$",
"url",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Given page id does not exist.'",
")",
";",
"}",
"$",
"url",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Controller",
"::",
"class",
")",
"->",
"generateFrontendUrl",
"(",
"$",
"jumpTo",
"->",
"row",
"(",
")",
")",
";",
"list",
"(",
",",
"$",
"queryString",
")",
"=",
"explode",
"(",
"'?'",
",",
"Environment",
"::",
"get",
"(",
"'request'",
")",
",",
"2",
")",
";",
"if",
"(",
"''",
"!=",
"$",
"queryString",
")",
"{",
"$",
"url",
".=",
"'?'",
".",
"$",
"queryString",
";",
"}",
"}",
"$",
"url",
"=",
"ampersand",
"(",
"$",
"url",
",",
"false",
")",
";",
"return",
"$",
"url",
";",
"}"
] |
Prepare URL from ID and keep query string from current string.
@param string|int|null
@return string
|
[
"Prepare",
"URL",
"from",
"ID",
"and",
"keep",
"query",
"string",
"from",
"current",
"string",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Url/UrlUtil.php#L286-L307
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findModelInstancesBy
|
public function findModelInstancesBy(string $table, $columns, $values, array $options = [])
{
/* @var Model $adapter */
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
$this->fixTablePrefixForDcMultilingual($table, $columns, $options);
if (\is_array($values) && (!isset($options['skipReplaceInsertTags']) || !$options['skipReplaceInsertTags'])) {
$values = array_map('\Contao\Controller::replaceInsertTags', $values);
}
if (empty($columns)) {
$columns = null;
}
return $adapter->findBy($columns, $values, $options);
}
|
php
|
public function findModelInstancesBy(string $table, $columns, $values, array $options = [])
{
/* @var Model $adapter */
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
$this->fixTablePrefixForDcMultilingual($table, $columns, $options);
if (\is_array($values) && (!isset($options['skipReplaceInsertTags']) || !$options['skipReplaceInsertTags'])) {
$values = array_map('\Contao\Controller::replaceInsertTags', $values);
}
if (empty($columns)) {
$columns = null;
}
return $adapter->findBy($columns, $values, $options);
}
|
[
"public",
"function",
"findModelInstancesBy",
"(",
"string",
"$",
"table",
",",
"$",
"columns",
",",
"$",
"values",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"/* @var Model $adapter */",
"if",
"(",
"!",
"(",
"$",
"modelClass",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Model",
"::",
"class",
")",
"->",
"getClassFromTable",
"(",
"$",
"table",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"null",
"===",
"(",
"$",
"adapter",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"$",
"modelClass",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"fixTablePrefixForDcMultilingual",
"(",
"$",
"table",
",",
"$",
"columns",
",",
"$",
"options",
")",
";",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"values",
")",
"&&",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'skipReplaceInsertTags'",
"]",
")",
"||",
"!",
"$",
"options",
"[",
"'skipReplaceInsertTags'",
"]",
")",
")",
"{",
"$",
"values",
"=",
"array_map",
"(",
"'\\Contao\\Controller::replaceInsertTags'",
",",
"$",
"values",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"columns",
")",
")",
"{",
"$",
"columns",
"=",
"null",
";",
"}",
"return",
"$",
"adapter",
"->",
"findBy",
"(",
"$",
"columns",
",",
"$",
"values",
",",
"$",
"options",
")",
";",
"}"
] |
Returns model instances by given table and search criteria.
@param string $table
@param mixed $columns
@param mixed $values
@param array $options
@return mixed
|
[
"Returns",
"model",
"instances",
"by",
"given",
"table",
"and",
"search",
"criteria",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L88-L110
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findMultipleModelInstancesByIds
|
public function findMultipleModelInstancesByIds(string $table, array $ids, array $options = [])
{
/* @var Model $adapter */
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
if ($this->container->get('huh.utils.dca')->isDcMultilingual($table)) {
$table = 't1';
}
return $adapter->findBy(["$table.id IN(".implode(',', array_map('\intval', $ids)).')'], null, $options);
}
|
php
|
public function findMultipleModelInstancesByIds(string $table, array $ids, array $options = [])
{
/* @var Model $adapter */
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
if ($this->container->get('huh.utils.dca')->isDcMultilingual($table)) {
$table = 't1';
}
return $adapter->findBy(["$table.id IN(".implode(',', array_map('\intval', $ids)).')'], null, $options);
}
|
[
"public",
"function",
"findMultipleModelInstancesByIds",
"(",
"string",
"$",
"table",
",",
"array",
"$",
"ids",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"/* @var Model $adapter */",
"if",
"(",
"!",
"(",
"$",
"modelClass",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Model",
"::",
"class",
")",
"->",
"getClassFromTable",
"(",
"$",
"table",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"null",
"===",
"(",
"$",
"adapter",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"$",
"modelClass",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.dca'",
")",
"->",
"isDcMultilingual",
"(",
"$",
"table",
")",
")",
"{",
"$",
"table",
"=",
"'t1'",
";",
"}",
"return",
"$",
"adapter",
"->",
"findBy",
"(",
"[",
"\"$table.id IN(\"",
".",
"implode",
"(",
"','",
",",
"array_map",
"(",
"'\\intval'",
",",
"$",
"ids",
")",
")",
".",
"')'",
"]",
",",
"null",
",",
"$",
"options",
")",
";",
"}"
] |
Returns multiple model instances by given table and ids.
@param string $table
@param array $ids
@param array $options
@return mixed
|
[
"Returns",
"multiple",
"model",
"instances",
"by",
"given",
"table",
"and",
"ids",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L155-L171
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findModelInstanceByIdOrAlias
|
public function findModelInstanceByIdOrAlias(string $table, $idOrAlias, array $options = [])
{
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
/* @var Model $adapter */
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
if ($this->container->get('huh.utils.dca')->isDcMultilingual($table)) {
$table = 't1';
}
$options = array_merge(
[
'limit' => 1,
'column' => !is_numeric($idOrAlias) ? ["$table.alias=?"] : ["$table.id=?"],
'value' => $idOrAlias,
'return' => 'Model',
],
$options
);
return $adapter->findByIdOrAlias($idOrAlias, $options);
}
|
php
|
public function findModelInstanceByIdOrAlias(string $table, $idOrAlias, array $options = [])
{
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
/* @var Model $adapter */
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
if ($this->container->get('huh.utils.dca')->isDcMultilingual($table)) {
$table = 't1';
}
$options = array_merge(
[
'limit' => 1,
'column' => !is_numeric($idOrAlias) ? ["$table.alias=?"] : ["$table.id=?"],
'value' => $idOrAlias,
'return' => 'Model',
],
$options
);
return $adapter->findByIdOrAlias($idOrAlias, $options);
}
|
[
"public",
"function",
"findModelInstanceByIdOrAlias",
"(",
"string",
"$",
"table",
",",
"$",
"idOrAlias",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"modelClass",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Model",
"::",
"class",
")",
"->",
"getClassFromTable",
"(",
"$",
"table",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"/* @var Model $adapter */",
"if",
"(",
"null",
"===",
"(",
"$",
"adapter",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"$",
"modelClass",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'huh.utils.dca'",
")",
"->",
"isDcMultilingual",
"(",
"$",
"table",
")",
")",
"{",
"$",
"table",
"=",
"'t1'",
";",
"}",
"$",
"options",
"=",
"array_merge",
"(",
"[",
"'limit'",
"=>",
"1",
",",
"'column'",
"=>",
"!",
"is_numeric",
"(",
"$",
"idOrAlias",
")",
"?",
"[",
"\"$table.alias=?\"",
"]",
":",
"[",
"\"$table.id=?\"",
"]",
",",
"'value'",
"=>",
"$",
"idOrAlias",
",",
"'return'",
"=>",
"'Model'",
",",
"]",
",",
"$",
"options",
")",
";",
"return",
"$",
"adapter",
"->",
"findByIdOrAlias",
"(",
"$",
"idOrAlias",
",",
"$",
"options",
")",
";",
"}"
] |
Returns multiple model instances by given table and id or alias.
@param string $table
@param mixed $idOrAlias
@param array $options
@return mixed
|
[
"Returns",
"multiple",
"model",
"instances",
"by",
"given",
"table",
"and",
"id",
"or",
"alias",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L182-L208
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.getDcMultilingualRootPageLanguages
|
public function getDcMultilingualRootPageLanguages()
{
$pages = $this->framework->createInstance(Database::class)->execute("SELECT DISTINCT language FROM tl_page WHERE type='root' AND language!=''");
$languages = $pages->fetchEach('language');
array_walk(
$languages,
function (&$value) {
$value = str_replace('-', '_', $value);
}
);
return $languages;
}
|
php
|
public function getDcMultilingualRootPageLanguages()
{
$pages = $this->framework->createInstance(Database::class)->execute("SELECT DISTINCT language FROM tl_page WHERE type='root' AND language!=''");
$languages = $pages->fetchEach('language');
array_walk(
$languages,
function (&$value) {
$value = str_replace('-', '_', $value);
}
);
return $languages;
}
|
[
"public",
"function",
"getDcMultilingualRootPageLanguages",
"(",
")",
"{",
"$",
"pages",
"=",
"$",
"this",
"->",
"framework",
"->",
"createInstance",
"(",
"Database",
"::",
"class",
")",
"->",
"execute",
"(",
"\"SELECT DISTINCT language FROM tl_page WHERE type='root' AND language!=''\"",
")",
";",
"$",
"languages",
"=",
"$",
"pages",
"->",
"fetchEach",
"(",
"'language'",
")",
";",
"array_walk",
"(",
"$",
"languages",
",",
"function",
"(",
"&",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"str_replace",
"(",
"'-'",
",",
"'_'",
",",
"$",
"value",
")",
";",
"}",
")",
";",
"return",
"$",
"languages",
";",
"}"
] |
Get the list of languages based on root pages.
@return array
|
[
"Get",
"the",
"list",
"of",
"languages",
"based",
"on",
"root",
"pages",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L325-L338
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findRootParentRecursively
|
public function findRootParentRecursively(string $parentProperty, string $table, Model $instance, bool $returnInstanceIfNoParent = true)
{
if (!$instance || !$instance->{$parentProperty}
|| null === ($parentInstance = $this->findModelInstanceByPk($table, $instance->{$parentProperty}))) {
return $returnInstanceIfNoParent ? $instance : null;
}
return $this->findRootParentRecursively($parentProperty, $table, $parentInstance);
}
|
php
|
public function findRootParentRecursively(string $parentProperty, string $table, Model $instance, bool $returnInstanceIfNoParent = true)
{
if (!$instance || !$instance->{$parentProperty}
|| null === ($parentInstance = $this->findModelInstanceByPk($table, $instance->{$parentProperty}))) {
return $returnInstanceIfNoParent ? $instance : null;
}
return $this->findRootParentRecursively($parentProperty, $table, $parentInstance);
}
|
[
"public",
"function",
"findRootParentRecursively",
"(",
"string",
"$",
"parentProperty",
",",
"string",
"$",
"table",
",",
"Model",
"$",
"instance",
",",
"bool",
"$",
"returnInstanceIfNoParent",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"instance",
"||",
"!",
"$",
"instance",
"->",
"{",
"$",
"parentProperty",
"}",
"||",
"null",
"===",
"(",
"$",
"parentInstance",
"=",
"$",
"this",
"->",
"findModelInstanceByPk",
"(",
"$",
"table",
",",
"$",
"instance",
"->",
"{",
"$",
"parentProperty",
"}",
")",
")",
")",
"{",
"return",
"$",
"returnInstanceIfNoParent",
"?",
"$",
"instance",
":",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"findRootParentRecursively",
"(",
"$",
"parentProperty",
",",
"$",
"table",
",",
"$",
"parentInstance",
")",
";",
"}"
] |
Recursively finds the root parent.
@param string $parentProperty
@param string $table
@param Model $instance
@param bool $returnInstanceIfNoParent
@return Model
|
[
"Recursively",
"finds",
"the",
"root",
"parent",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L350-L358
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findParentsRecursively
|
public function findParentsRecursively(string $parentProperty, string $table, Model $instance): array
{
$parents = [];
if (!$instance->{$parentProperty} || null === ($parentInstance = $this->findModelInstanceByPk($table, $instance->{$parentProperty}))) {
return $parents;
}
return array_merge($this->findParentsRecursively($parentProperty, $table, $parentInstance), [$parentInstance]);
}
|
php
|
public function findParentsRecursively(string $parentProperty, string $table, Model $instance): array
{
$parents = [];
if (!$instance->{$parentProperty} || null === ($parentInstance = $this->findModelInstanceByPk($table, $instance->{$parentProperty}))) {
return $parents;
}
return array_merge($this->findParentsRecursively($parentProperty, $table, $parentInstance), [$parentInstance]);
}
|
[
"public",
"function",
"findParentsRecursively",
"(",
"string",
"$",
"parentProperty",
",",
"string",
"$",
"table",
",",
"Model",
"$",
"instance",
")",
":",
"array",
"{",
"$",
"parents",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"instance",
"->",
"{",
"$",
"parentProperty",
"}",
"||",
"null",
"===",
"(",
"$",
"parentInstance",
"=",
"$",
"this",
"->",
"findModelInstanceByPk",
"(",
"$",
"table",
",",
"$",
"instance",
"->",
"{",
"$",
"parentProperty",
"}",
")",
")",
")",
"{",
"return",
"$",
"parents",
";",
"}",
"return",
"array_merge",
"(",
"$",
"this",
"->",
"findParentsRecursively",
"(",
"$",
"parentProperty",
",",
"$",
"table",
",",
"$",
"parentInstance",
")",
",",
"[",
"$",
"parentInstance",
"]",
")",
";",
"}"
] |
Returns an array of a model instance's parents in ascending order, i.e. the root parent comes first.
@param string $parentProperty
@param string $table
@param Model $instance
@return array
|
[
"Returns",
"an",
"array",
"of",
"a",
"model",
"instance",
"s",
"parents",
"in",
"ascending",
"order",
"i",
".",
"e",
".",
"the",
"root",
"parent",
"comes",
"first",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L369-L378
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findAllModelInstances
|
public function findAllModelInstances(string $table, array $arrOptions = []): ?Collection
{
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
/* @var Model $adapter */
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
return $adapter->findAll($arrOptions);
}
|
php
|
public function findAllModelInstances(string $table, array $arrOptions = []): ?Collection
{
if (!($modelClass = $this->framework->getAdapter(Model::class)->getClassFromTable($table))) {
return null;
}
/* @var Model $adapter */
if (null === ($adapter = $this->framework->getAdapter($modelClass))) {
return null;
}
return $adapter->findAll($arrOptions);
}
|
[
"public",
"function",
"findAllModelInstances",
"(",
"string",
"$",
"table",
",",
"array",
"$",
"arrOptions",
"=",
"[",
"]",
")",
":",
"?",
"Collection",
"{",
"if",
"(",
"!",
"(",
"$",
"modelClass",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"Model",
"::",
"class",
")",
"->",
"getClassFromTable",
"(",
"$",
"table",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"/* @var Model $adapter */",
"if",
"(",
"null",
"===",
"(",
"$",
"adapter",
"=",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"$",
"modelClass",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"adapter",
"->",
"findAll",
"(",
"$",
"arrOptions",
")",
";",
"}"
] |
Find all model instances for a given table.
@param string $table The table name
@param array $arrOptions Additional query options
@return Collection|null
|
[
"Find",
"all",
"model",
"instances",
"for",
"a",
"given",
"table",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L388-L400
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.hasValueChanged
|
public function hasValueChanged($newValue, DataContainer $dc): bool
{
if (null !== ($entity = $this->findModelInstanceByPk($dc->table, $dc->id))) {
return $newValue != $entity->{$dc->field};
}
return true;
}
|
php
|
public function hasValueChanged($newValue, DataContainer $dc): bool
{
if (null !== ($entity = $this->findModelInstanceByPk($dc->table, $dc->id))) {
return $newValue != $entity->{$dc->field};
}
return true;
}
|
[
"public",
"function",
"hasValueChanged",
"(",
"$",
"newValue",
",",
"DataContainer",
"$",
"dc",
")",
":",
"bool",
"{",
"if",
"(",
"null",
"!==",
"(",
"$",
"entity",
"=",
"$",
"this",
"->",
"findModelInstanceByPk",
"(",
"$",
"dc",
"->",
"table",
",",
"$",
"dc",
"->",
"id",
")",
")",
")",
"{",
"return",
"$",
"newValue",
"!=",
"$",
"entity",
"->",
"{",
"$",
"dc",
"->",
"field",
"}",
";",
"}",
"return",
"true",
";",
"}"
] |
Determine if given value is newer than DataContainer value.
@param mixed $newValue
@param DataContainer $dc
@return bool
|
[
"Determine",
"if",
"given",
"value",
"is",
"newer",
"than",
"DataContainer",
"value",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L455-L462
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.getModelInstanceFieldValue
|
public function getModelInstanceFieldValue(string $field, string $table, int $id)
{
if (null !== ($entity = $this->findModelInstanceByPk($table, $id))) {
return $entity->{$property};
}
return null;
}
|
php
|
public function getModelInstanceFieldValue(string $field, string $table, int $id)
{
if (null !== ($entity = $this->findModelInstanceByPk($table, $id))) {
return $entity->{$property};
}
return null;
}
|
[
"public",
"function",
"getModelInstanceFieldValue",
"(",
"string",
"$",
"field",
",",
"string",
"$",
"table",
",",
"int",
"$",
"id",
")",
"{",
"if",
"(",
"null",
"!==",
"(",
"$",
"entity",
"=",
"$",
"this",
"->",
"findModelInstanceByPk",
"(",
"$",
"table",
",",
"$",
"id",
")",
")",
")",
"{",
"return",
"$",
"entity",
"->",
"{",
"$",
"property",
"}",
";",
"}",
"return",
"null",
";",
"}"
] |
Get model instance value for given field.
@param string $field
@param string $table
@param int $id
@return mixed|null
|
[
"Get",
"model",
"instance",
"value",
"for",
"given",
"field",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L473-L480
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Model/ModelUtil.php
|
ModelUtil.findModulePages
|
public function findModulePages(ModuleModel $module, $collection = false, $useCache = true)
{
$cache = new FilesystemCache();
$modulePagesCache = $cache->get('huh.utils.model.modulepages');
$pageIds = [];
$cacheHit = false;
if ($useCache && $cache->has('huh.utils.model.modulepages')) {
$modulePagesCache = $cache->get('huh.utils.model.modulepages');
if (\is_array($modulePagesCache) && \array_key_exists($module->id, $modulePagesCache)) {
$pageIds = $modulePagesCache[$module->id];
$cacheHit = true;
}
}
if (!$cacheHit) {
/** @var Database $db */
$db = $this->framework->createInstance(Database::class);
$result = $db->prepare("SELECT `tl_page`.`id` FROM `tl_page` JOIN `tl_article` ON `tl_article`.`pid` = `tl_page`.`id` JOIN `tl_content` ON `tl_content`.`pid` = `tl_article`.`id` WHERE `tl_content`.`type` = 'module' AND `tl_content`.`module` = ?")->execute($module->id);
if ($result->count() > 0) {
$pageIds = $result->fetchEach('id');
}
if (\array_key_exists('blocks', $this->container->getParameter('kernel.bundles'))) {
$result = $db->prepare(
"SELECT `tl_page`.`id` FROM `tl_page`
JOIN `tl_article` ON `tl_article`.`pid` = `tl_page`.`id`
JOIN `tl_content` ON `tl_content`.`pid` = `tl_article`.`id`
JOIN `tl_block` ON `tl_block`.`module` = `tl_content`.`module`
JOIN `tl_block_module` ON `tl_block_module`.`pid` = `tl_block`.`id`
WHERE `tl_block_module`.`type` = 'default' AND `tl_block_module`.`module` = ?"
)->execute($module->id);
if ($result->count() > 0) {
$pageIds = array_unique(array_merge($pageIds, $result->fetchEach('id')));
}
}
$modulePagesCache[$module->id] = $pageIds;
$cache->set('huh.utils.model.modulepages', $modulePagesCache);
}
if ($collection) {
return $this->framework->getAdapter(PageModel::class)->findMultipleByIds($pageIds);
}
return $pageIds;
}
|
php
|
public function findModulePages(ModuleModel $module, $collection = false, $useCache = true)
{
$cache = new FilesystemCache();
$modulePagesCache = $cache->get('huh.utils.model.modulepages');
$pageIds = [];
$cacheHit = false;
if ($useCache && $cache->has('huh.utils.model.modulepages')) {
$modulePagesCache = $cache->get('huh.utils.model.modulepages');
if (\is_array($modulePagesCache) && \array_key_exists($module->id, $modulePagesCache)) {
$pageIds = $modulePagesCache[$module->id];
$cacheHit = true;
}
}
if (!$cacheHit) {
/** @var Database $db */
$db = $this->framework->createInstance(Database::class);
$result = $db->prepare("SELECT `tl_page`.`id` FROM `tl_page` JOIN `tl_article` ON `tl_article`.`pid` = `tl_page`.`id` JOIN `tl_content` ON `tl_content`.`pid` = `tl_article`.`id` WHERE `tl_content`.`type` = 'module' AND `tl_content`.`module` = ?")->execute($module->id);
if ($result->count() > 0) {
$pageIds = $result->fetchEach('id');
}
if (\array_key_exists('blocks', $this->container->getParameter('kernel.bundles'))) {
$result = $db->prepare(
"SELECT `tl_page`.`id` FROM `tl_page`
JOIN `tl_article` ON `tl_article`.`pid` = `tl_page`.`id`
JOIN `tl_content` ON `tl_content`.`pid` = `tl_article`.`id`
JOIN `tl_block` ON `tl_block`.`module` = `tl_content`.`module`
JOIN `tl_block_module` ON `tl_block_module`.`pid` = `tl_block`.`id`
WHERE `tl_block_module`.`type` = 'default' AND `tl_block_module`.`module` = ?"
)->execute($module->id);
if ($result->count() > 0) {
$pageIds = array_unique(array_merge($pageIds, $result->fetchEach('id')));
}
}
$modulePagesCache[$module->id] = $pageIds;
$cache->set('huh.utils.model.modulepages', $modulePagesCache);
}
if ($collection) {
return $this->framework->getAdapter(PageModel::class)->findMultipleByIds($pageIds);
}
return $pageIds;
}
|
[
"public",
"function",
"findModulePages",
"(",
"ModuleModel",
"$",
"module",
",",
"$",
"collection",
"=",
"false",
",",
"$",
"useCache",
"=",
"true",
")",
"{",
"$",
"cache",
"=",
"new",
"FilesystemCache",
"(",
")",
";",
"$",
"modulePagesCache",
"=",
"$",
"cache",
"->",
"get",
"(",
"'huh.utils.model.modulepages'",
")",
";",
"$",
"pageIds",
"=",
"[",
"]",
";",
"$",
"cacheHit",
"=",
"false",
";",
"if",
"(",
"$",
"useCache",
"&&",
"$",
"cache",
"->",
"has",
"(",
"'huh.utils.model.modulepages'",
")",
")",
"{",
"$",
"modulePagesCache",
"=",
"$",
"cache",
"->",
"get",
"(",
"'huh.utils.model.modulepages'",
")",
";",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"modulePagesCache",
")",
"&&",
"\\",
"array_key_exists",
"(",
"$",
"module",
"->",
"id",
",",
"$",
"modulePagesCache",
")",
")",
"{",
"$",
"pageIds",
"=",
"$",
"modulePagesCache",
"[",
"$",
"module",
"->",
"id",
"]",
";",
"$",
"cacheHit",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"cacheHit",
")",
"{",
"/** @var Database $db */",
"$",
"db",
"=",
"$",
"this",
"->",
"framework",
"->",
"createInstance",
"(",
"Database",
"::",
"class",
")",
";",
"$",
"result",
"=",
"$",
"db",
"->",
"prepare",
"(",
"\"SELECT `tl_page`.`id` FROM `tl_page` JOIN `tl_article` ON `tl_article`.`pid` = `tl_page`.`id` JOIN `tl_content` ON `tl_content`.`pid` = `tl_article`.`id` WHERE `tl_content`.`type` = 'module' AND `tl_content`.`module` = ?\"",
")",
"->",
"execute",
"(",
"$",
"module",
"->",
"id",
")",
";",
"if",
"(",
"$",
"result",
"->",
"count",
"(",
")",
">",
"0",
")",
"{",
"$",
"pageIds",
"=",
"$",
"result",
"->",
"fetchEach",
"(",
"'id'",
")",
";",
"}",
"if",
"(",
"\\",
"array_key_exists",
"(",
"'blocks'",
",",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'kernel.bundles'",
")",
")",
")",
"{",
"$",
"result",
"=",
"$",
"db",
"->",
"prepare",
"(",
"\"SELECT `tl_page`.`id` FROM `tl_page`\n JOIN `tl_article` ON `tl_article`.`pid` = `tl_page`.`id`\n JOIN `tl_content` ON `tl_content`.`pid` = `tl_article`.`id`\n JOIN `tl_block` ON `tl_block`.`module` = `tl_content`.`module`\n JOIN `tl_block_module` ON `tl_block_module`.`pid` = `tl_block`.`id`\n WHERE `tl_block_module`.`type` = 'default' AND `tl_block_module`.`module` = ?\"",
")",
"->",
"execute",
"(",
"$",
"module",
"->",
"id",
")",
";",
"if",
"(",
"$",
"result",
"->",
"count",
"(",
")",
">",
"0",
")",
"{",
"$",
"pageIds",
"=",
"array_unique",
"(",
"array_merge",
"(",
"$",
"pageIds",
",",
"$",
"result",
"->",
"fetchEach",
"(",
"'id'",
")",
")",
")",
";",
"}",
"}",
"$",
"modulePagesCache",
"[",
"$",
"module",
"->",
"id",
"]",
"=",
"$",
"pageIds",
";",
"$",
"cache",
"->",
"set",
"(",
"'huh.utils.model.modulepages'",
",",
"$",
"modulePagesCache",
")",
";",
"}",
"if",
"(",
"$",
"collection",
")",
"{",
"return",
"$",
"this",
"->",
"framework",
"->",
"getAdapter",
"(",
"PageModel",
"::",
"class",
")",
"->",
"findMultipleByIds",
"(",
"$",
"pageIds",
")",
";",
"}",
"return",
"$",
"pageIds",
";",
"}"
] |
Find module pages.
Returns page ids or models, where a frontend module is integrated
Also search within blocks (heimrichhannot/contao-blocks)
@param ModuleModel $module
@param bool $collection Return PageModel Collection if true. Default: false
@param bool $useCache If true, a filesystem cache will be used to save pages ids. Default: true
@return array|Collection|PageModel|PageModel[]|null An array of page Ids (can be empty if no page found!), a PageModel collection or null
|
[
"Find",
"module",
"pages",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Model/ModelUtil.php#L495-L543
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/FileCache.php
|
FileCache.exist
|
public function exist(string $identifier, string $fileExtension = '')
{
$fileName = $this->getCacheFileName($identifier);
$cachePath = $this->cacheFolderWithNamespace.'/'.$fileName;
if (!empty($fileExtension)) {
$cachePath .= '.'.$fileExtension;
}
$file = new File($cachePath);
if ($file->exists()) {
return true;
}
return false;
}
|
php
|
public function exist(string $identifier, string $fileExtension = '')
{
$fileName = $this->getCacheFileName($identifier);
$cachePath = $this->cacheFolderWithNamespace.'/'.$fileName;
if (!empty($fileExtension)) {
$cachePath .= '.'.$fileExtension;
}
$file = new File($cachePath);
if ($file->exists()) {
return true;
}
return false;
}
|
[
"public",
"function",
"exist",
"(",
"string",
"$",
"identifier",
",",
"string",
"$",
"fileExtension",
"=",
"''",
")",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"getCacheFileName",
"(",
"$",
"identifier",
")",
";",
"$",
"cachePath",
"=",
"$",
"this",
"->",
"cacheFolderWithNamespace",
".",
"'/'",
".",
"$",
"fileName",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"fileExtension",
")",
")",
"{",
"$",
"cachePath",
".=",
"'.'",
".",
"$",
"fileExtension",
";",
"}",
"$",
"file",
"=",
"new",
"File",
"(",
"$",
"cachePath",
")",
";",
"if",
"(",
"$",
"file",
"->",
"exists",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks if a cached file already exist in cache. Namespace is taken into account.
@param string $identifier The identifier
@param string $fileExtension If not set, a file with no file extension is searched
@throws \Exception
@return bool
|
[
"Checks",
"if",
"a",
"cached",
"file",
"already",
"exist",
"in",
"cache",
".",
"Namespace",
"is",
"taken",
"into",
"account",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/FileCache.php#L82-L97
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/FileCache.php
|
FileCache.get
|
public function get(string $identifier, string $fileExtension = '', callable $saveCallback = null)
{
$fileName = $this->getCacheFileName($identifier);
$cachePath = $this->cacheFolderWithNamespace.'/'.$fileName;
if (!empty($fileExtension)) {
$fileName .= '.'.$fileExtension;
$cachePath .= '.'.$fileExtension;
}
$file = new File($cachePath);
if (!$file->exists()) {
if (null !== $saveCallback) {
if ($saveCallback($identifier, $this->cacheFolderWithNamespace, $fileName)) {
return $this->cacheFolderWithNamespace.'/'.$fileName;
}
}
return false;
}
return $file->path;
}
|
php
|
public function get(string $identifier, string $fileExtension = '', callable $saveCallback = null)
{
$fileName = $this->getCacheFileName($identifier);
$cachePath = $this->cacheFolderWithNamespace.'/'.$fileName;
if (!empty($fileExtension)) {
$fileName .= '.'.$fileExtension;
$cachePath .= '.'.$fileExtension;
}
$file = new File($cachePath);
if (!$file->exists()) {
if (null !== $saveCallback) {
if ($saveCallback($identifier, $this->cacheFolderWithNamespace, $fileName)) {
return $this->cacheFolderWithNamespace.'/'.$fileName;
}
}
return false;
}
return $file->path;
}
|
[
"public",
"function",
"get",
"(",
"string",
"$",
"identifier",
",",
"string",
"$",
"fileExtension",
"=",
"''",
",",
"callable",
"$",
"saveCallback",
"=",
"null",
")",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"getCacheFileName",
"(",
"$",
"identifier",
")",
";",
"$",
"cachePath",
"=",
"$",
"this",
"->",
"cacheFolderWithNamespace",
".",
"'/'",
".",
"$",
"fileName",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"fileExtension",
")",
")",
"{",
"$",
"fileName",
".=",
"'.'",
".",
"$",
"fileExtension",
";",
"$",
"cachePath",
".=",
"'.'",
".",
"$",
"fileExtension",
";",
"}",
"$",
"file",
"=",
"new",
"File",
"(",
"$",
"cachePath",
")",
";",
"if",
"(",
"!",
"$",
"file",
"->",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"saveCallback",
")",
"{",
"if",
"(",
"$",
"saveCallback",
"(",
"$",
"identifier",
",",
"$",
"this",
"->",
"cacheFolderWithNamespace",
",",
"$",
"fileName",
")",
")",
"{",
"return",
"$",
"this",
"->",
"cacheFolderWithNamespace",
".",
"'/'",
".",
"$",
"fileName",
";",
"}",
"}",
"return",
"false",
";",
"}",
"return",
"$",
"file",
"->",
"path",
";",
"}"
] |
Get the file path for the given identifier. Namespace is taken into account.
@param string $identifier
@param string $fileExtension
@param callable $saveCallback A callback handles the file save functionality. Get filepath, filename and the identifier as parameter. Expects a boolean return value.
@throws \Exception
@return bool|string returns the path of the cached file or false, if cached file could not be found
|
[
"Get",
"the",
"file",
"path",
"for",
"the",
"given",
"identifier",
".",
"Namespace",
"is",
"taken",
"into",
"account",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/FileCache.php#L110-L132
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/FileCache.php
|
FileCache.generateCacheName
|
public function generateCacheName(string $identifier = '', string $prefix = '', bool $more_entropy = true, string $fileExtension = '')
{
if (empty($identifier)) {
$fileName = uniqid($prefix, $more_entropy);
} else {
$fileName = $this->getCacheFileName($identifier);
}
if (!empty($fileExtension)) {
$fileName .= '.'.$fileExtension;
}
return $fileName;
}
|
php
|
public function generateCacheName(string $identifier = '', string $prefix = '', bool $more_entropy = true, string $fileExtension = '')
{
if (empty($identifier)) {
$fileName = uniqid($prefix, $more_entropy);
} else {
$fileName = $this->getCacheFileName($identifier);
}
if (!empty($fileExtension)) {
$fileName .= '.'.$fileExtension;
}
return $fileName;
}
|
[
"public",
"function",
"generateCacheName",
"(",
"string",
"$",
"identifier",
"=",
"''",
",",
"string",
"$",
"prefix",
"=",
"''",
",",
"bool",
"$",
"more_entropy",
"=",
"true",
",",
"string",
"$",
"fileExtension",
"=",
"''",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"identifier",
")",
")",
"{",
"$",
"fileName",
"=",
"uniqid",
"(",
"$",
"prefix",
",",
"$",
"more_entropy",
")",
";",
"}",
"else",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"getCacheFileName",
"(",
"$",
"identifier",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"fileExtension",
")",
")",
"{",
"$",
"fileName",
".=",
"'.'",
".",
"$",
"fileExtension",
";",
"}",
"return",
"$",
"fileName",
";",
"}"
] |
Generate a file name for cache.
If a identifier is given, you get the resulting file name.
If no identifier is given, if will return a unique file name without extension.
@param string $identifier An identifier for the cache. For example be the source file name or path. If empty, a unique filename will be generated.
@param string $prefix Adds a prefix to the generated name. Only if $identifier is empty.
@param bool $more_entropy A longer name for the unique filename. Only if $identifier is empty. Default
@param string $fileExtension optional: If set, the file extension will be appended to the generated file name
@return string a unique filename for caching
|
[
"Generate",
"a",
"file",
"name",
"for",
"cache",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/FileCache.php#L147-L160
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/FileCache.php
|
FileCache.getCacheFilePath
|
public function getCacheFilePath(string $filename = '', string $prefix = '', bool $more_entropy = true)
{
return $this->cacheFolderWithNamespace.'/'.$this->generateCacheName($filename, $prefix, $more_entropy);
}
|
php
|
public function getCacheFilePath(string $filename = '', string $prefix = '', bool $more_entropy = true)
{
return $this->cacheFolderWithNamespace.'/'.$this->generateCacheName($filename, $prefix, $more_entropy);
}
|
[
"public",
"function",
"getCacheFilePath",
"(",
"string",
"$",
"filename",
"=",
"''",
",",
"string",
"$",
"prefix",
"=",
"''",
",",
"bool",
"$",
"more_entropy",
"=",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"cacheFolderWithNamespace",
".",
"'/'",
".",
"$",
"this",
"->",
"generateCacheName",
"(",
"$",
"filename",
",",
"$",
"prefix",
",",
"$",
"more_entropy",
")",
";",
"}"
] |
Same as generateCacheName, but returns complete path to cache.
If no filename is given, you need to add the file extension by yourself!
@param string $filename The filename of the file that should be cached. If empty, a unique filename will be generated.
@param string $prefix Adds a prefix to the generated name. Only if $filename is empty.
@param bool $more_entropy A longer name for the unique filename. Only if filename is empty. Default
@return string the path including the filename to save the file to the cache
|
[
"Same",
"as",
"generateCacheName",
"but",
"returns",
"complete",
"path",
"to",
"cache",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/FileCache.php#L185-L188
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Cache/FileCache.php
|
FileCache.generatePath
|
protected function generatePath()
{
$filesystem = new Filesystem();
$path = $this->cacheFolder;
$path = trim($path, '/');
if (!empty($this->namespace)) {
$path .= '/'.$this->namespace;
}
if (!$filesystem->exists($this->projectDir.'/'.$path)) {
$filesystem->mkdir($this->projectDir.'/'.$path);
}
$this->cacheFolderWithNamespace = $path;
}
|
php
|
protected function generatePath()
{
$filesystem = new Filesystem();
$path = $this->cacheFolder;
$path = trim($path, '/');
if (!empty($this->namespace)) {
$path .= '/'.$this->namespace;
}
if (!$filesystem->exists($this->projectDir.'/'.$path)) {
$filesystem->mkdir($this->projectDir.'/'.$path);
}
$this->cacheFolderWithNamespace = $path;
}
|
[
"protected",
"function",
"generatePath",
"(",
")",
"{",
"$",
"filesystem",
"=",
"new",
"Filesystem",
"(",
")",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"cacheFolder",
";",
"$",
"path",
"=",
"trim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"namespace",
")",
")",
"{",
"$",
"path",
".=",
"'/'",
".",
"$",
"this",
"->",
"namespace",
";",
"}",
"if",
"(",
"!",
"$",
"filesystem",
"->",
"exists",
"(",
"$",
"this",
"->",
"projectDir",
".",
"'/'",
".",
"$",
"path",
")",
")",
"{",
"$",
"filesystem",
"->",
"mkdir",
"(",
"$",
"this",
"->",
"projectDir",
".",
"'/'",
".",
"$",
"path",
")",
";",
"}",
"$",
"this",
"->",
"cacheFolderWithNamespace",
"=",
"$",
"path",
";",
"}"
] |
Recreates the path to the current cache folder.
|
[
"Recreates",
"the",
"path",
"to",
"the",
"current",
"cache",
"folder",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Cache/FileCache.php#L251-L265
|
train
|
heimrichhannot/contao-utils-bundle
|
src/Twig/DownloadExtension.php
|
DownloadExtension.getFilters
|
public function getFilters()
{
return [
new TwigFilter('download', [$this, 'getDownload']),
new TwigFilter('download_link', [$this, 'getDownloadLink']),
new TwigFilter('download_path', [$this, 'getDownloadPath']),
new TwigFilter('download_data', [$this, 'getDownloadData']),
new TwigFilter('download_title', [$this, 'getDownloadTitle']),
];
}
|
php
|
public function getFilters()
{
return [
new TwigFilter('download', [$this, 'getDownload']),
new TwigFilter('download_link', [$this, 'getDownloadLink']),
new TwigFilter('download_path', [$this, 'getDownloadPath']),
new TwigFilter('download_data', [$this, 'getDownloadData']),
new TwigFilter('download_title', [$this, 'getDownloadTitle']),
];
}
|
[
"public",
"function",
"getFilters",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFilter",
"(",
"'download'",
",",
"[",
"$",
"this",
",",
"'getDownload'",
"]",
")",
",",
"new",
"TwigFilter",
"(",
"'download_link'",
",",
"[",
"$",
"this",
",",
"'getDownloadLink'",
"]",
")",
",",
"new",
"TwigFilter",
"(",
"'download_path'",
",",
"[",
"$",
"this",
",",
"'getDownloadPath'",
"]",
")",
",",
"new",
"TwigFilter",
"(",
"'download_data'",
",",
"[",
"$",
"this",
",",
"'getDownloadData'",
"]",
")",
",",
"new",
"TwigFilter",
"(",
"'download_title'",
",",
"[",
"$",
"this",
",",
"'getDownloadTitle'",
"]",
")",
",",
"]",
";",
"}"
] |
Get list of twig filters.
@return array|\Twig_SimpleFilter[]
|
[
"Get",
"list",
"of",
"twig",
"filters",
"."
] |
96a765112a9cd013b75b6288d3e658ef64d29d4c
|
https://github.com/heimrichhannot/contao-utils-bundle/blob/96a765112a9cd013b75b6288d3e658ef64d29d4c/src/Twig/DownloadExtension.php#L31-L40
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.