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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ProAI/laravel-handlebars | src/HandlebarsServiceProvider.php | HandlebarsServiceProvider.registerFileExtensions | protected function registerFileExtensions()
{
$this->app->extend('view', function ($env, $app) {
$fileexts = $app['config']['handlebars.fileext'];
foreach ($fileexts as $fileext) {
$env->addExtension(trim($fileext, '.'), 'handlebars');
}
return $env;
});
} | php | protected function registerFileExtensions()
{
$this->app->extend('view', function ($env, $app) {
$fileexts = $app['config']['handlebars.fileext'];
foreach ($fileexts as $fileext) {
$env->addExtension(trim($fileext, '.'), 'handlebars');
}
return $env;
});
} | [
"protected",
"function",
"registerFileExtensions",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"extend",
"(",
"'view'",
",",
"function",
"(",
"$",
"env",
",",
"$",
"app",
")",
"{",
"$",
"fileexts",
"=",
"$",
"app",
"[",
"'config'",
"]",
"[",
"'han... | Register the file extensions.
@return void | [
"Register",
"the",
"file",
"extensions",
"."
] | c0e154d2df1dfa667c2226e19710f06b8acef94e | https://github.com/ProAI/laravel-handlebars/blob/c0e154d2df1dfa667c2226e19710f06b8acef94e/src/HandlebarsServiceProvider.php#L109-L120 | train |
ProAI/laravel-handlebars | src/Support/LightnCandy.php | LightnCandy.setupToken | protected static function setupToken(&$context, $left = '{{', $right = '}}')
{
parent::setupToken($context, $left, $right);
if (self::$compileHelpersOnly) {
$helperTokens = array();
foreach ($context['helpers'] as $helper => $value) {
$helperTokens[] = $helper . '.*?';
}
$helperTokens = implode('|', $helperTokens);
$context['tokens']['search'] = "/^(.*?)(\\s*)($left)(~?)([\\^#\\/!&>]?)(" . $helperTokens . ")(~?)($right)(\\s*)(.*)\$/s";
}
} | php | protected static function setupToken(&$context, $left = '{{', $right = '}}')
{
parent::setupToken($context, $left, $right);
if (self::$compileHelpersOnly) {
$helperTokens = array();
foreach ($context['helpers'] as $helper => $value) {
$helperTokens[] = $helper . '.*?';
}
$helperTokens = implode('|', $helperTokens);
$context['tokens']['search'] = "/^(.*?)(\\s*)($left)(~?)([\\^#\\/!&>]?)(" . $helperTokens . ")(~?)($right)(\\s*)(.*)\$/s";
}
} | [
"protected",
"static",
"function",
"setupToken",
"(",
"&",
"$",
"context",
",",
"$",
"left",
"=",
"'{{'",
",",
"$",
"right",
"=",
"'}}'",
")",
"{",
"parent",
"::",
"setupToken",
"(",
"$",
"context",
",",
"$",
"left",
",",
"$",
"right",
")",
";",
"i... | Setup token delimiter by default or provided string
@param array<string,array|string|integer> $context Current context
@param string $left left string of a token
@param string $right right string of a token | [
"Setup",
"token",
"delimiter",
"by",
"default",
"or",
"provided",
"string"
] | c0e154d2df1dfa667c2226e19710f06b8acef94e | https://github.com/ProAI/laravel-handlebars/blob/c0e154d2df1dfa667c2226e19710f06b8acef94e/src/Support/LightnCandy.php#L32-L45 | train |
me-io/php-lodash | src/Traits/Strings.php | Strings.kebabCase | public static function kebabCase(string $input): string
{
$words = __::words(preg_replace("/['\x{2019}]/u", '', $input));
return array_reduce(
$words,
function ($result, $word) use ($words) {
$isFirst = __::first($words) === $word;
return $result . (!$isFirst ? '-' : '') . __::toLower($word);
},
''
);
} | php | public static function kebabCase(string $input): string
{
$words = __::words(preg_replace("/['\x{2019}]/u", '', $input));
return array_reduce(
$words,
function ($result, $word) use ($words) {
$isFirst = __::first($words) === $word;
return $result . (!$isFirst ? '-' : '') . __::toLower($word);
},
''
);
} | [
"public",
"static",
"function",
"kebabCase",
"(",
"string",
"$",
"input",
")",
":",
"string",
"{",
"$",
"words",
"=",
"__",
"::",
"words",
"(",
"preg_replace",
"(",
"\"/['\\x{2019}]/u\"",
",",
"''",
",",
"$",
"input",
")",
")",
";",
"return",
"array_redu... | Converts string to kebab case.
@link https://en.wikipedia.org/wiki/Letter_case#Special_case_styles kebab case
@usage __::kebabCase('Foo Bar');
>> 'foo-bar'
@param string $input
@return string | [
"Converts",
"string",
"to",
"kebab",
"case",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Strings.php#L84-L97 | train |
me-io/php-lodash | src/Traits/Strings.php | Strings.startCase | public static function startCase(string $input): string
{
$words = __::words(preg_replace("/['\x{2019}]/u", '', $input));
return array_reduce(
$words,
function ($result, $word) use ($words) {
$isFirst = __::first($words) === $word;
return $result . (!$isFirst ? ' ' : '') . __::upperFirst($word);
},
''
);
} | php | public static function startCase(string $input): string
{
$words = __::words(preg_replace("/['\x{2019}]/u", '', $input));
return array_reduce(
$words,
function ($result, $word) use ($words) {
$isFirst = __::first($words) === $word;
return $result . (!$isFirst ? ' ' : '') . __::upperFirst($word);
},
''
);
} | [
"public",
"static",
"function",
"startCase",
"(",
"string",
"$",
"input",
")",
":",
"string",
"{",
"$",
"words",
"=",
"__",
"::",
"words",
"(",
"preg_replace",
"(",
"\"/['\\x{2019}]/u\"",
",",
"''",
",",
"$",
"input",
")",
")",
";",
"return",
"array_redu... | Converts string to start case.
@link https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage start case
@usage __::startCase('--foo-bar--');
>> 'Foo Bar'
@param string $input
@return string | [
"Converts",
"string",
"to",
"start",
"case",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Strings.php#L153-L166 | train |
me-io/php-lodash | src/Traits/Strings.php | Strings.upperCase | public static function upperCase(string $input): string
{
$words = __::words(preg_replace("/['\x{2019}]/u", '', $input));
return array_reduce(
$words,
function ($result, $word) use ($words) {
$isFirst = __::first($words) === $word;
return $result . (!$isFirst ? ' ' : '') . __::toUpper($word);
},
''
);
} | php | public static function upperCase(string $input): string
{
$words = __::words(preg_replace("/['\x{2019}]/u", '', $input));
return array_reduce(
$words,
function ($result, $word) use ($words) {
$isFirst = __::first($words) === $word;
return $result . (!$isFirst ? ' ' : '') . __::toUpper($word);
},
''
);
} | [
"public",
"static",
"function",
"upperCase",
"(",
"string",
"$",
"input",
")",
":",
"string",
"{",
"$",
"words",
"=",
"__",
"::",
"words",
"(",
"preg_replace",
"(",
"\"/['\\x{2019}]/u\"",
",",
"''",
",",
"$",
"input",
")",
")",
";",
"return",
"array_redu... | Converts string, as space separated words, to upper case.
@usage __::upperCase('--foo-bar');
>> 'FOO BAR'
@param string $input
@return string | [
"Converts",
"string",
"as",
"space",
"separated",
"words",
"to",
"upper",
"case",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Strings.php#L208-L221 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.filter | public static function filter(array $array = [], Closure $closure = null): array
{
if ($closure) {
$result = [];
foreach ($array as $key => $value) {
if (call_user_func($closure, $value)) {
$result[] = $value;
}
}
return $result;
}
return __::compact($array);
} | php | public static function filter(array $array = [], Closure $closure = null): array
{
if ($closure) {
$result = [];
foreach ($array as $key => $value) {
if (call_user_func($closure, $value)) {
$result[] = $value;
}
}
return $result;
}
return __::compact($array);
} | [
"public",
"static",
"function",
"filter",
"(",
"array",
"$",
"array",
"=",
"[",
"]",
",",
"Closure",
"$",
"closure",
"=",
"null",
")",
":",
"array",
"{",
"if",
"(",
"$",
"closure",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",... | Returns the values in the collection that pass the truth test.
@param array $array array to filter
@param \Closure $closure closure to filter array based on
@return array | [
"Returns",
"the",
"values",
"in",
"the",
"collection",
"that",
"pass",
"the",
"truth",
"test",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L20-L35 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.get | public static function get($collection = [], $key = null, $default = null)
{
if (__::isNull($key)) {
return $collection;
}
if (!__::isObject($collection) && isset($collection[$key])) {
return $collection[$key];
}
foreach (explode('.', $key) as $segment) {
if (__::isObject($collection)) {
if (!isset($collection->{$segment})) {
return $default instanceof Closure ? $default() : $default;
} else {
$collection = $collection->{$segment};
}
} else {
if (!isset($collection[$segment])) {
return $default instanceof Closure ? $default() : $default;
} else {
$collection = $collection[$segment];
}
}
}
return $collection;
} | php | public static function get($collection = [], $key = null, $default = null)
{
if (__::isNull($key)) {
return $collection;
}
if (!__::isObject($collection) && isset($collection[$key])) {
return $collection[$key];
}
foreach (explode('.', $key) as $segment) {
if (__::isObject($collection)) {
if (!isset($collection->{$segment})) {
return $default instanceof Closure ? $default() : $default;
} else {
$collection = $collection->{$segment};
}
} else {
if (!isset($collection[$segment])) {
return $default instanceof Closure ? $default() : $default;
} else {
$collection = $collection[$segment];
}
}
}
return $collection;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"collection",
"=",
"[",
"]",
",",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"__",
"::",
"isNull",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"collection",
... | Get item of an array by index, accepting nested index
@usage __::get(['foo' => ['bar' => 'ter']], 'foo.bar');
>> 'ter'
@param array|object $collection array of values
@param null|string $key key or index
@param mixed $default default value to return if index not exist
@return mixed | [
"Get",
"item",
"of",
"an",
"array",
"by",
"index",
"accepting",
"nested",
"index"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L69-L96 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.pluck | public static function pluck($collection, string $property): array
{
$result = array_map(function ($value) use ($property) {
if (is_array($value) && isset($value[$property])) {
return $value[$property];
} elseif (is_object($value) && isset($value->{$property})) {
return $value->{$property};
}
foreach (__::split($property, '.') as $segment) {
if (is_object($value)) {
if (isset($value->{$segment})) {
$value = $value->{$segment};
} else {
return null;
}
} else {
if (isset($value[$segment])) {
$value = $value[$segment];
} else {
return null;
}
}
}
return $value;
}, (array)$collection);
return array_values($result);
} | php | public static function pluck($collection, string $property): array
{
$result = array_map(function ($value) use ($property) {
if (is_array($value) && isset($value[$property])) {
return $value[$property];
} elseif (is_object($value) && isset($value->{$property})) {
return $value->{$property};
}
foreach (__::split($property, '.') as $segment) {
if (is_object($value)) {
if (isset($value->{$segment})) {
$value = $value->{$segment};
} else {
return null;
}
} else {
if (isset($value[$segment])) {
$value = $value[$segment];
} else {
return null;
}
}
}
return $value;
}, (array)$collection);
return array_values($result);
} | [
"public",
"static",
"function",
"pluck",
"(",
"$",
"collection",
",",
"string",
"$",
"property",
")",
":",
"array",
"{",
"$",
"result",
"=",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"use",
"(",
"$",
"property",
")",
"{",
"if",
"(",
"is_a... | Returns an array of values belonging to a given property of each item in a collection.
@usage $a = [
['foo' => 'bar', 'bis' => 'ter' ],
['foo' => 'bar2', 'bis' => 'ter2'],
];
__::pluck($a, 'foo');
>> ['bar', 'bar2']
@param array|object $collection array or object that can be converted to array
@param string $property property name
@return array | [
"Returns",
"an",
"array",
"of",
"values",
"belonging",
"to",
"a",
"given",
"property",
"of",
"each",
"item",
"in",
"a",
"collection",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L191-L219 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.where | public static function where(array $array = [], array $key = [], bool $keepKeys = false): array
{
$result = [];
foreach ($array as $k => $v) {
$not = false;
foreach ($key as $j => $w) {
if (__::isArray($w)) {
$inKV = $v[$j] ?? [];
if (count(array_intersect_assoc($w, $inKV)) == 0) {
$not = true;
break;
}
} else {
if (!isset($v[$j]) || $v[$j] != $w) {
$not = true;
break;
}
}
}
if ($not == false) {
if ($keepKeys) {
$result[$k] = $v;
} else {
$result[] = $v;
}
}
}
return $result;
} | php | public static function where(array $array = [], array $key = [], bool $keepKeys = false): array
{
$result = [];
foreach ($array as $k => $v) {
$not = false;
foreach ($key as $j => $w) {
if (__::isArray($w)) {
$inKV = $v[$j] ?? [];
if (count(array_intersect_assoc($w, $inKV)) == 0) {
$not = true;
break;
}
} else {
if (!isset($v[$j]) || $v[$j] != $w) {
$not = true;
break;
}
}
}
if ($not == false) {
if ($keepKeys) {
$result[$k] = $v;
} else {
$result[] = $v;
}
}
}
return $result;
} | [
"public",
"static",
"function",
"where",
"(",
"array",
"$",
"array",
"=",
"[",
"]",
",",
"array",
"$",
"key",
"=",
"[",
"]",
",",
"bool",
"$",
"keepKeys",
"=",
"false",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
... | Return data matching specific key value condition
@usage __::where($a, ['age' => 16]);
>> [['name' => 'maciej', 'age' => 16]]
@param array $array array of values
@param array $key condition in format of ['KEY'=>'VALUE']
@param bool $keepKeys keep original keys
@return array | [
"Return",
"data",
"matching",
"specific",
"key",
"value",
"condition"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L234-L266 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.assign | public static function assign($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
$result = __::set($result, $key, $sourceValue);
});
return $result;
}, []);
} | php | public static function assign($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
$result = __::set($result, $key, $sourceValue);
});
return $result;
}, []);
} | [
"public",
"static",
"function",
"assign",
"(",
"$",
"collection1",
",",
"$",
"collection2",
")",
"{",
"return",
"__",
"::",
"reduceRight",
"(",
"func_get_args",
"(",
")",
",",
"function",
"(",
"$",
"source",
",",
"$",
"result",
")",
"{",
"__",
"::",
"d... | Combines and merge collections provided with each others.
If the collections have common keys, then the last passed keys override the
previous. If numerical indexes are passed, then last passed indexes override
the previous.
For a recursive merge, see __::merge.
@usage __::assign(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
>> ['color' => ['favorite' => 'green', 'blue'], 10]
@param array|object $collection1 Collection to assign to.
@param array|object $collection2 Other collections to assign
@return array|object Assigned collection. | [
"Combines",
"and",
"merge",
"collections",
"provided",
"with",
"each",
"others",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L285-L294 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.doForEachRight | public static function doForEachRight($collection, Closure $iterateFn)
{
__::doForEach(__::iteratorReverse($collection), $iterateFn);
return true;
} | php | public static function doForEachRight($collection, Closure $iterateFn)
{
__::doForEach(__::iteratorReverse($collection), $iterateFn);
return true;
} | [
"public",
"static",
"function",
"doForEachRight",
"(",
"$",
"collection",
",",
"Closure",
"$",
"iterateFn",
")",
"{",
"__",
"::",
"doForEach",
"(",
"__",
"::",
"iteratorReverse",
"(",
"$",
"collection",
")",
",",
"$",
"iterateFn",
")",
";",
"return",
"true... | Iterate over elements of the collection, from right to left, and invokes iterate
for each element.
The iterate is invoked with three arguments: (value, index|key, collection).
Iterate functions may exit iteration early by explicitly returning false.
@usage __::doForEachRight([1, 2, 3], function ($value) { print_r($value) });
>> (Side effect: print 3, 2, 1)
@param array|object $collection The collection to iterate over.
@param \Closure $iterateFn The function to call for each value.
@return boolean | [
"Iterate",
"over",
"elements",
"of",
"the",
"collection",
"from",
"right",
"to",
"left",
"and",
"invokes",
"iterate",
"for",
"each",
"element",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L349-L353 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.doForEach | public static function doForEach($collection, Closure $iterateFn)
{
foreach ($collection as $key => $value) {
if ($iterateFn($value, $key, $collection) === false) {
break;
}
}
return true;
} | php | public static function doForEach($collection, Closure $iterateFn)
{
foreach ($collection as $key => $value) {
if ($iterateFn($value, $key, $collection) === false) {
break;
}
}
return true;
} | [
"public",
"static",
"function",
"doForEach",
"(",
"$",
"collection",
",",
"Closure",
"$",
"iterateFn",
")",
"{",
"foreach",
"(",
"$",
"collection",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"iterateFn",
"(",
"$",
"value",
",",
"... | Iterate over elements of the collection and invokes iterate for each element.
The iterate is invoked with three arguments: (value, index|key, collection).
Iterate functions may exit iteration early by explicitly returning false.
@usage __::doForEach([1, 2, 3], function ($value) { print_r($value) });
>> (Side effect: print 1, 2, 3)
@param array|object $collection The collection to iterate over.
@param \Closure $iterateFn The function to call for each value
@return boolean | [
"Iterate",
"over",
"elements",
"of",
"the",
"collection",
"and",
"invokes",
"iterate",
"for",
"each",
"element",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L369-L377 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.set | public static function set($collection, $path, $value = null)
{
if ($path === null) {
return $collection;
}
$portions = __::split($path, '.', 2);
$key = $portions[0];
if (count($portions) === 1) {
return __::universalSet($collection, $key, $value);
}
// Here we manage the case where the portion of the path points to nothing,
// or to a value that does not match the type of the source collection
// (e.g. the path portion 'foo.bar' points to an integer value, while we
// want to set a string at 'foo.bar.fun'. We first set an object or array
// - following the current collection type - to 'for.bar' before setting
// 'foo.bar.fun' to the specified value).
if (!__::has($collection, $key)
|| (__::isObject($collection) && !__::isObject(__::get($collection, $key)))
|| (__::isArray($collection) && !__::isArray(__::get($collection, $key)))
) {
$collection = __::universalSet($collection, $key, __::isObject($collection) ? new stdClass : []);
}
return __::universalSet($collection, $key, __::set(__::get($collection, $key), $portions[1], $value));
} | php | public static function set($collection, $path, $value = null)
{
if ($path === null) {
return $collection;
}
$portions = __::split($path, '.', 2);
$key = $portions[0];
if (count($portions) === 1) {
return __::universalSet($collection, $key, $value);
}
// Here we manage the case where the portion of the path points to nothing,
// or to a value that does not match the type of the source collection
// (e.g. the path portion 'foo.bar' points to an integer value, while we
// want to set a string at 'foo.bar.fun'. We first set an object or array
// - following the current collection type - to 'for.bar' before setting
// 'foo.bar.fun' to the specified value).
if (!__::has($collection, $key)
|| (__::isObject($collection) && !__::isObject(__::get($collection, $key)))
|| (__::isArray($collection) && !__::isArray(__::get($collection, $key)))
) {
$collection = __::universalSet($collection, $key, __::isObject($collection) ? new stdClass : []);
}
return __::universalSet($collection, $key, __::set(__::get($collection, $key), $portions[1], $value));
} | [
"public",
"static",
"function",
"set",
"(",
"$",
"collection",
",",
"$",
"path",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"path",
"===",
"null",
")",
"{",
"return",
"$",
"collection",
";",
"}",
"$",
"portions",
"=",
"__",
"::",
"... | Return a new collection with the item set at index to given value.
Index can be a path of nested indexes.
If a portion of path doesn't exist, it's created. Arrays are created for missing
index in an array; objects are created for missing property in an object.
@usage __::set(['foo' => ['bar' => 'ter']], 'foo.baz.ber', 'fer');
>> '['foo' => ['bar' => 'ter', 'baz' => ['ber' => 'fer']]]'
@param array|object $collection collection of values
@param string|int|null $path key or index
@param mixed $value the value to set at position $key
@throws \Exception if the path consists of a non collection and strict is set to false
@return array|object the new collection with the item set | [
"Return",
"a",
"new",
"collection",
"with",
"the",
"item",
"set",
"at",
"index",
"to",
"given",
"value",
".",
"Index",
"can",
"be",
"a",
"path",
"of",
"nested",
"indexes",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L409-L433 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.concat | public static function concat($collection1, $collection2)
{
$isObject = __::isObject($collection1);
$args = __::map(func_get_args(), function ($arg) {
return (array)$arg;
});
$merged = call_user_func_array('array_merge', $args);
return $isObject ? (object)$merged : $merged;
} | php | public static function concat($collection1, $collection2)
{
$isObject = __::isObject($collection1);
$args = __::map(func_get_args(), function ($arg) {
return (array)$arg;
});
$merged = call_user_func_array('array_merge', $args);
return $isObject ? (object)$merged : $merged;
} | [
"public",
"static",
"function",
"concat",
"(",
"$",
"collection1",
",",
"$",
"collection2",
")",
"{",
"$",
"isObject",
"=",
"__",
"::",
"isObject",
"(",
"$",
"collection1",
")",
";",
"$",
"args",
"=",
"__",
"::",
"map",
"(",
"func_get_args",
"(",
")",
... | Combines and concat collections provided with each others.
If the collections have common keys, then the values are appended in an array.
If numerical indexes are passed, then values are appended.
For a recursive merge, see __::merge.
@usage __::concat(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
>> ['color' => ['favorite' => ['green'], 5, 'blue'], 3, 10]
@param array|object $collection1 Collection to assign to.
@param array|object $collection2 Other collections to assign.
@return array|object Assigned collection. | [
"Combines",
"and",
"concat",
"collections",
"provided",
"with",
"each",
"others",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L534-L545 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.concatDeep | public static function concatDeep($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
if (!__::has($result, $key)) {
$result = __::set($result, $key, $sourceValue);
} else {
if (is_numeric($key)) {
$result = __::concat($result, [$sourceValue]);
} else {
$resultValue = __::get($result, $key);
$result = __::set($result, $key, __::concatDeep(
__::isCollection($resultValue) ? $resultValue : (array)$resultValue,
__::isCollection($sourceValue) ? $sourceValue : (array)$sourceValue
));
}
}
});
return $result;
}, []);
} | php | public static function concatDeep($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
if (!__::has($result, $key)) {
$result = __::set($result, $key, $sourceValue);
} else {
if (is_numeric($key)) {
$result = __::concat($result, [$sourceValue]);
} else {
$resultValue = __::get($result, $key);
$result = __::set($result, $key, __::concatDeep(
__::isCollection($resultValue) ? $resultValue : (array)$resultValue,
__::isCollection($sourceValue) ? $sourceValue : (array)$sourceValue
));
}
}
});
return $result;
}, []);
} | [
"public",
"static",
"function",
"concatDeep",
"(",
"$",
"collection1",
",",
"$",
"collection2",
")",
"{",
"return",
"__",
"::",
"reduceRight",
"(",
"func_get_args",
"(",
")",
",",
"function",
"(",
"$",
"source",
",",
"$",
"result",
")",
"{",
"__",
"::",
... | Recursively combines and concat collections provided with each others.
If the collections have common keys, then the values are appended in an array.
If numerical indexes are passed, then values are appended.
For a non-recursive concat, see __::concat.
@usage __::concatDeep(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green',
'blue']]);
>> ['color' => ['favorite' => ['red', 'green'], 5, 'blue'], 3, 10]
@param array|object $collection1 First collection to concatDeep.
@param array|object $collection2 other collections to concatDeep.
@return array|object Concatenated collection. | [
"Recursively",
"combines",
"and",
"concat",
"collections",
"provided",
"with",
"each",
"others",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L564-L585 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.ease | public static function ease(array $collection, string $glue = '.'): array
{
$map = [];
__::internalEase($map, $collection, $glue);
return $map;
} | php | public static function ease(array $collection, string $glue = '.'): array
{
$map = [];
__::internalEase($map, $collection, $glue);
return $map;
} | [
"public",
"static",
"function",
"ease",
"(",
"array",
"$",
"collection",
",",
"string",
"$",
"glue",
"=",
"'.'",
")",
":",
"array",
"{",
"$",
"map",
"=",
"[",
"]",
";",
"__",
"::",
"internalEase",
"(",
"$",
"map",
",",
"$",
"collection",
",",
"$",
... | Flattens a complex collection by mapping each ending leafs value to a key consisting of all previous indexes.
@usage __::ease(['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]);
>> '['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']'
@param array $collection array of values
@param string $glue glue between key path
@return array flatten collection | [
"Flattens",
"a",
"complex",
"collection",
"by",
"mapping",
"each",
"ending",
"leafs",
"value",
"to",
"a",
"key",
"consisting",
"of",
"all",
"previous",
"indexes",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L598-L604 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.every | public static function every($collection, Closure $iterateFn): bool
{
$truthy = true;
__::doForEach(
$collection,
function ($value, $key, $collection) use (&$truthy, $iterateFn) {
$truthy = $truthy && $iterateFn($value, $key, $collection);
if (!$truthy) {
return false;
}
}
);
return $truthy;
} | php | public static function every($collection, Closure $iterateFn): bool
{
$truthy = true;
__::doForEach(
$collection,
function ($value, $key, $collection) use (&$truthy, $iterateFn) {
$truthy = $truthy && $iterateFn($value, $key, $collection);
if (!$truthy) {
return false;
}
}
);
return $truthy;
} | [
"public",
"static",
"function",
"every",
"(",
"$",
"collection",
",",
"Closure",
"$",
"iterateFn",
")",
":",
"bool",
"{",
"$",
"truthy",
"=",
"true",
";",
"__",
"::",
"doForEach",
"(",
"$",
"collection",
",",
"function",
"(",
"$",
"value",
",",
"$",
... | Checks if predicate returns truthy for all elements of collection.
Iteration is stopped once predicate returns falsey.
The predicate is invoked with three arguments: (value, index|key, collection).
@usage __::every([1, 3, 4], function ($v) { return is_int($v); });
>> true
@param array|object $collection The collection to iterate over.
@param \Closure $iterateFn The function to call for each value.
@return bool | [
"Checks",
"if",
"predicate",
"returns",
"truthy",
"for",
"all",
"elements",
"of",
"collection",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L639-L654 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.isEmpty | public static function isEmpty($value): bool
{
return (!__::isArray($value) && !__::isObject($value)) || count((array)$value) === 0;
} | php | public static function isEmpty($value): bool
{
return (!__::isArray($value) && !__::isObject($value)) || count((array)$value) === 0;
} | [
"public",
"static",
"function",
"isEmpty",
"(",
"$",
"value",
")",
":",
"bool",
"{",
"return",
"(",
"!",
"__",
"::",
"isArray",
"(",
"$",
"value",
")",
"&&",
"!",
"__",
"::",
"isObject",
"(",
"$",
"value",
")",
")",
"||",
"count",
"(",
"(",
"arra... | Check if value is an empty array or object. We consider any non enumerable as empty.
@usage __::isEmpty([]);
>> true
@param mixed $value The value to check for emptiness.
@return bool | [
"Check",
"if",
"value",
"is",
"an",
"empty",
"array",
"or",
"object",
".",
"We",
"consider",
"any",
"non",
"enumerable",
"as",
"empty",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L743-L746 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.mapKeys | public static function mapKeys(array $array, Closure $closure = null): array
{
if (is_null($closure)) {
$closure = '__::identity';
}
$resultArray = [];
foreach ($array as $key => $value) {
$newKey = call_user_func_array($closure, [$key, $value, $array]);
// key must be a number or string
if (!is_numeric($newKey) && !is_string($newKey)) {
throw new Exception('closure must returns a number or string');
}
$resultArray[$newKey] = $value;
}
return $resultArray;
} | php | public static function mapKeys(array $array, Closure $closure = null): array
{
if (is_null($closure)) {
$closure = '__::identity';
}
$resultArray = [];
foreach ($array as $key => $value) {
$newKey = call_user_func_array($closure, [$key, $value, $array]);
// key must be a number or string
if (!is_numeric($newKey) && !is_string($newKey)) {
throw new Exception('closure must returns a number or string');
}
$resultArray[$newKey] = $value;
}
return $resultArray;
} | [
"public",
"static",
"function",
"mapKeys",
"(",
"array",
"$",
"array",
",",
"Closure",
"$",
"closure",
"=",
"null",
")",
":",
"array",
"{",
"if",
"(",
"is_null",
"(",
"$",
"closure",
")",
")",
"{",
"$",
"closure",
"=",
"'__::identity'",
";",
"}",
"$"... | Transforms the keys in a collection by running each key through the iterator
@param array $array array of values
@param \Closure $closure closure to map the keys
@throws \Exception if closure doesn't return a valid key that can be used in PHP array
@return array | [
"Transforms",
"the",
"keys",
"in",
"a",
"collection",
"by",
"running",
"each",
"key",
"through",
"the",
"iterator"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L758-L774 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.mapValues | public static function mapValues(array $array, Closure $closure = null): array
{
if (is_null($closure)) {
$closure = '__::identity';
}
$resultArray = [];
foreach ($array as $key => $value) {
$resultArray[$key] = call_user_func_array($closure, [$value, $key, $array]);
}
return $resultArray;
} | php | public static function mapValues(array $array, Closure $closure = null): array
{
if (is_null($closure)) {
$closure = '__::identity';
}
$resultArray = [];
foreach ($array as $key => $value) {
$resultArray[$key] = call_user_func_array($closure, [$value, $key, $array]);
}
return $resultArray;
} | [
"public",
"static",
"function",
"mapValues",
"(",
"array",
"$",
"array",
",",
"Closure",
"$",
"closure",
"=",
"null",
")",
":",
"array",
"{",
"if",
"(",
"is_null",
"(",
"$",
"closure",
")",
")",
"{",
"$",
"closure",
"=",
"'__::identity'",
";",
"}",
"... | Transforms the values in a collection by running each value through the iterator
@param array $array array of values
@param \Closure $closure closure to map the values
@return array | [
"Transforms",
"the",
"values",
"in",
"a",
"collection",
"by",
"running",
"each",
"value",
"through",
"the",
"iterator"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L784-L795 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.merge | public static function merge($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
$value = $sourceValue;
if (__::isCollection($value)) {
$value = __::merge(__::get($result, $key), $sourceValue);
}
$result = __::set($result, $key, $value);
});
return $result;
}, []);
} | php | public static function merge($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
$value = $sourceValue;
if (__::isCollection($value)) {
$value = __::merge(__::get($result, $key), $sourceValue);
}
$result = __::set($result, $key, $value);
});
return $result;
}, []);
} | [
"public",
"static",
"function",
"merge",
"(",
"$",
"collection1",
",",
"$",
"collection2",
")",
"{",
"return",
"__",
"::",
"reduceRight",
"(",
"func_get_args",
"(",
")",
",",
"function",
"(",
"$",
"source",
",",
"$",
"result",
")",
"{",
"__",
"::",
"do... | Recursively combines and merge collections provided with each others.
If the collections have common keys, then the last passed keys override the previous.
If numerical indexes are passed, then last passed indexes override the previous.
For a non-recursive merge, see __::merge.
@usage __::merge(['color' => ['favorite' => 'red', 'model' => 3, 5], 3], [10, 'color' => ['favorite' => 'green',
'blue']]);
>> ['color' => ['favorite' => 'green', 'model' => 3, 'blue'], 10]
@param array|object $collection1 First collection to merge.
@param array|object $collection2 Other collections to merge.
@return array|object Concatenated collection. | [
"Recursively",
"combines",
"and",
"merge",
"collections",
"provided",
"with",
"each",
"others",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L814-L827 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.pick | public static function pick($collection = [], array $paths = [], $default = null)
{
return __::reduce($paths, function ($results, $path) use ($collection, $default) {
return __::set($results, $path, __::get($collection, $path, $default));
}, __::isObject($collection) ? new stdClass() : []);
} | php | public static function pick($collection = [], array $paths = [], $default = null)
{
return __::reduce($paths, function ($results, $path) use ($collection, $default) {
return __::set($results, $path, __::get($collection, $path, $default));
}, __::isObject($collection) ? new stdClass() : []);
} | [
"public",
"static",
"function",
"pick",
"(",
"$",
"collection",
"=",
"[",
"]",
",",
"array",
"$",
"paths",
"=",
"[",
"]",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"__",
"::",
"reduce",
"(",
"$",
"paths",
",",
"function",
"(",
"$",
"r... | Returns an array having only keys present in the given path list. Values for missing keys values will be filled
with provided default value.
@usage __::pick(['a' => 1, 'b' => ['c' => 3, 'd' => 4]], ['a', 'b.d']);
>> ['a' => 1, 'b' => ['d' => 4]]
@param array|object $collection The collection to iterate over.
@param array $paths array paths to pick
@param null $default
@return array|object | [
"Returns",
"an",
"array",
"having",
"only",
"keys",
"present",
"in",
"the",
"given",
"path",
"list",
".",
"Values",
"for",
"missing",
"keys",
"values",
"will",
"be",
"filled",
"with",
"provided",
"default",
"value",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L842-L847 | train |
me-io/php-lodash | src/Traits/Collections.php | Collections.unease | public static function unease(array $collection, string $separator = '.'): array
{
$nonDefaultSeparator = $separator !== '.';
$map = [];
foreach ($collection as $key => $value) {
$map = __::set(
$map,
$nonDefaultSeparator ? str_replace($separator, '.', $key) : $key,
$value
);
}
return $map;
} | php | public static function unease(array $collection, string $separator = '.'): array
{
$nonDefaultSeparator = $separator !== '.';
$map = [];
foreach ($collection as $key => $value) {
$map = __::set(
$map,
$nonDefaultSeparator ? str_replace($separator, '.', $key) : $key,
$value
);
}
return $map;
} | [
"public",
"static",
"function",
"unease",
"(",
"array",
"$",
"collection",
",",
"string",
"$",
"separator",
"=",
"'.'",
")",
":",
"array",
"{",
"$",
"nonDefaultSeparator",
"=",
"$",
"separator",
"!==",
"'.'",
";",
"$",
"map",
"=",
"[",
"]",
";",
"forea... | Builds a multidimensional collection out of a hash map using the key as indicator where to put the value.
@usage __::unease(['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']);
>> '['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]'
@param array $collection hash map of values
@param string $separator the glue used in the keys
@return array
@throws \Exception | [
"Builds",
"a",
"multidimensional",
"collection",
"out",
"of",
"a",
"hash",
"map",
"using",
"the",
"key",
"as",
"indicator",
"where",
"to",
"put",
"the",
"value",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Collections.php#L935-L949 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.patch | public static function patch(array $array, array $patches, string $parent = ''): array
{
foreach ($array as $key => $value) {
$z = $parent . '/' . $key;
if (isset($patches[$z])) {
$array[$key] = $patches[$z];
unset($patches[$z]);
if (!count($patches)) {
break;
}
}
if (is_array($value)) {
$array[$key] = static::patch($value, $patches, $z);
}
}
return $array;
} | php | public static function patch(array $array, array $patches, string $parent = ''): array
{
foreach ($array as $key => $value) {
$z = $parent . '/' . $key;
if (isset($patches[$z])) {
$array[$key] = $patches[$z];
unset($patches[$z]);
if (!count($patches)) {
break;
}
}
if (is_array($value)) {
$array[$key] = static::patch($value, $patches, $z);
}
}
return $array;
} | [
"public",
"static",
"function",
"patch",
"(",
"array",
"$",
"array",
",",
"array",
"$",
"patches",
",",
"string",
"$",
"parent",
"=",
"''",
")",
":",
"array",
"{",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
... | Patches array by xpath.
@usage __::patch(
['addr' => ['country' => 'US', 'zip' => 12345]],
['/addr/country' => 'CA','/addr/zip' => 54321]
);
* >> ['addr' => ['country' => 'CA', 'zip' => 54321]]
@param array $array The array to patch
@param array $patches List of new xpath-value pairs
@param string $parent
@return array Returns patched array | [
"Patches",
"array",
"by",
"xpath",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L122-L142 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.range | public static function range($start = null, $stop = null, int $step = 1): array
{
if ($stop == null && $start != null) {
$stop = $start;
$start = 1;
}
return range($start, $stop, $step);
} | php | public static function range($start = null, $stop = null, int $step = 1): array
{
if ($stop == null && $start != null) {
$stop = $start;
$start = 1;
}
return range($start, $stop, $step);
} | [
"public",
"static",
"function",
"range",
"(",
"$",
"start",
"=",
"null",
",",
"$",
"stop",
"=",
"null",
",",
"int",
"$",
"step",
"=",
"1",
")",
":",
"array",
"{",
"if",
"(",
"$",
"stop",
"==",
"null",
"&&",
"$",
"start",
"!=",
"null",
")",
"{",... | Generate range of values based on start , end and step
@usage __::range(1, 10, 2);
* >> [1, 3, 5, 7, 9]
@param int|null $start range start
@param int|null $stop range end
@param int $step range step value
@return array range of values | [
"Generate",
"range",
"of",
"values",
"based",
"on",
"start",
"end",
"and",
"step"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L174-L182 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.repeat | public static function repeat($object = '', int $times = null): array
{
$times = abs($times);
if ($times == null) {
return [];
}
return array_fill(0, $times, $object);
} | php | public static function repeat($object = '', int $times = null): array
{
$times = abs($times);
if ($times == null) {
return [];
}
return array_fill(0, $times, $object);
} | [
"public",
"static",
"function",
"repeat",
"(",
"$",
"object",
"=",
"''",
",",
"int",
"$",
"times",
"=",
"null",
")",
":",
"array",
"{",
"$",
"times",
"=",
"abs",
"(",
"$",
"times",
")",
";",
"if",
"(",
"$",
"times",
"==",
"null",
")",
"{",
"ret... | Generate array of repeated values
@usage __::repeat('foo', 3);
* >> ['foo', 'foo', 'foo']
@param string $object The object to repeat.
@param int $times ow many times has to be repeated.
@return array Returns a new array of filled values. | [
"Generate",
"array",
"of",
"repeated",
"values"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L196-L204 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.randomize | public static function randomize(array $array): array
{
for ($i = 0, $c = count($array); $i < $c - 1; $i++) {
$j = rand($i + 1, $c - 1);
list($array[$i], $array[$j]) = [$array[$j], $array[$i]];
}
return $array;
} | php | public static function randomize(array $array): array
{
for ($i = 0, $c = count($array); $i < $c - 1; $i++) {
$j = rand($i + 1, $c - 1);
list($array[$i], $array[$j]) = [$array[$j], $array[$i]];
}
return $array;
} | [
"public",
"static",
"function",
"randomize",
"(",
"array",
"$",
"array",
")",
":",
"array",
"{",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"c",
"=",
"count",
"(",
"$",
"array",
")",
";",
"$",
"i",
"<",
"$",
"c",
"-",
"1",
";",
"$",
"i",
"++... | Shuffle an array ensuring no item remains in the same position.
@usage __::randomize([1, 2, 3]);
>> [2, 3, 1]
@param array $array original array
@return array | [
"Shuffle",
"an",
"array",
"ensuring",
"no",
"item",
"remains",
"in",
"the",
"same",
"position",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L251-L259 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.intersection | public static function intersection(array $a, array $b): array
{
$a = (array)$a;
$b = (array)$b;
return array_values(array_intersect($a, $b));
} | php | public static function intersection(array $a, array $b): array
{
$a = (array)$a;
$b = (array)$b;
return array_values(array_intersect($a, $b));
} | [
"public",
"static",
"function",
"intersection",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"array",
"{",
"$",
"a",
"=",
"(",
"array",
")",
"$",
"a",
";",
"$",
"b",
"=",
"(",
"array",
")",
"$",
"b",
";",
"return",
"array_values",
... | Return an array with all elements found in both input arrays.
@usage __::intersection(["green", "red", "blue"], ["green", "yellow", "red"])
>> ["green", "red"]
@param array $a
@param array $b
@return array | [
"Return",
"an",
"array",
"with",
"all",
"elements",
"found",
"in",
"both",
"input",
"arrays",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L374-L380 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.intersects | public static function intersects(array $a, array $b): bool
{
$a = (array)$a;
$b = (array)$b;
return count(self::intersection($a, $b)) > 0;
} | php | public static function intersects(array $a, array $b): bool
{
$a = (array)$a;
$b = (array)$b;
return count(self::intersection($a, $b)) > 0;
} | [
"public",
"static",
"function",
"intersects",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"bool",
"{",
"$",
"a",
"=",
"(",
"array",
")",
"$",
"a",
";",
"$",
"b",
"=",
"(",
"array",
")",
"$",
"b",
";",
"return",
"count",
"(",
"se... | Return a boolean flag which indicates whether the two input arrays have any common elements.
@usage __::intersects(["green", "red", "blue"], ["green", "yellow", "red"])
>> true
@param array $a
@param array $b
@return bool | [
"Return",
"a",
"boolean",
"flag",
"which",
"indicates",
"whether",
"the",
"two",
"input",
"arrays",
"have",
"any",
"common",
"elements",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L393-L399 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.sortKeys | public static function sortKeys(array $array, string $direction = 'ASC')
{
$direction = (strtolower($direction) === 'desc') ? SORT_DESC : SORT_ASC;
if ($direction === SORT_ASC) {
ksort($array);
} else {
krsort($array);
}
return $array;
} | php | public static function sortKeys(array $array, string $direction = 'ASC')
{
$direction = (strtolower($direction) === 'desc') ? SORT_DESC : SORT_ASC;
if ($direction === SORT_ASC) {
ksort($array);
} else {
krsort($array);
}
return $array;
} | [
"public",
"static",
"function",
"sortKeys",
"(",
"array",
"$",
"array",
",",
"string",
"$",
"direction",
"=",
"'ASC'",
")",
"{",
"$",
"direction",
"=",
"(",
"strtolower",
"(",
"$",
"direction",
")",
"===",
"'desc'",
")",
"?",
"SORT_DESC",
":",
"SORT_ASC"... | Sort an array by key.
@usage __::sortKeys(['z' => 0, 'b' => 1, 'r' => 2])
>> ['b' => 1, 'r' => 2, 'z' => 0]
@param array $array
@param string $direction
@return mixed | [
"Sort",
"an",
"array",
"by",
"key",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L446-L456 | train |
me-io/php-lodash | src/Traits/Arrays.php | Arrays.without | public static function without(array $array, $remove, $preserveKeys = false): array
{
$remove = !is_array($remove) ? [$remove] : $remove;
$result = [];
foreach ($array as $key => $value) {
if (in_array($value, $remove)) {
continue;
}
if ($preserveKeys) {
$result[$key] = $value;
} else {
$result[] = $value;
}
}
return $result;
} | php | public static function without(array $array, $remove, $preserveKeys = false): array
{
$remove = !is_array($remove) ? [$remove] : $remove;
$result = [];
foreach ($array as $key => $value) {
if (in_array($value, $remove)) {
continue;
}
if ($preserveKeys) {
$result[$key] = $value;
} else {
$result[] = $value;
}
}
return $result;
} | [
"public",
"static",
"function",
"without",
"(",
"array",
"$",
"array",
",",
"$",
"remove",
",",
"$",
"preserveKeys",
"=",
"false",
")",
":",
"array",
"{",
"$",
"remove",
"=",
"!",
"is_array",
"(",
"$",
"remove",
")",
"?",
"[",
"$",
"remove",
"]",
"... | Remove unwanted values from array
@param array $array
@param array|string $remove
@param bool $preserveKeys , set true if you want to preserve the keys. by default false
@usage _::without([1,5=>3,2 => 4,5],2)
@return array | [
"Remove",
"unwanted",
"values",
"from",
"array"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Arrays.php#L469-L486 | train |
me-io/php-lodash | src/Traits/Functions.php | Functions.urlify | public static function urlify(string $string)
{
/* Proposed by:
* Søren Løvborg
* http://stackoverflow.com/users/136796/soren-lovborg
* http://stackoverflow.com/questions/17900004/turn-plain-text-urls-into-active-links-using-php/17900021#17900021
*/
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
return preg_replace_callback(
"&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
function ($match) {
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">' . $match[2] . $match[3] . $match[4] . '</a>';
},
htmlspecialchars($string)
);
} | php | public static function urlify(string $string)
{
/* Proposed by:
* Søren Løvborg
* http://stackoverflow.com/users/136796/soren-lovborg
* http://stackoverflow.com/questions/17900004/turn-plain-text-urls-into-active-links-using-php/17900021#17900021
*/
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
return preg_replace_callback(
"&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
function ($match) {
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">' . $match[2] . $match[3] . $match[4] . '</a>';
},
htmlspecialchars($string)
);
} | [
"public",
"static",
"function",
"urlify",
"(",
"string",
"$",
"string",
")",
"{",
"/* Proposed by:\n * Søren Løvborg\n * http://stackoverflow.com/users/136796/soren-lovborg\n * http://stackoverflow.com/questions/17900004/turn-plain-text-urls-into-active-links-using-php/17... | Find the urls inside a string a put them inside anchor tags.
@usage __::urlify("I love https://google.com");
>> 'I love <a href="https://google.com">google.com</a>'
@param string $string
@return string|mixed | [
"Find",
"the",
"urls",
"inside",
"a",
"string",
"a",
"put",
"them",
"inside",
"anchor",
"tags",
"."
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Functions.php#L372-L396 | train |
me-io/php-lodash | src/Traits/Functions.php | Functions.truncate | public static function truncate(string $text, int $limit = 40): string
{
if (str_word_count($text, 0) > $limit) {
$words = (array)str_word_count($text, 2);
$pos = array_keys($words);
$text = mb_substr($text, 0, $pos[$limit], 'UTF-8') . '...';
}
return $text;
} | php | public static function truncate(string $text, int $limit = 40): string
{
if (str_word_count($text, 0) > $limit) {
$words = (array)str_word_count($text, 2);
$pos = array_keys($words);
$text = mb_substr($text, 0, $pos[$limit], 'UTF-8') . '...';
}
return $text;
} | [
"public",
"static",
"function",
"truncate",
"(",
"string",
"$",
"text",
",",
"int",
"$",
"limit",
"=",
"40",
")",
":",
"string",
"{",
"if",
"(",
"str_word_count",
"(",
"$",
"text",
",",
"0",
")",
">",
"$",
"limit",
")",
"{",
"$",
"words",
"=",
"(... | Truncate string based on count of words
@usage $string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et mi orci.';
__::truncate($string);
>> 'Lorem ipsum dolor sit amet, consectetur...'
@param string $text text to truncate
@param integer $limit limit of words
@return string | [
"Truncate",
"string",
"based",
"on",
"count",
"of",
"words"
] | b91c31fe4a03f85d21923b56a8bb45bcd857fdda | https://github.com/me-io/php-lodash/blob/b91c31fe4a03f85d21923b56a8bb45bcd857fdda/src/Traits/Functions.php#L411-L420 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.validate | public function validate(&$error = null)
{
if (!$this->isCountryCodeValid()) {
$error = 'IBAN country code not valid or not supported';
} elseif (!$this->isLengthValid()) {
$error = 'IBAN length is invalid';
} elseif (!$this->isFormatValid()) {
$error = 'IBAN format is invalid';
} elseif (!$this->isChecksumValid()) {
$error = 'IBAN checksum is invalid';
} else {
$error = '';
return true;
}
return false;
} | php | public function validate(&$error = null)
{
if (!$this->isCountryCodeValid()) {
$error = 'IBAN country code not valid or not supported';
} elseif (!$this->isLengthValid()) {
$error = 'IBAN length is invalid';
} elseif (!$this->isFormatValid()) {
$error = 'IBAN format is invalid';
} elseif (!$this->isChecksumValid()) {
$error = 'IBAN checksum is invalid';
} else {
$error = '';
return true;
}
return false;
} | [
"public",
"function",
"validate",
"(",
"&",
"$",
"error",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isCountryCodeValid",
"(",
")",
")",
"{",
"$",
"error",
"=",
"'IBAN country code not valid or not supported'",
";",
"}",
"elseif",
"(",
"!",... | Validates the supplied IBAN and provides passthrough failure message when validation fails
@param null $error passthrough variable
@return bool | [
"Validates",
"the",
"supplied",
"IBAN",
"and",
"provides",
"passthrough",
"failure",
"message",
"when",
"validation",
"fails"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L159-L175 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.format | public function format()
{
return sprintf(
'%s %s %s',
$this->getCountryCode() . $this->getChecksum(),
substr($this->getInstituteIdentification(), 0, 4),
implode(' ', str_split($this->getBankAccountNumber(), 4))
);
} | php | public function format()
{
return sprintf(
'%s %s %s',
$this->getCountryCode() . $this->getChecksum(),
substr($this->getInstituteIdentification(), 0, 4),
implode(' ', str_split($this->getBankAccountNumber(), 4))
);
} | [
"public",
"function",
"format",
"(",
")",
"{",
"return",
"sprintf",
"(",
"'%s %s %s'",
",",
"$",
"this",
"->",
"getCountryCode",
"(",
")",
".",
"$",
"this",
"->",
"getChecksum",
"(",
")",
",",
"substr",
"(",
"$",
"this",
"->",
"getInstituteIdentification",... | Pretty print IBAN
@return string | [
"Pretty",
"print",
"IBAN"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L182-L190 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.getBankAccountNumber | public function getBankAccountNumber()
{
$countryCode = $this->getCountryCode();
$length = static::$ibanFormatMap[$countryCode][0] - static::INSTITUTE_IDENTIFICATION_LENGTH;
return substr($this->iban, static::BANK_ACCOUNT_NUMBER_OFFSET, $length);
} | php | public function getBankAccountNumber()
{
$countryCode = $this->getCountryCode();
$length = static::$ibanFormatMap[$countryCode][0] - static::INSTITUTE_IDENTIFICATION_LENGTH;
return substr($this->iban, static::BANK_ACCOUNT_NUMBER_OFFSET, $length);
} | [
"public",
"function",
"getBankAccountNumber",
"(",
")",
"{",
"$",
"countryCode",
"=",
"$",
"this",
"->",
"getCountryCode",
"(",
")",
";",
"$",
"length",
"=",
"static",
"::",
"$",
"ibanFormatMap",
"[",
"$",
"countryCode",
"]",
"[",
"0",
"]",
"-",
"static"... | Extract Bank Account number from IBAN
@return string | [
"Extract",
"Bank",
"Account",
"number",
"from",
"IBAN"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L237-L242 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.isLengthValid | private function isLengthValid()
{
$countryCode = $this->getCountryCode();
$validLength = static::COUNTRY_CODE_LENGTH + static::CHECKSUM_LENGTH + static::$ibanFormatMap[$countryCode][0];
return strlen($this->iban) === $validLength;
} | php | private function isLengthValid()
{
$countryCode = $this->getCountryCode();
$validLength = static::COUNTRY_CODE_LENGTH + static::CHECKSUM_LENGTH + static::$ibanFormatMap[$countryCode][0];
return strlen($this->iban) === $validLength;
} | [
"private",
"function",
"isLengthValid",
"(",
")",
"{",
"$",
"countryCode",
"=",
"$",
"this",
"->",
"getCountryCode",
"(",
")",
";",
"$",
"validLength",
"=",
"static",
"::",
"COUNTRY_CODE_LENGTH",
"+",
"static",
"::",
"CHECKSUM_LENGTH",
"+",
"static",
"::",
"... | Validate IBAN length boundaries
@return bool | [
"Validate",
"IBAN",
"length",
"boundaries"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L249-L255 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.isFormatValid | private function isFormatValid()
{
$countryCode = $this->getCountryCode();
$accountIdentification = $this->getAccountIdentification();
return !(preg_match('/' . static::$ibanFormatMap[$countryCode][1] . '/', $accountIdentification) !== 1);
} | php | private function isFormatValid()
{
$countryCode = $this->getCountryCode();
$accountIdentification = $this->getAccountIdentification();
return !(preg_match('/' . static::$ibanFormatMap[$countryCode][1] . '/', $accountIdentification) !== 1);
} | [
"private",
"function",
"isFormatValid",
"(",
")",
"{",
"$",
"countryCode",
"=",
"$",
"this",
"->",
"getCountryCode",
"(",
")",
";",
"$",
"accountIdentification",
"=",
"$",
"this",
"->",
"getAccountIdentification",
"(",
")",
";",
"return",
"!",
"(",
"preg_mat... | Validate the IBAN format according to the country code
@return bool | [
"Validate",
"the",
"IBAN",
"format",
"according",
"to",
"the",
"country",
"code"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L274-L280 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.isChecksumValid | private function isChecksumValid()
{
$countryCode = $this->getCountryCode();
$checksum = $this->getChecksum();
$accountIdentification = $this->getAccountIdentification();
$numericCountryCode = $this->getNumericCountryCode($countryCode);
$numericAccountIdentification = $this->getNumericAccountIdentification($accountIdentification);
$invertedIban = $numericAccountIdentification . $numericCountryCode . $checksum;
return $this->bcmod($invertedIban, 97) === '1';
} | php | private function isChecksumValid()
{
$countryCode = $this->getCountryCode();
$checksum = $this->getChecksum();
$accountIdentification = $this->getAccountIdentification();
$numericCountryCode = $this->getNumericCountryCode($countryCode);
$numericAccountIdentification = $this->getNumericAccountIdentification($accountIdentification);
$invertedIban = $numericAccountIdentification . $numericCountryCode . $checksum;
return $this->bcmod($invertedIban, 97) === '1';
} | [
"private",
"function",
"isChecksumValid",
"(",
")",
"{",
"$",
"countryCode",
"=",
"$",
"this",
"->",
"getCountryCode",
"(",
")",
";",
"$",
"checksum",
"=",
"$",
"this",
"->",
"getChecksum",
"(",
")",
";",
"$",
"accountIdentification",
"=",
"$",
"this",
"... | Validates if the checksum number is valid according to the IBAN
@return bool | [
"Validates",
"if",
"the",
"checksum",
"number",
"is",
"valid",
"according",
"to",
"the",
"IBAN"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L287-L297 | train |
cmpayments/iban | src/lib/IBAN.php | IBAN.getNumericRepresentation | private function getNumericRepresentation($letterRepresentation)
{
$numericRepresentation = '';
foreach (str_split($letterRepresentation) as $char) {
$ord = ord($char);
if ($ord >= 65 && $ord <= 90) {
$numericRepresentation .= (string) ($ord - 55);
} elseif ($ord >= 48 && $ord <= 57) {
$numericRepresentation .= (string) ($ord - 48);
}
}
return $numericRepresentation;
} | php | private function getNumericRepresentation($letterRepresentation)
{
$numericRepresentation = '';
foreach (str_split($letterRepresentation) as $char) {
$ord = ord($char);
if ($ord >= 65 && $ord <= 90) {
$numericRepresentation .= (string) ($ord - 55);
} elseif ($ord >= 48 && $ord <= 57) {
$numericRepresentation .= (string) ($ord - 48);
}
}
return $numericRepresentation;
} | [
"private",
"function",
"getNumericRepresentation",
"(",
"$",
"letterRepresentation",
")",
"{",
"$",
"numericRepresentation",
"=",
"''",
";",
"foreach",
"(",
"str_split",
"(",
"$",
"letterRepresentation",
")",
"as",
"$",
"char",
")",
"{",
"$",
"ord",
"=",
"ord"... | Retrieve numeric presentation of a letter part of the IBAN
@param $letterRepresentation
@return string | [
"Retrieve",
"numeric",
"presentation",
"of",
"a",
"letter",
"part",
"of",
"the",
"IBAN"
] | f3666e58a00f166e43eafc46a9b502ad971ca954 | https://github.com/cmpayments/iban/blob/f3666e58a00f166e43eafc46a9b502ad971ca954/src/lib/IBAN.php#L330-L344 | train |
philiplb/CRUDlex | src/CRUDlex/FileHandler.php | FileHandler.getPath | protected function getPath($entityName, Entity $entity, $field)
{
return $this->entityDefinition->getField($field, 'path').'/'.$entityName.'/'.$entity->get('id').'/'.$field;
} | php | protected function getPath($entityName, Entity $entity, $field)
{
return $this->entityDefinition->getField($field, 'path').'/'.$entityName.'/'.$entity->get('id').'/'.$field;
} | [
"protected",
"function",
"getPath",
"(",
"$",
"entityName",
",",
"Entity",
"$",
"entity",
",",
"$",
"field",
")",
"{",
"return",
"$",
"this",
"->",
"entityDefinition",
"->",
"getField",
"(",
"$",
"field",
",",
"'path'",
")",
".",
"'/'",
".",
"$",
"enti... | Constructs a file system path for the given parameters for storing the
file of the file field.
@param string $entityName
the entity name
@param Entity $entity
the entity
@param string $field
the file field in the entity
@return string
the constructed path for storing the file of the file field | [
"Constructs",
"a",
"file",
"system",
"path",
"for",
"the",
"given",
"parameters",
"for",
"storing",
"the",
"file",
"of",
"the",
"file",
"field",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/FileHandler.php#L50-L53 | train |
philiplb/CRUDlex | src/CRUDlex/FileHandler.php | FileHandler.performOnFiles | protected function performOnFiles(Entity $entity, $entityName, $function)
{
$fields = $this->entityDefinition->getEditableFieldNames();
foreach ($fields as $field) {
if ($this->entityDefinition->getType($field) == 'file') {
$function($entity, $entityName, $field);
}
}
} | php | protected function performOnFiles(Entity $entity, $entityName, $function)
{
$fields = $this->entityDefinition->getEditableFieldNames();
foreach ($fields as $field) {
if ($this->entityDefinition->getType($field) == 'file') {
$function($entity, $entityName, $field);
}
}
} | [
"protected",
"function",
"performOnFiles",
"(",
"Entity",
"$",
"entity",
",",
"$",
"entityName",
",",
"$",
"function",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"entityDefinition",
"->",
"getEditableFieldNames",
"(",
")",
";",
"foreach",
"(",
"$",
"... | Executes a function for each file field of this entity.
@param Entity $entity
the just created entity
@param string $entityName
the name of the entity as this class here is not aware of it
@param \Closure $function
the function to perform, takes $entity, $entityName and $field as parameter | [
"Executes",
"a",
"function",
"for",
"each",
"file",
"field",
"of",
"this",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/FileHandler.php#L65-L73 | train |
philiplb/CRUDlex | src/CRUDlex/FileHandler.php | FileHandler.shouldWriteFile | protected function shouldWriteFile(AbstractData $data, Request $request, Entity $entity, $entityName, $action)
{
$result = $data->getEvents()->shouldExecute($entity, 'before', $action);
if (!$result) {
return false;
}
$filesystem = $this->filesystem;
$this->performOnFiles($entity, $entityName, function($entity, $entityName, $field) use ($filesystem, $request) {
$file = $request->files->get($field);
if ($file !== null && $file->isValid()) {
$path = $this->getPath($entityName, $entity, $field);
$filename = $path.'/'.$file->getClientOriginalName();
if ($filesystem->has($filename)) {
$filesystem->delete($filename);
}
$stream = fopen($file->getRealPath(), 'r+');
$filesystem->writeStream($filename, $stream);
fclose($stream);
}
});
$data->getEvents()->shouldExecute($entity, 'after', $action);
return true;
} | php | protected function shouldWriteFile(AbstractData $data, Request $request, Entity $entity, $entityName, $action)
{
$result = $data->getEvents()->shouldExecute($entity, 'before', $action);
if (!$result) {
return false;
}
$filesystem = $this->filesystem;
$this->performOnFiles($entity, $entityName, function($entity, $entityName, $field) use ($filesystem, $request) {
$file = $request->files->get($field);
if ($file !== null && $file->isValid()) {
$path = $this->getPath($entityName, $entity, $field);
$filename = $path.'/'.$file->getClientOriginalName();
if ($filesystem->has($filename)) {
$filesystem->delete($filename);
}
$stream = fopen($file->getRealPath(), 'r+');
$filesystem->writeStream($filename, $stream);
fclose($stream);
}
});
$data->getEvents()->shouldExecute($entity, 'after', $action);
return true;
} | [
"protected",
"function",
"shouldWriteFile",
"(",
"AbstractData",
"$",
"data",
",",
"Request",
"$",
"request",
",",
"Entity",
"$",
"entity",
",",
"$",
"entityName",
",",
"$",
"action",
")",
"{",
"$",
"result",
"=",
"$",
"data",
"->",
"getEvents",
"(",
")"... | Writes the uploaded files.
@param AbstractData $data
the AbstractData instance who should receive the events
@param Request $request
the HTTP request containing the file data
@param Entity $entity
the just manipulated entity
@param string $entityName
the name of the entity as this class here is not aware of it
@param string $action
the name of the performed action
@return boolean
true if all before events passed | [
"Writes",
"the",
"uploaded",
"files",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/FileHandler.php#L92-L114 | train |
philiplb/CRUDlex | src/CRUDlex/FileHandler.php | FileHandler.deleteFiles | public function deleteFiles(AbstractData $data, Entity $entity, $entityName)
{
$result = $data->getEvents()->shouldExecute($entity, 'before', 'deleteFiles');
if (!$result) {
return false;
}
$this->performOnFiles($entity, $entityName, function($entity, $entityName, $field) {
// For now, we are defensive and don't delete ever. As soon as soft deletion is optional, files will get deleted.
});
$data->getEvents()->shouldExecute($entity, 'after', 'deleteFiles');
return true;
} | php | public function deleteFiles(AbstractData $data, Entity $entity, $entityName)
{
$result = $data->getEvents()->shouldExecute($entity, 'before', 'deleteFiles');
if (!$result) {
return false;
}
$this->performOnFiles($entity, $entityName, function($entity, $entityName, $field) {
// For now, we are defensive and don't delete ever. As soon as soft deletion is optional, files will get deleted.
});
$data->getEvents()->shouldExecute($entity, 'after', 'deleteFiles');
return true;
} | [
"public",
"function",
"deleteFiles",
"(",
"AbstractData",
"$",
"data",
",",
"Entity",
"$",
"entity",
",",
"$",
"entityName",
")",
"{",
"$",
"result",
"=",
"$",
"data",
"->",
"getEvents",
"(",
")",
"->",
"shouldExecute",
"(",
"$",
"entity",
",",
"'before'... | Deletes all files of an existing entity.
@param AbstractData $data
the AbstractData instance who should receive the events
@param Entity $entity
the entity to delete the files from
@param string $entityName
the name of the entity as this class here is not aware of it
@return boolean
true on successful deletion | [
"Deletes",
"all",
"files",
"of",
"an",
"existing",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/FileHandler.php#L181-L192 | train |
philiplb/CRUDlex | src/CRUDlex/FileHandler.php | FileHandler.deleteFile | public function deleteFile(AbstractData $data, Entity $entity, $entityName, $field)
{
$result = $data->getEvents()->shouldExecute($entity, 'before', 'deleteFile');
if (!$result) {
return false;
}
// For now, we are defensive and don't delete ever. As soon as soft deletion is optional, files will get deleted.
$data->getEvents()->shouldExecute($entity, 'after', 'deleteFile');
return true;
} | php | public function deleteFile(AbstractData $data, Entity $entity, $entityName, $field)
{
$result = $data->getEvents()->shouldExecute($entity, 'before', 'deleteFile');
if (!$result) {
return false;
}
// For now, we are defensive and don't delete ever. As soon as soft deletion is optional, files will get deleted.
$data->getEvents()->shouldExecute($entity, 'after', 'deleteFile');
return true;
} | [
"public",
"function",
"deleteFile",
"(",
"AbstractData",
"$",
"data",
",",
"Entity",
"$",
"entity",
",",
"$",
"entityName",
",",
"$",
"field",
")",
"{",
"$",
"result",
"=",
"$",
"data",
"->",
"getEvents",
"(",
")",
"->",
"shouldExecute",
"(",
"$",
"ent... | Deletes a specific file from an existing entity.
@param AbstractData $data
the AbstractData instance who should receive the events
@param Entity $entity
the entity to delete the file from
@param string $entityName
the name of the entity as this class here is not aware of it
@param string $field
the field of the entity containing the file to be deleted
@return bool true on successful deletion
true on successful deletion | [
"Deletes",
"a",
"specific",
"file",
"from",
"an",
"existing",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/FileHandler.php#L208-L217 | train |
philiplb/CRUDlex | src/CRUDlex/FileHandler.php | FileHandler.updateFiles | public function updateFiles(AbstractData $data, Request $request, Entity $entity, $entityName)
{
// With optional soft deletion, the file should be deleted first.
return $this->shouldWriteFile($data, $request, $entity, $entityName, 'updateFiles');
} | php | public function updateFiles(AbstractData $data, Request $request, Entity $entity, $entityName)
{
// With optional soft deletion, the file should be deleted first.
return $this->shouldWriteFile($data, $request, $entity, $entityName, 'updateFiles');
} | [
"public",
"function",
"updateFiles",
"(",
"AbstractData",
"$",
"data",
",",
"Request",
"$",
"request",
",",
"Entity",
"$",
"entity",
",",
"$",
"entityName",
")",
"{",
"// With optional soft deletion, the file should be deleted first.",
"return",
"$",
"this",
"->",
"... | Updates the uploaded files of an updated entity.
@param AbstractData $data
the AbstractData instance who should receive the events
@param Request $request
the HTTP request containing the file data
@param Entity $entity
the updated entity
@param string $entityName
the name of the entity as this class here is not aware of it
@return boolean
true on successful update | [
"Updates",
"the",
"uploaded",
"files",
"of",
"an",
"updated",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/FileHandler.php#L254-L258 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.getLocales | public static function getLocales()
{
$localeDir = __DIR__.'/../locales';
$languageFiles = scandir($localeDir);
$locales = [];
foreach ($languageFiles as $languageFile) {
if (in_array($languageFile, ['.', '..'])) {
continue;
}
$extensionPos = strpos($languageFile, '.yml');
if ($extensionPos !== false) {
$locale = substr($languageFile, 0, $extensionPos);
$locales[] = $locale;
}
}
sort($locales);
return $locales;
} | php | public static function getLocales()
{
$localeDir = __DIR__.'/../locales';
$languageFiles = scandir($localeDir);
$locales = [];
foreach ($languageFiles as $languageFile) {
if (in_array($languageFile, ['.', '..'])) {
continue;
}
$extensionPos = strpos($languageFile, '.yml');
if ($extensionPos !== false) {
$locale = substr($languageFile, 0, $extensionPos);
$locales[] = $locale;
}
}
sort($locales);
return $locales;
} | [
"public",
"static",
"function",
"getLocales",
"(",
")",
"{",
"$",
"localeDir",
"=",
"__DIR__",
".",
"'/../locales'",
";",
"$",
"languageFiles",
"=",
"scandir",
"(",
"$",
"localeDir",
")",
";",
"$",
"locales",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"l... | Gets the available locales.
@return array
the available locales | [
"Gets",
"the",
"available",
"locales",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L57-L74 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.initChildren | protected function initChildren()
{
foreach ($this->datas as $name => $data) {
$fields = $data->getDefinition()->getFieldNames();
foreach ($fields as $field) {
if ($data->getDefinition()->getType($field) == 'reference') {
$this->datas[$data->getDefinition()->getSubTypeField($field, 'reference', 'entity')]->getDefinition()->addChild($data->getDefinition()->getTable(), $field, $name);
}
}
}
} | php | protected function initChildren()
{
foreach ($this->datas as $name => $data) {
$fields = $data->getDefinition()->getFieldNames();
foreach ($fields as $field) {
if ($data->getDefinition()->getType($field) == 'reference') {
$this->datas[$data->getDefinition()->getSubTypeField($field, 'reference', 'entity')]->getDefinition()->addChild($data->getDefinition()->getTable(), $field, $name);
}
}
}
} | [
"protected",
"function",
"initChildren",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"datas",
"as",
"$",
"name",
"=>",
"$",
"data",
")",
"{",
"$",
"fields",
"=",
"$",
"data",
"->",
"getDefinition",
"(",
")",
"->",
"getFieldNames",
"(",
")",
";"... | Initializes the children of the data entries. | [
"Initializes",
"the",
"children",
"of",
"the",
"data",
"entries",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L79-L89 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.getLocaleLabels | protected function getLocaleLabels(array $crud)
{
$locales = $this->getLocales();
$localeLabels = [];
foreach ($locales as $locale) {
if (array_key_exists('label_'.$locale, $crud)) {
$localeLabels[$locale] = $crud['label_'.$locale];
}
}
return $localeLabels;
} | php | protected function getLocaleLabels(array $crud)
{
$locales = $this->getLocales();
$localeLabels = [];
foreach ($locales as $locale) {
if (array_key_exists('label_'.$locale, $crud)) {
$localeLabels[$locale] = $crud['label_'.$locale];
}
}
return $localeLabels;
} | [
"protected",
"function",
"getLocaleLabels",
"(",
"array",
"$",
"crud",
")",
"{",
"$",
"locales",
"=",
"$",
"this",
"->",
"getLocales",
"(",
")",
";",
"$",
"localeLabels",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"locales",
"as",
"$",
"locale",
")",
"... | Gets a map with localized entity labels from the CRUD YML.
@param array $crud
the CRUD entity map
@return array
the map with localized entity labels | [
"Gets",
"a",
"map",
"with",
"localized",
"entity",
"labels",
"from",
"the",
"CRUD",
"YML",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L100-L110 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.configureDefinition | protected function configureDefinition(EntityDefinition $definition, array $crud)
{
$toConfigure = [
'deleteCascade',
'listFields',
'filter',
'childrenLabelFields',
'pageSize',
'initialSortField',
'initialSortAscending',
'navBarGroup',
'optimisticLocking',
'hardDeletion',
];
foreach ($toConfigure as $field) {
if (array_key_exists($field, $crud)) {
$function = 'set'.ucfirst($field);
$definition->$function($crud[$field]);
}
}
} | php | protected function configureDefinition(EntityDefinition $definition, array $crud)
{
$toConfigure = [
'deleteCascade',
'listFields',
'filter',
'childrenLabelFields',
'pageSize',
'initialSortField',
'initialSortAscending',
'navBarGroup',
'optimisticLocking',
'hardDeletion',
];
foreach ($toConfigure as $field) {
if (array_key_exists($field, $crud)) {
$function = 'set'.ucfirst($field);
$definition->$function($crud[$field]);
}
}
} | [
"protected",
"function",
"configureDefinition",
"(",
"EntityDefinition",
"$",
"definition",
",",
"array",
"$",
"crud",
")",
"{",
"$",
"toConfigure",
"=",
"[",
"'deleteCascade'",
",",
"'listFields'",
",",
"'filter'",
",",
"'childrenLabelFields'",
",",
"'pageSize'",
... | Configures the EntityDefinition according to the given
CRUD entity map.
@param EntityDefinition $definition
the definition to configure
@param array $crud
the CRUD entity map | [
"Configures",
"the",
"EntityDefinition",
"according",
"to",
"the",
"given",
"CRUD",
"entity",
"map",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L121-L141 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.createDefinition | protected function createDefinition(TranslatorInterface $translator, EntityDefinitionFactoryInterface $entityDefinitionFactory, array $crud, $name)
{
$label = array_key_exists('label', $crud) ? $crud['label'] : $name;
$localeLabels = $this->getLocaleLabels($crud);
$standardFieldLabels = [
'id' => $translator->trans('crudlex.label.id'),
'created_at' => $translator->trans('crudlex.label.created_at'),
'updated_at' => $translator->trans('crudlex.label.updated_at')
];
$definition = $entityDefinitionFactory->createEntityDefinition(
$crud['table'],
$crud['fields'],
$label,
$localeLabels,
$standardFieldLabels,
$this
);
$this->configureDefinition($definition, $crud);
return $definition;
} | php | protected function createDefinition(TranslatorInterface $translator, EntityDefinitionFactoryInterface $entityDefinitionFactory, array $crud, $name)
{
$label = array_key_exists('label', $crud) ? $crud['label'] : $name;
$localeLabels = $this->getLocaleLabels($crud);
$standardFieldLabels = [
'id' => $translator->trans('crudlex.label.id'),
'created_at' => $translator->trans('crudlex.label.created_at'),
'updated_at' => $translator->trans('crudlex.label.updated_at')
];
$definition = $entityDefinitionFactory->createEntityDefinition(
$crud['table'],
$crud['fields'],
$label,
$localeLabels,
$standardFieldLabels,
$this
);
$this->configureDefinition($definition, $crud);
return $definition;
} | [
"protected",
"function",
"createDefinition",
"(",
"TranslatorInterface",
"$",
"translator",
",",
"EntityDefinitionFactoryInterface",
"$",
"entityDefinitionFactory",
",",
"array",
"$",
"crud",
",",
"$",
"name",
")",
"{",
"$",
"label",
"=",
"array_key_exists",
"(",
"'... | Creates and setups an EntityDefinition instance.
@param TranslatorInterface $translator
the Translator to use for some standard field labels
@param EntityDefinitionFactoryInterface $entityDefinitionFactory
the EntityDefinitionFactory to use
@param array $crud
the parsed YAML of a CRUD entity
@param string $name
the name of the entity
@return EntityDefinition
the EntityDefinition good to go | [
"Creates",
"and",
"setups",
"an",
"EntityDefinition",
"instance",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L158-L178 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.getData | public function getData($name)
{
if (!array_key_exists($name, $this->datas)) {
return null;
}
return $this->datas[$name];
} | php | public function getData($name)
{
if (!array_key_exists($name, $this->datas)) {
return null;
}
return $this->datas[$name];
} | [
"public",
"function",
"getData",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"datas",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"datas",
"[",
"$",
"name",
... | Getter for the AbstractData instances.
@param string $name
the entity name of the desired Data instance
@return AbstractData
the AbstractData instance or null on invalid name | [
"Getter",
"for",
"the",
"AbstractData",
"instances",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L234-L240 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.getEntitiesNavBar | public function getEntitiesNavBar()
{
$result = [];
foreach ($this->datas as $entity => $data) {
$navBarGroup = $data->getDefinition()->getNavBarGroup();
if ($navBarGroup !== 'main') {
$result[$navBarGroup][] = $entity;
} else {
$result[$entity] = 'main';
}
}
return $result;
} | php | public function getEntitiesNavBar()
{
$result = [];
foreach ($this->datas as $entity => $data) {
$navBarGroup = $data->getDefinition()->getNavBarGroup();
if ($navBarGroup !== 'main') {
$result[$navBarGroup][] = $entity;
} else {
$result[$entity] = 'main';
}
}
return $result;
} | [
"public",
"function",
"getEntitiesNavBar",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"datas",
"as",
"$",
"entity",
"=>",
"$",
"data",
")",
"{",
"$",
"navBarGroup",
"=",
"$",
"data",
"->",
"getDefinition",
"(... | Getter for the entities for the navigation bar.
@return string[]
a list of all available entity names with their group | [
"Getter",
"for",
"the",
"entities",
"for",
"the",
"navigation",
"bar",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L259-L271 | train |
philiplb/CRUDlex | src/CRUDlex/Service.php | Service.setLocale | public function setLocale($locale)
{
foreach ($this->datas as $data) {
$data->getDefinition()->setLocale($locale);
}
} | php | public function setLocale($locale)
{
foreach ($this->datas as $data) {
$data->getDefinition()->setLocale($locale);
}
} | [
"public",
"function",
"setLocale",
"(",
"$",
"locale",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"datas",
"as",
"$",
"data",
")",
"{",
"$",
"data",
"->",
"getDefinition",
"(",
")",
"->",
"setLocale",
"(",
"$",
"locale",
")",
";",
"}",
"}"
] | Sets the locale to be used.
@param string $locale
the locale to be used. | [
"Sets",
"the",
"locale",
"to",
"be",
"used",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Service.php#L334-L339 | train |
philiplb/CRUDlex | src/CRUDlex/TwigExtensions.php | TwigExtensions.formatFloat | public function formatFloat($float)
{
if (!$float) {
return $float;
}
$zeroFraction = $float - floor($float) == 0 ? '0' : '';
// We don't want values like 0.004 converted to 0.00400000000000000008
if ($float > 0.0001) {
return $float.($zeroFraction === '0' ? '.'.$zeroFraction : '');
}
// We don't want values like 0.00004 converted to its scientific notation 4.0E-5
return rtrim(sprintf('%.20F', $float), '0').$zeroFraction;
} | php | public function formatFloat($float)
{
if (!$float) {
return $float;
}
$zeroFraction = $float - floor($float) == 0 ? '0' : '';
// We don't want values like 0.004 converted to 0.00400000000000000008
if ($float > 0.0001) {
return $float.($zeroFraction === '0' ? '.'.$zeroFraction : '');
}
// We don't want values like 0.00004 converted to its scientific notation 4.0E-5
return rtrim(sprintf('%.20F', $float), '0').$zeroFraction;
} | [
"public",
"function",
"formatFloat",
"(",
"$",
"float",
")",
"{",
"if",
"(",
"!",
"$",
"float",
")",
"{",
"return",
"$",
"float",
";",
"}",
"$",
"zeroFraction",
"=",
"$",
"float",
"-",
"floor",
"(",
"$",
"float",
")",
"==",
"0",
"?",
"'0'",
":",
... | Formats a float to not display in scientific notation.
@param float $float
the float to format
@return double|string
the formated float | [
"Formats",
"a",
"float",
"to",
"not",
"display",
"in",
"scientific",
"notation",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/TwigExtensions.php#L82-L98 | train |
philiplb/CRUDlex | src/CRUDlex/TwigExtensions.php | TwigExtensions.formatDate | public function formatDate($value, $isUTC)
{
$timezone = $isUTC ? 'UTC' : date_default_timezone_get();
return $this->formatTime($value, $timezone, 'Y-m-d');
} | php | public function formatDate($value, $isUTC)
{
$timezone = $isUTC ? 'UTC' : date_default_timezone_get();
return $this->formatTime($value, $timezone, 'Y-m-d');
} | [
"public",
"function",
"formatDate",
"(",
"$",
"value",
",",
"$",
"isUTC",
")",
"{",
"$",
"timezone",
"=",
"$",
"isUTC",
"?",
"'UTC'",
":",
"date_default_timezone_get",
"(",
")",
";",
"return",
"$",
"this",
"->",
"formatTime",
"(",
"$",
"value",
",",
"$... | Formats the given value to a date of the format 'Y-m-d'.
@param string $value
the value, might be of the format 'Y-m-d H:i' or 'Y-m-d'
@param boolean $isUTC
whether the given value is in UTC
@return string
the formatted result or an empty string on null value | [
"Formats",
"the",
"given",
"value",
"to",
"a",
"date",
"of",
"the",
"format",
"Y",
"-",
"m",
"-",
"d",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/TwigExtensions.php#L111-L115 | train |
philiplb/CRUDlex | src/CRUDlex/EntityValidator.php | EntityValidator.fieldTypeToRules | protected function fieldTypeToRules($field, AbstractData $data, Validator $validator)
{
$setItems = $this->definition->getField($field, 'items', []);
$rulesMapping = [
'boolean' => ['boolean'],
'float' => ['floating'],
'integer' => ['integer'],
'date' => ['dateTime', 'Y-m-d'],
'datetime' => ['or', $validator, ['dateTime', 'Y-m-d H:i'], ['dateTime', 'Y-m-d H:i:s']],
'set' => array_merge(['inSet'], $setItems),
'reference' => ['reference', $data, $field],
'many' => ['many', $data, $field]
];
$type = $this->definition->getType($field);
$rules = [];
if (array_key_exists($type, $rulesMapping)) {
$rules[] = $rulesMapping[$type];
}
return $rules;
} | php | protected function fieldTypeToRules($field, AbstractData $data, Validator $validator)
{
$setItems = $this->definition->getField($field, 'items', []);
$rulesMapping = [
'boolean' => ['boolean'],
'float' => ['floating'],
'integer' => ['integer'],
'date' => ['dateTime', 'Y-m-d'],
'datetime' => ['or', $validator, ['dateTime', 'Y-m-d H:i'], ['dateTime', 'Y-m-d H:i:s']],
'set' => array_merge(['inSet'], $setItems),
'reference' => ['reference', $data, $field],
'many' => ['many', $data, $field]
];
$type = $this->definition->getType($field);
$rules = [];
if (array_key_exists($type, $rulesMapping)) {
$rules[] = $rulesMapping[$type];
}
return $rules;
} | [
"protected",
"function",
"fieldTypeToRules",
"(",
"$",
"field",
",",
"AbstractData",
"$",
"data",
",",
"Validator",
"$",
"validator",
")",
"{",
"$",
"setItems",
"=",
"$",
"this",
"->",
"definition",
"->",
"getField",
"(",
"$",
"field",
",",
"'items'",
",",... | Builds up the validation rules for a single field according to the
entity definition type.
@param string $field
the field for the rules
@param AbstractData $data
the data instance to use for validation
@param Validator $validator
the validator to use
@return array
the validation rules for the field | [
"Builds",
"up",
"the",
"validation",
"rules",
"for",
"a",
"single",
"field",
"according",
"to",
"the",
"entity",
"definition",
"type",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityValidator.php#L50-L69 | train |
philiplb/CRUDlex | src/CRUDlex/EntityValidator.php | EntityValidator.fieldConstraintsToRules | protected function fieldConstraintsToRules($field, AbstractData $data)
{
$rules = [];
if ($this->definition->getField($field, 'required', false)) {
$rules[] = ['required'];
}
if ($this->definition->getField($field, 'unique', false)) {
$rules[] = ['unique', $data, $this->entity, $field];
}
return $rules;
} | php | protected function fieldConstraintsToRules($field, AbstractData $data)
{
$rules = [];
if ($this->definition->getField($field, 'required', false)) {
$rules[] = ['required'];
}
if ($this->definition->getField($field, 'unique', false)) {
$rules[] = ['unique', $data, $this->entity, $field];
}
return $rules;
} | [
"protected",
"function",
"fieldConstraintsToRules",
"(",
"$",
"field",
",",
"AbstractData",
"$",
"data",
")",
"{",
"$",
"rules",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"definition",
"->",
"getField",
"(",
"$",
"field",
",",
"'required'",
",",
... | Builds up the validation rules for a single field according to the
entity definition constraints.
@param string $field
the field for the rules
@param AbstractData $data
the data instance to use for validation
@return array
the validation rules for the field | [
"Builds",
"up",
"the",
"validation",
"rules",
"for",
"a",
"single",
"field",
"according",
"to",
"the",
"entity",
"definition",
"constraints",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityValidator.php#L84-L94 | train |
philiplb/CRUDlex | src/CRUDlex/EntityValidator.php | EntityValidator.buildUpData | protected function buildUpData()
{
$data = [];
$fields = $this->definition->getEditableFieldNames();
foreach ($fields as $field) {
$data[$field] = $this->entity->getRaw($field);
$fixed = $this->definition->getField($field, 'value');
if ($fixed) {
$data[$field] = $fixed;
}
}
return $data;
} | php | protected function buildUpData()
{
$data = [];
$fields = $this->definition->getEditableFieldNames();
foreach ($fields as $field) {
$data[$field] = $this->entity->getRaw($field);
$fixed = $this->definition->getField($field, 'value');
if ($fixed) {
$data[$field] = $fixed;
}
}
return $data;
} | [
"protected",
"function",
"buildUpData",
"(",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"fields",
"=",
"$",
"this",
"->",
"definition",
"->",
"getEditableFieldNames",
"(",
")",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"$... | Builds up the data to validate from the entity.
@return array
a map field to raw value | [
"Builds",
"up",
"the",
"data",
"to",
"validate",
"from",
"the",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityValidator.php#L129-L141 | train |
philiplb/CRUDlex | src/CRUDlex/EntityValidator.php | EntityValidator.validate | public function validate(AbstractData $data, $expectedVersion)
{
$validator = new Validator();
$validator->addValidator('unique', new UniqueValidator());
$validator->addValidator('reference', new ReferenceValidator());
$validator->addValidator('many', new ManyValidator());
$rules = $this->buildUpRules($data, $validator);
$toValidate = $this->buildUpData();
if ($this->definition->hasOptimisticLocking()) {
$rules['version'] = [['value', $expectedVersion]];
$toValidate['version'] = $this->entity->get('version');
}
$validation = $validator->isValid($rules, $toValidate);
return $validation;
} | php | public function validate(AbstractData $data, $expectedVersion)
{
$validator = new Validator();
$validator->addValidator('unique', new UniqueValidator());
$validator->addValidator('reference', new ReferenceValidator());
$validator->addValidator('many', new ManyValidator());
$rules = $this->buildUpRules($data, $validator);
$toValidate = $this->buildUpData();
if ($this->definition->hasOptimisticLocking()) {
$rules['version'] = [['value', $expectedVersion]];
$toValidate['version'] = $this->entity->get('version');
}
$validation = $validator->isValid($rules, $toValidate);
return $validation;
} | [
"public",
"function",
"validate",
"(",
"AbstractData",
"$",
"data",
",",
"$",
"expectedVersion",
")",
"{",
"$",
"validator",
"=",
"new",
"Validator",
"(",
")",
";",
"$",
"validator",
"->",
"addValidator",
"(",
"'unique'",
",",
"new",
"UniqueValidator",
"(",
... | Validates the entity against the definition.
@param AbstractData $data
the data access instance used for counting things
@param integer $expectedVersion
the version to perform the optimistic locking check on
@return array
an array with the fields "valid" and "errors"; valid provides a quick
check whether the given entity passes the validation and errors is an
array with all errored fields as keys and arrays as values; this field arrays
contains the actual errors on the field: "boolean", "floating", "integer",
"dateTime" (for dates and datetime fields), "inSet", "reference", "required",
"unique", "value" (only for the version field, set if the optimistic locking
failed). | [
"Validates",
"the",
"entity",
"against",
"the",
"definition",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityValidator.php#L174-L188 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.addSoftDeletionToQuery | protected function addSoftDeletionToQuery(EntityDefinition $definition, QueryBuilder $queryBuilder, $fieldPrefix = '', $method = 'andWhere')
{
if (!$definition->isHardDeletion()) {
$queryBuilder->$method($fieldPrefix.'deleted_at IS NULL');
}
} | php | protected function addSoftDeletionToQuery(EntityDefinition $definition, QueryBuilder $queryBuilder, $fieldPrefix = '', $method = 'andWhere')
{
if (!$definition->isHardDeletion()) {
$queryBuilder->$method($fieldPrefix.'deleted_at IS NULL');
}
} | [
"protected",
"function",
"addSoftDeletionToQuery",
"(",
"EntityDefinition",
"$",
"definition",
",",
"QueryBuilder",
"$",
"queryBuilder",
",",
"$",
"fieldPrefix",
"=",
"''",
",",
"$",
"method",
"=",
"'andWhere'",
")",
"{",
"if",
"(",
"!",
"$",
"definition",
"->... | Adds the soft deletion parameters if activated.
@param EntityDefinition $definition
the entity definition which might have soft deletion activated
@param QueryBuilder $queryBuilder
the query builder to add the deletion condition to
@param string $fieldPrefix
the prefix to add before the deleted_at field like an table alias
@param string $method
the method to use of the query builder, "where" or "andWhere" | [
"Adds",
"the",
"soft",
"deletion",
"parameters",
"if",
"activated",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L48-L53 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.setValuesAndParameters | protected function setValuesAndParameters(Entity $entity, QueryBuilder $queryBuilder, $setMethod)
{
$formFields = $this->getFormFields();
$count = count($formFields);
for ($i = 0; $i < $count; ++$i) {
$type = $this->definition->getType($formFields[$i]);
$value = $entity->get($formFields[$i]);
if ($type == 'boolean') {
$value = $value ? 1 : 0;
}
if ($type == 'reference' && is_array($value)) {
$value = $value['id'];
}
$queryBuilder->$setMethod('`'.$formFields[$i].'`', '?');
$queryBuilder->setParameter($i, $value);
}
} | php | protected function setValuesAndParameters(Entity $entity, QueryBuilder $queryBuilder, $setMethod)
{
$formFields = $this->getFormFields();
$count = count($formFields);
for ($i = 0; $i < $count; ++$i) {
$type = $this->definition->getType($formFields[$i]);
$value = $entity->get($formFields[$i]);
if ($type == 'boolean') {
$value = $value ? 1 : 0;
}
if ($type == 'reference' && is_array($value)) {
$value = $value['id'];
}
$queryBuilder->$setMethod('`'.$formFields[$i].'`', '?');
$queryBuilder->setParameter($i, $value);
}
} | [
"protected",
"function",
"setValuesAndParameters",
"(",
"Entity",
"$",
"entity",
",",
"QueryBuilder",
"$",
"queryBuilder",
",",
"$",
"setMethod",
")",
"{",
"$",
"formFields",
"=",
"$",
"this",
"->",
"getFormFields",
"(",
")",
";",
"$",
"count",
"=",
"count",... | Sets the values and parameters of the upcoming given query according
to the entity.
@param Entity $entity
the entity with its fields and values
@param QueryBuilder $queryBuilder
the upcoming query
@param string $setMethod
what method to use on the QueryBuilder: 'setValue' or 'set' | [
"Sets",
"the",
"values",
"and",
"parameters",
"of",
"the",
"upcoming",
"given",
"query",
"according",
"to",
"the",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L66-L82 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.hasChildren | protected function hasChildren($id)
{
foreach ($this->definition->getChildren() as $child) {
$queryBuilder = $this->database->createQueryBuilder();
$queryBuilder
->select('COUNT(id)')
->from('`'.$child[0].'`', '`'.$child[0].'`')
->where('`'.$child[1].'` = ?')
->setParameter(0, $id)
;
$this->addSoftDeletionToQuery($this->getDefinition()->getService()->getData($child[2])->getDefinition(), $queryBuilder);
$queryResult = $queryBuilder->execute();
$result = $queryResult->fetch(\PDO::FETCH_NUM);
if ($result[0] > 0) {
return true;
}
}
return false;
} | php | protected function hasChildren($id)
{
foreach ($this->definition->getChildren() as $child) {
$queryBuilder = $this->database->createQueryBuilder();
$queryBuilder
->select('COUNT(id)')
->from('`'.$child[0].'`', '`'.$child[0].'`')
->where('`'.$child[1].'` = ?')
->setParameter(0, $id)
;
$this->addSoftDeletionToQuery($this->getDefinition()->getService()->getData($child[2])->getDefinition(), $queryBuilder);
$queryResult = $queryBuilder->execute();
$result = $queryResult->fetch(\PDO::FETCH_NUM);
if ($result[0] > 0) {
return true;
}
}
return false;
} | [
"protected",
"function",
"hasChildren",
"(",
"$",
"id",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"definition",
"->",
"getChildren",
"(",
")",
"as",
"$",
"child",
")",
"{",
"$",
"queryBuilder",
"=",
"$",
"this",
"->",
"database",
"->",
"createQueryBui... | Checks whether the by id given entity still has children referencing it.
@param integer $id
the current entities id
@return boolean
true if the entity still has children | [
"Checks",
"whether",
"the",
"by",
"id",
"given",
"entity",
"still",
"has",
"children",
"referencing",
"it",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L93-L111 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.deleteManyToManyReferences | protected function deleteManyToManyReferences(Entity $entity)
{
foreach ($this->definition->getService()->getEntities() as $entityName) {
$data = $this->definition->getService()->getData($entityName);
foreach ($data->getDefinition()->getFieldNames(true) as $field) {
if ($data->getDefinition()->getType($field) == 'many') {
$otherEntity = $data->getDefinition()->getSubTypeField($field, 'many', 'entity');
$otherData = $this->definition->getService()->getData($otherEntity);
if ($entity->getDefinition()->getTable() == $otherData->getDefinition()->getTable()) {
$thatField = $data->getDefinition()->getSubTypeField($field, 'many', 'thatField');
$queryBuilder = $this->database->createQueryBuilder();
$queryBuilder
->delete('`'.$field.'`')
->where('`'.$thatField.'` = ?')
->setParameter(0, $entity->get('id'))
->execute()
;
}
}
}
}
} | php | protected function deleteManyToManyReferences(Entity $entity)
{
foreach ($this->definition->getService()->getEntities() as $entityName) {
$data = $this->definition->getService()->getData($entityName);
foreach ($data->getDefinition()->getFieldNames(true) as $field) {
if ($data->getDefinition()->getType($field) == 'many') {
$otherEntity = $data->getDefinition()->getSubTypeField($field, 'many', 'entity');
$otherData = $this->definition->getService()->getData($otherEntity);
if ($entity->getDefinition()->getTable() == $otherData->getDefinition()->getTable()) {
$thatField = $data->getDefinition()->getSubTypeField($field, 'many', 'thatField');
$queryBuilder = $this->database->createQueryBuilder();
$queryBuilder
->delete('`'.$field.'`')
->where('`'.$thatField.'` = ?')
->setParameter(0, $entity->get('id'))
->execute()
;
}
}
}
}
} | [
"protected",
"function",
"deleteManyToManyReferences",
"(",
"Entity",
"$",
"entity",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"definition",
"->",
"getService",
"(",
")",
"->",
"getEntities",
"(",
")",
"as",
"$",
"entityName",
")",
"{",
"$",
"data",
"="... | Deletes any many to many references pointing to the given entity.
@param Entity $entity
the referenced entity | [
"Deletes",
"any",
"many",
"to",
"many",
"references",
"pointing",
"to",
"the",
"given",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L119-L140 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.getManyIds | protected function getManyIds(array $fields, array $params)
{
$manyIds = [];
foreach ($fields as $field) {
$thisField = $this->definition->getSubTypeField($field, 'many', 'thisField');
$thatField = $this->definition->getSubTypeField($field, 'many', 'thatField');
$queryBuilder = $this->database->createQueryBuilder();
$queryBuilder
->select('`'.$thisField.'`')
->from($field)
->where('`'.$thatField.'` IN (?)')
->setParameter(0, array_column($params[$field], 'id'), Connection::PARAM_STR_ARRAY)
->groupBy('`'.$thisField.'`')
;
$queryResult = $queryBuilder->execute();
$manyResults = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
$manyIds = array_merge($manyIds, array_column($manyResults, $thisField));
}
return $manyIds;
} | php | protected function getManyIds(array $fields, array $params)
{
$manyIds = [];
foreach ($fields as $field) {
$thisField = $this->definition->getSubTypeField($field, 'many', 'thisField');
$thatField = $this->definition->getSubTypeField($field, 'many', 'thatField');
$queryBuilder = $this->database->createQueryBuilder();
$queryBuilder
->select('`'.$thisField.'`')
->from($field)
->where('`'.$thatField.'` IN (?)')
->setParameter(0, array_column($params[$field], 'id'), Connection::PARAM_STR_ARRAY)
->groupBy('`'.$thisField.'`')
;
$queryResult = $queryBuilder->execute();
$manyResults = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
$manyIds = array_merge($manyIds, array_column($manyResults, $thisField));
}
return $manyIds;
} | [
"protected",
"function",
"getManyIds",
"(",
"array",
"$",
"fields",
",",
"array",
"$",
"params",
")",
"{",
"$",
"manyIds",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"$",
"thisField",
"=",
"$",
"this",
"->",
"d... | Gets all possible many-to-many ids existing for this definition.
@param array $fields
the many field names to fetch for
@param $params
the parameters the possible many field values to fetch for
@return array
an array of this many-to-many ids | [
"Gets",
"all",
"possible",
"many",
"-",
"to",
"-",
"many",
"ids",
"existing",
"for",
"this",
"definition",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L186-L206 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.addPagination | protected function addPagination(QueryBuilder $queryBuilder, $skip, $amount)
{
$queryBuilder->setMaxResults(9999999999);
if ($amount !== null) {
$queryBuilder->setMaxResults(abs(intval($amount)));
}
if ($skip !== null) {
$queryBuilder->setFirstResult(abs(intval($skip)));
}
} | php | protected function addPagination(QueryBuilder $queryBuilder, $skip, $amount)
{
$queryBuilder->setMaxResults(9999999999);
if ($amount !== null) {
$queryBuilder->setMaxResults(abs(intval($amount)));
}
if ($skip !== null) {
$queryBuilder->setFirstResult(abs(intval($skip)));
}
} | [
"protected",
"function",
"addPagination",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"$",
"skip",
",",
"$",
"amount",
")",
"{",
"$",
"queryBuilder",
"->",
"setMaxResults",
"(",
"9999999999",
")",
";",
"if",
"(",
"$",
"amount",
"!==",
"null",
")",
"{",
... | Adds pagination parameters to the query.
@param QueryBuilder $queryBuilder
the query
@param integer|null $skip
the rows to skip
@param integer|null $amount
the maximum amount of rows | [
"Adds",
"pagination",
"parameters",
"to",
"the",
"query",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L256-L265 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.fetchReferencesForField | protected function fetchReferencesForField(array &$entities, $field)
{
$nameField = $this->definition->getSubTypeField($field, 'reference', 'nameField');
$queryBuilder = $this->database->createQueryBuilder();
$ids = $this->getReferenceIds($entities, $field);
$referenceEntity = $this->definition->getSubTypeField($field, 'reference', 'entity');
$table = $this->definition->getService()->getData($referenceEntity)->getDefinition()->getTable();
$queryBuilder
->from('`'.$table.'`', '`'.$table.'`')
->where('id IN (?)')
;
$this->addSoftDeletionToQuery($this->definition, $queryBuilder);
if ($nameField) {
$queryBuilder->select('id', $nameField);
} else {
$queryBuilder->select('id');
}
$queryBuilder->setParameter(0, $ids, Connection::PARAM_STR_ARRAY);
$queryResult = $queryBuilder->execute();
$rows = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
$amount = count($entities);
foreach ($rows as $row) {
for ($i = 0; $i < $amount; ++$i) {
if ($entities[$i]->get($field) == $row['id']) {
$value = ['id' => $entities[$i]->get($field)];
if ($nameField) {
$value['name'] = $row[$nameField];
}
$entities[$i]->set($field, $value);
}
}
}
} | php | protected function fetchReferencesForField(array &$entities, $field)
{
$nameField = $this->definition->getSubTypeField($field, 'reference', 'nameField');
$queryBuilder = $this->database->createQueryBuilder();
$ids = $this->getReferenceIds($entities, $field);
$referenceEntity = $this->definition->getSubTypeField($field, 'reference', 'entity');
$table = $this->definition->getService()->getData($referenceEntity)->getDefinition()->getTable();
$queryBuilder
->from('`'.$table.'`', '`'.$table.'`')
->where('id IN (?)')
;
$this->addSoftDeletionToQuery($this->definition, $queryBuilder);
if ($nameField) {
$queryBuilder->select('id', $nameField);
} else {
$queryBuilder->select('id');
}
$queryBuilder->setParameter(0, $ids, Connection::PARAM_STR_ARRAY);
$queryResult = $queryBuilder->execute();
$rows = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
$amount = count($entities);
foreach ($rows as $row) {
for ($i = 0; $i < $amount; ++$i) {
if ($entities[$i]->get($field) == $row['id']) {
$value = ['id' => $entities[$i]->get($field)];
if ($nameField) {
$value['name'] = $row[$nameField];
}
$entities[$i]->set($field, $value);
}
}
}
} | [
"protected",
"function",
"fetchReferencesForField",
"(",
"array",
"&",
"$",
"entities",
",",
"$",
"field",
")",
"{",
"$",
"nameField",
"=",
"$",
"this",
"->",
"definition",
"->",
"getSubTypeField",
"(",
"$",
"field",
",",
"'reference'",
",",
"'nameField'",
"... | Adds the id and name of referenced entities to the given entities. The
reference field is before the raw id of the referenced entity and after
the fetch, it's an array with the keys id and name.
@param Entity[] &$entities
the entities to fetch the references for
@param string $field
the reference field | [
"Adds",
"the",
"id",
"and",
"name",
"of",
"referenced",
"entities",
"to",
"the",
"given",
"entities",
".",
"The",
"reference",
"field",
"is",
"before",
"the",
"raw",
"id",
"of",
"the",
"referenced",
"entity",
"and",
"after",
"the",
"fetch",
"it",
"s",
"a... | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L301-L337 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.generateUUID | protected function generateUUID()
{
$uuid = null;
if ($this->useUUIDs) {
$sql = 'SELECT UUID() as id';
$result = $this->database->fetchAssoc($sql);
$uuid = $result['id'];
}
return $uuid;
} | php | protected function generateUUID()
{
$uuid = null;
if ($this->useUUIDs) {
$sql = 'SELECT UUID() as id';
$result = $this->database->fetchAssoc($sql);
$uuid = $result['id'];
}
return $uuid;
} | [
"protected",
"function",
"generateUUID",
"(",
")",
"{",
"$",
"uuid",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"useUUIDs",
")",
"{",
"$",
"sql",
"=",
"'SELECT UUID() as id'",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"database",
"->",
"fetchAss... | Generates a new UUID.
@return string|null
the new UUID or null if this instance isn't configured to do so | [
"Generates",
"a",
"new",
"UUID",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L345-L354 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.enrichWithManyField | protected function enrichWithManyField(&$idToData, $manyField)
{
$queryBuilder = $this->database->createQueryBuilder();
$nameField = $this->definition->getSubTypeField($manyField, 'many', 'nameField');
$thisField = $this->definition->getSubTypeField($manyField, 'many', 'thisField');
$thatField = $this->definition->getSubTypeField($manyField, 'many', 'thatField');
$entity = $this->definition->getSubTypeField($manyField, 'many', 'entity');
$entityDefinition = $this->definition->getService()->getData($entity)->getDefinition();
$entityTable = $entityDefinition->getTable();
$nameSelect = $nameField !== null ? ', t2.`'.$nameField.'` AS name' : '';
$queryBuilder
->select('t1.`'.$thisField.'` AS this, t1.`'.$thatField.'` AS id'.$nameSelect)
->from('`'.$manyField.'`', 't1')
->leftJoin('t1', '`'.$entityTable.'`', 't2', 't2.id = t1.`'.$thatField.'`')
->where('t1.`'.$thisField.'` IN (?)')
;
$this->addSoftDeletionToQuery($entityDefinition, $queryBuilder);
$queryBuilder->setParameter(0, array_keys($idToData), Connection::PARAM_STR_ARRAY);
$queryResult = $queryBuilder->execute();
$manyReferences = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
foreach ($manyReferences as $manyReference) {
$entityId = $manyReference['this'];
unset($manyReference['this']);
$idToData[$entityId][$manyField][] = $manyReference;
}
} | php | protected function enrichWithManyField(&$idToData, $manyField)
{
$queryBuilder = $this->database->createQueryBuilder();
$nameField = $this->definition->getSubTypeField($manyField, 'many', 'nameField');
$thisField = $this->definition->getSubTypeField($manyField, 'many', 'thisField');
$thatField = $this->definition->getSubTypeField($manyField, 'many', 'thatField');
$entity = $this->definition->getSubTypeField($manyField, 'many', 'entity');
$entityDefinition = $this->definition->getService()->getData($entity)->getDefinition();
$entityTable = $entityDefinition->getTable();
$nameSelect = $nameField !== null ? ', t2.`'.$nameField.'` AS name' : '';
$queryBuilder
->select('t1.`'.$thisField.'` AS this, t1.`'.$thatField.'` AS id'.$nameSelect)
->from('`'.$manyField.'`', 't1')
->leftJoin('t1', '`'.$entityTable.'`', 't2', 't2.id = t1.`'.$thatField.'`')
->where('t1.`'.$thisField.'` IN (?)')
;
$this->addSoftDeletionToQuery($entityDefinition, $queryBuilder);
$queryBuilder->setParameter(0, array_keys($idToData), Connection::PARAM_STR_ARRAY);
$queryResult = $queryBuilder->execute();
$manyReferences = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
foreach ($manyReferences as $manyReference) {
$entityId = $manyReference['this'];
unset($manyReference['this']);
$idToData[$entityId][$manyField][] = $manyReference;
}
} | [
"protected",
"function",
"enrichWithManyField",
"(",
"&",
"$",
"idToData",
",",
"$",
"manyField",
")",
"{",
"$",
"queryBuilder",
"=",
"$",
"this",
"->",
"database",
"->",
"createQueryBuilder",
"(",
")",
";",
"$",
"nameField",
"=",
"$",
"this",
"->",
"defin... | Enriches the given mapping of entity id to raw entity data with some many-to-many data.
@param array $idToData
a reference to the map entity id to raw entity data
@param $manyField
the many field to enrich data with | [
"Enriches",
"the",
"given",
"mapping",
"of",
"entity",
"id",
"to",
"raw",
"entity",
"data",
"with",
"some",
"many",
"-",
"to",
"-",
"many",
"data",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L364-L389 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.enrichWithMany | protected function enrichWithMany(array $rows)
{
$manyFields = $this->getManyFields();
$idToData = [];
foreach ($rows as $row) {
foreach ($manyFields as $manyField) {
$row[$manyField] = [];
}
$idToData[$row['id']] = $row;
}
foreach ($manyFields as $manyField) {
$this->enrichWithManyField($idToData, $manyField);
}
return array_values($idToData);
} | php | protected function enrichWithMany(array $rows)
{
$manyFields = $this->getManyFields();
$idToData = [];
foreach ($rows as $row) {
foreach ($manyFields as $manyField) {
$row[$manyField] = [];
}
$idToData[$row['id']] = $row;
}
foreach ($manyFields as $manyField) {
$this->enrichWithManyField($idToData, $manyField);
}
return array_values($idToData);
} | [
"protected",
"function",
"enrichWithMany",
"(",
"array",
"$",
"rows",
")",
"{",
"$",
"manyFields",
"=",
"$",
"this",
"->",
"getManyFields",
"(",
")",
";",
"$",
"idToData",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"rows",
"as",
"$",
"row",
")",
"{",
... | Fetches to the rows belonging many-to-many entries and adds them to the rows.
@param array $rows
the rows to enrich
@return array
the enriched rows | [
"Fetches",
"to",
"the",
"rows",
"belonging",
"many",
"-",
"to",
"-",
"many",
"entries",
"and",
"adds",
"them",
"to",
"the",
"rows",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L399-L413 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.saveMany | protected function saveMany(Entity $entity)
{
$manyFields = $this->getManyFields();
$id = $entity->get('id');
foreach ($manyFields as $manyField) {
$thisField = '`'.$this->definition->getSubTypeField($manyField, 'many', 'thisField').'`';
$thatField = '`'.$this->definition->getSubTypeField($manyField, 'many', 'thatField').'`';
$this->database->delete($manyField, [$thisField => $id]);
$manyValues = $entity->get($manyField) ?: [];
foreach ($manyValues as $thatId) {
$this->database->insert($manyField, [
$thisField => $id,
$thatField => $thatId['id']
]);
}
}
} | php | protected function saveMany(Entity $entity)
{
$manyFields = $this->getManyFields();
$id = $entity->get('id');
foreach ($manyFields as $manyField) {
$thisField = '`'.$this->definition->getSubTypeField($manyField, 'many', 'thisField').'`';
$thatField = '`'.$this->definition->getSubTypeField($manyField, 'many', 'thatField').'`';
$this->database->delete($manyField, [$thisField => $id]);
$manyValues = $entity->get($manyField) ?: [];
foreach ($manyValues as $thatId) {
$this->database->insert($manyField, [
$thisField => $id,
$thatField => $thatId['id']
]);
}
}
} | [
"protected",
"function",
"saveMany",
"(",
"Entity",
"$",
"entity",
")",
"{",
"$",
"manyFields",
"=",
"$",
"this",
"->",
"getManyFields",
"(",
")",
";",
"$",
"id",
"=",
"$",
"entity",
"->",
"get",
"(",
"'id'",
")",
";",
"foreach",
"(",
"$",
"manyField... | First, deletes all to the given entity related many-to-many entries from the DB
and then writes them again.
@param Entity $entity
the entity to save the many-to-many entries of | [
"First",
"deletes",
"all",
"to",
"the",
"given",
"entity",
"related",
"many",
"-",
"to",
"-",
"many",
"entries",
"from",
"the",
"DB",
"and",
"then",
"writes",
"them",
"again",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L422-L438 | train |
philiplb/CRUDlex | src/CRUDlex/MySQLData.php | MySQLData.enrichWithReference | protected function enrichWithReference(array &$entities)
{
if (empty($entities)) {
return;
}
foreach ($this->definition->getFieldNames() as $field) {
if ($this->definition->getType($field) !== 'reference') {
continue;
}
$this->fetchReferencesForField($entities, $field);
}
} | php | protected function enrichWithReference(array &$entities)
{
if (empty($entities)) {
return;
}
foreach ($this->definition->getFieldNames() as $field) {
if ($this->definition->getType($field) !== 'reference') {
continue;
}
$this->fetchReferencesForField($entities, $field);
}
} | [
"protected",
"function",
"enrichWithReference",
"(",
"array",
"&",
"$",
"entities",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"entities",
")",
")",
"{",
"return",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"definition",
"->",
"getFieldNames",
"(",
")",
... | Adds the id and name of referenced entities to the given entities. Each
reference field is before the raw id of the referenced entity and after
the fetch, it's an array with the keys id and name.
@param Entity[] &$entities
the entities to fetch the references for
@return void | [
"Adds",
"the",
"id",
"and",
"name",
"of",
"referenced",
"entities",
"to",
"the",
"given",
"entities",
".",
"Each",
"reference",
"field",
"is",
"before",
"the",
"raw",
"id",
"of",
"the",
"referenced",
"entity",
"and",
"after",
"the",
"fetch",
"it",
"s",
"... | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/MySQLData.php#L450-L461 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.hydrate | protected function hydrate(array $row)
{
$fieldNames = $this->definition->getFieldNames(true);
$entity = new Entity($this->definition);
foreach ($fieldNames as $fieldName) {
$entity->set($fieldName, $row[$fieldName]);
}
return $entity;
} | php | protected function hydrate(array $row)
{
$fieldNames = $this->definition->getFieldNames(true);
$entity = new Entity($this->definition);
foreach ($fieldNames as $fieldName) {
$entity->set($fieldName, $row[$fieldName]);
}
return $entity;
} | [
"protected",
"function",
"hydrate",
"(",
"array",
"$",
"row",
")",
"{",
"$",
"fieldNames",
"=",
"$",
"this",
"->",
"definition",
"->",
"getFieldNames",
"(",
"true",
")",
";",
"$",
"entity",
"=",
"new",
"Entity",
"(",
"$",
"this",
"->",
"definition",
")... | Creates an Entity from the raw data array with the field name
as keys and field values as values.
@param array $row
the array with the raw data
@return Entity
the entity containing the array data then | [
"Creates",
"an",
"Entity",
"from",
"the",
"raw",
"data",
"array",
"with",
"the",
"field",
"name",
"as",
"keys",
"and",
"field",
"values",
"as",
"values",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L78-L86 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.getManyFields | protected function getManyFields()
{
$fields = $this->definition->getFieldNames(true);
return array_filter($fields, function($field) {
return $this->definition->getType($field) === 'many';
});
} | php | protected function getManyFields()
{
$fields = $this->definition->getFieldNames(true);
return array_filter($fields, function($field) {
return $this->definition->getType($field) === 'many';
});
} | [
"protected",
"function",
"getManyFields",
"(",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"definition",
"->",
"getFieldNames",
"(",
"true",
")",
";",
"return",
"array_filter",
"(",
"$",
"fields",
",",
"function",
"(",
"$",
"field",
")",
"{",
"retur... | Gets the many-to-many fields.
@return array|\string[]
the many-to-many fields | [
"Gets",
"the",
"many",
"-",
"to",
"-",
"many",
"fields",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L112-L118 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.getFormFields | protected function getFormFields()
{
$manyFields = $this->getManyFields();
$formFields = [];
foreach ($this->definition->getEditableFieldNames() as $field) {
if (!in_array($field, $manyFields)) {
$formFields[] = $field;
}
}
return $formFields;
} | php | protected function getFormFields()
{
$manyFields = $this->getManyFields();
$formFields = [];
foreach ($this->definition->getEditableFieldNames() as $field) {
if (!in_array($field, $manyFields)) {
$formFields[] = $field;
}
}
return $formFields;
} | [
"protected",
"function",
"getFormFields",
"(",
")",
"{",
"$",
"manyFields",
"=",
"$",
"this",
"->",
"getManyFields",
"(",
")",
";",
"$",
"formFields",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"definition",
"->",
"getEditableFieldNames",
"(",
... | Gets all form fields including the many-to-many-ones.
@return array
all form fields | [
"Gets",
"all",
"form",
"fields",
"including",
"the",
"many",
"-",
"to",
"-",
"many",
"-",
"ones",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L126-L136 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.deleteChildren | protected function deleteChildren($id, $deleteCascade)
{
foreach ($this->definition->getChildren() as $childArray) {
$childData = $this->definition->getService()->getData($childArray[2]);
$children = $childData->listEntries([$childArray[1] => $id]);
foreach ($children as $child) {
$result = $childData->events->shouldExecute($child, 'before', 'delete');
if (!$result) {
return static::DELETION_FAILED_EVENT;
}
$childData->doDelete($child, $deleteCascade);
$childData->events->shouldExecute($child, 'after', 'delete');
}
}
return static::DELETION_SUCCESS;
} | php | protected function deleteChildren($id, $deleteCascade)
{
foreach ($this->definition->getChildren() as $childArray) {
$childData = $this->definition->getService()->getData($childArray[2]);
$children = $childData->listEntries([$childArray[1] => $id]);
foreach ($children as $child) {
$result = $childData->events->shouldExecute($child, 'before', 'delete');
if (!$result) {
return static::DELETION_FAILED_EVENT;
}
$childData->doDelete($child, $deleteCascade);
$childData->events->shouldExecute($child, 'after', 'delete');
}
}
return static::DELETION_SUCCESS;
} | [
"protected",
"function",
"deleteChildren",
"(",
"$",
"id",
",",
"$",
"deleteCascade",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"definition",
"->",
"getChildren",
"(",
")",
"as",
"$",
"childArray",
")",
"{",
"$",
"childData",
"=",
"$",
"this",
"->",
... | Performs the cascading children deletion.
@param integer $id
the current entities id
@param boolean $deleteCascade
whether to delete children and sub children
@return integer
returns one of:
- AbstractData::DELETION_SUCCESS -> successful deletion
- AbstractData::DELETION_FAILED_STILL_REFERENCED -> failed deletion due to existing references
- AbstractData::DELETION_FAILED_EVENT -> failed deletion due to a failed before delete event | [
"Performs",
"the",
"cascading",
"children",
"deletion",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L152-L167 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.getReferenceIds | protected function getReferenceIds(array $entities, $field)
{
$ids = array_map(function(Entity $entity) use ($field) {
$id = $entity->get($field);
return is_array($id) ? $id['id'] : $id;
}, $entities);
return $ids;
} | php | protected function getReferenceIds(array $entities, $field)
{
$ids = array_map(function(Entity $entity) use ($field) {
$id = $entity->get($field);
return is_array($id) ? $id['id'] : $id;
}, $entities);
return $ids;
} | [
"protected",
"function",
"getReferenceIds",
"(",
"array",
"$",
"entities",
",",
"$",
"field",
")",
"{",
"$",
"ids",
"=",
"array_map",
"(",
"function",
"(",
"Entity",
"$",
"entity",
")",
"use",
"(",
"$",
"field",
")",
"{",
"$",
"id",
"=",
"$",
"entity... | Gets an array of reference ids for the given entities.
@param array $entities
the entities to extract the ids
@param string $field
the reference field
@return array
the extracted ids | [
"Gets",
"an",
"array",
"of",
"reference",
"ids",
"for",
"the",
"given",
"entities",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L180-L187 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.create | public function create(Entity $entity)
{
$result = $this->events->shouldExecute($entity, 'before', 'create');
if (!$result) {
return false;
}
$result = $this->doCreate($entity);
$this->events->shouldExecute($entity, 'after', 'create');
return $result;
} | php | public function create(Entity $entity)
{
$result = $this->events->shouldExecute($entity, 'before', 'create');
if (!$result) {
return false;
}
$result = $this->doCreate($entity);
$this->events->shouldExecute($entity, 'after', 'create');
return $result;
} | [
"public",
"function",
"create",
"(",
"Entity",
"$",
"entity",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"events",
"->",
"shouldExecute",
"(",
"$",
"entity",
",",
"'before'",
",",
"'create'",
")",
";",
"if",
"(",
"!",
"$",
"result",
")",
"{",
... | Persists the given entity as new entry in the datasource.
@param Entity $entity
the entity to persist
@return boolean
true on successful creation | [
"Persists",
"the",
"given",
"entity",
"as",
"new",
"entry",
"in",
"the",
"datasource",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L267-L276 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.update | public function update(Entity $entity)
{
if (!$this->events->shouldExecute($entity, 'before', 'update')) {
return false;
}
$result = $this->doUpdate($entity);
$this->events->shouldExecute($entity, 'after', 'update');
return $result;
} | php | public function update(Entity $entity)
{
if (!$this->events->shouldExecute($entity, 'before', 'update')) {
return false;
}
$result = $this->doUpdate($entity);
$this->events->shouldExecute($entity, 'after', 'update');
return $result;
} | [
"public",
"function",
"update",
"(",
"Entity",
"$",
"entity",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"events",
"->",
"shouldExecute",
"(",
"$",
"entity",
",",
"'before'",
",",
"'update'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"result... | Updates an existing entry in the datasource having the same id.
@param Entity $entity
the entity with the new data
@return boolean
true on successful update | [
"Updates",
"an",
"existing",
"entry",
"in",
"the",
"datasource",
"having",
"the",
"same",
"id",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L287-L295 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.delete | public function delete($entity)
{
$result = $this->events->shouldExecute($entity, 'before', 'delete');
if (!$result) {
return static::DELETION_FAILED_EVENT;
}
$result = $this->doDelete($entity, $this->definition->isDeleteCascade());
$this->events->shouldExecute($entity, 'after', 'delete');
return $result;
} | php | public function delete($entity)
{
$result = $this->events->shouldExecute($entity, 'before', 'delete');
if (!$result) {
return static::DELETION_FAILED_EVENT;
}
$result = $this->doDelete($entity, $this->definition->isDeleteCascade());
$this->events->shouldExecute($entity, 'after', 'delete');
return $result;
} | [
"public",
"function",
"delete",
"(",
"$",
"entity",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"events",
"->",
"shouldExecute",
"(",
"$",
"entity",
",",
"'before'",
",",
"'delete'",
")",
";",
"if",
"(",
"!",
"$",
"result",
")",
"{",
"return",
... | Deletes an entry from the datasource.
@param Entity $entity
the entity to delete
@return integer
returns one of:
- AbstractData::DELETION_SUCCESS -> successful deletion
- AbstractData::DELETION_FAILED_STILL_REFERENCED -> failed deletion due to existing references
- AbstractData::DELETION_FAILED_EVENT -> failed deletion due to a failed before delete event | [
"Deletes",
"an",
"entry",
"from",
"the",
"datasource",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L309-L318 | train |
philiplb/CRUDlex | src/CRUDlex/AbstractData.php | AbstractData.createEmpty | public function createEmpty()
{
$entity = new Entity($this->definition);
$fields = $this->definition->getEditableFieldNames();
foreach ($fields as $field) {
$value = null;
if ($this->definition->getType($field) == 'fixed') {
$value = $this->definition->getField($field, 'value');
}
$entity->set($field, $value);
}
$entity->set('id', null);
return $entity;
} | php | public function createEmpty()
{
$entity = new Entity($this->definition);
$fields = $this->definition->getEditableFieldNames();
foreach ($fields as $field) {
$value = null;
if ($this->definition->getType($field) == 'fixed') {
$value = $this->definition->getField($field, 'value');
}
$entity->set($field, $value);
}
$entity->set('id', null);
return $entity;
} | [
"public",
"function",
"createEmpty",
"(",
")",
"{",
"$",
"entity",
"=",
"new",
"Entity",
"(",
"$",
"this",
"->",
"definition",
")",
";",
"$",
"fields",
"=",
"$",
"this",
"->",
"definition",
"->",
"getEditableFieldNames",
"(",
")",
";",
"foreach",
"(",
... | Creates a new, empty entity instance having all fields prefilled with
null or the defined value in case of fixed fields.
@return Entity
the newly created entity | [
"Creates",
"a",
"new",
"empty",
"entity",
"instance",
"having",
"all",
"fields",
"prefilled",
"with",
"null",
"or",
"the",
"defined",
"value",
"in",
"case",
"of",
"fixed",
"fields",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/AbstractData.php#L386-L399 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.getFilteredFieldNames | protected function getFilteredFieldNames(array $exclude)
{
$fieldNames = $this->getFieldNames(true);
$result = [];
foreach ($fieldNames as $fieldName) {
if (!in_array($fieldName, $exclude)) {
$result[] = $fieldName;
}
}
return $result;
} | php | protected function getFilteredFieldNames(array $exclude)
{
$fieldNames = $this->getFieldNames(true);
$result = [];
foreach ($fieldNames as $fieldName) {
if (!in_array($fieldName, $exclude)) {
$result[] = $fieldName;
}
}
return $result;
} | [
"protected",
"function",
"getFilteredFieldNames",
"(",
"array",
"$",
"exclude",
")",
"{",
"$",
"fieldNames",
"=",
"$",
"this",
"->",
"getFieldNames",
"(",
"true",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"fieldNames",
"as",
"$",
... | Gets the field names exluding the given ones.
@param string[] $exclude
the field names to exclude
@return array
all field names excluding the given ones | [
"Gets",
"the",
"field",
"names",
"exluding",
"the",
"given",
"ones",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L141-L151 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.checkFieldNames | protected function checkFieldNames($reference, $fieldNames)
{
$validFieldNames = $this->getPublicFieldNames();
$invalidFieldNames = [];
foreach ($fieldNames as $fieldName) {
if (!in_array($fieldName, $validFieldNames)) {
$invalidFieldNames[] = $fieldName;
}
}
if (!empty($invalidFieldNames)) {
throw new \InvalidArgumentException('Invalid fields ('.join(', ', $invalidFieldNames).') in '.$reference.', valid ones are: '.join(', ', $validFieldNames));
}
} | php | protected function checkFieldNames($reference, $fieldNames)
{
$validFieldNames = $this->getPublicFieldNames();
$invalidFieldNames = [];
foreach ($fieldNames as $fieldName) {
if (!in_array($fieldName, $validFieldNames)) {
$invalidFieldNames[] = $fieldName;
}
}
if (!empty($invalidFieldNames)) {
throw new \InvalidArgumentException('Invalid fields ('.join(', ', $invalidFieldNames).') in '.$reference.', valid ones are: '.join(', ', $validFieldNames));
}
} | [
"protected",
"function",
"checkFieldNames",
"(",
"$",
"reference",
",",
"$",
"fieldNames",
")",
"{",
"$",
"validFieldNames",
"=",
"$",
"this",
"->",
"getPublicFieldNames",
"(",
")",
";",
"$",
"invalidFieldNames",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"f... | Checks whether the given field names are declared and existing.
@param string $reference
a hint towards the source of an invalid field name
@param array $fieldNames
the field names to check
@throws \InvalidArgumentException
thrown with all invalid field names | [
"Checks",
"whether",
"the",
"given",
"field",
"names",
"are",
"declared",
"and",
"existing",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L163-L175 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.getFieldNames | public function getFieldNames($includeMany = false)
{
$fieldNames = $this->getReadOnlyFields();
foreach ($this->fields as $field => $value) {
if ($includeMany || $this->getType($field) !== 'many') {
$fieldNames[] = $field;
}
}
return $fieldNames;
} | php | public function getFieldNames($includeMany = false)
{
$fieldNames = $this->getReadOnlyFields();
foreach ($this->fields as $field => $value) {
if ($includeMany || $this->getType($field) !== 'many') {
$fieldNames[] = $field;
}
}
return $fieldNames;
} | [
"public",
"function",
"getFieldNames",
"(",
"$",
"includeMany",
"=",
"false",
")",
"{",
"$",
"fieldNames",
"=",
"$",
"this",
"->",
"getReadOnlyFields",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"fields",
"as",
"$",
"field",
"=>",
"$",
"value",
... | Gets all field names, including the implicit ones like "id" or
"created_at".
@param boolean $includeMany
whether to include the many fields as well
@return string[]
the field names | [
"Gets",
"all",
"field",
"names",
"including",
"the",
"implicit",
"ones",
"like",
"id",
"or",
"created_at",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L225-L234 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.getFieldLabel | public function getFieldLabel($fieldName)
{
$result = $this->getField($fieldName, 'label_'.$this->locale, $this->getField($fieldName, 'label'));
if ($result === null && array_key_exists($fieldName, $this->standardFieldLabels)) {
$result = $this->standardFieldLabels[$fieldName];
}
if ($result === null) {
$result = $fieldName;
}
return $result;
} | php | public function getFieldLabel($fieldName)
{
$result = $this->getField($fieldName, 'label_'.$this->locale, $this->getField($fieldName, 'label'));
if ($result === null && array_key_exists($fieldName, $this->standardFieldLabels)) {
$result = $this->standardFieldLabels[$fieldName];
}
if ($result === null) {
$result = $fieldName;
}
return $result;
} | [
"public",
"function",
"getFieldLabel",
"(",
"$",
"fieldName",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"getField",
"(",
"$",
"fieldName",
",",
"'label_'",
".",
"$",
"this",
"->",
"locale",
",",
"$",
"this",
"->",
"getField",
"(",
"$",
"fieldNam... | Gets the label of a field.
@param string $fieldName
the field name
@return string
the label of the field or the field name if no label is set in the CRUD
YAML | [
"Gets",
"the",
"label",
"of",
"a",
"field",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L469-L482 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.getLabel | public function getLabel()
{
if ($this->locale && array_key_exists($this->locale, $this->localeLabels)) {
return $this->localeLabels[$this->locale];
}
return $this->label;
} | php | public function getLabel()
{
if ($this->locale && array_key_exists($this->locale, $this->localeLabels)) {
return $this->localeLabels[$this->locale];
}
return $this->label;
} | [
"public",
"function",
"getLabel",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"locale",
"&&",
"array_key_exists",
"(",
"$",
"this",
"->",
"locale",
",",
"$",
"this",
"->",
"localeLabels",
")",
")",
"{",
"return",
"$",
"this",
"->",
"localeLabels",
"["... | Gets the label for the entity.
@return string
the label for the entity | [
"Gets",
"the",
"label",
"for",
"the",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L525-L531 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.getSubTypeField | public function getSubTypeField($fieldName, $subType, $key)
{
if (!isset($this->fields[$fieldName][$subType][$key])) {
return null;
}
return $this->fields[$fieldName][$subType][$key];
} | php | public function getSubTypeField($fieldName, $subType, $key)
{
if (!isset($this->fields[$fieldName][$subType][$key])) {
return null;
}
return $this->fields[$fieldName][$subType][$key];
} | [
"public",
"function",
"getSubTypeField",
"(",
"$",
"fieldName",
",",
"$",
"subType",
",",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"fields",
"[",
"$",
"fieldName",
"]",
"[",
"$",
"subType",
"]",
"[",
"$",
"key",
"]",
... | Gets a sub field of an field.
@param string $fieldName
the field name of the sub type
@param string $subType
the sub type like "reference" or "many"
@param string $key
the key of the value
@return string
the value of the sub field | [
"Gets",
"a",
"sub",
"field",
"of",
"an",
"field",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L726-L734 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.getField | public function getField($name, $key, $default = null)
{
if (array_key_exists($name, $this->fields) && array_key_exists($key, $this->fields[$name])) {
return $this->fields[$name][$key];
}
return $default;
} | php | public function getField($name, $key, $default = null)
{
if (array_key_exists($name, $this->fields) && array_key_exists($key, $this->fields[$name])) {
return $this->fields[$name][$key];
}
return $default;
} | [
"public",
"function",
"getField",
"(",
"$",
"name",
",",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"fields",
")",
"&&",
"array_key_exists",
"(",
"$",
"key",
",",
... | Gets the value of a field key.
@param string $name
the name of the field
@param string $key
the value of the key
@param mixed $default
the default value to return if nothing is found
@return mixed
the value of the field key or null if not existing | [
"Gets",
"the",
"value",
"of",
"a",
"field",
"key",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L749-L755 | train |
philiplb/CRUDlex | src/CRUDlex/EntityDefinition.php | EntityDefinition.setField | public function setField($name, $key, $value)
{
if (!array_key_exists($name, $this->fields)) {
$this->fields[$name] = [];
}
$this->fields[$name][$key] = $value;
} | php | public function setField($name, $key, $value)
{
if (!array_key_exists($name, $this->fields)) {
$this->fields[$name] = [];
}
$this->fields[$name][$key] = $value;
} | [
"public",
"function",
"setField",
"(",
"$",
"name",
",",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"fields",
")",
")",
"{",
"$",
"this",
"->",
"fields",
"[",
"$",
"name"... | Sets the value of a field key. If the field or the key in the field
don't exist, they get created.
@param string $name
the name of the field
@param string $key
the value of the key
@param mixed $value
the new value | [
"Sets",
"the",
"value",
"of",
"a",
"field",
"key",
".",
"If",
"the",
"field",
"or",
"the",
"key",
"in",
"the",
"field",
"don",
"t",
"exist",
"they",
"get",
"created",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityDefinition.php#L768-L774 | train |
philiplb/CRUDlex | src/CRUDlex/Controller.php | Controller.modifyFilesAndSetFlashBag | protected function modifyFilesAndSetFlashBag(Request $request, AbstractData $crudData, Entity $instance, $entity, $mode)
{
$id = $instance->get('id');
$fileHandler = new FileHandler($this->filesystem, $crudData->getDefinition());
$result = $mode == 'edit' ? $fileHandler->updateFiles($crudData, $request, $instance, $entity) : $fileHandler->createFiles($crudData, $request, $instance, $entity);
if (!$result) {
return null;
}
$this->session->getFlashBag()->add('success', $this->translator->trans('crudlex.'.$mode.'.success', [
'%label%' => $crudData->getDefinition()->getLabel(),
'%id%' => $id
]));
return new RedirectResponse($this->service->generateURL('crudShow', ['entity' => $entity, 'id' => $id]));
} | php | protected function modifyFilesAndSetFlashBag(Request $request, AbstractData $crudData, Entity $instance, $entity, $mode)
{
$id = $instance->get('id');
$fileHandler = new FileHandler($this->filesystem, $crudData->getDefinition());
$result = $mode == 'edit' ? $fileHandler->updateFiles($crudData, $request, $instance, $entity) : $fileHandler->createFiles($crudData, $request, $instance, $entity);
if (!$result) {
return null;
}
$this->session->getFlashBag()->add('success', $this->translator->trans('crudlex.'.$mode.'.success', [
'%label%' => $crudData->getDefinition()->getLabel(),
'%id%' => $id
]));
return new RedirectResponse($this->service->generateURL('crudShow', ['entity' => $entity, 'id' => $id]));
} | [
"protected",
"function",
"modifyFilesAndSetFlashBag",
"(",
"Request",
"$",
"request",
",",
"AbstractData",
"$",
"crudData",
",",
"Entity",
"$",
"instance",
",",
"$",
"entity",
",",
"$",
"mode",
")",
"{",
"$",
"id",
"=",
"$",
"instance",
"->",
"get",
"(",
... | Postprocesses the entity after modification by handling the uploaded
files and setting the flash.
@param Request $request
the current request
@param AbstractData $crudData
the data instance of the entity
@param Entity $instance
the entity
@param string $entity
the name of the entity
@param string $mode
whether to 'edit' or to 'create' the entity
@return null|\Symfony\Component\HttpFoundation\RedirectResponse
the HTTP response of this modification | [
"Postprocesses",
"the",
"entity",
"after",
"modification",
"by",
"handling",
"the",
"uploaded",
"files",
"and",
"setting",
"the",
"flash",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Controller.php#L78-L91 | train |
philiplb/CRUDlex | src/CRUDlex/Controller.php | Controller.setValidationFailedFlashes | protected function setValidationFailedFlashes($optimisticLocking, $mode)
{
$this->session->getFlashBag()->add('danger', $this->translator->trans('crudlex.'.$mode.'.error'));
if ($optimisticLocking) {
$this->session->getFlashBag()->add('danger', $this->translator->trans('crudlex.edit.locked'));
}
} | php | protected function setValidationFailedFlashes($optimisticLocking, $mode)
{
$this->session->getFlashBag()->add('danger', $this->translator->trans('crudlex.'.$mode.'.error'));
if ($optimisticLocking) {
$this->session->getFlashBag()->add('danger', $this->translator->trans('crudlex.edit.locked'));
}
} | [
"protected",
"function",
"setValidationFailedFlashes",
"(",
"$",
"optimisticLocking",
",",
"$",
"mode",
")",
"{",
"$",
"this",
"->",
"session",
"->",
"getFlashBag",
"(",
")",
"->",
"add",
"(",
"'danger'",
",",
"$",
"this",
"->",
"translator",
"->",
"trans",
... | Sets the flashes of a failed entity modification.
@param boolean $optimisticLocking
whether the optimistic locking failed
@param string $mode
the modification mode, either 'create' or 'edit' | [
"Sets",
"the",
"flashes",
"of",
"a",
"failed",
"entity",
"modification",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Controller.php#L101-L107 | train |
philiplb/CRUDlex | src/CRUDlex/Controller.php | Controller.modifyEntity | protected function modifyEntity(Request $request, AbstractData $crudData, Entity $instance, $entity, $edit)
{
$fieldErrors = [];
$mode = $edit ? 'edit' : 'create';
if ($request->getMethod() == 'POST') {
$instance->populateViaRequest($request);
$validator = new EntityValidator($instance);
$validation = $validator->validate($crudData, intval($request->get('version')));
$fieldErrors = $validation['errors'];
if (!$validation['valid']) {
$optimisticLocking = isset($fieldErrors['version']);
$this->setValidationFailedFlashes($optimisticLocking, $mode);
} else {
$modified = $edit ? $crudData->update($instance) : $crudData->create($instance);
$response = $modified ? $this->modifyFilesAndSetFlashBag($request, $crudData, $instance, $entity, $mode) : false;
if ($response) {
return $response;
}
$this->session->getFlashBag()->add('danger', $this->translator->trans('crudlex.'.$mode.'.failed'));
}
}
return new Response($this->twig->render($this->service->getTemplate('template', 'form', $entity), [
'crud' => $this->service,
'crudEntity' => $entity,
'crudData' => $crudData,
'entity' => $instance,
'mode' => $mode,
'fieldErrors' => $fieldErrors,
'layout' => $this->service->getTemplate('layout', $mode, $entity)
]));
} | php | protected function modifyEntity(Request $request, AbstractData $crudData, Entity $instance, $entity, $edit)
{
$fieldErrors = [];
$mode = $edit ? 'edit' : 'create';
if ($request->getMethod() == 'POST') {
$instance->populateViaRequest($request);
$validator = new EntityValidator($instance);
$validation = $validator->validate($crudData, intval($request->get('version')));
$fieldErrors = $validation['errors'];
if (!$validation['valid']) {
$optimisticLocking = isset($fieldErrors['version']);
$this->setValidationFailedFlashes($optimisticLocking, $mode);
} else {
$modified = $edit ? $crudData->update($instance) : $crudData->create($instance);
$response = $modified ? $this->modifyFilesAndSetFlashBag($request, $crudData, $instance, $entity, $mode) : false;
if ($response) {
return $response;
}
$this->session->getFlashBag()->add('danger', $this->translator->trans('crudlex.'.$mode.'.failed'));
}
}
return new Response($this->twig->render($this->service->getTemplate('template', 'form', $entity), [
'crud' => $this->service,
'crudEntity' => $entity,
'crudData' => $crudData,
'entity' => $instance,
'mode' => $mode,
'fieldErrors' => $fieldErrors,
'layout' => $this->service->getTemplate('layout', $mode, $entity)
]));
} | [
"protected",
"function",
"modifyEntity",
"(",
"Request",
"$",
"request",
",",
"AbstractData",
"$",
"crudData",
",",
"Entity",
"$",
"instance",
",",
"$",
"entity",
",",
"$",
"edit",
")",
"{",
"$",
"fieldErrors",
"=",
"[",
"]",
";",
"$",
"mode",
"=",
"$"... | Validates and saves the new or updated entity and returns the appropriate HTTP
response.
@param Request $request
the current request
@param AbstractData $crudData
the data instance of the entity
@param Entity $instance
the entity
@param string $entity
the name of the entity
@param boolean $edit
whether to edit (true) or to create (false) the entity
@return Response
the HTTP response of this modification | [
"Validates",
"and",
"saves",
"the",
"new",
"or",
"updated",
"entity",
"and",
"returns",
"the",
"appropriate",
"HTTP",
"response",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Controller.php#L127-L159 | train |
philiplb/CRUDlex | src/CRUDlex/Controller.php | Controller.getAfterDeleteRedirectParameters | protected function getAfterDeleteRedirectParameters(Request $request, $entity, &$redirectPage)
{
$redirectPage = 'crudList';
$redirectParameters = ['entity' => $entity];
$redirectEntity = $request->get('redirectEntity');
$redirectId = $request->get('redirectId');
if ($redirectEntity && $redirectId) {
$redirectPage = 'crudShow';
$redirectParameters = [
'entity' => $redirectEntity,
'id' => $redirectId
];
}
return $redirectParameters;
} | php | protected function getAfterDeleteRedirectParameters(Request $request, $entity, &$redirectPage)
{
$redirectPage = 'crudList';
$redirectParameters = ['entity' => $entity];
$redirectEntity = $request->get('redirectEntity');
$redirectId = $request->get('redirectId');
if ($redirectEntity && $redirectId) {
$redirectPage = 'crudShow';
$redirectParameters = [
'entity' => $redirectEntity,
'id' => $redirectId
];
}
return $redirectParameters;
} | [
"protected",
"function",
"getAfterDeleteRedirectParameters",
"(",
"Request",
"$",
"request",
",",
"$",
"entity",
",",
"&",
"$",
"redirectPage",
")",
"{",
"$",
"redirectPage",
"=",
"'crudList'",
";",
"$",
"redirectParameters",
"=",
"[",
"'entity'",
"=>",
"$",
"... | Gets the parameters for the redirection after deleting an entity.
@param Request $request
the current request
@param string $entity
the entity name
@param string $redirectPage
reference, where the page to redirect to will be stored
@return array<string,string>
the parameters of the redirection, entity and id | [
"Gets",
"the",
"parameters",
"for",
"the",
"redirection",
"after",
"deleting",
"an",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Controller.php#L174-L188 | train |
philiplb/CRUDlex | src/CRUDlex/Controller.php | Controller.buildUpListFilter | protected function buildUpListFilter(Request $request, EntityDefinition $definition, &$filter, &$filterActive, &$filterToUse, &$filterOperators)
{
$rawFilter = [];
foreach ($definition->getFilter() as $filterField) {
$type = $definition->getType($filterField);
$filter[$filterField] = $request->get('crudFilter'.$filterField);
$rawFilter[$filterField] = $filter[$filterField];
if ($filter[$filterField]) {
$filterActive = true;
$filterToUse[$filterField] = $filter[$filterField];
$filterOperators[$filterField] = '=';
if ($type === 'boolean') {
$filterToUse[$filterField] = $filter[$filterField] == 'true' ? 1 : 0;
} else if ($type === 'reference') {
$filter[$filterField] = ['id' => $filter[$filterField]];
} else if ($type === 'many') {
$filter[$filterField] = array_map(function($value) {
return ['id' => $value];
}, $filter[$filterField]);
$filterToUse[$filterField] = $filter[$filterField];
} else if (in_array($type, ['text', 'multiline', 'fixed'])) {
$filterToUse[$filterField] = '%'.$filter[$filterField].'%';
$filterOperators[$filterField] = 'LIKE';
}
}
}
return $rawFilter;
} | php | protected function buildUpListFilter(Request $request, EntityDefinition $definition, &$filter, &$filterActive, &$filterToUse, &$filterOperators)
{
$rawFilter = [];
foreach ($definition->getFilter() as $filterField) {
$type = $definition->getType($filterField);
$filter[$filterField] = $request->get('crudFilter'.$filterField);
$rawFilter[$filterField] = $filter[$filterField];
if ($filter[$filterField]) {
$filterActive = true;
$filterToUse[$filterField] = $filter[$filterField];
$filterOperators[$filterField] = '=';
if ($type === 'boolean') {
$filterToUse[$filterField] = $filter[$filterField] == 'true' ? 1 : 0;
} else if ($type === 'reference') {
$filter[$filterField] = ['id' => $filter[$filterField]];
} else if ($type === 'many') {
$filter[$filterField] = array_map(function($value) {
return ['id' => $value];
}, $filter[$filterField]);
$filterToUse[$filterField] = $filter[$filterField];
} else if (in_array($type, ['text', 'multiline', 'fixed'])) {
$filterToUse[$filterField] = '%'.$filter[$filterField].'%';
$filterOperators[$filterField] = 'LIKE';
}
}
}
return $rawFilter;
} | [
"protected",
"function",
"buildUpListFilter",
"(",
"Request",
"$",
"request",
",",
"EntityDefinition",
"$",
"definition",
",",
"&",
"$",
"filter",
",",
"&",
"$",
"filterActive",
",",
"&",
"$",
"filterToUse",
",",
"&",
"$",
"filterOperators",
")",
"{",
"$",
... | Builds up the parameters of the list page filters.
@param Request $request
the current request
@param EntityDefinition $definition
the current entity definition
@param array &$filter
will hold a map of fields to request parameters for the filters
@param boolean $filterActive
reference, will be true if at least one filter is active
@param array $filterToUse
reference, will hold a map of fields to integers (0 or 1) which boolean filters are active
@param array $filterOperators
reference, will hold a map of fields to operators for AbstractData::listEntries()
@return array
the raw filter query parameters | [
"Builds",
"up",
"the",
"parameters",
"of",
"the",
"list",
"page",
"filters",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Controller.php#L209-L236 | train |
philiplb/CRUDlex | src/CRUDlex/Controller.php | Controller.getNotFoundPage | protected function getNotFoundPage($error)
{
return new Response($this->twig->render('@crud/notFound.twig', [
'crud' => $this->service,
'error' => $error,
'crudEntity' => '',
'layout' => $this->service->getTemplate('layout', '', '')
]), 404);
} | php | protected function getNotFoundPage($error)
{
return new Response($this->twig->render('@crud/notFound.twig', [
'crud' => $this->service,
'error' => $error,
'crudEntity' => '',
'layout' => $this->service->getTemplate('layout', '', '')
]), 404);
} | [
"protected",
"function",
"getNotFoundPage",
"(",
"$",
"error",
")",
"{",
"return",
"new",
"Response",
"(",
"$",
"this",
"->",
"twig",
"->",
"render",
"(",
"'@crud/notFound.twig'",
",",
"[",
"'crud'",
"=>",
"$",
"this",
"->",
"service",
",",
"'error'",
"=>"... | Generates the not found page.
@param string $error
the cause of the not found error
@return Response
the rendered not found page with the status code 404 | [
"Generates",
"the",
"not",
"found",
"page",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/Controller.php#L247-L255 | train |
philiplb/CRUDlex | src/CRUDlex/StreamedFileResponse.php | StreamedFileResponse.getStreamedFileFunction | public function getStreamedFileFunction($file)
{
return function() use ($file) {
set_time_limit(0);
$handle = fopen($file, 'rb');
if ($handle !== false) {
$chunkSize = 1024 * 1024;
while (!feof($handle)) {
$buffer = fread($handle, $chunkSize);
echo $buffer;
flush();
}
fclose($handle);
}
};
} | php | public function getStreamedFileFunction($file)
{
return function() use ($file) {
set_time_limit(0);
$handle = fopen($file, 'rb');
if ($handle !== false) {
$chunkSize = 1024 * 1024;
while (!feof($handle)) {
$buffer = fread($handle, $chunkSize);
echo $buffer;
flush();
}
fclose($handle);
}
};
} | [
"public",
"function",
"getStreamedFileFunction",
"(",
"$",
"file",
")",
"{",
"return",
"function",
"(",
")",
"use",
"(",
"$",
"file",
")",
"{",
"set_time_limit",
"(",
"0",
")",
";",
"$",
"handle",
"=",
"fopen",
"(",
"$",
"file",
",",
"'rb'",
")",
";"... | Generates a lambda which is streaming the given file to standard output.
@param string $file
the filename to stream
@return \Closure
the generated lambda | [
"Generates",
"a",
"lambda",
"which",
"is",
"streaming",
"the",
"given",
"file",
"to",
"standard",
"output",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/StreamedFileResponse.php#L30-L45 | train |
philiplb/CRUDlex | src/CRUDlex/EntityEvents.php | EntityEvents.shouldExecute | public function shouldExecute(Entity $entity, $moment, $action)
{
if (!isset($this->events[$moment.'.'.$action])) {
return true;
}
foreach ($this->events[$moment.'.'.$action] as $event) {
$result = $event($entity);
if (!$result) {
return false;
}
}
return true;
} | php | public function shouldExecute(Entity $entity, $moment, $action)
{
if (!isset($this->events[$moment.'.'.$action])) {
return true;
}
foreach ($this->events[$moment.'.'.$action] as $event) {
$result = $event($entity);
if (!$result) {
return false;
}
}
return true;
} | [
"public",
"function",
"shouldExecute",
"(",
"Entity",
"$",
"entity",
",",
"$",
"moment",
",",
"$",
"action",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"events",
"[",
"$",
"moment",
".",
"'.'",
".",
"$",
"action",
"]",
")",
")",
"... | Executes the event chain of an entity.
@param Entity $entity
the entity having the event chain to execute
@param string $moment
the "moment" of the event, can be either "before" or "after"
@param string $action
the "action" of the event, can be either "create", "update" or "delete"
@return boolean
true on successful execution of the full chain or false if it broke at
any point (and stopped the execution) | [
"Executes",
"the",
"event",
"chain",
"of",
"an",
"entity",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityEvents.php#L40-L52 | train |
philiplb/CRUDlex | src/CRUDlex/EntityEvents.php | EntityEvents.pop | public function pop($moment, $action)
{
if (array_key_exists($moment.'.'.$action, $this->events)) {
return array_pop($this->events[$moment.'.'.$action]);
}
return null;
} | php | public function pop($moment, $action)
{
if (array_key_exists($moment.'.'.$action, $this->events)) {
return array_pop($this->events[$moment.'.'.$action]);
}
return null;
} | [
"public",
"function",
"pop",
"(",
"$",
"moment",
",",
"$",
"action",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"moment",
".",
"'.'",
".",
"$",
"action",
",",
"$",
"this",
"->",
"events",
")",
")",
"{",
"return",
"array_pop",
"(",
"$",
"thi... | Removes and returns the latest event for the given parameters.
@param string $moment
the "moment" of the event, can be either "before" or "after"
@param string $action
the "action" of the event, can be either "create", "update" or "delete"
@return \Closure|null
the popped event or null if no event was available. | [
"Removes",
"and",
"returns",
"the",
"latest",
"event",
"for",
"the",
"given",
"parameters",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/EntityEvents.php#L88-L94 | train |
philiplb/CRUDlex | src/CRUDlex/UniqueValidator.php | UniqueValidator.isValidUniqueMany | protected function isValidUniqueMany(array $value, AbstractData $data, Entity $entity, $field)
{
return !$data->hasManySet($field, array_column($value, 'id'), $entity->get('id'));
} | php | protected function isValidUniqueMany(array $value, AbstractData $data, Entity $entity, $field)
{
return !$data->hasManySet($field, array_column($value, 'id'), $entity->get('id'));
} | [
"protected",
"function",
"isValidUniqueMany",
"(",
"array",
"$",
"value",
",",
"AbstractData",
"$",
"data",
",",
"Entity",
"$",
"entity",
",",
"$",
"field",
")",
"{",
"return",
"!",
"$",
"data",
"->",
"hasManySet",
"(",
"$",
"field",
",",
"array_column",
... | Checks whether the unique constraint is valid for a many-to-many field.
@param array $value
the value to check
@param AbstractData $data
the data to perform the check with
@param Entity $entity
the entity to perform the check on
@param $field
the many field to perform the check on
@return boolean
true if it is a valid unique many-to-many constraint | [
"Checks",
"whether",
"the",
"unique",
"constraint",
"is",
"valid",
"for",
"a",
"many",
"-",
"to",
"-",
"many",
"field",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/UniqueValidator.php#L37-L40 | train |
philiplb/CRUDlex | src/CRUDlex/UniqueValidator.php | UniqueValidator.isValidUnique | protected function isValidUnique($value, AbstractData $data, Entity $entity, $field, $type)
{
$params = [$field => $type === 'reference' ? $value['id'] : $value];
$paramsOperators = [$field => '='];
if ($entity->get('id') !== null) {
$params['id'] = $entity->get('id');
$paramsOperators['id'] = '!=';
}
$amount = intval($data->countBy($data->getDefinition()->getTable(), $params, $paramsOperators, true));
return $amount == 0;
} | php | protected function isValidUnique($value, AbstractData $data, Entity $entity, $field, $type)
{
$params = [$field => $type === 'reference' ? $value['id'] : $value];
$paramsOperators = [$field => '='];
if ($entity->get('id') !== null) {
$params['id'] = $entity->get('id');
$paramsOperators['id'] = '!=';
}
$amount = intval($data->countBy($data->getDefinition()->getTable(), $params, $paramsOperators, true));
return $amount == 0;
} | [
"protected",
"function",
"isValidUnique",
"(",
"$",
"value",
",",
"AbstractData",
"$",
"data",
",",
"Entity",
"$",
"entity",
",",
"$",
"field",
",",
"$",
"type",
")",
"{",
"$",
"params",
"=",
"[",
"$",
"field",
"=>",
"$",
"type",
"===",
"'reference'",
... | Performs the regular unique validation.
@param $value
the value to validate
@param $data
the data instance to validate with
@param $entity
the entity of the field
@param $field
the field to validate
@param $type
the type of the field to validate
@return boolean
true if everything is valid | [
"Performs",
"the",
"regular",
"unique",
"validation",
"."
] | 6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc | https://github.com/philiplb/CRUDlex/blob/6c6c9fe554134e6b300d576a1cf4447f3c7aa1dc/src/CRUDlex/UniqueValidator.php#L59-L69 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.