repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
vaniocz/stdlib | src/UniversalJsonSerializer.php | UniversalJsonSerializer.encode | private static function encode($value, SplObjectStorage $objectIds)
{
$encoded = [$value];
array_walk_recursive($encoded, function (&$value) use ($objectIds) {
if (!is_object($value)) {
return;
}
$isReference = isset($objectIds[$value]);
$meta = [
'#' => !$isReference ? $objectIds[$value] = count($objectIds) : $objectIds[$value],
'fqn' => get_class($value),
];
$value = ($isReference ? [] : self::encode(self::objectProperties($value), $objectIds)) + ['μ' => $meta];
});
return $encoded[0];
} | php | private static function encode($value, SplObjectStorage $objectIds)
{
$encoded = [$value];
array_walk_recursive($encoded, function (&$value) use ($objectIds) {
if (!is_object($value)) {
return;
}
$isReference = isset($objectIds[$value]);
$meta = [
'#' => !$isReference ? $objectIds[$value] = count($objectIds) : $objectIds[$value],
'fqn' => get_class($value),
];
$value = ($isReference ? [] : self::encode(self::objectProperties($value), $objectIds)) + ['μ' => $meta];
});
return $encoded[0];
} | [
"private",
"static",
"function",
"encode",
"(",
"$",
"value",
",",
"SplObjectStorage",
"$",
"objectIds",
")",
"{",
"$",
"encoded",
"=",
"[",
"$",
"value",
"]",
";",
"array_walk_recursive",
"(",
"$",
"encoded",
",",
"function",
"(",
"&",
"$",
"value",
")",
"use",
"(",
"$",
"objectIds",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"value",
")",
")",
"{",
"return",
";",
"}",
"$",
"isReference",
"=",
"isset",
"(",
"$",
"objectIds",
"[",
"$",
"value",
"]",
")",
";",
"$",
"meta",
"=",
"[",
"'#'",
"=>",
"!",
"$",
"isReference",
"?",
"$",
"objectIds",
"[",
"$",
"value",
"]",
"=",
"count",
"(",
"$",
"objectIds",
")",
":",
"$",
"objectIds",
"[",
"$",
"value",
"]",
",",
"'fqn'",
"=>",
"get_class",
"(",
"$",
"value",
")",
",",
"]",
";",
"$",
"value",
"=",
"(",
"$",
"isReference",
"?",
"[",
"]",
":",
"self",
"::",
"encode",
"(",
"self",
"::",
"objectProperties",
"(",
"$",
"value",
")",
",",
"$",
"objectIds",
")",
")",
"+",
"[",
"'μ' ",
"> ",
"m",
"eta]",
";",
"",
"}",
")",
";",
"return",
"$",
"encoded",
"[",
"0",
"]",
";",
"}"
] | Encode the given value into a normalized structure.
@param mixed $value The value to be encoded into a normalized structure.
@param SplObjectStorage $objectIds The set of IDs of all currently processed objects.
@return mixed The normalized structure. | [
"Encode",
"the",
"given",
"value",
"into",
"a",
"normalized",
"structure",
"."
] | train | https://github.com/vaniocz/stdlib/blob/06a8343c42829d8fdeecad2bb5c30946fbd73e74/src/UniversalJsonSerializer.php#L44-L63 |
vaniocz/stdlib | src/UniversalJsonSerializer.php | UniversalJsonSerializer.objectProperties | private static function objectProperties($object): array
{
if ($object instanceof Serializable) {
return ['$' => $object->serialize()];
}
$class = get_class($object);
$properties = [];
do {
try {
$properties += Closure::bind(function () use ($object) {
return get_object_vars($object);
}, null, $class)->__invoke();
} catch (Throwable $e) {
return get_object_vars($object);
}
} while ($class = get_parent_class($class));
return method_exists($object, '__sleep')
? array_intersect_key($properties, array_flip($object->__sleep()))
: $properties;
} | php | private static function objectProperties($object): array
{
if ($object instanceof Serializable) {
return ['$' => $object->serialize()];
}
$class = get_class($object);
$properties = [];
do {
try {
$properties += Closure::bind(function () use ($object) {
return get_object_vars($object);
}, null, $class)->__invoke();
} catch (Throwable $e) {
return get_object_vars($object);
}
} while ($class = get_parent_class($class));
return method_exists($object, '__sleep')
? array_intersect_key($properties, array_flip($object->__sleep()))
: $properties;
} | [
"private",
"static",
"function",
"objectProperties",
"(",
"$",
"object",
")",
":",
"array",
"{",
"if",
"(",
"$",
"object",
"instanceof",
"Serializable",
")",
"{",
"return",
"[",
"'$'",
"=>",
"$",
"object",
"->",
"serialize",
"(",
")",
"]",
";",
"}",
"$",
"class",
"=",
"get_class",
"(",
"$",
"object",
")",
";",
"$",
"properties",
"=",
"[",
"]",
";",
"do",
"{",
"try",
"{",
"$",
"properties",
"+=",
"Closure",
"::",
"bind",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"object",
")",
"{",
"return",
"get_object_vars",
"(",
"$",
"object",
")",
";",
"}",
",",
"null",
",",
"$",
"class",
")",
"->",
"__invoke",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"$",
"e",
")",
"{",
"return",
"get_object_vars",
"(",
"$",
"object",
")",
";",
"}",
"}",
"while",
"(",
"$",
"class",
"=",
"get_parent_class",
"(",
"$",
"class",
")",
")",
";",
"return",
"method_exists",
"(",
"$",
"object",
",",
"'__sleep'",
")",
"?",
"array_intersect_key",
"(",
"$",
"properties",
",",
"array_flip",
"(",
"$",
"object",
"->",
"__sleep",
"(",
")",
")",
")",
":",
"$",
"properties",
";",
"}"
] | Get array of all the object properties.
@param object $object
@return mixed[] The array of all the object properties. | [
"Get",
"array",
"of",
"all",
"the",
"object",
"properties",
"."
] | train | https://github.com/vaniocz/stdlib/blob/06a8343c42829d8fdeecad2bb5c30946fbd73e74/src/UniversalJsonSerializer.php#L72-L94 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php | ResolveBindingsPass.process | public function process(ContainerBuilder $container)
{
try {
parent::process($container);
foreach ($this->unusedBindings as list($key, $serviceId)) {
$message = sprintf('Unused binding "%s" in service "%s".', $key, $serviceId);
if ($this->errorMessages) {
$message .= sprintf("\nCould be related to%s:", 1 < \count($this->errorMessages) ? ' one of' : '');
}
foreach ($this->errorMessages as $m) {
$message .= "\n - ".$m;
}
throw new InvalidArgumentException($message);
}
} finally {
$this->usedBindings = array();
$this->unusedBindings = array();
$this->errorMessages = array();
}
} | php | public function process(ContainerBuilder $container)
{
try {
parent::process($container);
foreach ($this->unusedBindings as list($key, $serviceId)) {
$message = sprintf('Unused binding "%s" in service "%s".', $key, $serviceId);
if ($this->errorMessages) {
$message .= sprintf("\nCould be related to%s:", 1 < \count($this->errorMessages) ? ' one of' : '');
}
foreach ($this->errorMessages as $m) {
$message .= "\n - ".$m;
}
throw new InvalidArgumentException($message);
}
} finally {
$this->usedBindings = array();
$this->unusedBindings = array();
$this->errorMessages = array();
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"try",
"{",
"parent",
"::",
"process",
"(",
"$",
"container",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"unusedBindings",
"as",
"list",
"(",
"$",
"key",
",",
"$",
"serviceId",
")",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"'Unused binding \"%s\" in service \"%s\".'",
",",
"$",
"key",
",",
"$",
"serviceId",
")",
";",
"if",
"(",
"$",
"this",
"->",
"errorMessages",
")",
"{",
"$",
"message",
".=",
"sprintf",
"(",
"\"\\nCould be related to%s:\"",
",",
"1",
"<",
"\\",
"count",
"(",
"$",
"this",
"->",
"errorMessages",
")",
"?",
"' one of'",
":",
"''",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"errorMessages",
"as",
"$",
"m",
")",
"{",
"$",
"message",
".=",
"\"\\n - \"",
".",
"$",
"m",
";",
"}",
"throw",
"new",
"InvalidArgumentException",
"(",
"$",
"message",
")",
";",
"}",
"}",
"finally",
"{",
"$",
"this",
"->",
"usedBindings",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"unusedBindings",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"errorMessages",
"=",
"array",
"(",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php#L35-L55 |
phpgears/event-async | src/Discriminator/ArrayEventDiscriminator.php | ArrayEventDiscriminator.shouldEnqueue | public function shouldEnqueue(Event $event): bool
{
return \in_array(\get_class($event), $this->events, true);
} | php | public function shouldEnqueue(Event $event): bool
{
return \in_array(\get_class($event), $this->events, true);
} | [
"public",
"function",
"shouldEnqueue",
"(",
"Event",
"$",
"event",
")",
":",
"bool",
"{",
"return",
"\\",
"in_array",
"(",
"\\",
"get_class",
"(",
"$",
"event",
")",
",",
"$",
"this",
"->",
"events",
",",
"true",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/phpgears/event-async/blob/e2d72b32e8852ec3926636af1c686a7c582b0bca/src/Discriminator/ArrayEventDiscriminator.php#L38-L41 |
zodream/html | src/Dark/Input.php | Input.getColumnsSource | protected static function getColumnsSource($data, $value = 'name', $key = 'id', array $prepend = []) {
if (is_array($value)) {
list($prepend, $value, $key) = [$value, 'name', 'id'];
} elseif (is_array($key)) {
list($prepend, $key) = [$key, 'id'];
}
if (empty($data)) {
return $prepend;
}
foreach ($data as $item) {
// 支持值作为键值
if (is_numeric($item) || is_string($item)) {
$prepend[$item] = $item;
continue;
}
$prepend[$item[$key]] = $item[$value];
}
return $prepend;
} | php | protected static function getColumnsSource($data, $value = 'name', $key = 'id', array $prepend = []) {
if (is_array($value)) {
list($prepend, $value, $key) = [$value, 'name', 'id'];
} elseif (is_array($key)) {
list($prepend, $key) = [$key, 'id'];
}
if (empty($data)) {
return $prepend;
}
foreach ($data as $item) {
// 支持值作为键值
if (is_numeric($item) || is_string($item)) {
$prepend[$item] = $item;
continue;
}
$prepend[$item[$key]] = $item[$value];
}
return $prepend;
} | [
"protected",
"static",
"function",
"getColumnsSource",
"(",
"$",
"data",
",",
"$",
"value",
"=",
"'name'",
",",
"$",
"key",
"=",
"'id'",
",",
"array",
"$",
"prepend",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"list",
"(",
"$",
"prepend",
",",
"$",
"value",
",",
"$",
"key",
")",
"=",
"[",
"$",
"value",
",",
"'name'",
",",
"'id'",
"]",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"key",
")",
")",
"{",
"list",
"(",
"$",
"prepend",
",",
"$",
"key",
")",
"=",
"[",
"$",
"key",
",",
"'id'",
"]",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"return",
"$",
"prepend",
";",
"}",
"foreach",
"(",
"$",
"data",
"as",
"$",
"item",
")",
"{",
"// 支持值作为键值",
"if",
"(",
"is_numeric",
"(",
"$",
"item",
")",
"||",
"is_string",
"(",
"$",
"item",
")",
")",
"{",
"$",
"prepend",
"[",
"$",
"item",
"]",
"=",
"$",
"item",
";",
"continue",
";",
"}",
"$",
"prepend",
"[",
"$",
"item",
"[",
"$",
"key",
"]",
"]",
"=",
"$",
"item",
"[",
"$",
"value",
"]",
";",
"}",
"return",
"$",
"prepend",
";",
"}"
] | 转化为键值对数组
@param array $data
@param string $value
@param string $key
@param array $prepend
@return array|mixed | [
"转化为键值对数组"
] | train | https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/Dark/Input.php#L262-L280 |
wearenolte/wp-acf | src/Acf/Transforms/Repeater.php | Repeater.apply | public static function apply( $field ) {
if ( 'repeater' === $field['type'] && is_array( $field['value'] ) ) {
self::transform_image_fields( $field );
self::transform_to_object( $field );
}
return $field['value'];
} | php | public static function apply( $field ) {
if ( 'repeater' === $field['type'] && is_array( $field['value'] ) ) {
self::transform_image_fields( $field );
self::transform_to_object( $field );
}
return $field['value'];
} | [
"public",
"static",
"function",
"apply",
"(",
"$",
"field",
")",
"{",
"if",
"(",
"'repeater'",
"===",
"$",
"field",
"[",
"'type'",
"]",
"&&",
"is_array",
"(",
"$",
"field",
"[",
"'value'",
"]",
")",
")",
"{",
"self",
"::",
"transform_image_fields",
"(",
"$",
"field",
")",
";",
"self",
"::",
"transform_to_object",
"(",
"$",
"field",
")",
";",
"}",
"return",
"$",
"field",
"[",
"'value'",
"]",
";",
"}"
] | Apply the transforms
@param array $field The field.
@return array | [
"Apply",
"the",
"transforms"
] | train | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf/Transforms/Repeater.php#L17-L25 |
wearenolte/wp-acf | src/Acf/Transforms/Repeater.php | Repeater.transform_image_fields | public static function transform_image_fields( &$field ) {
if ( empty( $field['value'] ) ) {
return $field['value'];
}
foreach ( $field['sub_fields'] as $sub_field ) {
if ( 'image' === $sub_field['type'] && 'id' === $sub_field['return_format'] ) {
foreach ( $field['value'] as $id => $item ) {
$field['value'][ $id ][ $sub_field['name'] ] =
Image::get_image_fields( $field, $item[ $sub_field['name'] ], $sub_field['name'] );
}
}
}
} | php | public static function transform_image_fields( &$field ) {
if ( empty( $field['value'] ) ) {
return $field['value'];
}
foreach ( $field['sub_fields'] as $sub_field ) {
if ( 'image' === $sub_field['type'] && 'id' === $sub_field['return_format'] ) {
foreach ( $field['value'] as $id => $item ) {
$field['value'][ $id ][ $sub_field['name'] ] =
Image::get_image_fields( $field, $item[ $sub_field['name'] ], $sub_field['name'] );
}
}
}
} | [
"public",
"static",
"function",
"transform_image_fields",
"(",
"&",
"$",
"field",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"field",
"[",
"'value'",
"]",
")",
")",
"{",
"return",
"$",
"field",
"[",
"'value'",
"]",
";",
"}",
"foreach",
"(",
"$",
"field",
"[",
"'sub_fields'",
"]",
"as",
"$",
"sub_field",
")",
"{",
"if",
"(",
"'image'",
"===",
"$",
"sub_field",
"[",
"'type'",
"]",
"&&",
"'id'",
"===",
"$",
"sub_field",
"[",
"'return_format'",
"]",
")",
"{",
"foreach",
"(",
"$",
"field",
"[",
"'value'",
"]",
"as",
"$",
"id",
"=>",
"$",
"item",
")",
"{",
"$",
"field",
"[",
"'value'",
"]",
"[",
"$",
"id",
"]",
"[",
"$",
"sub_field",
"[",
"'name'",
"]",
"]",
"=",
"Image",
"::",
"get_image_fields",
"(",
"$",
"field",
",",
"$",
"item",
"[",
"$",
"sub_field",
"[",
"'name'",
"]",
"]",
",",
"$",
"sub_field",
"[",
"'name'",
"]",
")",
";",
"}",
"}",
"}",
"}"
] | Do the image size transform for an image sub fields.
@param string $field Field.
@return array | [
"Do",
"the",
"image",
"size",
"transform",
"for",
"an",
"image",
"sub",
"fields",
"."
] | train | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf/Transforms/Repeater.php#L33-L46 |
wearenolte/wp-acf | src/Acf/Transforms/Repeater.php | Repeater.transform_to_object | public static function transform_to_object( &$field ) {
if ( 1 !== count( $field['value'] ) ) {
return $field['value'];
}
$as_array = ! ( 1 === $field['min'] && 1 === $field['max'] );
$as_array = apply_filters( Filter::REPEATER_AS_ARRAY, $as_array, $field );
$field['value'] = $as_array ? $field['value'] : $field['value'][0];
} | php | public static function transform_to_object( &$field ) {
if ( 1 !== count( $field['value'] ) ) {
return $field['value'];
}
$as_array = ! ( 1 === $field['min'] && 1 === $field['max'] );
$as_array = apply_filters( Filter::REPEATER_AS_ARRAY, $as_array, $field );
$field['value'] = $as_array ? $field['value'] : $field['value'][0];
} | [
"public",
"static",
"function",
"transform_to_object",
"(",
"&",
"$",
"field",
")",
"{",
"if",
"(",
"1",
"!==",
"count",
"(",
"$",
"field",
"[",
"'value'",
"]",
")",
")",
"{",
"return",
"$",
"field",
"[",
"'value'",
"]",
";",
"}",
"$",
"as_array",
"=",
"!",
"(",
"1",
"===",
"$",
"field",
"[",
"'min'",
"]",
"&&",
"1",
"===",
"$",
"field",
"[",
"'max'",
"]",
")",
";",
"$",
"as_array",
"=",
"apply_filters",
"(",
"Filter",
"::",
"REPEATER_AS_ARRAY",
",",
"$",
"as_array",
",",
"$",
"field",
")",
";",
"$",
"field",
"[",
"'value'",
"]",
"=",
"$",
"as_array",
"?",
"$",
"field",
"[",
"'value'",
"]",
":",
"$",
"field",
"[",
"'value'",
"]",
"[",
"0",
"]",
";",
"}"
] | Transform to an object if the filter is set and there is only 1 item.
@param array $field Field.
@return mixed | [
"Transform",
"to",
"an",
"object",
"if",
"the",
"filter",
"is",
"set",
"and",
"there",
"is",
"only",
"1",
"item",
"."
] | train | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf/Transforms/Repeater.php#L54-L63 |
danielgp/browser-agent-info | source/ArchitecturesCpu.php | ArchiecturesCpu.listOfKnownCpuArchitectures | private function listOfKnownCpuArchitectures()
{
$arc = array_merge($this->listOfCpuArchitecturesX86(), $this->listOfCpuArchitecturesX64());
ksort($arc);
return $arc;
} | php | private function listOfKnownCpuArchitectures()
{
$arc = array_merge($this->listOfCpuArchitecturesX86(), $this->listOfCpuArchitecturesX64());
ksort($arc);
return $arc;
} | [
"private",
"function",
"listOfKnownCpuArchitectures",
"(",
")",
"{",
"$",
"arc",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"listOfCpuArchitecturesX86",
"(",
")",
",",
"$",
"this",
"->",
"listOfCpuArchitecturesX64",
"(",
")",
")",
";",
"ksort",
"(",
"$",
"arc",
")",
";",
"return",
"$",
"arc",
";",
"}"
] | Holds a list of Known CPU Srchitectures as array
@return array | [
"Holds",
"a",
"list",
"of",
"Known",
"CPU",
"Srchitectures",
"as",
"array"
] | train | https://github.com/danielgp/browser-agent-info/blob/5e4b2c01793ee47ce517be2c799d64abe78d7f8a/source/ArchitecturesCpu.php#L164-L169 |
Soneritics/Database | Soneritics/Database/DatabaseConnection/PDOMySQL.php | PDOMySQL.quote | public function quote($value)
{
if (is_array($value)) {
$result = [];
foreach ($value as $single) {
$result[] = $this->quote($single);
}
return sprintf(
'(%s)',
implode(', ', $result)
);
} else {
return $this->pdo->quote($value);
}
} | php | public function quote($value)
{
if (is_array($value)) {
$result = [];
foreach ($value as $single) {
$result[] = $this->quote($single);
}
return sprintf(
'(%s)',
implode(', ', $result)
);
} else {
return $this->pdo->quote($value);
}
} | [
"public",
"function",
"quote",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"single",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"this",
"->",
"quote",
"(",
"$",
"single",
")",
";",
"}",
"return",
"sprintf",
"(",
"'(%s)'",
",",
"implode",
"(",
"', '",
",",
"$",
"result",
")",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"pdo",
"->",
"quote",
"(",
"$",
"value",
")",
";",
"}",
"}"
] | Quote a value for use in a query.
@param $value
@return string | [
"Quote",
"a",
"value",
"for",
"use",
"in",
"a",
"query",
"."
] | train | https://github.com/Soneritics/Database/blob/20cb74f2a2ee8d9161d3144b5c061a6da11cd066/Soneritics/Database/DatabaseConnection/PDOMySQL.php#L67-L81 |
Soneritics/Database | Soneritics/Database/DatabaseConnection/PDOMySQL.php | PDOMySQL.query | public function query($query)
{
if (is_subclass_of($query, 'Database\Query\QueryAbstract')) {
return $this->query($this->buildQuery($query));
}
$debug = (new Debug\ExecutedQuery($query))->setBacktrace(debug_backtrace());
$startTime = microtime(true);
try {
$result = $this->pdo->query($query);
} catch (\Throwable $throwable) {
$debug->setException($throwable);
throw $throwable;
} finally {
$debug->setExecutionTime(microtime(true) - $startTime);
Debug::addQuery($debug);
}
return $this->getPDODatabaseRecord($result);
} | php | public function query($query)
{
if (is_subclass_of($query, 'Database\Query\QueryAbstract')) {
return $this->query($this->buildQuery($query));
}
$debug = (new Debug\ExecutedQuery($query))->setBacktrace(debug_backtrace());
$startTime = microtime(true);
try {
$result = $this->pdo->query($query);
} catch (\Throwable $throwable) {
$debug->setException($throwable);
throw $throwable;
} finally {
$debug->setExecutionTime(microtime(true) - $startTime);
Debug::addQuery($debug);
}
return $this->getPDODatabaseRecord($result);
} | [
"public",
"function",
"query",
"(",
"$",
"query",
")",
"{",
"if",
"(",
"is_subclass_of",
"(",
"$",
"query",
",",
"'Database\\Query\\QueryAbstract'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"query",
"(",
"$",
"this",
"->",
"buildQuery",
"(",
"$",
"query",
")",
")",
";",
"}",
"$",
"debug",
"=",
"(",
"new",
"Debug",
"\\",
"ExecutedQuery",
"(",
"$",
"query",
")",
")",
"->",
"setBacktrace",
"(",
"debug_backtrace",
"(",
")",
")",
";",
"$",
"startTime",
"=",
"microtime",
"(",
"true",
")",
";",
"try",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"query",
")",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"throwable",
")",
"{",
"$",
"debug",
"->",
"setException",
"(",
"$",
"throwable",
")",
";",
"throw",
"$",
"throwable",
";",
"}",
"finally",
"{",
"$",
"debug",
"->",
"setExecutionTime",
"(",
"microtime",
"(",
"true",
")",
"-",
"$",
"startTime",
")",
";",
"Debug",
"::",
"addQuery",
"(",
"$",
"debug",
")",
";",
"}",
"return",
"$",
"this",
"->",
"getPDODatabaseRecord",
"(",
"$",
"result",
")",
";",
"}"
] | Execute a query. The parameter can either be a Query(Abstract) object, or a string containing a full query.
@param $query
@return DatabaseRecord | [
"Execute",
"a",
"query",
".",
"The",
"parameter",
"can",
"either",
"be",
"a",
"Query",
"(",
"Abstract",
")",
"object",
"or",
"a",
"string",
"containing",
"a",
"full",
"query",
"."
] | train | https://github.com/Soneritics/Database/blob/20cb74f2a2ee8d9161d3144b5c061a6da11cd066/Soneritics/Database/DatabaseConnection/PDOMySQL.php#L88-L107 |
miguelibero/meinhof | src/Meinhof/Assetic/DelegatingResourceLoader.php | DelegatingResourceLoader.setLoaders | public function setLoaders(array $loaders)
{
$this->loaders = array();
foreach ($loaders as $type=>$loader) {
if (!$loader instanceof ResourceLoaderInterface) {
throw new \InvalidArgumentException("Not a valid resource loader.");
}
$this->loaders[$type] = $loader;
}
} | php | public function setLoaders(array $loaders)
{
$this->loaders = array();
foreach ($loaders as $type=>$loader) {
if (!$loader instanceof ResourceLoaderInterface) {
throw new \InvalidArgumentException("Not a valid resource loader.");
}
$this->loaders[$type] = $loader;
}
} | [
"public",
"function",
"setLoaders",
"(",
"array",
"$",
"loaders",
")",
"{",
"$",
"this",
"->",
"loaders",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"loaders",
"as",
"$",
"type",
"=>",
"$",
"loader",
")",
"{",
"if",
"(",
"!",
"$",
"loader",
"instanceof",
"ResourceLoaderInterface",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Not a valid resource loader.\"",
")",
";",
"}",
"$",
"this",
"->",
"loaders",
"[",
"$",
"type",
"]",
"=",
"$",
"loader",
";",
"}",
"}"
] | sets the list of available resource loaders
@param array $loaders a list of resource loaders indexed by type | [
"sets",
"the",
"list",
"of",
"available",
"resource",
"loaders"
] | train | https://github.com/miguelibero/meinhof/blob/3a090f08485dc0da3e27463cf349dba374201072/src/Meinhof/Assetic/DelegatingResourceLoader.php#L56-L65 |
miguelibero/meinhof | src/Meinhof/Assetic/DelegatingResourceLoader.php | DelegatingResourceLoader.getLoader | protected function getLoader($type)
{
if (!isset($this->loaders[$type])) {
throw new \InvalidArgumentException("No loader defined for type '${type}'.");
}
return $this->loaders[$type];
} | php | protected function getLoader($type)
{
if (!isset($this->loaders[$type])) {
throw new \InvalidArgumentException("No loader defined for type '${type}'.");
}
return $this->loaders[$type];
} | [
"protected",
"function",
"getLoader",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"loaders",
"[",
"$",
"type",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"No loader defined for type '${type}'.\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"loaders",
"[",
"$",
"type",
"]",
";",
"}"
] | Get the resource loader for a given type
@param string $type the resource type
@return ResourceLoaderInterface the resource loader
@throws \InvalidArgumentException if no loader defined for the given type | [
"Get",
"the",
"resource",
"loader",
"for",
"a",
"given",
"type"
] | train | https://github.com/miguelibero/meinhof/blob/3a090f08485dc0da3e27463cf349dba374201072/src/Meinhof/Assetic/DelegatingResourceLoader.php#L87-L94 |
miguelibero/meinhof | src/Meinhof/Assetic/DelegatingResourceLoader.php | DelegatingResourceLoader.getResourceType | protected function getResourceType($name)
{
if (!isset($this->types[$name])) {
$template = $this->parser->parse($name);
if ($template instanceof TemplateReferenceInterface) {
$this->types[$name] = $template->get('engine');
}
}
if (!isset($this->types[$name])) {
throw new \RuntimeException("Could not load the given resource.");
}
return $this->types[$name];
} | php | protected function getResourceType($name)
{
if (!isset($this->types[$name])) {
$template = $this->parser->parse($name);
if ($template instanceof TemplateReferenceInterface) {
$this->types[$name] = $template->get('engine');
}
}
if (!isset($this->types[$name])) {
throw new \RuntimeException("Could not load the given resource.");
}
return $this->types[$name];
} | [
"protected",
"function",
"getResourceType",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"types",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"parser",
"->",
"parse",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"template",
"instanceof",
"TemplateReferenceInterface",
")",
"{",
"$",
"this",
"->",
"types",
"[",
"$",
"name",
"]",
"=",
"$",
"template",
"->",
"get",
"(",
"'engine'",
")",
";",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"types",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Could not load the given resource.\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"types",
"[",
"$",
"name",
"]",
";",
"}"
] | Returns the type of a resource
@param string $name the name of the resource
@return string type of the resource
@throws \RuntimeException if the resource could not be loaded | [
"Returns",
"the",
"type",
"of",
"a",
"resource"
] | train | https://github.com/miguelibero/meinhof/blob/3a090f08485dc0da3e27463cf349dba374201072/src/Meinhof/Assetic/DelegatingResourceLoader.php#L104-L117 |
nguyenanhung/my-debug | src/Manager/File.php | File.directoryScanner | public function directoryScanner($path = '', $include = NULL, $exclude = NULL)
{
$scanner = new DirectoryScanner();
if (is_array($include) && !empty($include)) {
foreach ($include as $inc) {
$scanner->addInclude($inc);
}
}
if (is_array($exclude) && !empty($exclude)) {
foreach ($exclude as $exc) {
$scanner->addExclude($exc);
}
}
return $scanner($path);
} | php | public function directoryScanner($path = '', $include = NULL, $exclude = NULL)
{
$scanner = new DirectoryScanner();
if (is_array($include) && !empty($include)) {
foreach ($include as $inc) {
$scanner->addInclude($inc);
}
}
if (is_array($exclude) && !empty($exclude)) {
foreach ($exclude as $exc) {
$scanner->addExclude($exc);
}
}
return $scanner($path);
} | [
"public",
"function",
"directoryScanner",
"(",
"$",
"path",
"=",
"''",
",",
"$",
"include",
"=",
"NULL",
",",
"$",
"exclude",
"=",
"NULL",
")",
"{",
"$",
"scanner",
"=",
"new",
"DirectoryScanner",
"(",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"include",
")",
"&&",
"!",
"empty",
"(",
"$",
"include",
")",
")",
"{",
"foreach",
"(",
"$",
"include",
"as",
"$",
"inc",
")",
"{",
"$",
"scanner",
"->",
"addInclude",
"(",
"$",
"inc",
")",
";",
"}",
"}",
"if",
"(",
"is_array",
"(",
"$",
"exclude",
")",
"&&",
"!",
"empty",
"(",
"$",
"exclude",
")",
")",
"{",
"foreach",
"(",
"$",
"exclude",
"as",
"$",
"exc",
")",
"{",
"$",
"scanner",
"->",
"addExclude",
"(",
"$",
"exc",
")",
";",
"}",
"}",
"return",
"$",
"scanner",
"(",
"$",
"path",
")",
";",
"}"
] | Hàm quét thư mục và list ra danh sách các file con
@author: 713uk13m <[email protected]>
@time : 10/17/18 10:19
@param string $path Đường dẫn thư mục cần quét, VD: /your/to/path
@param null|array $include Mảng dữ liệu chứa các thuộc tính cần quét
@param null|array $exclude Mảng dữ liệu chứa các thuộc tính bỏ qua không quét
@see https://github.com/theseer/DirectoryScanner/blob/master/samples/sample.php
@return \Iterator | [
"Hàm",
"quét",
"thư",
"mục",
"và",
"list",
"ra",
"danh",
"sách",
"các",
"file",
"con"
] | train | https://github.com/nguyenanhung/my-debug/blob/9dde293d6c04098ee68858035bd04076874f43d6/src/Manager/File.php#L72-L87 |
nguyenanhung/my-debug | src/Manager/File.php | File.cleanLog | public function cleanLog($path = '', $dayToDel = 3)
{
$getDir = $this->directoryScanner($path, $this->scanInclude, $this->scanExclude);
$result = [];
$result['time'] = date('Y-m-d H:i:s');
$result['listFile'] = [];
foreach ($getDir as $fileName) {
$SplFileInfo = new \SplFileInfo($fileName);
$filename = $SplFileInfo->getPathname();
$format = 'YmdHis';
// Lấy thời gian xác định xóa fileName
$dateTime = new \DateTime("-" . $dayToDel . " days");
$deleteTime = $dateTime->format($format);
// Lấy modifyTime của file
$getfileTime = filemtime($filename);
$fileTime = date($format, $getfileTime);
if ($fileTime < $deleteTime) {
$this->chmod($filename, 0777);
$this->remove($filename);
$result['listFile'][] .= "Delete file: " . $filename;
}
}
return $result;
} | php | public function cleanLog($path = '', $dayToDel = 3)
{
$getDir = $this->directoryScanner($path, $this->scanInclude, $this->scanExclude);
$result = [];
$result['time'] = date('Y-m-d H:i:s');
$result['listFile'] = [];
foreach ($getDir as $fileName) {
$SplFileInfo = new \SplFileInfo($fileName);
$filename = $SplFileInfo->getPathname();
$format = 'YmdHis';
// Lấy thời gian xác định xóa fileName
$dateTime = new \DateTime("-" . $dayToDel . " days");
$deleteTime = $dateTime->format($format);
// Lấy modifyTime của file
$getfileTime = filemtime($filename);
$fileTime = date($format, $getfileTime);
if ($fileTime < $deleteTime) {
$this->chmod($filename, 0777);
$this->remove($filename);
$result['listFile'][] .= "Delete file: " . $filename;
}
}
return $result;
} | [
"public",
"function",
"cleanLog",
"(",
"$",
"path",
"=",
"''",
",",
"$",
"dayToDel",
"=",
"3",
")",
"{",
"$",
"getDir",
"=",
"$",
"this",
"->",
"directoryScanner",
"(",
"$",
"path",
",",
"$",
"this",
"->",
"scanInclude",
",",
"$",
"this",
"->",
"scanExclude",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"result",
"[",
"'time'",
"]",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"result",
"[",
"'listFile'",
"]",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"getDir",
"as",
"$",
"fileName",
")",
"{",
"$",
"SplFileInfo",
"=",
"new",
"\\",
"SplFileInfo",
"(",
"$",
"fileName",
")",
";",
"$",
"filename",
"=",
"$",
"SplFileInfo",
"->",
"getPathname",
"(",
")",
";",
"$",
"format",
"=",
"'YmdHis'",
";",
"// Lấy thời gian xác định xóa fileName",
"$",
"dateTime",
"=",
"new",
"\\",
"DateTime",
"(",
"\"-\"",
".",
"$",
"dayToDel",
".",
"\" days\"",
")",
";",
"$",
"deleteTime",
"=",
"$",
"dateTime",
"->",
"format",
"(",
"$",
"format",
")",
";",
"// Lấy modifyTime của file",
"$",
"getfileTime",
"=",
"filemtime",
"(",
"$",
"filename",
")",
";",
"$",
"fileTime",
"=",
"date",
"(",
"$",
"format",
",",
"$",
"getfileTime",
")",
";",
"if",
"(",
"$",
"fileTime",
"<",
"$",
"deleteTime",
")",
"{",
"$",
"this",
"->",
"chmod",
"(",
"$",
"filename",
",",
"0777",
")",
";",
"$",
"this",
"->",
"remove",
"(",
"$",
"filename",
")",
";",
"$",
"result",
"[",
"'listFile'",
"]",
"[",
"]",
".=",
"\"Delete file: \"",
".",
"$",
"filename",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Hàm xóa các file Log được chỉ định
@author: 713uk13m <[email protected]>
@time : 10/17/18 10:21
@param string $path Thư mục cần quét và xóa
@param int $dayToDel Số ngày cần giữ lại file
@return array Mảng thông tin về các file đã xóa
@throws \Exception | [
"Hàm",
"xóa",
"các",
"file",
"Log",
"được",
"chỉ",
"định"
] | train | https://github.com/nguyenanhung/my-debug/blob/9dde293d6c04098ee68858035bd04076874f43d6/src/Manager/File.php#L127-L151 |
nguyenanhung/my-debug | src/Manager/File.php | File.scanAndZip | public function scanAndZip($scanPath = '', $dayToZip = 3, $zipPath = '')
{
$getDir = $this->directoryScanner($scanPath, $this->scanInclude, $this->scanExclude);
if (empty($zipPath)) {
/**
* Nếu không truyền folder đích lưu trữ file Zip
* sẽ Tạo 1 thư mục Con trong folder đó để lưu trữ file Zip
*/
$zipPath = $scanPath . DIRECTORY_SEPARATOR . 'Zip-Archive' . DIRECTORY_SEPARATOR;
}
$zipPathFilename = $zipPath . date('Y-m-d-H-i-s') . '-archive.zip';
// Lấy thời gian xác định sẽ Zip file
$format = 'YmdHis';
$dateTime = new \DateTime("-" . $dayToZip . " days");
$zipTime = $dateTime->format($format);
$result = [];
$result['time'] = date('Y-m-d H:i:s');
$result['timeToZip'] = $dateTime->format('Y-m-d H:i:s');
$result['zipPath'] = $zipPath;
$result['zipFilePath'] = $zipPathFilename;
$result['listFile'] = [];
foreach ($getDir as $fileName) {
$SplFileInfo = new \SplFileInfo($fileName);
$filename = $SplFileInfo->getPathname();
// Lấy modifyTime của file
$getfileTime = filemtime($filename);
$fileTime = date($format, $getfileTime);
if ($fileTime < $zipTime) {
if (!file_exists($zipPath)) {
$this->mkdir($zipPath);
}
// Load Zippy
$zippy = Zippy::load();
$archive = $zippy->create($zipPathFilename, [
$filename => $filename
], TRUE);
$result['listFile'][] .= "Zip file: " . $filename . ' -> ' . json_encode($archive);
}
}
return $result;
} | php | public function scanAndZip($scanPath = '', $dayToZip = 3, $zipPath = '')
{
$getDir = $this->directoryScanner($scanPath, $this->scanInclude, $this->scanExclude);
if (empty($zipPath)) {
/**
* Nếu không truyền folder đích lưu trữ file Zip
* sẽ Tạo 1 thư mục Con trong folder đó để lưu trữ file Zip
*/
$zipPath = $scanPath . DIRECTORY_SEPARATOR . 'Zip-Archive' . DIRECTORY_SEPARATOR;
}
$zipPathFilename = $zipPath . date('Y-m-d-H-i-s') . '-archive.zip';
// Lấy thời gian xác định sẽ Zip file
$format = 'YmdHis';
$dateTime = new \DateTime("-" . $dayToZip . " days");
$zipTime = $dateTime->format($format);
$result = [];
$result['time'] = date('Y-m-d H:i:s');
$result['timeToZip'] = $dateTime->format('Y-m-d H:i:s');
$result['zipPath'] = $zipPath;
$result['zipFilePath'] = $zipPathFilename;
$result['listFile'] = [];
foreach ($getDir as $fileName) {
$SplFileInfo = new \SplFileInfo($fileName);
$filename = $SplFileInfo->getPathname();
// Lấy modifyTime của file
$getfileTime = filemtime($filename);
$fileTime = date($format, $getfileTime);
if ($fileTime < $zipTime) {
if (!file_exists($zipPath)) {
$this->mkdir($zipPath);
}
// Load Zippy
$zippy = Zippy::load();
$archive = $zippy->create($zipPathFilename, [
$filename => $filename
], TRUE);
$result['listFile'][] .= "Zip file: " . $filename . ' -> ' . json_encode($archive);
}
}
return $result;
} | [
"public",
"function",
"scanAndZip",
"(",
"$",
"scanPath",
"=",
"''",
",",
"$",
"dayToZip",
"=",
"3",
",",
"$",
"zipPath",
"=",
"''",
")",
"{",
"$",
"getDir",
"=",
"$",
"this",
"->",
"directoryScanner",
"(",
"$",
"scanPath",
",",
"$",
"this",
"->",
"scanInclude",
",",
"$",
"this",
"->",
"scanExclude",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"zipPath",
")",
")",
"{",
"/**\n * Nếu không truyền folder đích lưu trữ file Zip\n * sẽ Tạo 1 thư mục Con trong folder đó để lưu trữ file Zip\n */",
"$",
"zipPath",
"=",
"$",
"scanPath",
".",
"DIRECTORY_SEPARATOR",
".",
"'Zip-Archive'",
".",
"DIRECTORY_SEPARATOR",
";",
"}",
"$",
"zipPathFilename",
"=",
"$",
"zipPath",
".",
"date",
"(",
"'Y-m-d-H-i-s'",
")",
".",
"'-archive.zip'",
";",
"// Lấy thời gian xác định sẽ Zip file",
"$",
"format",
"=",
"'YmdHis'",
";",
"$",
"dateTime",
"=",
"new",
"\\",
"DateTime",
"(",
"\"-\"",
".",
"$",
"dayToZip",
".",
"\" days\"",
")",
";",
"$",
"zipTime",
"=",
"$",
"dateTime",
"->",
"format",
"(",
"$",
"format",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"result",
"[",
"'time'",
"]",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"result",
"[",
"'timeToZip'",
"]",
"=",
"$",
"dateTime",
"->",
"format",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"result",
"[",
"'zipPath'",
"]",
"=",
"$",
"zipPath",
";",
"$",
"result",
"[",
"'zipFilePath'",
"]",
"=",
"$",
"zipPathFilename",
";",
"$",
"result",
"[",
"'listFile'",
"]",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"getDir",
"as",
"$",
"fileName",
")",
"{",
"$",
"SplFileInfo",
"=",
"new",
"\\",
"SplFileInfo",
"(",
"$",
"fileName",
")",
";",
"$",
"filename",
"=",
"$",
"SplFileInfo",
"->",
"getPathname",
"(",
")",
";",
"// Lấy modifyTime của file",
"$",
"getfileTime",
"=",
"filemtime",
"(",
"$",
"filename",
")",
";",
"$",
"fileTime",
"=",
"date",
"(",
"$",
"format",
",",
"$",
"getfileTime",
")",
";",
"if",
"(",
"$",
"fileTime",
"<",
"$",
"zipTime",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"zipPath",
")",
")",
"{",
"$",
"this",
"->",
"mkdir",
"(",
"$",
"zipPath",
")",
";",
"}",
"// Load Zippy",
"$",
"zippy",
"=",
"Zippy",
"::",
"load",
"(",
")",
";",
"$",
"archive",
"=",
"$",
"zippy",
"->",
"create",
"(",
"$",
"zipPathFilename",
",",
"[",
"$",
"filename",
"=>",
"$",
"filename",
"]",
",",
"TRUE",
")",
";",
"$",
"result",
"[",
"'listFile'",
"]",
"[",
"]",
".=",
"\"Zip file: \"",
".",
"$",
"filename",
".",
"' -> '",
".",
"json_encode",
"(",
"$",
"archive",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Hàm quét thư mục và zip toàn bộ các file thỏa mãn điều kiện
@author: 713uk13m <[email protected]>
@time : 10/17/18 10:51
@param string $scanPath Thư mục cần quét file và zip
@param int $dayToZip Số ngày bỏ qua không zipm mặc định = 3
@param string $zipPath Thư mục lưu trữ file Zip
@return array Mảng thông tin về các file đã Zip được và thư mục lưu trữ file Zip, trong đó
'time' => Là thời gian thực hiện quét và nén file
'timeToZip' => Là mốc thời gian thực hiện để quét file
'zipPath' => Là thư mục đích lưu trữ file đã nén
'zipFilePath' => Tên file nén
'listFile' => Mảng dữ liệu chứa danh sách file đã nén, trống biến này nghĩa là ko tìm thấy file nào
@throws \Exception | [
"Hàm",
"quét",
"thư",
"mục",
"và",
"zip",
"toàn",
"bộ",
"các",
"file",
"thỏa",
"mãn",
"điều",
"kiện"
] | train | https://github.com/nguyenanhung/my-debug/blob/9dde293d6c04098ee68858035bd04076874f43d6/src/Manager/File.php#L176-L217 |
ekyna/PaymentBundle | Controller/Admin/MethodController.php | MethodController.newAction | public function newAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
throw new NotFoundHttpException('Method creation through XMLHttpRequest is not yet implemented.');
}
$this->isGranted('CREATE');
$context = $this->loadContext($request);
$resource = $this->createNew($context);
$resourceName = $this->config->getResourceName();
$context->addResource($resourceName, $resource);
$flow = $this->get('ekyna_payment.method_create.form_flow');
$flow->bind($resource);
$form = $flow->createForm();
if ($flow->isValid($form)) {
$flow->saveCurrentStepData($form);
if ($flow->nextStep()) {
// form for the next step
$form = $flow->createForm();
} else {
// TODO use ResourceManager
$event = $this->getOperator()->create($resource);
$event->toFlashes($this->getFlashBag());
if (!$event->hasErrors()) {
return $this->redirect($this->generateUrl(
$this->config->getRoute('show'),
$context->getIdentifiers(true)
));
}
}
}
$this->appendBreadcrumb(sprintf('%s-new', $resourceName), 'ekyna_core.button.create');
return $this->render(
$this->config->getTemplate('new.html'),
$context->getTemplateVars([
'flow' => $flow,
'form' => $form->createView()
])
);
} | php | public function newAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
throw new NotFoundHttpException('Method creation through XMLHttpRequest is not yet implemented.');
}
$this->isGranted('CREATE');
$context = $this->loadContext($request);
$resource = $this->createNew($context);
$resourceName = $this->config->getResourceName();
$context->addResource($resourceName, $resource);
$flow = $this->get('ekyna_payment.method_create.form_flow');
$flow->bind($resource);
$form = $flow->createForm();
if ($flow->isValid($form)) {
$flow->saveCurrentStepData($form);
if ($flow->nextStep()) {
// form for the next step
$form = $flow->createForm();
} else {
// TODO use ResourceManager
$event = $this->getOperator()->create($resource);
$event->toFlashes($this->getFlashBag());
if (!$event->hasErrors()) {
return $this->redirect($this->generateUrl(
$this->config->getRoute('show'),
$context->getIdentifiers(true)
));
}
}
}
$this->appendBreadcrumb(sprintf('%s-new', $resourceName), 'ekyna_core.button.create');
return $this->render(
$this->config->getTemplate('new.html'),
$context->getTemplateVars([
'flow' => $flow,
'form' => $form->createView()
])
);
} | [
"public",
"function",
"newAction",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"isXmlHttpRequest",
"(",
")",
")",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"'Method creation through XMLHttpRequest is not yet implemented.'",
")",
";",
"}",
"$",
"this",
"->",
"isGranted",
"(",
"'CREATE'",
")",
";",
"$",
"context",
"=",
"$",
"this",
"->",
"loadContext",
"(",
"$",
"request",
")",
";",
"$",
"resource",
"=",
"$",
"this",
"->",
"createNew",
"(",
"$",
"context",
")",
";",
"$",
"resourceName",
"=",
"$",
"this",
"->",
"config",
"->",
"getResourceName",
"(",
")",
";",
"$",
"context",
"->",
"addResource",
"(",
"$",
"resourceName",
",",
"$",
"resource",
")",
";",
"$",
"flow",
"=",
"$",
"this",
"->",
"get",
"(",
"'ekyna_payment.method_create.form_flow'",
")",
";",
"$",
"flow",
"->",
"bind",
"(",
"$",
"resource",
")",
";",
"$",
"form",
"=",
"$",
"flow",
"->",
"createForm",
"(",
")",
";",
"if",
"(",
"$",
"flow",
"->",
"isValid",
"(",
"$",
"form",
")",
")",
"{",
"$",
"flow",
"->",
"saveCurrentStepData",
"(",
"$",
"form",
")",
";",
"if",
"(",
"$",
"flow",
"->",
"nextStep",
"(",
")",
")",
"{",
"// form for the next step",
"$",
"form",
"=",
"$",
"flow",
"->",
"createForm",
"(",
")",
";",
"}",
"else",
"{",
"// TODO use ResourceManager",
"$",
"event",
"=",
"$",
"this",
"->",
"getOperator",
"(",
")",
"->",
"create",
"(",
"$",
"resource",
")",
";",
"$",
"event",
"->",
"toFlashes",
"(",
"$",
"this",
"->",
"getFlashBag",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"event",
"->",
"hasErrors",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"redirect",
"(",
"$",
"this",
"->",
"generateUrl",
"(",
"$",
"this",
"->",
"config",
"->",
"getRoute",
"(",
"'show'",
")",
",",
"$",
"context",
"->",
"getIdentifiers",
"(",
"true",
")",
")",
")",
";",
"}",
"}",
"}",
"$",
"this",
"->",
"appendBreadcrumb",
"(",
"sprintf",
"(",
"'%s-new'",
",",
"$",
"resourceName",
")",
",",
"'ekyna_core.button.create'",
")",
";",
"return",
"$",
"this",
"->",
"render",
"(",
"$",
"this",
"->",
"config",
"->",
"getTemplate",
"(",
"'new.html'",
")",
",",
"$",
"context",
"->",
"getTemplateVars",
"(",
"[",
"'flow'",
"=>",
"$",
"flow",
",",
"'form'",
"=>",
"$",
"form",
"->",
"createView",
"(",
")",
"]",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Controller/Admin/MethodController.php#L24-L73 |
praxigento/mobi_mod_downline | Observer/CustomerSaveAfterDataObject/A/GroupSwitch.php | GroupSwitch.registerGroupChange | private function registerGroupChange($custId, $groupIdOld, $groupIdNew)
{
$data = new EChangeGroup();
$data->setCustomerRef($custId);
$data->setGroupOld($groupIdOld);
$data->setGroupNew($groupIdNew);
$dateChanged = $this->hlpDate->getUtcNowForDb();
$data->setDateChanged($dateChanged);
$this->daoChangeGroup->create($data);
} | php | private function registerGroupChange($custId, $groupIdOld, $groupIdNew)
{
$data = new EChangeGroup();
$data->setCustomerRef($custId);
$data->setGroupOld($groupIdOld);
$data->setGroupNew($groupIdNew);
$dateChanged = $this->hlpDate->getUtcNowForDb();
$data->setDateChanged($dateChanged);
$this->daoChangeGroup->create($data);
} | [
"private",
"function",
"registerGroupChange",
"(",
"$",
"custId",
",",
"$",
"groupIdOld",
",",
"$",
"groupIdNew",
")",
"{",
"$",
"data",
"=",
"new",
"EChangeGroup",
"(",
")",
";",
"$",
"data",
"->",
"setCustomerRef",
"(",
"$",
"custId",
")",
";",
"$",
"data",
"->",
"setGroupOld",
"(",
"$",
"groupIdOld",
")",
";",
"$",
"data",
"->",
"setGroupNew",
"(",
"$",
"groupIdNew",
")",
";",
"$",
"dateChanged",
"=",
"$",
"this",
"->",
"hlpDate",
"->",
"getUtcNowForDb",
"(",
")",
";",
"$",
"data",
"->",
"setDateChanged",
"(",
"$",
"dateChanged",
")",
";",
"$",
"this",
"->",
"daoChangeGroup",
"->",
"create",
"(",
"$",
"data",
")",
";",
"}"
] | Save group change event into registry.
@param int $custId
@param int $groupIdOld
@param int $groupIdNew | [
"Save",
"group",
"change",
"event",
"into",
"registry",
"."
] | train | https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Observer/CustomerSaveAfterDataObject/A/GroupSwitch.php#L65-L74 |
praxigento/mobi_mod_downline | Observer/CustomerSaveAfterDataObject/A/GroupSwitch.php | GroupSwitch.switchDownline | private function switchDownline($custId, $groupIdBefore, $groupIdAfter)
{
$isDowngrade = $this->hlpGroupTrans->isDowngrade($groupIdBefore, $groupIdAfter);
if ($isDowngrade) {
/* we need to switch all customer's children to the customer's parent */
$req = new ASwitchUpRequest();
$req->setCustomerId($custId);
$this->servSwitchUp->exec($req);
} else {
$isUpgrade = $this->hlpGroupTrans->isUpgrade($groupIdBefore, $groupIdAfter);
if ($isUpgrade) {
/* we need to place customer under the first distributor in upline */
$req = new AStickUpRequest();
$req->setCustomerId($custId);
$this->servStickUp->exec($req);
}
}
} | php | private function switchDownline($custId, $groupIdBefore, $groupIdAfter)
{
$isDowngrade = $this->hlpGroupTrans->isDowngrade($groupIdBefore, $groupIdAfter);
if ($isDowngrade) {
/* we need to switch all customer's children to the customer's parent */
$req = new ASwitchUpRequest();
$req->setCustomerId($custId);
$this->servSwitchUp->exec($req);
} else {
$isUpgrade = $this->hlpGroupTrans->isUpgrade($groupIdBefore, $groupIdAfter);
if ($isUpgrade) {
/* we need to place customer under the first distributor in upline */
$req = new AStickUpRequest();
$req->setCustomerId($custId);
$this->servStickUp->exec($req);
}
}
} | [
"private",
"function",
"switchDownline",
"(",
"$",
"custId",
",",
"$",
"groupIdBefore",
",",
"$",
"groupIdAfter",
")",
"{",
"$",
"isDowngrade",
"=",
"$",
"this",
"->",
"hlpGroupTrans",
"->",
"isDowngrade",
"(",
"$",
"groupIdBefore",
",",
"$",
"groupIdAfter",
")",
";",
"if",
"(",
"$",
"isDowngrade",
")",
"{",
"/* we need to switch all customer's children to the customer's parent */",
"$",
"req",
"=",
"new",
"ASwitchUpRequest",
"(",
")",
";",
"$",
"req",
"->",
"setCustomerId",
"(",
"$",
"custId",
")",
";",
"$",
"this",
"->",
"servSwitchUp",
"->",
"exec",
"(",
"$",
"req",
")",
";",
"}",
"else",
"{",
"$",
"isUpgrade",
"=",
"$",
"this",
"->",
"hlpGroupTrans",
"->",
"isUpgrade",
"(",
"$",
"groupIdBefore",
",",
"$",
"groupIdAfter",
")",
";",
"if",
"(",
"$",
"isUpgrade",
")",
"{",
"/* we need to place customer under the first distributor in upline */",
"$",
"req",
"=",
"new",
"AStickUpRequest",
"(",
")",
";",
"$",
"req",
"->",
"setCustomerId",
"(",
"$",
"custId",
")",
";",
"$",
"this",
"->",
"servStickUp",
"->",
"exec",
"(",
"$",
"req",
")",
";",
"}",
"}",
"}"
] | Change downline on group upgrade/downgrade event.
@param int $custId
@param int $groupIdBefore
@param int $groupIdAfter
@throws \Exception | [
"Change",
"downline",
"on",
"group",
"upgrade",
"/",
"downgrade",
"event",
"."
] | train | https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Observer/CustomerSaveAfterDataObject/A/GroupSwitch.php#L84-L101 |
Aviogram/Common | src/Hydrator/ByClassMethods.php | ByClassMethods.hydrate | public function hydrate(
$object,
$data,
$recursive = true,
&$remainder = array()
) {
// Object should be an object. Duh makes sense ;)
if (is_object($object) === false) {
$type = gettype($object);
throw new Exception\HydrateFailed(sprintf($this->exceptions[1], $type), 1);
}
// The input data should be an array or should implements ArrayIterator
if (
is_array($data) === false &&
($data instanceof ArrayIterator) === false
) {
$type = gettype($data);
throw new Exception\HydrateFailed(sprintf($this->exceptions[2], $type), 2);
}
// Fetch all the set methods with method information
$methods = $this->getSetters($object);
// Is ArrayIterator
$isIterator = (bool) ($object instanceof ArrayIterator);
// Loop through the input data
foreach ($data as $offset => $value) {
// Generate setMethod name
$setMethod = StringUtils::underscoreToCamelCase('set_' . $offset);
// If method does not exists on the object, continue
if ($methods->offsetExists($setMethod) === false) {
$setMethod = 'setOffsetEntity';
if ($methods->offsetExists($setMethod) === false) {
// When the method has implemented an iterator. We can
// set the offset for injection the data
if ($isIterator === true) {
$object->offsetSet($offset, $value);
}
$remainder[$offset] = $value;
continue;
}
}
// Get method information
$method = $methods->offsetGet($setMethod);
// Validate input against typehint array
if ($method->isTypehintArray() && ($method->isRequired() === true && is_array($value) === false)) {
$class = get_class($object);
$type = is_object($value) ? get_class($value) : gettype($value);
throw new Exception\HydrateFailed(
sprintf($this->exceptions[3], $class, $setMethod, 'array', $type),
3
);
// Validate input against typehint object
} else if (
$method->isTypehintArray() === false &&
$method->getTypehint() !== null
) {
$typehint = $method->getTypehint();
// Hydrate to an object when the input data is an array
if ($recursive === true && is_object($value) === false && is_array($value)) {
$value = $this->hydrate(new $typehint, $value);
}
// If the parameter is required. It should have instanceof check
if ($method->isRequired() && ($value instanceof $typehint) === false) {
$class = get_class($object);
$type = is_object($value) ? get_class($value) : gettype($value);
throw new Exception\HydrateFailed(
sprintf($this->exceptions[3], $class, $setMethod, $typehint, $type),
3
);
}
}
// Set the actual value
$object->{$setMethod}($value, $offset);
}
return $object;
} | php | public function hydrate(
$object,
$data,
$recursive = true,
&$remainder = array()
) {
// Object should be an object. Duh makes sense ;)
if (is_object($object) === false) {
$type = gettype($object);
throw new Exception\HydrateFailed(sprintf($this->exceptions[1], $type), 1);
}
// The input data should be an array or should implements ArrayIterator
if (
is_array($data) === false &&
($data instanceof ArrayIterator) === false
) {
$type = gettype($data);
throw new Exception\HydrateFailed(sprintf($this->exceptions[2], $type), 2);
}
// Fetch all the set methods with method information
$methods = $this->getSetters($object);
// Is ArrayIterator
$isIterator = (bool) ($object instanceof ArrayIterator);
// Loop through the input data
foreach ($data as $offset => $value) {
// Generate setMethod name
$setMethod = StringUtils::underscoreToCamelCase('set_' . $offset);
// If method does not exists on the object, continue
if ($methods->offsetExists($setMethod) === false) {
$setMethod = 'setOffsetEntity';
if ($methods->offsetExists($setMethod) === false) {
// When the method has implemented an iterator. We can
// set the offset for injection the data
if ($isIterator === true) {
$object->offsetSet($offset, $value);
}
$remainder[$offset] = $value;
continue;
}
}
// Get method information
$method = $methods->offsetGet($setMethod);
// Validate input against typehint array
if ($method->isTypehintArray() && ($method->isRequired() === true && is_array($value) === false)) {
$class = get_class($object);
$type = is_object($value) ? get_class($value) : gettype($value);
throw new Exception\HydrateFailed(
sprintf($this->exceptions[3], $class, $setMethod, 'array', $type),
3
);
// Validate input against typehint object
} else if (
$method->isTypehintArray() === false &&
$method->getTypehint() !== null
) {
$typehint = $method->getTypehint();
// Hydrate to an object when the input data is an array
if ($recursive === true && is_object($value) === false && is_array($value)) {
$value = $this->hydrate(new $typehint, $value);
}
// If the parameter is required. It should have instanceof check
if ($method->isRequired() && ($value instanceof $typehint) === false) {
$class = get_class($object);
$type = is_object($value) ? get_class($value) : gettype($value);
throw new Exception\HydrateFailed(
sprintf($this->exceptions[3], $class, $setMethod, $typehint, $type),
3
);
}
}
// Set the actual value
$object->{$setMethod}($value, $offset);
}
return $object;
} | [
"public",
"function",
"hydrate",
"(",
"$",
"object",
",",
"$",
"data",
",",
"$",
"recursive",
"=",
"true",
",",
"&",
"$",
"remainder",
"=",
"array",
"(",
")",
")",
"{",
"// Object should be an object. Duh makes sense ;)\r",
"if",
"(",
"is_object",
"(",
"$",
"object",
")",
"===",
"false",
")",
"{",
"$",
"type",
"=",
"gettype",
"(",
"$",
"object",
")",
";",
"throw",
"new",
"Exception",
"\\",
"HydrateFailed",
"(",
"sprintf",
"(",
"$",
"this",
"->",
"exceptions",
"[",
"1",
"]",
",",
"$",
"type",
")",
",",
"1",
")",
";",
"}",
"// The input data should be an array or should implements ArrayIterator\r",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
"===",
"false",
"&&",
"(",
"$",
"data",
"instanceof",
"ArrayIterator",
")",
"===",
"false",
")",
"{",
"$",
"type",
"=",
"gettype",
"(",
"$",
"data",
")",
";",
"throw",
"new",
"Exception",
"\\",
"HydrateFailed",
"(",
"sprintf",
"(",
"$",
"this",
"->",
"exceptions",
"[",
"2",
"]",
",",
"$",
"type",
")",
",",
"2",
")",
";",
"}",
"// Fetch all the set methods with method information\r",
"$",
"methods",
"=",
"$",
"this",
"->",
"getSetters",
"(",
"$",
"object",
")",
";",
"// Is ArrayIterator\r",
"$",
"isIterator",
"=",
"(",
"bool",
")",
"(",
"$",
"object",
"instanceof",
"ArrayIterator",
")",
";",
"// Loop through the input data\r",
"foreach",
"(",
"$",
"data",
"as",
"$",
"offset",
"=>",
"$",
"value",
")",
"{",
"// Generate setMethod name\r",
"$",
"setMethod",
"=",
"StringUtils",
"::",
"underscoreToCamelCase",
"(",
"'set_'",
".",
"$",
"offset",
")",
";",
"// If method does not exists on the object, continue\r",
"if",
"(",
"$",
"methods",
"->",
"offsetExists",
"(",
"$",
"setMethod",
")",
"===",
"false",
")",
"{",
"$",
"setMethod",
"=",
"'setOffsetEntity'",
";",
"if",
"(",
"$",
"methods",
"->",
"offsetExists",
"(",
"$",
"setMethod",
")",
"===",
"false",
")",
"{",
"// When the method has implemented an iterator. We can\r",
"// set the offset for injection the data\r",
"if",
"(",
"$",
"isIterator",
"===",
"true",
")",
"{",
"$",
"object",
"->",
"offsetSet",
"(",
"$",
"offset",
",",
"$",
"value",
")",
";",
"}",
"$",
"remainder",
"[",
"$",
"offset",
"]",
"=",
"$",
"value",
";",
"continue",
";",
"}",
"}",
"// Get method information\r",
"$",
"method",
"=",
"$",
"methods",
"->",
"offsetGet",
"(",
"$",
"setMethod",
")",
";",
"// Validate input against typehint array\r",
"if",
"(",
"$",
"method",
"->",
"isTypehintArray",
"(",
")",
"&&",
"(",
"$",
"method",
"->",
"isRequired",
"(",
")",
"===",
"true",
"&&",
"is_array",
"(",
"$",
"value",
")",
"===",
"false",
")",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"object",
")",
";",
"$",
"type",
"=",
"is_object",
"(",
"$",
"value",
")",
"?",
"get_class",
"(",
"$",
"value",
")",
":",
"gettype",
"(",
"$",
"value",
")",
";",
"throw",
"new",
"Exception",
"\\",
"HydrateFailed",
"(",
"sprintf",
"(",
"$",
"this",
"->",
"exceptions",
"[",
"3",
"]",
",",
"$",
"class",
",",
"$",
"setMethod",
",",
"'array'",
",",
"$",
"type",
")",
",",
"3",
")",
";",
"// Validate input against typehint object\r",
"}",
"else",
"if",
"(",
"$",
"method",
"->",
"isTypehintArray",
"(",
")",
"===",
"false",
"&&",
"$",
"method",
"->",
"getTypehint",
"(",
")",
"!==",
"null",
")",
"{",
"$",
"typehint",
"=",
"$",
"method",
"->",
"getTypehint",
"(",
")",
";",
"// Hydrate to an object when the input data is an array\r",
"if",
"(",
"$",
"recursive",
"===",
"true",
"&&",
"is_object",
"(",
"$",
"value",
")",
"===",
"false",
"&&",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"hydrate",
"(",
"new",
"$",
"typehint",
",",
"$",
"value",
")",
";",
"}",
"// If the parameter is required. It should have instanceof check\r",
"if",
"(",
"$",
"method",
"->",
"isRequired",
"(",
")",
"&&",
"(",
"$",
"value",
"instanceof",
"$",
"typehint",
")",
"===",
"false",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"object",
")",
";",
"$",
"type",
"=",
"is_object",
"(",
"$",
"value",
")",
"?",
"get_class",
"(",
"$",
"value",
")",
":",
"gettype",
"(",
"$",
"value",
")",
";",
"throw",
"new",
"Exception",
"\\",
"HydrateFailed",
"(",
"sprintf",
"(",
"$",
"this",
"->",
"exceptions",
"[",
"3",
"]",
",",
"$",
"class",
",",
"$",
"setMethod",
",",
"$",
"typehint",
",",
"$",
"type",
")",
",",
"3",
")",
";",
"}",
"}",
"// Set the actual value\r",
"$",
"object",
"->",
"{",
"$",
"setMethod",
"}",
"(",
"$",
"value",
",",
"$",
"offset",
")",
";",
"}",
"return",
"$",
"object",
";",
"}"
] | Hydrate aan array to an object. By default in recursive manner
@param object $object
@param array | ArrayIterator $data
@param boolean $recursive
@param array $remainder Contains the unhydrated values from data not added to the target object
@return object
@throws Exception\HydrateFailed When $object is no object or $data is not array | [
"Hydrate",
"aan",
"array",
"to",
"an",
"object",
".",
"By",
"default",
"in",
"recursive",
"manner"
] | train | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByClassMethods.php#L40-L128 |
Aviogram/Common | src/Hydrator/ByClassMethods.php | ByClassMethods.getSetters | protected function getSetters($object)
{
// Get the current class
$class = get_class($object);
// Check if we have already parsed this class
if (array_key_exists($class, $this->classMethodsCache) === true) {
return $this->classMethodsCache[$class];
}
// Regex for parsing ReflectionParameter::__toString()
$regex = '/\[\s\<(?P<required>[^\>]+)\>\s' .
'(?:(?P<typehint_a>[^\s]+|(?P<typehint_b>[^\s]+)\sor\s(?P<typehint_c>[^\s]+))\s)?' .
'(?P<variable>\$[^\s]+)\s(?:=\s(?P<default>[^\]]+)\s)?\]/';
// Make reflection and fetch the methods
$reflectionClass = new ReflectionClass($object);
$methods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);
// Make result container
$setters = new Collection\Method();
// Loop through the methods
foreach ($methods as $method) {
// We only care about the setters
if (substr($method->getName(), 0, 3) !== 'set') {
continue;
}
// Get parameter collection
$parameters = $method->getParameters();
// We only take care of the first parameter of the setter
$parameter = $parameters[0];
$raw = (string) $parameter;
// If we cannot match it we continue
if (($result = preg_match($regex, $raw, $matches)) === false || $result === 0) {
continue;
}
// Parse the result of the regex
$required = ($matches['required'] === 'required');
$variable = $matches['variable'];
$default = $required ? null : $matches['default'];
$typehint = null;
// Advanced typehint detection
if (empty($matches['typehint_b']) === false) {
$typehint = $matches['typehint_b'];
} else if (empty($matches['typehint_a']) === false){
$typehint = $matches['typehint_a'];
}
// Set the correct default value
switch ($default) {
case null:
case 'NULL':
$default = null;
break;
case 'Array':
$default = array();
break;
default:
$default = trim($default, "'");
break;
}
// Has it child objects
$childObject = ($typehint !== null && $typehint !== 'array');
// Set the results the the response object
$setters->offsetSet(
$method->getName(),
new Entity\Method(
$required,
$default,
$typehint,
$childObject
)
);
}
// Return the just generated response
return $this->classMethodsCache[$class] = $setters;
} | php | protected function getSetters($object)
{
// Get the current class
$class = get_class($object);
// Check if we have already parsed this class
if (array_key_exists($class, $this->classMethodsCache) === true) {
return $this->classMethodsCache[$class];
}
// Regex for parsing ReflectionParameter::__toString()
$regex = '/\[\s\<(?P<required>[^\>]+)\>\s' .
'(?:(?P<typehint_a>[^\s]+|(?P<typehint_b>[^\s]+)\sor\s(?P<typehint_c>[^\s]+))\s)?' .
'(?P<variable>\$[^\s]+)\s(?:=\s(?P<default>[^\]]+)\s)?\]/';
// Make reflection and fetch the methods
$reflectionClass = new ReflectionClass($object);
$methods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);
// Make result container
$setters = new Collection\Method();
// Loop through the methods
foreach ($methods as $method) {
// We only care about the setters
if (substr($method->getName(), 0, 3) !== 'set') {
continue;
}
// Get parameter collection
$parameters = $method->getParameters();
// We only take care of the first parameter of the setter
$parameter = $parameters[0];
$raw = (string) $parameter;
// If we cannot match it we continue
if (($result = preg_match($regex, $raw, $matches)) === false || $result === 0) {
continue;
}
// Parse the result of the regex
$required = ($matches['required'] === 'required');
$variable = $matches['variable'];
$default = $required ? null : $matches['default'];
$typehint = null;
// Advanced typehint detection
if (empty($matches['typehint_b']) === false) {
$typehint = $matches['typehint_b'];
} else if (empty($matches['typehint_a']) === false){
$typehint = $matches['typehint_a'];
}
// Set the correct default value
switch ($default) {
case null:
case 'NULL':
$default = null;
break;
case 'Array':
$default = array();
break;
default:
$default = trim($default, "'");
break;
}
// Has it child objects
$childObject = ($typehint !== null && $typehint !== 'array');
// Set the results the the response object
$setters->offsetSet(
$method->getName(),
new Entity\Method(
$required,
$default,
$typehint,
$childObject
)
);
}
// Return the just generated response
return $this->classMethodsCache[$class] = $setters;
} | [
"protected",
"function",
"getSetters",
"(",
"$",
"object",
")",
"{",
"// Get the current class\r",
"$",
"class",
"=",
"get_class",
"(",
"$",
"object",
")",
";",
"// Check if we have already parsed this class\r",
"if",
"(",
"array_key_exists",
"(",
"$",
"class",
",",
"$",
"this",
"->",
"classMethodsCache",
")",
"===",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"classMethodsCache",
"[",
"$",
"class",
"]",
";",
"}",
"// Regex for parsing ReflectionParameter::__toString()\r",
"$",
"regex",
"=",
"'/\\[\\s\\<(?P<required>[^\\>]+)\\>\\s'",
".",
"'(?:(?P<typehint_a>[^\\s]+|(?P<typehint_b>[^\\s]+)\\sor\\s(?P<typehint_c>[^\\s]+))\\s)?'",
".",
"'(?P<variable>\\$[^\\s]+)\\s(?:=\\s(?P<default>[^\\]]+)\\s)?\\]/'",
";",
"// Make reflection and fetch the methods\r",
"$",
"reflectionClass",
"=",
"new",
"ReflectionClass",
"(",
"$",
"object",
")",
";",
"$",
"methods",
"=",
"$",
"reflectionClass",
"->",
"getMethods",
"(",
"ReflectionMethod",
"::",
"IS_PUBLIC",
")",
";",
"// Make result container\r",
"$",
"setters",
"=",
"new",
"Collection",
"\\",
"Method",
"(",
")",
";",
"// Loop through the methods\r",
"foreach",
"(",
"$",
"methods",
"as",
"$",
"method",
")",
"{",
"// We only care about the setters\r",
"if",
"(",
"substr",
"(",
"$",
"method",
"->",
"getName",
"(",
")",
",",
"0",
",",
"3",
")",
"!==",
"'set'",
")",
"{",
"continue",
";",
"}",
"// Get parameter collection\r",
"$",
"parameters",
"=",
"$",
"method",
"->",
"getParameters",
"(",
")",
";",
"// We only take care of the first parameter of the setter\r",
"$",
"parameter",
"=",
"$",
"parameters",
"[",
"0",
"]",
";",
"$",
"raw",
"=",
"(",
"string",
")",
"$",
"parameter",
";",
"// If we cannot match it we continue\r",
"if",
"(",
"(",
"$",
"result",
"=",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"raw",
",",
"$",
"matches",
")",
")",
"===",
"false",
"||",
"$",
"result",
"===",
"0",
")",
"{",
"continue",
";",
"}",
"// Parse the result of the regex\r",
"$",
"required",
"=",
"(",
"$",
"matches",
"[",
"'required'",
"]",
"===",
"'required'",
")",
";",
"$",
"variable",
"=",
"$",
"matches",
"[",
"'variable'",
"]",
";",
"$",
"default",
"=",
"$",
"required",
"?",
"null",
":",
"$",
"matches",
"[",
"'default'",
"]",
";",
"$",
"typehint",
"=",
"null",
";",
"// Advanced typehint detection\r",
"if",
"(",
"empty",
"(",
"$",
"matches",
"[",
"'typehint_b'",
"]",
")",
"===",
"false",
")",
"{",
"$",
"typehint",
"=",
"$",
"matches",
"[",
"'typehint_b'",
"]",
";",
"}",
"else",
"if",
"(",
"empty",
"(",
"$",
"matches",
"[",
"'typehint_a'",
"]",
")",
"===",
"false",
")",
"{",
"$",
"typehint",
"=",
"$",
"matches",
"[",
"'typehint_a'",
"]",
";",
"}",
"// Set the correct default value\r",
"switch",
"(",
"$",
"default",
")",
"{",
"case",
"null",
":",
"case",
"'NULL'",
":",
"$",
"default",
"=",
"null",
";",
"break",
";",
"case",
"'Array'",
":",
"$",
"default",
"=",
"array",
"(",
")",
";",
"break",
";",
"default",
":",
"$",
"default",
"=",
"trim",
"(",
"$",
"default",
",",
"\"'\"",
")",
";",
"break",
";",
"}",
"// Has it child objects\r",
"$",
"childObject",
"=",
"(",
"$",
"typehint",
"!==",
"null",
"&&",
"$",
"typehint",
"!==",
"'array'",
")",
";",
"// Set the results the the response object\r",
"$",
"setters",
"->",
"offsetSet",
"(",
"$",
"method",
"->",
"getName",
"(",
")",
",",
"new",
"Entity",
"\\",
"Method",
"(",
"$",
"required",
",",
"$",
"default",
",",
"$",
"typehint",
",",
"$",
"childObject",
")",
")",
";",
"}",
"// Return the just generated response\r",
"return",
"$",
"this",
"->",
"classMethodsCache",
"[",
"$",
"class",
"]",
"=",
"$",
"setters",
";",
"}"
] | Get the setters of an object
@param mixed $object
@return Collection\Method | [
"Get",
"the",
"setters",
"of",
"an",
"object"
] | train | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByClassMethods.php#L136-L221 |
geoffadams/bedrest-core | library/BedRest/Content/Negotiation/Negotiator.php | Negotiator.setSupportedMediaTypes | public function setSupportedMediaTypes(array $mediaTypes)
{
foreach ($mediaTypes as $mediaType => $converterClass) {
if (!is_string($mediaType)) {
throw new Exception('Media type must be a string.');
}
if (!is_string($converterClass)) {
throw new Exception('Converter class name must be a string.');
}
}
$this->supportedMediaTypes = $mediaTypes;
} | php | public function setSupportedMediaTypes(array $mediaTypes)
{
foreach ($mediaTypes as $mediaType => $converterClass) {
if (!is_string($mediaType)) {
throw new Exception('Media type must be a string.');
}
if (!is_string($converterClass)) {
throw new Exception('Converter class name must be a string.');
}
}
$this->supportedMediaTypes = $mediaTypes;
} | [
"public",
"function",
"setSupportedMediaTypes",
"(",
"array",
"$",
"mediaTypes",
")",
"{",
"foreach",
"(",
"$",
"mediaTypes",
"as",
"$",
"mediaType",
"=>",
"$",
"converterClass",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"mediaType",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Media type must be a string.'",
")",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"converterClass",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Converter class name must be a string.'",
")",
";",
"}",
"}",
"$",
"this",
"->",
"supportedMediaTypes",
"=",
"$",
"mediaTypes",
";",
"}"
] | Sets the list of supported media types for negotiation.
@param array $mediaTypes
@throws \BedRest\Content\Negotiation\Exception | [
"Sets",
"the",
"list",
"of",
"supported",
"media",
"types",
"for",
"negotiation",
"."
] | train | https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Content/Negotiation/Negotiator.php#L54-L67 |
geoffadams/bedrest-core | library/BedRest/Content/Negotiation/Negotiator.php | Negotiator.negotiate | public function negotiate($content, MediaTypeList $mediaTypeList)
{
$contentType = $mediaTypeList->getBestMatch(array_keys($this->supportedMediaTypes));
if (!$contentType) {
throw new Exception('A suitable Content-Type could not be found.');
}
$result = new NegotiatedResult();
$result->contentType = $contentType;
$result->content = $this->encode($content, $contentType);
return $result;
} | php | public function negotiate($content, MediaTypeList $mediaTypeList)
{
$contentType = $mediaTypeList->getBestMatch(array_keys($this->supportedMediaTypes));
if (!$contentType) {
throw new Exception('A suitable Content-Type could not be found.');
}
$result = new NegotiatedResult();
$result->contentType = $contentType;
$result->content = $this->encode($content, $contentType);
return $result;
} | [
"public",
"function",
"negotiate",
"(",
"$",
"content",
",",
"MediaTypeList",
"$",
"mediaTypeList",
")",
"{",
"$",
"contentType",
"=",
"$",
"mediaTypeList",
"->",
"getBestMatch",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"supportedMediaTypes",
")",
")",
";",
"if",
"(",
"!",
"$",
"contentType",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'A suitable Content-Type could not be found.'",
")",
";",
"}",
"$",
"result",
"=",
"new",
"NegotiatedResult",
"(",
")",
";",
"$",
"result",
"->",
"contentType",
"=",
"$",
"contentType",
";",
"$",
"result",
"->",
"content",
"=",
"$",
"this",
"->",
"encode",
"(",
"$",
"content",
",",
"$",
"contentType",
")",
";",
"return",
"$",
"result",
";",
"}"
] | Negotiates content based on a set of input criteria.
@param mixed $content
@param \BedRest\Content\Negotiation\MediaTypeList $mediaTypeList
@throws \BedRest\Content\Negotiation\Exception
@return \BedRest\Content\Negotiation\NegotiatedResult | [
"Negotiates",
"content",
"based",
"on",
"a",
"set",
"of",
"input",
"criteria",
"."
] | train | https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Content/Negotiation/Negotiator.php#L78-L90 |
geoffadams/bedrest-core | library/BedRest/Content/Negotiation/Negotiator.php | Negotiator.getConverter | protected function getConverter($contentType)
{
if (!isset($this->supportedMediaTypes[$contentType])) {
throw new Exception("No converter found for content type '$contentType'");
}
$converterClass = $this->supportedMediaTypes[$contentType];
return new $converterClass;
} | php | protected function getConverter($contentType)
{
if (!isset($this->supportedMediaTypes[$contentType])) {
throw new Exception("No converter found for content type '$contentType'");
}
$converterClass = $this->supportedMediaTypes[$contentType];
return new $converterClass;
} | [
"protected",
"function",
"getConverter",
"(",
"$",
"contentType",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"supportedMediaTypes",
"[",
"$",
"contentType",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"No converter found for content type '$contentType'\"",
")",
";",
"}",
"$",
"converterClass",
"=",
"$",
"this",
"->",
"supportedMediaTypes",
"[",
"$",
"contentType",
"]",
";",
"return",
"new",
"$",
"converterClass",
";",
"}"
] | @todo This should use a service locator.
@param string $contentType
@return mixed | [
"@todo",
"This",
"should",
"use",
"a",
"service",
"locator",
"."
] | train | https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Content/Negotiation/Negotiator.php#L99-L108 |
geoffadams/bedrest-core | library/BedRest/Content/Negotiation/Negotiator.php | Negotiator.encode | public function encode($content, $contentType)
{
$converter = $this->getConverter($contentType);
return $converter->encode($content);
} | php | public function encode($content, $contentType)
{
$converter = $this->getConverter($contentType);
return $converter->encode($content);
} | [
"public",
"function",
"encode",
"(",
"$",
"content",
",",
"$",
"contentType",
")",
"{",
"$",
"converter",
"=",
"$",
"this",
"->",
"getConverter",
"(",
"$",
"contentType",
")",
";",
"return",
"$",
"converter",
"->",
"encode",
"(",
"$",
"content",
")",
";",
"}"
] | @param mixed $content
@param string $contentType
@return mixed | [
"@param",
"mixed",
"$content",
"@param",
"string",
"$contentType"
] | train | https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Content/Negotiation/Negotiator.php#L116-L121 |
geoffadams/bedrest-core | library/BedRest/Content/Negotiation/Negotiator.php | Negotiator.decode | public function decode($content, $contentType)
{
$converter = $this->getConverter($contentType);
return $converter->decode($content);
} | php | public function decode($content, $contentType)
{
$converter = $this->getConverter($contentType);
return $converter->decode($content);
} | [
"public",
"function",
"decode",
"(",
"$",
"content",
",",
"$",
"contentType",
")",
"{",
"$",
"converter",
"=",
"$",
"this",
"->",
"getConverter",
"(",
"$",
"contentType",
")",
";",
"return",
"$",
"converter",
"->",
"decode",
"(",
"$",
"content",
")",
";",
"}"
] | @param mixed $content
@param string $contentType
@return mixed | [
"@param",
"mixed",
"$content",
"@param",
"string",
"$contentType"
] | train | https://github.com/geoffadams/bedrest-core/blob/a77bf8b7492dfbfb720b201f7ec91a4f03417b5c/library/BedRest/Content/Negotiation/Negotiator.php#L129-L134 |
fuelphp-storage/security | src/Filter/HtmlEntities.php | HtmlEntities.cleanString | protected function cleanString($input)
{
return htmlentities(
$input,
$this->parent->getConfig('htmlentities_flags', ENT_QUOTES),
$this->parent->getConfig('htmlentities_encoding', 'UTF-8'),
$this->parent->getConfig('htmlentities_double_encode', false)
);
} | php | protected function cleanString($input)
{
return htmlentities(
$input,
$this->parent->getConfig('htmlentities_flags', ENT_QUOTES),
$this->parent->getConfig('htmlentities_encoding', 'UTF-8'),
$this->parent->getConfig('htmlentities_double_encode', false)
);
} | [
"protected",
"function",
"cleanString",
"(",
"$",
"input",
")",
"{",
"return",
"htmlentities",
"(",
"$",
"input",
",",
"$",
"this",
"->",
"parent",
"->",
"getConfig",
"(",
"'htmlentities_flags'",
",",
"ENT_QUOTES",
")",
",",
"$",
"this",
"->",
"parent",
"->",
"getConfig",
"(",
"'htmlentities_encoding'",
",",
"'UTF-8'",
")",
",",
"$",
"this",
"->",
"parent",
"->",
"getConfig",
"(",
"'htmlentities_double_encode'",
",",
"false",
")",
")",
";",
"}"
] | @param string $input
@return string | [
"@param",
"string",
"$input"
] | train | https://github.com/fuelphp-storage/security/blob/2cad42a8432bc9c9de46486623b71e105ff84b1b/src/Filter/HtmlEntities.php#L25-L33 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.parseDefinitions | private function parseDefinitions(array $content, $file)
{
if (!isset($content['services'])) {
return;
}
if (!is_array($content['services'])) {
throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file));
}
if (array_key_exists('_instanceof', $content['services'])) {
$instanceof = $content['services']['_instanceof'];
unset($content['services']['_instanceof']);
if (!is_array($instanceof)) {
throw new InvalidArgumentException(sprintf('Service "_instanceof" key must be an array, "%s" given in "%s".', gettype($instanceof), $file));
}
$this->instanceof = array();
$this->isLoadingInstanceof = true;
foreach ($instanceof as $id => $service) {
if (!$service || !is_array($service)) {
throw new InvalidArgumentException(sprintf('Type definition "%s" must be a non-empty array within "_instanceof" in %s. Check your YAML syntax.', $id, $file));
}
if (is_string($service) && 0 === strpos($service, '@')) {
throw new InvalidArgumentException(sprintf('Type definition "%s" cannot be an alias within "_instanceof" in %s. Check your YAML syntax.', $id, $file));
}
$this->parseDefinition($id, $service, $file, array());
}
}
$this->isLoadingInstanceof = false;
$defaults = $this->parseDefaults($content, $file);
foreach ($content['services'] as $id => $service) {
$this->parseDefinition($id, $service, $file, $defaults);
}
} | php | private function parseDefinitions(array $content, $file)
{
if (!isset($content['services'])) {
return;
}
if (!is_array($content['services'])) {
throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file));
}
if (array_key_exists('_instanceof', $content['services'])) {
$instanceof = $content['services']['_instanceof'];
unset($content['services']['_instanceof']);
if (!is_array($instanceof)) {
throw new InvalidArgumentException(sprintf('Service "_instanceof" key must be an array, "%s" given in "%s".', gettype($instanceof), $file));
}
$this->instanceof = array();
$this->isLoadingInstanceof = true;
foreach ($instanceof as $id => $service) {
if (!$service || !is_array($service)) {
throw new InvalidArgumentException(sprintf('Type definition "%s" must be a non-empty array within "_instanceof" in %s. Check your YAML syntax.', $id, $file));
}
if (is_string($service) && 0 === strpos($service, '@')) {
throw new InvalidArgumentException(sprintf('Type definition "%s" cannot be an alias within "_instanceof" in %s. Check your YAML syntax.', $id, $file));
}
$this->parseDefinition($id, $service, $file, array());
}
}
$this->isLoadingInstanceof = false;
$defaults = $this->parseDefaults($content, $file);
foreach ($content['services'] as $id => $service) {
$this->parseDefinition($id, $service, $file, $defaults);
}
} | [
"private",
"function",
"parseDefinitions",
"(",
"array",
"$",
"content",
",",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"content",
"[",
"'services'",
"]",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"content",
"[",
"'services'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The \"services\" key should contain an array in %s. Check your YAML syntax.'",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'_instanceof'",
",",
"$",
"content",
"[",
"'services'",
"]",
")",
")",
"{",
"$",
"instanceof",
"=",
"$",
"content",
"[",
"'services'",
"]",
"[",
"'_instanceof'",
"]",
";",
"unset",
"(",
"$",
"content",
"[",
"'services'",
"]",
"[",
"'_instanceof'",
"]",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"instanceof",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Service \"_instanceof\" key must be an array, \"%s\" given in \"%s\".'",
",",
"gettype",
"(",
"$",
"instanceof",
")",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"this",
"->",
"instanceof",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"isLoadingInstanceof",
"=",
"true",
";",
"foreach",
"(",
"$",
"instanceof",
"as",
"$",
"id",
"=>",
"$",
"service",
")",
"{",
"if",
"(",
"!",
"$",
"service",
"||",
"!",
"is_array",
"(",
"$",
"service",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Type definition \"%s\" must be a non-empty array within \"_instanceof\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"service",
")",
"&&",
"0",
"===",
"strpos",
"(",
"$",
"service",
",",
"'@'",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Type definition \"%s\" cannot be an alias within \"_instanceof\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"this",
"->",
"parseDefinition",
"(",
"$",
"id",
",",
"$",
"service",
",",
"$",
"file",
",",
"array",
"(",
")",
")",
";",
"}",
"}",
"$",
"this",
"->",
"isLoadingInstanceof",
"=",
"false",
";",
"$",
"defaults",
"=",
"$",
"this",
"->",
"parseDefaults",
"(",
"$",
"content",
",",
"$",
"file",
")",
";",
"foreach",
"(",
"$",
"content",
"[",
"'services'",
"]",
"as",
"$",
"id",
"=>",
"$",
"service",
")",
"{",
"$",
"this",
"->",
"parseDefinition",
"(",
"$",
"id",
",",
"$",
"service",
",",
"$",
"file",
",",
"$",
"defaults",
")",
";",
"}",
"}"
] | Parses definitions.
@param array $content
@param string $file | [
"Parses",
"definitions",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L206-L241 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.parseDefaults | private function parseDefaults(array &$content, $file)
{
if (!array_key_exists('_defaults', $content['services'])) {
return array();
}
$defaults = $content['services']['_defaults'];
unset($content['services']['_defaults']);
if (!is_array($defaults)) {
throw new InvalidArgumentException(sprintf('Service "_defaults" key must be an array, "%s" given in "%s".', gettype($defaults), $file));
}
foreach ($defaults as $key => $default) {
if (!isset(self::$defaultsKeywords[$key])) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" cannot be used to define a default value in "%s". Allowed keys are "%s".', $key, $file, implode('", "', self::$defaultsKeywords)));
}
}
if (isset($defaults['tags'])) {
if (!is_array($tags = $defaults['tags'])) {
throw new InvalidArgumentException(sprintf('Parameter "tags" in "_defaults" must be an array in %s. Check your YAML syntax.', $file));
}
foreach ($tags as $tag) {
if (!is_array($tag)) {
$tag = array('name' => $tag);
}
if (!isset($tag['name'])) {
throw new InvalidArgumentException(sprintf('A "tags" entry in "_defaults" is missing a "name" key in %s.', $file));
}
$name = $tag['name'];
unset($tag['name']);
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException(sprintf('The tag name in "_defaults" must be a non-empty string in %s.', $file));
}
foreach ($tag as $attribute => $value) {
if (!is_scalar($value) && null !== $value) {
throw new InvalidArgumentException(sprintf('Tag "%s", attribute "%s" in "_defaults" must be of a scalar-type in %s. Check your YAML syntax.', $name, $attribute, $file));
}
}
}
}
if (isset($defaults['bind'])) {
if (!is_array($defaults['bind'])) {
throw new InvalidArgumentException(sprintf('Parameter "bind" in "_defaults" must be an array in %s. Check your YAML syntax.', $file));
}
$defaults['bind'] = array_map(function ($v) { return new BoundArgument($v); }, $this->resolveServices($defaults['bind'], $file));
}
return $defaults;
} | php | private function parseDefaults(array &$content, $file)
{
if (!array_key_exists('_defaults', $content['services'])) {
return array();
}
$defaults = $content['services']['_defaults'];
unset($content['services']['_defaults']);
if (!is_array($defaults)) {
throw new InvalidArgumentException(sprintf('Service "_defaults" key must be an array, "%s" given in "%s".', gettype($defaults), $file));
}
foreach ($defaults as $key => $default) {
if (!isset(self::$defaultsKeywords[$key])) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" cannot be used to define a default value in "%s". Allowed keys are "%s".', $key, $file, implode('", "', self::$defaultsKeywords)));
}
}
if (isset($defaults['tags'])) {
if (!is_array($tags = $defaults['tags'])) {
throw new InvalidArgumentException(sprintf('Parameter "tags" in "_defaults" must be an array in %s. Check your YAML syntax.', $file));
}
foreach ($tags as $tag) {
if (!is_array($tag)) {
$tag = array('name' => $tag);
}
if (!isset($tag['name'])) {
throw new InvalidArgumentException(sprintf('A "tags" entry in "_defaults" is missing a "name" key in %s.', $file));
}
$name = $tag['name'];
unset($tag['name']);
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException(sprintf('The tag name in "_defaults" must be a non-empty string in %s.', $file));
}
foreach ($tag as $attribute => $value) {
if (!is_scalar($value) && null !== $value) {
throw new InvalidArgumentException(sprintf('Tag "%s", attribute "%s" in "_defaults" must be of a scalar-type in %s. Check your YAML syntax.', $name, $attribute, $file));
}
}
}
}
if (isset($defaults['bind'])) {
if (!is_array($defaults['bind'])) {
throw new InvalidArgumentException(sprintf('Parameter "bind" in "_defaults" must be an array in %s. Check your YAML syntax.', $file));
}
$defaults['bind'] = array_map(function ($v) { return new BoundArgument($v); }, $this->resolveServices($defaults['bind'], $file));
}
return $defaults;
} | [
"private",
"function",
"parseDefaults",
"(",
"array",
"&",
"$",
"content",
",",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'_defaults'",
",",
"$",
"content",
"[",
"'services'",
"]",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"defaults",
"=",
"$",
"content",
"[",
"'services'",
"]",
"[",
"'_defaults'",
"]",
";",
"unset",
"(",
"$",
"content",
"[",
"'services'",
"]",
"[",
"'_defaults'",
"]",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"defaults",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Service \"_defaults\" key must be an array, \"%s\" given in \"%s\".'",
",",
"gettype",
"(",
"$",
"defaults",
")",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"defaults",
"as",
"$",
"key",
"=>",
"$",
"default",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"defaultsKeywords",
"[",
"$",
"key",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The configuration key \"%s\" cannot be used to define a default value in \"%s\". Allowed keys are \"%s\".'",
",",
"$",
"key",
",",
"$",
"file",
",",
"implode",
"(",
"'\", \"'",
",",
"self",
"::",
"$",
"defaultsKeywords",
")",
")",
")",
";",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'tags'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"tags",
"=",
"$",
"defaults",
"[",
"'tags'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Parameter \"tags\" in \"_defaults\" must be an array in %s. Check your YAML syntax.'",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"tag",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"tag",
")",
")",
"{",
"$",
"tag",
"=",
"array",
"(",
"'name'",
"=>",
"$",
"tag",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"tag",
"[",
"'name'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A \"tags\" entry in \"_defaults\" is missing a \"name\" key in %s.'",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"name",
"=",
"$",
"tag",
"[",
"'name'",
"]",
";",
"unset",
"(",
"$",
"tag",
"[",
"'name'",
"]",
")",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"name",
")",
"||",
"''",
"===",
"$",
"name",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The tag name in \"_defaults\" must be a non-empty string in %s.'",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"tag",
"as",
"$",
"attribute",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"value",
")",
"&&",
"null",
"!==",
"$",
"value",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Tag \"%s\", attribute \"%s\" in \"_defaults\" must be of a scalar-type in %s. Check your YAML syntax.'",
",",
"$",
"name",
",",
"$",
"attribute",
",",
"$",
"file",
")",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'bind'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"defaults",
"[",
"'bind'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Parameter \"bind\" in \"_defaults\" must be an array in %s. Check your YAML syntax.'",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"defaults",
"[",
"'bind'",
"]",
"=",
"array_map",
"(",
"function",
"(",
"$",
"v",
")",
"{",
"return",
"new",
"BoundArgument",
"(",
"$",
"v",
")",
";",
"}",
",",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"defaults",
"[",
"'bind'",
"]",
",",
"$",
"file",
")",
")",
";",
"}",
"return",
"$",
"defaults",
";",
"}"
] | @param array $content
@param string $file
@return array
@throws InvalidArgumentException | [
"@param",
"array",
"$content",
"@param",
"string",
"$file"
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L251-L306 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.isUsingShortSyntax | private function isUsingShortSyntax(array $service)
{
foreach ($service as $key => $value) {
if (is_string($key) && ('' === $key || '$' !== $key[0])) {
return false;
}
}
return true;
} | php | private function isUsingShortSyntax(array $service)
{
foreach ($service as $key => $value) {
if (is_string($key) && ('' === $key || '$' !== $key[0])) {
return false;
}
}
return true;
} | [
"private",
"function",
"isUsingShortSyntax",
"(",
"array",
"$",
"service",
")",
"{",
"foreach",
"(",
"$",
"service",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"key",
")",
"&&",
"(",
"''",
"===",
"$",
"key",
"||",
"'$'",
"!==",
"$",
"key",
"[",
"0",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | @param array $service
@return bool | [
"@param",
"array",
"$service"
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L313-L322 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.parseDefinition | private function parseDefinition($id, $service, $file, array $defaults)
{
if (preg_match('/^_[a-zA-Z0-9_]*$/', $id)) {
@trigger_error(sprintf('Service names that start with an underscore are deprecated since Symfony 3.3 and will be reserved in 4.0. Rename the "%s" service or define it in XML instead.', $id), E_USER_DEPRECATED);
}
if (is_string($service) && 0 === strpos($service, '@')) {
$this->container->setAlias($id, $alias = new Alias(substr($service, 1)));
if (isset($defaults['public'])) {
$alias->setPublic($defaults['public']);
}
return;
}
if (is_array($service) && $this->isUsingShortSyntax($service)) {
$service = array('arguments' => $service);
}
if (null === $service) {
$service = array();
}
if (!is_array($service)) {
throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file));
}
$this->checkDefinition($id, $service, $file);
if (isset($service['alias'])) {
$this->container->setAlias($id, $alias = new Alias($service['alias']));
if (array_key_exists('public', $service)) {
$alias->setPublic($service['public']);
} elseif (isset($defaults['public'])) {
$alias->setPublic($defaults['public']);
}
foreach ($service as $key => $value) {
if (!in_array($key, array('alias', 'public'))) {
@trigger_error(sprintf('The configuration key "%s" is unsupported for the service "%s" which is defined as an alias in "%s". Allowed configuration keys for service aliases are "alias" and "public". The YamlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported attributes.', $key, $id, $file), E_USER_DEPRECATED);
}
}
return;
}
if ($this->isLoadingInstanceof) {
$definition = new ChildDefinition('');
} elseif (isset($service['parent'])) {
if (!empty($this->instanceof)) {
throw new InvalidArgumentException(sprintf('The service "%s" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.', $id));
}
foreach ($defaults as $k => $v) {
if ('tags' === $k) {
// since tags are never inherited from parents, there is no confusion
// thus we can safely add them as defaults to ChildDefinition
continue;
}
if ('bind' === $k) {
throw new InvalidArgumentException(sprintf('Attribute "bind" on service "%s" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file.', $id));
}
if (!isset($service[$k])) {
throw new InvalidArgumentException(sprintf('Attribute "%s" on service "%s" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.', $k, $id));
}
}
$definition = new ChildDefinition($service['parent']);
} else {
$definition = new Definition();
if (isset($defaults['public'])) {
$definition->setPublic($defaults['public']);
}
if (isset($defaults['autowire'])) {
$definition->setAutowired($defaults['autowire']);
}
if (isset($defaults['autoconfigure'])) {
$definition->setAutoconfigured($defaults['autoconfigure']);
}
$definition->setChanges(array());
}
if (isset($service['class'])) {
$definition->setClass($service['class']);
}
if (isset($service['shared'])) {
$definition->setShared($service['shared']);
}
if (isset($service['synthetic'])) {
$definition->setSynthetic($service['synthetic']);
}
if (isset($service['lazy'])) {
$definition->setLazy($service['lazy']);
}
if (isset($service['public'])) {
$definition->setPublic($service['public']);
}
if (isset($service['abstract'])) {
$definition->setAbstract($service['abstract']);
}
if (array_key_exists('deprecated', $service)) {
$definition->setDeprecated(true, $service['deprecated']);
}
if (isset($service['factory'])) {
$definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file));
}
if (isset($service['file'])) {
$definition->setFile($service['file']);
}
if (isset($service['arguments'])) {
$definition->setArguments($this->resolveServices($service['arguments'], $file));
}
if (isset($service['properties'])) {
$definition->setProperties($this->resolveServices($service['properties'], $file));
}
if (isset($service['configurator'])) {
$definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id, $file));
}
if (isset($service['calls'])) {
if (!is_array($service['calls'])) {
throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
foreach ($service['calls'] as $call) {
if (isset($call['method'])) {
$method = $call['method'];
$args = isset($call['arguments']) ? $this->resolveServices($call['arguments'], $file) : array();
} else {
$method = $call[0];
$args = isset($call[1]) ? $this->resolveServices($call[1], $file) : array();
}
if (!is_array($args)) {
throw new InvalidArgumentException(sprintf('The second parameter for function call "%s" must be an array of its arguments for service "%s" in %s. Check your YAML syntax.', $method, $id, $file));
}
$definition->addMethodCall($method, $args);
}
}
$tags = isset($service['tags']) ? $service['tags'] : array();
if (!is_array($tags)) {
throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
if (isset($defaults['tags'])) {
$tags = array_merge($tags, $defaults['tags']);
}
foreach ($tags as $tag) {
if (!is_array($tag)) {
$tag = array('name' => $tag);
}
if (!isset($tag['name'])) {
throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
}
$name = $tag['name'];
unset($tag['name']);
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file));
}
foreach ($tag as $attribute => $value) {
if (!is_scalar($value) && null !== $value) {
throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file));
}
}
$definition->addTag($name, $tag);
}
if (isset($service['decorates'])) {
if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) {
throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($service['decorates'], 1)));
}
$renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
$priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
$definition->setDecoratedService($service['decorates'], $renameId, $priority);
}
if (isset($service['autowire'])) {
$definition->setAutowired($service['autowire']);
}
if (isset($service['autowiring_types'])) {
if (is_string($service['autowiring_types'])) {
$definition->addAutowiringType($service['autowiring_types']);
} else {
if (!is_array($service['autowiring_types'])) {
throw new InvalidArgumentException(sprintf('Parameter "autowiring_types" must be a string or an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
foreach ($service['autowiring_types'] as $autowiringType) {
if (!is_string($autowiringType)) {
throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$definition->addAutowiringType($autowiringType);
}
}
}
if (isset($defaults['bind']) || isset($service['bind'])) {
// deep clone, to avoid multiple process of the same instance in the passes
$bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : array();
if (isset($service['bind'])) {
if (!is_array($service['bind'])) {
throw new InvalidArgumentException(sprintf('Parameter "bind" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$bindings = array_merge($bindings, $this->resolveServices($service['bind'], $file));
}
$definition->setBindings($bindings);
}
if (isset($service['autoconfigure'])) {
if (!$definition instanceof ChildDefinition) {
$definition->setAutoconfigured($service['autoconfigure']);
} elseif ($service['autoconfigure']) {
throw new InvalidArgumentException(sprintf('The service "%s" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service.', $id));
}
}
if (array_key_exists('namespace', $service) && !array_key_exists('resource', $service)) {
throw new InvalidArgumentException(sprintf('A "resource" attribute must be set when the "namespace" attribute is set for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
if (array_key_exists('resource', $service)) {
if (!is_string($service['resource'])) {
throw new InvalidArgumentException(sprintf('A "resource" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$exclude = isset($service['exclude']) ? $service['exclude'] : null;
$namespace = isset($service['namespace']) ? $service['namespace'] : $id;
$this->registerClasses($definition, $namespace, $service['resource'], $exclude);
} else {
$this->setDefinition($id, $definition);
}
} | php | private function parseDefinition($id, $service, $file, array $defaults)
{
if (preg_match('/^_[a-zA-Z0-9_]*$/', $id)) {
@trigger_error(sprintf('Service names that start with an underscore are deprecated since Symfony 3.3 and will be reserved in 4.0. Rename the "%s" service or define it in XML instead.', $id), E_USER_DEPRECATED);
}
if (is_string($service) && 0 === strpos($service, '@')) {
$this->container->setAlias($id, $alias = new Alias(substr($service, 1)));
if (isset($defaults['public'])) {
$alias->setPublic($defaults['public']);
}
return;
}
if (is_array($service) && $this->isUsingShortSyntax($service)) {
$service = array('arguments' => $service);
}
if (null === $service) {
$service = array();
}
if (!is_array($service)) {
throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file));
}
$this->checkDefinition($id, $service, $file);
if (isset($service['alias'])) {
$this->container->setAlias($id, $alias = new Alias($service['alias']));
if (array_key_exists('public', $service)) {
$alias->setPublic($service['public']);
} elseif (isset($defaults['public'])) {
$alias->setPublic($defaults['public']);
}
foreach ($service as $key => $value) {
if (!in_array($key, array('alias', 'public'))) {
@trigger_error(sprintf('The configuration key "%s" is unsupported for the service "%s" which is defined as an alias in "%s". Allowed configuration keys for service aliases are "alias" and "public". The YamlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported attributes.', $key, $id, $file), E_USER_DEPRECATED);
}
}
return;
}
if ($this->isLoadingInstanceof) {
$definition = new ChildDefinition('');
} elseif (isset($service['parent'])) {
if (!empty($this->instanceof)) {
throw new InvalidArgumentException(sprintf('The service "%s" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.', $id));
}
foreach ($defaults as $k => $v) {
if ('tags' === $k) {
// since tags are never inherited from parents, there is no confusion
// thus we can safely add them as defaults to ChildDefinition
continue;
}
if ('bind' === $k) {
throw new InvalidArgumentException(sprintf('Attribute "bind" on service "%s" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file.', $id));
}
if (!isset($service[$k])) {
throw new InvalidArgumentException(sprintf('Attribute "%s" on service "%s" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.', $k, $id));
}
}
$definition = new ChildDefinition($service['parent']);
} else {
$definition = new Definition();
if (isset($defaults['public'])) {
$definition->setPublic($defaults['public']);
}
if (isset($defaults['autowire'])) {
$definition->setAutowired($defaults['autowire']);
}
if (isset($defaults['autoconfigure'])) {
$definition->setAutoconfigured($defaults['autoconfigure']);
}
$definition->setChanges(array());
}
if (isset($service['class'])) {
$definition->setClass($service['class']);
}
if (isset($service['shared'])) {
$definition->setShared($service['shared']);
}
if (isset($service['synthetic'])) {
$definition->setSynthetic($service['synthetic']);
}
if (isset($service['lazy'])) {
$definition->setLazy($service['lazy']);
}
if (isset($service['public'])) {
$definition->setPublic($service['public']);
}
if (isset($service['abstract'])) {
$definition->setAbstract($service['abstract']);
}
if (array_key_exists('deprecated', $service)) {
$definition->setDeprecated(true, $service['deprecated']);
}
if (isset($service['factory'])) {
$definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file));
}
if (isset($service['file'])) {
$definition->setFile($service['file']);
}
if (isset($service['arguments'])) {
$definition->setArguments($this->resolveServices($service['arguments'], $file));
}
if (isset($service['properties'])) {
$definition->setProperties($this->resolveServices($service['properties'], $file));
}
if (isset($service['configurator'])) {
$definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id, $file));
}
if (isset($service['calls'])) {
if (!is_array($service['calls'])) {
throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
foreach ($service['calls'] as $call) {
if (isset($call['method'])) {
$method = $call['method'];
$args = isset($call['arguments']) ? $this->resolveServices($call['arguments'], $file) : array();
} else {
$method = $call[0];
$args = isset($call[1]) ? $this->resolveServices($call[1], $file) : array();
}
if (!is_array($args)) {
throw new InvalidArgumentException(sprintf('The second parameter for function call "%s" must be an array of its arguments for service "%s" in %s. Check your YAML syntax.', $method, $id, $file));
}
$definition->addMethodCall($method, $args);
}
}
$tags = isset($service['tags']) ? $service['tags'] : array();
if (!is_array($tags)) {
throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
if (isset($defaults['tags'])) {
$tags = array_merge($tags, $defaults['tags']);
}
foreach ($tags as $tag) {
if (!is_array($tag)) {
$tag = array('name' => $tag);
}
if (!isset($tag['name'])) {
throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
}
$name = $tag['name'];
unset($tag['name']);
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file));
}
foreach ($tag as $attribute => $value) {
if (!is_scalar($value) && null !== $value) {
throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file));
}
}
$definition->addTag($name, $tag);
}
if (isset($service['decorates'])) {
if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) {
throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($service['decorates'], 1)));
}
$renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
$priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
$definition->setDecoratedService($service['decorates'], $renameId, $priority);
}
if (isset($service['autowire'])) {
$definition->setAutowired($service['autowire']);
}
if (isset($service['autowiring_types'])) {
if (is_string($service['autowiring_types'])) {
$definition->addAutowiringType($service['autowiring_types']);
} else {
if (!is_array($service['autowiring_types'])) {
throw new InvalidArgumentException(sprintf('Parameter "autowiring_types" must be a string or an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
foreach ($service['autowiring_types'] as $autowiringType) {
if (!is_string($autowiringType)) {
throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$definition->addAutowiringType($autowiringType);
}
}
}
if (isset($defaults['bind']) || isset($service['bind'])) {
// deep clone, to avoid multiple process of the same instance in the passes
$bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : array();
if (isset($service['bind'])) {
if (!is_array($service['bind'])) {
throw new InvalidArgumentException(sprintf('Parameter "bind" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$bindings = array_merge($bindings, $this->resolveServices($service['bind'], $file));
}
$definition->setBindings($bindings);
}
if (isset($service['autoconfigure'])) {
if (!$definition instanceof ChildDefinition) {
$definition->setAutoconfigured($service['autoconfigure']);
} elseif ($service['autoconfigure']) {
throw new InvalidArgumentException(sprintf('The service "%s" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service.', $id));
}
}
if (array_key_exists('namespace', $service) && !array_key_exists('resource', $service)) {
throw new InvalidArgumentException(sprintf('A "resource" attribute must be set when the "namespace" attribute is set for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
if (array_key_exists('resource', $service)) {
if (!is_string($service['resource'])) {
throw new InvalidArgumentException(sprintf('A "resource" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$exclude = isset($service['exclude']) ? $service['exclude'] : null;
$namespace = isset($service['namespace']) ? $service['namespace'] : $id;
$this->registerClasses($definition, $namespace, $service['resource'], $exclude);
} else {
$this->setDefinition($id, $definition);
}
} | [
"private",
"function",
"parseDefinition",
"(",
"$",
"id",
",",
"$",
"service",
",",
"$",
"file",
",",
"array",
"$",
"defaults",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/^_[a-zA-Z0-9_]*$/'",
",",
"$",
"id",
")",
")",
"{",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'Service names that start with an underscore are deprecated since Symfony 3.3 and will be reserved in 4.0. Rename the \"%s\" service or define it in XML instead.'",
",",
"$",
"id",
")",
",",
"E_USER_DEPRECATED",
")",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"service",
")",
"&&",
"0",
"===",
"strpos",
"(",
"$",
"service",
",",
"'@'",
")",
")",
"{",
"$",
"this",
"->",
"container",
"->",
"setAlias",
"(",
"$",
"id",
",",
"$",
"alias",
"=",
"new",
"Alias",
"(",
"substr",
"(",
"$",
"service",
",",
"1",
")",
")",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'public'",
"]",
")",
")",
"{",
"$",
"alias",
"->",
"setPublic",
"(",
"$",
"defaults",
"[",
"'public'",
"]",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"service",
")",
"&&",
"$",
"this",
"->",
"isUsingShortSyntax",
"(",
"$",
"service",
")",
")",
"{",
"$",
"service",
"=",
"array",
"(",
"'arguments'",
"=>",
"$",
"service",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"service",
")",
"{",
"$",
"service",
"=",
"array",
"(",
")",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"service",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A service definition must be an array or a string starting with \"@\" but %s found for service \"%s\" in %s. Check your YAML syntax.'",
",",
"gettype",
"(",
"$",
"service",
")",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"this",
"->",
"checkDefinition",
"(",
"$",
"id",
",",
"$",
"service",
",",
"$",
"file",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'alias'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"container",
"->",
"setAlias",
"(",
"$",
"id",
",",
"$",
"alias",
"=",
"new",
"Alias",
"(",
"$",
"service",
"[",
"'alias'",
"]",
")",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"'public'",
",",
"$",
"service",
")",
")",
"{",
"$",
"alias",
"->",
"setPublic",
"(",
"$",
"service",
"[",
"'public'",
"]",
")",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'public'",
"]",
")",
")",
"{",
"$",
"alias",
"->",
"setPublic",
"(",
"$",
"defaults",
"[",
"'public'",
"]",
")",
";",
"}",
"foreach",
"(",
"$",
"service",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"key",
",",
"array",
"(",
"'alias'",
",",
"'public'",
")",
")",
")",
"{",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'The configuration key \"%s\" is unsupported for the service \"%s\" which is defined as an alias in \"%s\". Allowed configuration keys for service aliases are \"alias\" and \"public\". The YamlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported attributes.'",
",",
"$",
"key",
",",
"$",
"id",
",",
"$",
"file",
")",
",",
"E_USER_DEPRECATED",
")",
";",
"}",
"}",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isLoadingInstanceof",
")",
"{",
"$",
"definition",
"=",
"new",
"ChildDefinition",
"(",
"''",
")",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"service",
"[",
"'parent'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"instanceof",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The service \"%s\" cannot use the \"parent\" option in the same file where \"_instanceof\" configuration is defined as using both is not supported. Move your child definitions to a separate file.'",
",",
"$",
"id",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"defaults",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"'tags'",
"===",
"$",
"k",
")",
"{",
"// since tags are never inherited from parents, there is no confusion",
"// thus we can safely add them as defaults to ChildDefinition",
"continue",
";",
"}",
"if",
"(",
"'bind'",
"===",
"$",
"k",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Attribute \"bind\" on service \"%s\" cannot be inherited from \"_defaults\" when a \"parent\" is set. Move your child definitions to a separate file.'",
",",
"$",
"id",
")",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"service",
"[",
"$",
"k",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Attribute \"%s\" on service \"%s\" cannot be inherited from \"_defaults\" when a \"parent\" is set. Move your child definitions to a separate file or define this attribute explicitly.'",
",",
"$",
"k",
",",
"$",
"id",
")",
")",
";",
"}",
"}",
"$",
"definition",
"=",
"new",
"ChildDefinition",
"(",
"$",
"service",
"[",
"'parent'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"definition",
"=",
"new",
"Definition",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'public'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setPublic",
"(",
"$",
"defaults",
"[",
"'public'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'autowire'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setAutowired",
"(",
"$",
"defaults",
"[",
"'autowire'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'autoconfigure'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setAutoconfigured",
"(",
"$",
"defaults",
"[",
"'autoconfigure'",
"]",
")",
";",
"}",
"$",
"definition",
"->",
"setChanges",
"(",
"array",
"(",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'class'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setClass",
"(",
"$",
"service",
"[",
"'class'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'shared'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setShared",
"(",
"$",
"service",
"[",
"'shared'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'synthetic'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setSynthetic",
"(",
"$",
"service",
"[",
"'synthetic'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'lazy'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setLazy",
"(",
"$",
"service",
"[",
"'lazy'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'public'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setPublic",
"(",
"$",
"service",
"[",
"'public'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'abstract'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setAbstract",
"(",
"$",
"service",
"[",
"'abstract'",
"]",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'deprecated'",
",",
"$",
"service",
")",
")",
"{",
"$",
"definition",
"->",
"setDeprecated",
"(",
"true",
",",
"$",
"service",
"[",
"'deprecated'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'factory'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setFactory",
"(",
"$",
"this",
"->",
"parseCallable",
"(",
"$",
"service",
"[",
"'factory'",
"]",
",",
"'factory'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'file'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setFile",
"(",
"$",
"service",
"[",
"'file'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'arguments'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setArguments",
"(",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"service",
"[",
"'arguments'",
"]",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'properties'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setProperties",
"(",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"service",
"[",
"'properties'",
"]",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'configurator'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setConfigurator",
"(",
"$",
"this",
"->",
"parseCallable",
"(",
"$",
"service",
"[",
"'configurator'",
"]",
",",
"'configurator'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'calls'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"service",
"[",
"'calls'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Parameter \"calls\" must be an array for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"service",
"[",
"'calls'",
"]",
"as",
"$",
"call",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"call",
"[",
"'method'",
"]",
")",
")",
"{",
"$",
"method",
"=",
"$",
"call",
"[",
"'method'",
"]",
";",
"$",
"args",
"=",
"isset",
"(",
"$",
"call",
"[",
"'arguments'",
"]",
")",
"?",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"call",
"[",
"'arguments'",
"]",
",",
"$",
"file",
")",
":",
"array",
"(",
")",
";",
"}",
"else",
"{",
"$",
"method",
"=",
"$",
"call",
"[",
"0",
"]",
";",
"$",
"args",
"=",
"isset",
"(",
"$",
"call",
"[",
"1",
"]",
")",
"?",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"call",
"[",
"1",
"]",
",",
"$",
"file",
")",
":",
"array",
"(",
")",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"args",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The second parameter for function call \"%s\" must be an array of its arguments for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"method",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"definition",
"->",
"addMethodCall",
"(",
"$",
"method",
",",
"$",
"args",
")",
";",
"}",
"}",
"$",
"tags",
"=",
"isset",
"(",
"$",
"service",
"[",
"'tags'",
"]",
")",
"?",
"$",
"service",
"[",
"'tags'",
"]",
":",
"array",
"(",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"tags",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Parameter \"tags\" must be an array for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'tags'",
"]",
")",
")",
"{",
"$",
"tags",
"=",
"array_merge",
"(",
"$",
"tags",
",",
"$",
"defaults",
"[",
"'tags'",
"]",
")",
";",
"}",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"tag",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"tag",
")",
")",
"{",
"$",
"tag",
"=",
"array",
"(",
"'name'",
"=>",
"$",
"tag",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"tag",
"[",
"'name'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A \"tags\" entry is missing a \"name\" key for service \"%s\" in %s.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"name",
"=",
"$",
"tag",
"[",
"'name'",
"]",
";",
"unset",
"(",
"$",
"tag",
"[",
"'name'",
"]",
")",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"name",
")",
"||",
"''",
"===",
"$",
"name",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The tag name for service \"%s\" in %s must be a non-empty string.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"tag",
"as",
"$",
"attribute",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_scalar",
"(",
"$",
"value",
")",
"&&",
"null",
"!==",
"$",
"value",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A \"tags\" attribute must be of a scalar-type for service \"%s\", tag \"%s\", attribute \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"name",
",",
"$",
"attribute",
",",
"$",
"file",
")",
")",
";",
"}",
"}",
"$",
"definition",
"->",
"addTag",
"(",
"$",
"name",
",",
"$",
"tag",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'decorates'",
"]",
")",
")",
"{",
"if",
"(",
"''",
"!==",
"$",
"service",
"[",
"'decorates'",
"]",
"&&",
"'@'",
"===",
"$",
"service",
"[",
"'decorates'",
"]",
"[",
"0",
"]",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The value of the \"decorates\" option for the \"%s\" service must be the id of the service without the \"@\" prefix (replace \"%s\" with \"%s\").'",
",",
"$",
"id",
",",
"$",
"service",
"[",
"'decorates'",
"]",
",",
"substr",
"(",
"$",
"service",
"[",
"'decorates'",
"]",
",",
"1",
")",
")",
")",
";",
"}",
"$",
"renameId",
"=",
"isset",
"(",
"$",
"service",
"[",
"'decoration_inner_name'",
"]",
")",
"?",
"$",
"service",
"[",
"'decoration_inner_name'",
"]",
":",
"null",
";",
"$",
"priority",
"=",
"isset",
"(",
"$",
"service",
"[",
"'decoration_priority'",
"]",
")",
"?",
"$",
"service",
"[",
"'decoration_priority'",
"]",
":",
"0",
";",
"$",
"definition",
"->",
"setDecoratedService",
"(",
"$",
"service",
"[",
"'decorates'",
"]",
",",
"$",
"renameId",
",",
"$",
"priority",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'autowire'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"setAutowired",
"(",
"$",
"service",
"[",
"'autowire'",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'autowiring_types'",
"]",
")",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"service",
"[",
"'autowiring_types'",
"]",
")",
")",
"{",
"$",
"definition",
"->",
"addAutowiringType",
"(",
"$",
"service",
"[",
"'autowiring_types'",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"service",
"[",
"'autowiring_types'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Parameter \"autowiring_types\" must be a string or an array for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"service",
"[",
"'autowiring_types'",
"]",
"as",
"$",
"autowiringType",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"autowiringType",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A \"autowiring_types\" attribute must be of type string for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"definition",
"->",
"addAutowiringType",
"(",
"$",
"autowiringType",
")",
";",
"}",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"defaults",
"[",
"'bind'",
"]",
")",
"||",
"isset",
"(",
"$",
"service",
"[",
"'bind'",
"]",
")",
")",
"{",
"// deep clone, to avoid multiple process of the same instance in the passes",
"$",
"bindings",
"=",
"isset",
"(",
"$",
"defaults",
"[",
"'bind'",
"]",
")",
"?",
"unserialize",
"(",
"serialize",
"(",
"$",
"defaults",
"[",
"'bind'",
"]",
")",
")",
":",
"array",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'bind'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"service",
"[",
"'bind'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Parameter \"bind\" must be an array for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"bindings",
"=",
"array_merge",
"(",
"$",
"bindings",
",",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"service",
"[",
"'bind'",
"]",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"definition",
"->",
"setBindings",
"(",
"$",
"bindings",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"service",
"[",
"'autoconfigure'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"$",
"definition",
"instanceof",
"ChildDefinition",
")",
"{",
"$",
"definition",
"->",
"setAutoconfigured",
"(",
"$",
"service",
"[",
"'autoconfigure'",
"]",
")",
";",
"}",
"elseif",
"(",
"$",
"service",
"[",
"'autoconfigure'",
"]",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The service \"%s\" cannot have a \"parent\" and also have \"autoconfigure\". Try setting \"autoconfigure: false\" for the service.'",
",",
"$",
"id",
")",
")",
";",
"}",
"}",
"if",
"(",
"array_key_exists",
"(",
"'namespace'",
",",
"$",
"service",
")",
"&&",
"!",
"array_key_exists",
"(",
"'resource'",
",",
"$",
"service",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A \"resource\" attribute must be set when the \"namespace\" attribute is set for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'resource'",
",",
"$",
"service",
")",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"service",
"[",
"'resource'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'A \"resource\" attribute must be of type string for service \"%s\" in %s. Check your YAML syntax.'",
",",
"$",
"id",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"exclude",
"=",
"isset",
"(",
"$",
"service",
"[",
"'exclude'",
"]",
")",
"?",
"$",
"service",
"[",
"'exclude'",
"]",
":",
"null",
";",
"$",
"namespace",
"=",
"isset",
"(",
"$",
"service",
"[",
"'namespace'",
"]",
")",
"?",
"$",
"service",
"[",
"'namespace'",
"]",
":",
"$",
"id",
";",
"$",
"this",
"->",
"registerClasses",
"(",
"$",
"definition",
",",
"$",
"namespace",
",",
"$",
"service",
"[",
"'resource'",
"]",
",",
"$",
"exclude",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"setDefinition",
"(",
"$",
"id",
",",
"$",
"definition",
")",
";",
"}",
"}"
] | Parses a definition.
@param string $id
@param array|string $service
@param string $file
@param array $defaults
@throws InvalidArgumentException When tags are invalid | [
"Parses",
"a",
"definition",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L334-L588 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.loadFile | protected function loadFile($file)
{
if (!class_exists('zxf\Symfony\Component\Yaml\Parser')) {
throw new RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.');
}
if (!stream_is_local($file)) {
throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
}
if (!file_exists($file)) {
throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
}
if (null === $this->yamlParser) {
$this->yamlParser = new YamlParser();
}
$prevErrorHandler = set_error_handler(function ($level, $message, $script, $line) use ($file, &$prevErrorHandler) {
$message = E_USER_DEPRECATED === $level ? preg_replace('/ on line \d+/', ' in "'.$file.'"$0', $message) : $message;
return $prevErrorHandler ? $prevErrorHandler($level, $message, $script, $line) : false;
});
try {
$configuration = $this->yamlParser->parseFile($file, Yaml::PARSE_CONSTANT | Yaml::PARSE_CUSTOM_TAGS);
} catch (ParseException $e) {
throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e);
} finally {
restore_error_handler();
}
return $this->validate($configuration, $file);
} | php | protected function loadFile($file)
{
if (!class_exists('zxf\Symfony\Component\Yaml\Parser')) {
throw new RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.');
}
if (!stream_is_local($file)) {
throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
}
if (!file_exists($file)) {
throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
}
if (null === $this->yamlParser) {
$this->yamlParser = new YamlParser();
}
$prevErrorHandler = set_error_handler(function ($level, $message, $script, $line) use ($file, &$prevErrorHandler) {
$message = E_USER_DEPRECATED === $level ? preg_replace('/ on line \d+/', ' in "'.$file.'"$0', $message) : $message;
return $prevErrorHandler ? $prevErrorHandler($level, $message, $script, $line) : false;
});
try {
$configuration = $this->yamlParser->parseFile($file, Yaml::PARSE_CONSTANT | Yaml::PARSE_CUSTOM_TAGS);
} catch (ParseException $e) {
throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e);
} finally {
restore_error_handler();
}
return $this->validate($configuration, $file);
} | [
"protected",
"function",
"loadFile",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'zxf\\Symfony\\Component\\Yaml\\Parser'",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Unable to load YAML config files as the Symfony Yaml Component is not installed.'",
")",
";",
"}",
"if",
"(",
"!",
"stream_is_local",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'This is not a local file \"%s\".'",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The file \"%s\" does not exist.'",
",",
"$",
"file",
")",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"yamlParser",
")",
"{",
"$",
"this",
"->",
"yamlParser",
"=",
"new",
"YamlParser",
"(",
")",
";",
"}",
"$",
"prevErrorHandler",
"=",
"set_error_handler",
"(",
"function",
"(",
"$",
"level",
",",
"$",
"message",
",",
"$",
"script",
",",
"$",
"line",
")",
"use",
"(",
"$",
"file",
",",
"&",
"$",
"prevErrorHandler",
")",
"{",
"$",
"message",
"=",
"E_USER_DEPRECATED",
"===",
"$",
"level",
"?",
"preg_replace",
"(",
"'/ on line \\d+/'",
",",
"' in \"'",
".",
"$",
"file",
".",
"'\"$0'",
",",
"$",
"message",
")",
":",
"$",
"message",
";",
"return",
"$",
"prevErrorHandler",
"?",
"$",
"prevErrorHandler",
"(",
"$",
"level",
",",
"$",
"message",
",",
"$",
"script",
",",
"$",
"line",
")",
":",
"false",
";",
"}",
")",
";",
"try",
"{",
"$",
"configuration",
"=",
"$",
"this",
"->",
"yamlParser",
"->",
"parseFile",
"(",
"$",
"file",
",",
"Yaml",
"::",
"PARSE_CONSTANT",
"|",
"Yaml",
"::",
"PARSE_CUSTOM_TAGS",
")",
";",
"}",
"catch",
"(",
"ParseException",
"$",
"e",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The file \"%s\" does not contain valid YAML.'",
",",
"$",
"file",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"finally",
"{",
"restore_error_handler",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"validate",
"(",
"$",
"configuration",
",",
"$",
"file",
")",
";",
"}"
] | Loads a YAML file.
@param string $file
@return array The file content
@throws InvalidArgumentException when the given file is not a local file or when it does not exist | [
"Loads",
"a",
"YAML",
"file",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L642-L675 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.validate | private function validate($content, $file)
{
if (null === $content) {
return $content;
}
if (!is_array($content)) {
throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
}
foreach ($content as $namespace => $data) {
if (in_array($namespace, array('imports', 'parameters', 'services'))) {
continue;
}
if (!$this->container->hasExtension($namespace)) {
$extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
throw new InvalidArgumentException(sprintf(
'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
$namespace,
$file,
$namespace,
$extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
));
}
}
return $content;
} | php | private function validate($content, $file)
{
if (null === $content) {
return $content;
}
if (!is_array($content)) {
throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
}
foreach ($content as $namespace => $data) {
if (in_array($namespace, array('imports', 'parameters', 'services'))) {
continue;
}
if (!$this->container->hasExtension($namespace)) {
$extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
throw new InvalidArgumentException(sprintf(
'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
$namespace,
$file,
$namespace,
$extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
));
}
}
return $content;
} | [
"private",
"function",
"validate",
"(",
"$",
"content",
",",
"$",
"file",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"content",
")",
"{",
"return",
"$",
"content",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"content",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The service file \"%s\" is not valid. It should contain an array. Check your YAML syntax.'",
",",
"$",
"file",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"content",
"as",
"$",
"namespace",
"=>",
"$",
"data",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"namespace",
",",
"array",
"(",
"'imports'",
",",
"'parameters'",
",",
"'services'",
")",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"container",
"->",
"hasExtension",
"(",
"$",
"namespace",
")",
")",
"{",
"$",
"extensionNamespaces",
"=",
"array_filter",
"(",
"array_map",
"(",
"function",
"(",
"$",
"ext",
")",
"{",
"return",
"$",
"ext",
"->",
"getAlias",
"(",
")",
";",
"}",
",",
"$",
"this",
"->",
"container",
"->",
"getExtensions",
"(",
")",
")",
")",
";",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'There is no extension able to load the configuration for \"%s\" (in %s). Looked for namespace \"%s\", found %s'",
",",
"$",
"namespace",
",",
"$",
"file",
",",
"$",
"namespace",
",",
"$",
"extensionNamespaces",
"?",
"sprintf",
"(",
"'\"%s\"'",
",",
"implode",
"(",
"'\", \"'",
",",
"$",
"extensionNamespaces",
")",
")",
":",
"'none'",
")",
")",
";",
"}",
"}",
"return",
"$",
"content",
";",
"}"
] | Validates a YAML file.
@param mixed $content
@param string $file
@return array
@throws InvalidArgumentException When service file is not valid | [
"Validates",
"a",
"YAML",
"file",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L687-L715 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.resolveServices | private function resolveServices($value, $file, $isParameter = false)
{
if ($value instanceof TaggedValue) {
$argument = $value->getValue();
if ('iterator' === $value->getTag()) {
if (!is_array($argument)) {
throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts sequences in "%s".', $file));
}
$argument = $this->resolveServices($argument, $file, $isParameter);
try {
return new IteratorArgument($argument);
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts arrays of "@service" references in "%s".', $file));
}
}
if ('tagged' === $value->getTag()) {
if (!is_string($argument) || !$argument) {
throw new InvalidArgumentException(sprintf('"!tagged" tag only accepts non empty string in "%s".', $file));
}
return new TaggedIteratorArgument($argument);
}
if ('service' === $value->getTag()) {
if ($isParameter) {
throw new InvalidArgumentException(sprintf('Using an anonymous service in a parameter is not allowed in "%s".', $file));
}
$isLoadingInstanceof = $this->isLoadingInstanceof;
$this->isLoadingInstanceof = false;
$instanceof = $this->instanceof;
$this->instanceof = array();
$id = sprintf('%d_%s', ++$this->anonymousServicesCount, preg_replace('/^.*\\\\/', '', isset($argument['class']) ? $argument['class'] : '').$this->anonymousServicesSuffix);
$this->parseDefinition($id, $argument, $file, array());
if (!$this->container->hasDefinition($id)) {
throw new InvalidArgumentException(sprintf('Creating an alias using the tag "!service" is not allowed in "%s".', $file));
}
$this->container->getDefinition($id)->setPublic(false);
$this->isLoadingInstanceof = $isLoadingInstanceof;
$this->instanceof = $instanceof;
return new Reference($id);
}
throw new InvalidArgumentException(sprintf('Unsupported tag "!%s".', $value->getTag()));
}
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = $this->resolveServices($v, $file, $isParameter);
}
} elseif (is_string($value) && 0 === strpos($value, '@=')) {
if (!class_exists(Expression::class)) {
throw new \LogicException(sprintf('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".'));
}
return new Expression(substr($value, 2));
} elseif (is_string($value) && 0 === strpos($value, '@')) {
if (0 === strpos($value, '@@')) {
$value = substr($value, 1);
$invalidBehavior = null;
} elseif (0 === strpos($value, '@!')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
} elseif (0 === strpos($value, '@?')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
} else {
$value = substr($value, 1);
$invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
}
if ('=' === substr($value, -1)) {
@trigger_error(sprintf('The "=" suffix that used to disable strict references in Symfony 2.x is deprecated since Symfony 3.3 and will be unsupported in 4.0. Remove it in "%s".', $value), E_USER_DEPRECATED);
$value = substr($value, 0, -1);
}
if (null !== $invalidBehavior) {
$value = new Reference($value, $invalidBehavior);
}
}
return $value;
} | php | private function resolveServices($value, $file, $isParameter = false)
{
if ($value instanceof TaggedValue) {
$argument = $value->getValue();
if ('iterator' === $value->getTag()) {
if (!is_array($argument)) {
throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts sequences in "%s".', $file));
}
$argument = $this->resolveServices($argument, $file, $isParameter);
try {
return new IteratorArgument($argument);
} catch (InvalidArgumentException $e) {
throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts arrays of "@service" references in "%s".', $file));
}
}
if ('tagged' === $value->getTag()) {
if (!is_string($argument) || !$argument) {
throw new InvalidArgumentException(sprintf('"!tagged" tag only accepts non empty string in "%s".', $file));
}
return new TaggedIteratorArgument($argument);
}
if ('service' === $value->getTag()) {
if ($isParameter) {
throw new InvalidArgumentException(sprintf('Using an anonymous service in a parameter is not allowed in "%s".', $file));
}
$isLoadingInstanceof = $this->isLoadingInstanceof;
$this->isLoadingInstanceof = false;
$instanceof = $this->instanceof;
$this->instanceof = array();
$id = sprintf('%d_%s', ++$this->anonymousServicesCount, preg_replace('/^.*\\\\/', '', isset($argument['class']) ? $argument['class'] : '').$this->anonymousServicesSuffix);
$this->parseDefinition($id, $argument, $file, array());
if (!$this->container->hasDefinition($id)) {
throw new InvalidArgumentException(sprintf('Creating an alias using the tag "!service" is not allowed in "%s".', $file));
}
$this->container->getDefinition($id)->setPublic(false);
$this->isLoadingInstanceof = $isLoadingInstanceof;
$this->instanceof = $instanceof;
return new Reference($id);
}
throw new InvalidArgumentException(sprintf('Unsupported tag "!%s".', $value->getTag()));
}
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = $this->resolveServices($v, $file, $isParameter);
}
} elseif (is_string($value) && 0 === strpos($value, '@=')) {
if (!class_exists(Expression::class)) {
throw new \LogicException(sprintf('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".'));
}
return new Expression(substr($value, 2));
} elseif (is_string($value) && 0 === strpos($value, '@')) {
if (0 === strpos($value, '@@')) {
$value = substr($value, 1);
$invalidBehavior = null;
} elseif (0 === strpos($value, '@!')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
} elseif (0 === strpos($value, '@?')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
} else {
$value = substr($value, 1);
$invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
}
if ('=' === substr($value, -1)) {
@trigger_error(sprintf('The "=" suffix that used to disable strict references in Symfony 2.x is deprecated since Symfony 3.3 and will be unsupported in 4.0. Remove it in "%s".', $value), E_USER_DEPRECATED);
$value = substr($value, 0, -1);
}
if (null !== $invalidBehavior) {
$value = new Reference($value, $invalidBehavior);
}
}
return $value;
} | [
"private",
"function",
"resolveServices",
"(",
"$",
"value",
",",
"$",
"file",
",",
"$",
"isParameter",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"TaggedValue",
")",
"{",
"$",
"argument",
"=",
"$",
"value",
"->",
"getValue",
"(",
")",
";",
"if",
"(",
"'iterator'",
"===",
"$",
"value",
"->",
"getTag",
"(",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"argument",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"!iterator\" tag only accepts sequences in \"%s\".'",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"argument",
"=",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"argument",
",",
"$",
"file",
",",
"$",
"isParameter",
")",
";",
"try",
"{",
"return",
"new",
"IteratorArgument",
"(",
"$",
"argument",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"!iterator\" tag only accepts arrays of \"@service\" references in \"%s\".'",
",",
"$",
"file",
")",
")",
";",
"}",
"}",
"if",
"(",
"'tagged'",
"===",
"$",
"value",
"->",
"getTag",
"(",
")",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"argument",
")",
"||",
"!",
"$",
"argument",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"!tagged\" tag only accepts non empty string in \"%s\".'",
",",
"$",
"file",
")",
")",
";",
"}",
"return",
"new",
"TaggedIteratorArgument",
"(",
"$",
"argument",
")",
";",
"}",
"if",
"(",
"'service'",
"===",
"$",
"value",
"->",
"getTag",
"(",
")",
")",
"{",
"if",
"(",
"$",
"isParameter",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Using an anonymous service in a parameter is not allowed in \"%s\".'",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"isLoadingInstanceof",
"=",
"$",
"this",
"->",
"isLoadingInstanceof",
";",
"$",
"this",
"->",
"isLoadingInstanceof",
"=",
"false",
";",
"$",
"instanceof",
"=",
"$",
"this",
"->",
"instanceof",
";",
"$",
"this",
"->",
"instanceof",
"=",
"array",
"(",
")",
";",
"$",
"id",
"=",
"sprintf",
"(",
"'%d_%s'",
",",
"++",
"$",
"this",
"->",
"anonymousServicesCount",
",",
"preg_replace",
"(",
"'/^.*\\\\\\\\/'",
",",
"''",
",",
"isset",
"(",
"$",
"argument",
"[",
"'class'",
"]",
")",
"?",
"$",
"argument",
"[",
"'class'",
"]",
":",
"''",
")",
".",
"$",
"this",
"->",
"anonymousServicesSuffix",
")",
";",
"$",
"this",
"->",
"parseDefinition",
"(",
"$",
"id",
",",
"$",
"argument",
",",
"$",
"file",
",",
"array",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"container",
"->",
"hasDefinition",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Creating an alias using the tag \"!service\" is not allowed in \"%s\".'",
",",
"$",
"file",
")",
")",
";",
"}",
"$",
"this",
"->",
"container",
"->",
"getDefinition",
"(",
"$",
"id",
")",
"->",
"setPublic",
"(",
"false",
")",
";",
"$",
"this",
"->",
"isLoadingInstanceof",
"=",
"$",
"isLoadingInstanceof",
";",
"$",
"this",
"->",
"instanceof",
"=",
"$",
"instanceof",
";",
"return",
"new",
"Reference",
"(",
"$",
"id",
")",
";",
"}",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unsupported tag \"!%s\".'",
",",
"$",
"value",
"->",
"getTag",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"foreach",
"(",
"$",
"value",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"value",
"[",
"$",
"k",
"]",
"=",
"$",
"this",
"->",
"resolveServices",
"(",
"$",
"v",
",",
"$",
"file",
",",
"$",
"isParameter",
")",
";",
"}",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"value",
")",
"&&",
"0",
"===",
"strpos",
"(",
"$",
"value",
",",
"'@='",
")",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"Expression",
"::",
"class",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"sprintf",
"(",
"'The \"@=\" expression syntax cannot be used without the ExpressionLanguage component. Try running \"composer require symfony/expression-language\".'",
")",
")",
";",
"}",
"return",
"new",
"Expression",
"(",
"substr",
"(",
"$",
"value",
",",
"2",
")",
")",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"value",
")",
"&&",
"0",
"===",
"strpos",
"(",
"$",
"value",
",",
"'@'",
")",
")",
"{",
"if",
"(",
"0",
"===",
"strpos",
"(",
"$",
"value",
",",
"'@@'",
")",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"1",
")",
";",
"$",
"invalidBehavior",
"=",
"null",
";",
"}",
"elseif",
"(",
"0",
"===",
"strpos",
"(",
"$",
"value",
",",
"'@!'",
")",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"2",
")",
";",
"$",
"invalidBehavior",
"=",
"ContainerInterface",
"::",
"IGNORE_ON_UNINITIALIZED_REFERENCE",
";",
"}",
"elseif",
"(",
"0",
"===",
"strpos",
"(",
"$",
"value",
",",
"'@?'",
")",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"2",
")",
";",
"$",
"invalidBehavior",
"=",
"ContainerInterface",
"::",
"IGNORE_ON_INVALID_REFERENCE",
";",
"}",
"else",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"1",
")",
";",
"$",
"invalidBehavior",
"=",
"ContainerInterface",
"::",
"EXCEPTION_ON_INVALID_REFERENCE",
";",
"}",
"if",
"(",
"'='",
"===",
"substr",
"(",
"$",
"value",
",",
"-",
"1",
")",
")",
"{",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'The \"=\" suffix that used to disable strict references in Symfony 2.x is deprecated since Symfony 3.3 and will be unsupported in 4.0. Remove it in \"%s\".'",
",",
"$",
"value",
")",
",",
"E_USER_DEPRECATED",
")",
";",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"-",
"1",
")",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"invalidBehavior",
")",
"{",
"$",
"value",
"=",
"new",
"Reference",
"(",
"$",
"value",
",",
"$",
"invalidBehavior",
")",
";",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] | Resolves services.
@param mixed $value
@param string $file
@param bool $isParameter
@return array|string|Reference|ArgumentInterface | [
"Resolves",
"services",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L726-L812 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.loadFromExtensions | private function loadFromExtensions(array $content)
{
foreach ($content as $namespace => $values) {
if (in_array($namespace, array('imports', 'parameters', 'services'))) {
continue;
}
if (!is_array($values) && null !== $values) {
$values = array();
}
$this->container->loadFromExtension($namespace, $values);
}
} | php | private function loadFromExtensions(array $content)
{
foreach ($content as $namespace => $values) {
if (in_array($namespace, array('imports', 'parameters', 'services'))) {
continue;
}
if (!is_array($values) && null !== $values) {
$values = array();
}
$this->container->loadFromExtension($namespace, $values);
}
} | [
"private",
"function",
"loadFromExtensions",
"(",
"array",
"$",
"content",
")",
"{",
"foreach",
"(",
"$",
"content",
"as",
"$",
"namespace",
"=>",
"$",
"values",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"namespace",
",",
"array",
"(",
"'imports'",
",",
"'parameters'",
",",
"'services'",
")",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"values",
")",
"&&",
"null",
"!==",
"$",
"values",
")",
"{",
"$",
"values",
"=",
"array",
"(",
")",
";",
"}",
"$",
"this",
"->",
"container",
"->",
"loadFromExtension",
"(",
"$",
"namespace",
",",
"$",
"values",
")",
";",
"}",
"}"
] | Loads from Extensions. | [
"Loads",
"from",
"Extensions",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L817-L830 |
zhaoxianfang/tools | src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php | YamlFileLoader.checkDefinition | private function checkDefinition($id, array $definition, $file)
{
if ($throw = $this->isLoadingInstanceof) {
$keywords = self::$instanceofKeywords;
} elseif ($throw = (isset($definition['resource']) || isset($definition['namespace']))) {
$keywords = self::$prototypeKeywords;
} else {
$keywords = self::$serviceKeywords;
}
foreach ($definition as $key => $value) {
if (!isset($keywords[$key])) {
if ($throw) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for definition "%s" in "%s". Allowed configuration keys are "%s".', $key, $id, $file, implode('", "', $keywords)));
}
@trigger_error(sprintf('The configuration key "%s" is unsupported for service definition "%s" in "%s". Allowed configuration keys are "%s". The YamlFileLoader object will raise an exception instead in Symfony 4.0 when detecting an unsupported service configuration key.', $key, $id, $file, implode('", "', $keywords)), E_USER_DEPRECATED);
}
}
} | php | private function checkDefinition($id, array $definition, $file)
{
if ($throw = $this->isLoadingInstanceof) {
$keywords = self::$instanceofKeywords;
} elseif ($throw = (isset($definition['resource']) || isset($definition['namespace']))) {
$keywords = self::$prototypeKeywords;
} else {
$keywords = self::$serviceKeywords;
}
foreach ($definition as $key => $value) {
if (!isset($keywords[$key])) {
if ($throw) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for definition "%s" in "%s". Allowed configuration keys are "%s".', $key, $id, $file, implode('", "', $keywords)));
}
@trigger_error(sprintf('The configuration key "%s" is unsupported for service definition "%s" in "%s". Allowed configuration keys are "%s". The YamlFileLoader object will raise an exception instead in Symfony 4.0 when detecting an unsupported service configuration key.', $key, $id, $file, implode('", "', $keywords)), E_USER_DEPRECATED);
}
}
} | [
"private",
"function",
"checkDefinition",
"(",
"$",
"id",
",",
"array",
"$",
"definition",
",",
"$",
"file",
")",
"{",
"if",
"(",
"$",
"throw",
"=",
"$",
"this",
"->",
"isLoadingInstanceof",
")",
"{",
"$",
"keywords",
"=",
"self",
"::",
"$",
"instanceofKeywords",
";",
"}",
"elseif",
"(",
"$",
"throw",
"=",
"(",
"isset",
"(",
"$",
"definition",
"[",
"'resource'",
"]",
")",
"||",
"isset",
"(",
"$",
"definition",
"[",
"'namespace'",
"]",
")",
")",
")",
"{",
"$",
"keywords",
"=",
"self",
"::",
"$",
"prototypeKeywords",
";",
"}",
"else",
"{",
"$",
"keywords",
"=",
"self",
"::",
"$",
"serviceKeywords",
";",
"}",
"foreach",
"(",
"$",
"definition",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"keywords",
"[",
"$",
"key",
"]",
")",
")",
"{",
"if",
"(",
"$",
"throw",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The configuration key \"%s\" is unsupported for definition \"%s\" in \"%s\". Allowed configuration keys are \"%s\".'",
",",
"$",
"key",
",",
"$",
"id",
",",
"$",
"file",
",",
"implode",
"(",
"'\", \"'",
",",
"$",
"keywords",
")",
")",
")",
";",
"}",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'The configuration key \"%s\" is unsupported for service definition \"%s\" in \"%s\". Allowed configuration keys are \"%s\". The YamlFileLoader object will raise an exception instead in Symfony 4.0 when detecting an unsupported service configuration key.'",
",",
"$",
"key",
",",
"$",
"id",
",",
"$",
"file",
",",
"implode",
"(",
"'\", \"'",
",",
"$",
"keywords",
")",
")",
",",
"E_USER_DEPRECATED",
")",
";",
"}",
"}",
"}"
] | Checks the keywords used to define a service.
@param string $id The service name
@param array $definition The service definition to check
@param string $file The loaded YAML file | [
"Checks",
"the",
"keywords",
"used",
"to",
"define",
"a",
"service",
"."
] | train | https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php#L839-L858 |
rutger-speksnijder/simpleroute | src/SimpleRoute/Router.php | Router.setUrl | public function setUrl($url)
{
$this->url = $url;
// Check if the url ends with a slash
if ($this->url && substr($this->url, -1) !== '/') {
$this->url .= '/';
}
return $this;
} | php | public function setUrl($url)
{
$this->url = $url;
// Check if the url ends with a slash
if ($this->url && substr($this->url, -1) !== '/') {
$this->url .= '/';
}
return $this;
} | [
"public",
"function",
"setUrl",
"(",
"$",
"url",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"$",
"url",
";",
"// Check if the url ends with a slash",
"if",
"(",
"$",
"this",
"->",
"url",
"&&",
"substr",
"(",
"$",
"this",
"->",
"url",
",",
"-",
"1",
")",
"!==",
"'/'",
")",
"{",
"$",
"this",
"->",
"url",
".=",
"'/'",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Sets the request url.
@param string $url The url.
@return $this The current object. | [
"Sets",
"the",
"request",
"url",
"."
] | train | https://github.com/rutger-speksnijder/simpleroute/blob/b862cea540d515e91d2c3a912b53e5e31939695e/src/SimpleRoute/Router.php#L124-L134 |
rutger-speksnijder/simpleroute | src/SimpleRoute/Router.php | Router.add | public function add($route, $callable, $type = 'any')
{
// Check if the route ends with a forward slash
if ($route && substr($route, -1) !== '/') {
$route .= '/';
}
// Add the route
$this->routes[strtolower($type)][$route] = $callable;
return $this;
} | php | public function add($route, $callable, $type = 'any')
{
// Check if the route ends with a forward slash
if ($route && substr($route, -1) !== '/') {
$route .= '/';
}
// Add the route
$this->routes[strtolower($type)][$route] = $callable;
return $this;
} | [
"public",
"function",
"add",
"(",
"$",
"route",
",",
"$",
"callable",
",",
"$",
"type",
"=",
"'any'",
")",
"{",
"// Check if the route ends with a forward slash",
"if",
"(",
"$",
"route",
"&&",
"substr",
"(",
"$",
"route",
",",
"-",
"1",
")",
"!==",
"'/'",
")",
"{",
"$",
"route",
".=",
"'/'",
";",
"}",
"// Add the route",
"$",
"this",
"->",
"routes",
"[",
"strtolower",
"(",
"$",
"type",
")",
"]",
"[",
"$",
"route",
"]",
"=",
"$",
"callable",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a route to the router.
@param string $route The route.
@param callable $callable The method to execute when this route gets called.
@param string $type The request type to bind this route to.
@return $this The current object. | [
"Adds",
"a",
"route",
"to",
"the",
"router",
"."
] | train | https://github.com/rutger-speksnijder/simpleroute/blob/b862cea540d515e91d2c3a912b53e5e31939695e/src/SimpleRoute/Router.php#L155-L165 |
rutger-speksnijder/simpleroute | src/SimpleRoute/Router.php | Router.remove | public function remove($route, $type = 'any')
{
if (isset($this->routes[$type][$route])) {
unset($this->routes[$type][$route]);
}
return $this;
} | php | public function remove($route, $type = 'any')
{
if (isset($this->routes[$type][$route])) {
unset($this->routes[$type][$route]);
}
return $this;
} | [
"public",
"function",
"remove",
"(",
"$",
"route",
",",
"$",
"type",
"=",
"'any'",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"type",
"]",
"[",
"$",
"route",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"type",
"]",
"[",
"$",
"route",
"]",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Removes a route.
@param string $route The route to remove.
@param string $type The request type.
@return \SimpleRoute\Router The current object. | [
"Removes",
"a",
"route",
"."
] | train | https://github.com/rutger-speksnijder/simpleroute/blob/b862cea540d515e91d2c3a912b53e5e31939695e/src/SimpleRoute/Router.php#L259-L265 |
rutger-speksnijder/simpleroute | src/SimpleRoute/Router.php | Router.getMethodsByRoute | public function getMethodsByRoute($route)
{
// Check if a route was provided
if (!$route) {
return [];
}
// Loop through our routes
$methods = [];
foreach ($this->routes as $method => $routes) {
foreach ($routes as $availableRoute => $callable) {
// Check if the available route is the same as the specified route
if ($availableRoute === $route) {
$methods[] = $method;
continue 2;
}
// Check if the route matches
$regex = '/^' . str_replace('/', '\/', $availableRoute) . '/Uim';
if (preg_match($regex, $route, $matches) === 1 && $matches[0] === $route) {
$methods[] = $method;
continue 2;
}
}
}
// Return the methods array
return $methods;
} | php | public function getMethodsByRoute($route)
{
// Check if a route was provided
if (!$route) {
return [];
}
// Loop through our routes
$methods = [];
foreach ($this->routes as $method => $routes) {
foreach ($routes as $availableRoute => $callable) {
// Check if the available route is the same as the specified route
if ($availableRoute === $route) {
$methods[] = $method;
continue 2;
}
// Check if the route matches
$regex = '/^' . str_replace('/', '\/', $availableRoute) . '/Uim';
if (preg_match($regex, $route, $matches) === 1 && $matches[0] === $route) {
$methods[] = $method;
continue 2;
}
}
}
// Return the methods array
return $methods;
} | [
"public",
"function",
"getMethodsByRoute",
"(",
"$",
"route",
")",
"{",
"// Check if a route was provided",
"if",
"(",
"!",
"$",
"route",
")",
"{",
"return",
"[",
"]",
";",
"}",
"// Loop through our routes",
"$",
"methods",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"routes",
"as",
"$",
"method",
"=>",
"$",
"routes",
")",
"{",
"foreach",
"(",
"$",
"routes",
"as",
"$",
"availableRoute",
"=>",
"$",
"callable",
")",
"{",
"// Check if the available route is the same as the specified route",
"if",
"(",
"$",
"availableRoute",
"===",
"$",
"route",
")",
"{",
"$",
"methods",
"[",
"]",
"=",
"$",
"method",
";",
"continue",
"2",
";",
"}",
"// Check if the route matches",
"$",
"regex",
"=",
"'/^'",
".",
"str_replace",
"(",
"'/'",
",",
"'\\/'",
",",
"$",
"availableRoute",
")",
".",
"'/Uim'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"route",
",",
"$",
"matches",
")",
"===",
"1",
"&&",
"$",
"matches",
"[",
"0",
"]",
"===",
"$",
"route",
")",
"{",
"$",
"methods",
"[",
"]",
"=",
"$",
"method",
";",
"continue",
"2",
";",
"}",
"}",
"}",
"// Return the methods array",
"return",
"$",
"methods",
";",
"}"
] | Returns an array of methods defined for a specific route.
Useful for an "OPTIONS" request.
@param string $route The route to get the methods from.
@return array An array with methods. | [
"Returns",
"an",
"array",
"of",
"methods",
"defined",
"for",
"a",
"specific",
"route",
".",
"Useful",
"for",
"an",
"OPTIONS",
"request",
"."
] | train | https://github.com/rutger-speksnijder/simpleroute/blob/b862cea540d515e91d2c3a912b53e5e31939695e/src/SimpleRoute/Router.php#L275-L303 |
rutger-speksnijder/simpleroute | src/SimpleRoute/Router.php | Router.execute | public function execute()
{
// Check if we have a url
if (!$this->url || trim($this->url) == '') {
$this->url = '/';
}
// Make sure the url starts with a slash
if (substr($this->url, 0, 1) !== '/') {
$this->url = '/' . $this->url;
}
// Check if the absolute route exists in our routes array
// - and if that route has the same type of request as the current request.
if (isset($this->routes[$this->method][$this->url])) {
return call_user_func_array($this->routes[$this->method][$this->url], []);
}
// Check if the absolute route exists in our routes array
// - and if that route has the "any" type.
if (isset($this->routes['any'][$this->url])) {
return call_user_func_array($this->routes['any'][$this->url], []);
}
// Create an array of methods to check and loop through them
$methods = [$this->method, 'any'];
foreach ($methods as $method) {
// Loop through the routes set for this method
foreach ($this->routes[$method] as $route => $callable) {
// Check if the route matches
$regex = '/^' . str_replace('/', '\/', $route) . '/Uim';
$matches = [];
if (preg_match($regex, $this->url, $matches) === 1 && $matches[0] === $this->url) {
// First value in the array is the string that matched
array_shift($matches);
// Execute the callable method
return call_user_func_array($callable, $matches);
}
}
}
// No route found, check if we have an empty route.
// - We should always have an empty route.
if (!isset($this->routes['any']['/'])) {
header('HTTP/1.1 404 Not Found');
exit;
}
// Return the empty route's callable
return call_user_func_array($this->routes['any']['/'], []);
} | php | public function execute()
{
// Check if we have a url
if (!$this->url || trim($this->url) == '') {
$this->url = '/';
}
// Make sure the url starts with a slash
if (substr($this->url, 0, 1) !== '/') {
$this->url = '/' . $this->url;
}
// Check if the absolute route exists in our routes array
// - and if that route has the same type of request as the current request.
if (isset($this->routes[$this->method][$this->url])) {
return call_user_func_array($this->routes[$this->method][$this->url], []);
}
// Check if the absolute route exists in our routes array
// - and if that route has the "any" type.
if (isset($this->routes['any'][$this->url])) {
return call_user_func_array($this->routes['any'][$this->url], []);
}
// Create an array of methods to check and loop through them
$methods = [$this->method, 'any'];
foreach ($methods as $method) {
// Loop through the routes set for this method
foreach ($this->routes[$method] as $route => $callable) {
// Check if the route matches
$regex = '/^' . str_replace('/', '\/', $route) . '/Uim';
$matches = [];
if (preg_match($regex, $this->url, $matches) === 1 && $matches[0] === $this->url) {
// First value in the array is the string that matched
array_shift($matches);
// Execute the callable method
return call_user_func_array($callable, $matches);
}
}
}
// No route found, check if we have an empty route.
// - We should always have an empty route.
if (!isset($this->routes['any']['/'])) {
header('HTTP/1.1 404 Not Found');
exit;
}
// Return the empty route's callable
return call_user_func_array($this->routes['any']['/'], []);
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"// Check if we have a url",
"if",
"(",
"!",
"$",
"this",
"->",
"url",
"||",
"trim",
"(",
"$",
"this",
"->",
"url",
")",
"==",
"''",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"'/'",
";",
"}",
"// Make sure the url starts with a slash",
"if",
"(",
"substr",
"(",
"$",
"this",
"->",
"url",
",",
"0",
",",
"1",
")",
"!==",
"'/'",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"'/'",
".",
"$",
"this",
"->",
"url",
";",
"}",
"// Check if the absolute route exists in our routes array",
"// - and if that route has the same type of request as the current request.",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"this",
"->",
"method",
"]",
"[",
"$",
"this",
"->",
"url",
"]",
")",
")",
"{",
"return",
"call_user_func_array",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"this",
"->",
"method",
"]",
"[",
"$",
"this",
"->",
"url",
"]",
",",
"[",
"]",
")",
";",
"}",
"// Check if the absolute route exists in our routes array",
"// - and if that route has the \"any\" type.",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"'any'",
"]",
"[",
"$",
"this",
"->",
"url",
"]",
")",
")",
"{",
"return",
"call_user_func_array",
"(",
"$",
"this",
"->",
"routes",
"[",
"'any'",
"]",
"[",
"$",
"this",
"->",
"url",
"]",
",",
"[",
"]",
")",
";",
"}",
"// Create an array of methods to check and loop through them",
"$",
"methods",
"=",
"[",
"$",
"this",
"->",
"method",
",",
"'any'",
"]",
";",
"foreach",
"(",
"$",
"methods",
"as",
"$",
"method",
")",
"{",
"// Loop through the routes set for this method",
"foreach",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"method",
"]",
"as",
"$",
"route",
"=>",
"$",
"callable",
")",
"{",
"// Check if the route matches",
"$",
"regex",
"=",
"'/^'",
".",
"str_replace",
"(",
"'/'",
",",
"'\\/'",
",",
"$",
"route",
")",
".",
"'/Uim'",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"this",
"->",
"url",
",",
"$",
"matches",
")",
"===",
"1",
"&&",
"$",
"matches",
"[",
"0",
"]",
"===",
"$",
"this",
"->",
"url",
")",
"{",
"// First value in the array is the string that matched",
"array_shift",
"(",
"$",
"matches",
")",
";",
"// Execute the callable method",
"return",
"call_user_func_array",
"(",
"$",
"callable",
",",
"$",
"matches",
")",
";",
"}",
"}",
"}",
"// No route found, check if we have an empty route.",
"// - We should always have an empty route.",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"routes",
"[",
"'any'",
"]",
"[",
"'/'",
"]",
")",
")",
"{",
"header",
"(",
"'HTTP/1.1 404 Not Found'",
")",
";",
"exit",
";",
"}",
"// Return the empty route's callable",
"return",
"call_user_func_array",
"(",
"$",
"this",
"->",
"routes",
"[",
"'any'",
"]",
"[",
"'/'",
"]",
",",
"[",
"]",
")",
";",
"}"
] | Executes the router based on the url.
@throws Exception Throws an exception if no location was set and no default route was found.
@return mixed The result of the callable method. | [
"Executes",
"the",
"router",
"based",
"on",
"the",
"url",
"."
] | train | https://github.com/rutger-speksnijder/simpleroute/blob/b862cea540d515e91d2c3a912b53e5e31939695e/src/SimpleRoute/Router.php#L312-L363 |
kduma-OSS/L5-permissions | SampleMigrations/2015_01_01_000005_create_and_assign_roles_and_permissions.php | CreateAndAssignRolesAndPermissions.up | public function up()
{
PermissionsManager::createRole('admin', 'Administrator');
PermissionsManager::createRole('user', 'User');
PermissionsManager::createRole('banned', 'Banned user');
PermissionsManager::createPermission('login', 'Allow login');
PermissionsManager::createPermission('panel', 'Allow access to admin panel');
PermissionsManager::attach(['admin', 'user'], [
'login',
]);
PermissionsManager::attach('admin', [
'panel',
]);
} | php | public function up()
{
PermissionsManager::createRole('admin', 'Administrator');
PermissionsManager::createRole('user', 'User');
PermissionsManager::createRole('banned', 'Banned user');
PermissionsManager::createPermission('login', 'Allow login');
PermissionsManager::createPermission('panel', 'Allow access to admin panel');
PermissionsManager::attach(['admin', 'user'], [
'login',
]);
PermissionsManager::attach('admin', [
'panel',
]);
} | [
"public",
"function",
"up",
"(",
")",
"{",
"PermissionsManager",
"::",
"createRole",
"(",
"'admin'",
",",
"'Administrator'",
")",
";",
"PermissionsManager",
"::",
"createRole",
"(",
"'user'",
",",
"'User'",
")",
";",
"PermissionsManager",
"::",
"createRole",
"(",
"'banned'",
",",
"'Banned user'",
")",
";",
"PermissionsManager",
"::",
"createPermission",
"(",
"'login'",
",",
"'Allow login'",
")",
";",
"PermissionsManager",
"::",
"createPermission",
"(",
"'panel'",
",",
"'Allow access to admin panel'",
")",
";",
"PermissionsManager",
"::",
"attach",
"(",
"[",
"'admin'",
",",
"'user'",
"]",
",",
"[",
"'login'",
",",
"]",
")",
";",
"PermissionsManager",
"::",
"attach",
"(",
"'admin'",
",",
"[",
"'panel'",
",",
"]",
")",
";",
"}"
] | Run the migrations.
@return void | [
"Run",
"the",
"migrations",
"."
] | train | https://github.com/kduma-OSS/L5-permissions/blob/0e11c1dc1dc083f972cef5a52ced664b7390b054/SampleMigrations/2015_01_01_000005_create_and_assign_roles_and_permissions.php#L12-L30 |
kduma-OSS/L5-permissions | SampleMigrations/2015_01_01_000005_create_and_assign_roles_and_permissions.php | CreateAndAssignRolesAndPermissions.down | public function down()
{
PermissionsManager::deleteRole('admin', 'Administrator');
PermissionsManager::deleteRole('user', 'User');
PermissionsManager::deleteRole('banned', 'Banned user');
PermissionsManager::deletePermission('login', 'Allow login');
PermissionsManager::deletePermission('panel', 'Allow access to admin panel');
} | php | public function down()
{
PermissionsManager::deleteRole('admin', 'Administrator');
PermissionsManager::deleteRole('user', 'User');
PermissionsManager::deleteRole('banned', 'Banned user');
PermissionsManager::deletePermission('login', 'Allow login');
PermissionsManager::deletePermission('panel', 'Allow access to admin panel');
} | [
"public",
"function",
"down",
"(",
")",
"{",
"PermissionsManager",
"::",
"deleteRole",
"(",
"'admin'",
",",
"'Administrator'",
")",
";",
"PermissionsManager",
"::",
"deleteRole",
"(",
"'user'",
",",
"'User'",
")",
";",
"PermissionsManager",
"::",
"deleteRole",
"(",
"'banned'",
",",
"'Banned user'",
")",
";",
"PermissionsManager",
"::",
"deletePermission",
"(",
"'login'",
",",
"'Allow login'",
")",
";",
"PermissionsManager",
"::",
"deletePermission",
"(",
"'panel'",
",",
"'Allow access to admin panel'",
")",
";",
"}"
] | Reverse the migrations.
@return void | [
"Reverse",
"the",
"migrations",
"."
] | train | https://github.com/kduma-OSS/L5-permissions/blob/0e11c1dc1dc083f972cef5a52ced664b7390b054/SampleMigrations/2015_01_01_000005_create_and_assign_roles_and_permissions.php#L37-L45 |
Stinger-Soft/DoctrineCommons | src/StingerSoft/DoctrineCommons/Utils/JsonImporter.php | JsonImporter.before | protected function before() {
if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) {
$this->connection->executeUpdate('EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"');
} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
$this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=0');
} else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
$this->connection->executeUpdate('PRAGMA foreign_keys = OFF');
}
} | php | protected function before() {
if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) {
$this->connection->executeUpdate('EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"');
} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
$this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=0');
} else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
$this->connection->executeUpdate('PRAGMA foreign_keys = OFF');
}
} | [
"protected",
"function",
"before",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"connection",
"->",
"getDatabasePlatform",
"(",
")",
"instanceof",
"SQLServerPlatform",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"executeUpdate",
"(",
"'EXEC sp_msforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"'",
")",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"connection",
"->",
"getDatabasePlatform",
"(",
")",
"instanceof",
"MySqlPlatform",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"executeUpdate",
"(",
"'SET FOREIGN_KEY_CHECKS=0'",
")",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"connection",
"->",
"getDatabasePlatform",
"(",
")",
"instanceof",
"SqlitePlatform",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"executeUpdate",
"(",
"'PRAGMA foreign_keys = OFF'",
")",
";",
"}",
"}"
] | Executed before the import is started | [
"Executed",
"before",
"the",
"import",
"is",
"started"
] | train | https://github.com/Stinger-Soft/DoctrineCommons/blob/1f0dd56a94654c8de63927d7eec2175aab3cf809/src/StingerSoft/DoctrineCommons/Utils/JsonImporter.php#L132-L140 |
Stinger-Soft/DoctrineCommons | src/StingerSoft/DoctrineCommons/Utils/JsonImporter.php | JsonImporter.after | protected function after() {
if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) {
$this->connection->executeUpdate('exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"');
} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
$this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=1');
} else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
$this->connection->executeUpdate('PRAGMA foreign_keys = ON');
}
} | php | protected function after() {
if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) {
$this->connection->executeUpdate('exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"');
} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
$this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=1');
} else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
$this->connection->executeUpdate('PRAGMA foreign_keys = ON');
}
} | [
"protected",
"function",
"after",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"connection",
"->",
"getDatabasePlatform",
"(",
")",
"instanceof",
"SQLServerPlatform",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"executeUpdate",
"(",
"'exec sp_msforeachtable \"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"'",
")",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"connection",
"->",
"getDatabasePlatform",
"(",
")",
"instanceof",
"MySqlPlatform",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"executeUpdate",
"(",
"'SET FOREIGN_KEY_CHECKS=1'",
")",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"connection",
"->",
"getDatabasePlatform",
"(",
")",
"instanceof",
"SqlitePlatform",
")",
"{",
"$",
"this",
"->",
"connection",
"->",
"executeUpdate",
"(",
"'PRAGMA foreign_keys = ON'",
")",
";",
"}",
"}"
] | Executed after the import is finished | [
"Executed",
"after",
"the",
"import",
"is",
"finished"
] | train | https://github.com/Stinger-Soft/DoctrineCommons/blob/1f0dd56a94654c8de63927d7eec2175aab3cf809/src/StingerSoft/DoctrineCommons/Utils/JsonImporter.php#L145-L153 |
kambalabs/KmbPmProxy | src/KmbPmProxy/Hydrator/GroupHydrator.php | GroupHydrator.hydrate | public function hydrate($puppetModules, $group)
{
$availableClasses = [];
if (!empty($puppetModules)) {
foreach ($puppetModules as $puppetModule) {
if ($puppetModule->hasClasses()) {
foreach ($puppetModule->getClasses() as $puppetClass) {
$groupClass = $group->getClassByName($puppetClass->getName());
if ($groupClass != null) {
if ($puppetClass->hasParametersTemplates()) {
$this->groupClassHydrator->hydrate($puppetClass->getParametersTemplates(), $groupClass);
}
} else {
$availableClasses[$puppetModule->getName()][] = $puppetClass->getName();
}
}
}
}
}
return $group->setAvailableClasses($availableClasses);
} | php | public function hydrate($puppetModules, $group)
{
$availableClasses = [];
if (!empty($puppetModules)) {
foreach ($puppetModules as $puppetModule) {
if ($puppetModule->hasClasses()) {
foreach ($puppetModule->getClasses() as $puppetClass) {
$groupClass = $group->getClassByName($puppetClass->getName());
if ($groupClass != null) {
if ($puppetClass->hasParametersTemplates()) {
$this->groupClassHydrator->hydrate($puppetClass->getParametersTemplates(), $groupClass);
}
} else {
$availableClasses[$puppetModule->getName()][] = $puppetClass->getName();
}
}
}
}
}
return $group->setAvailableClasses($availableClasses);
} | [
"public",
"function",
"hydrate",
"(",
"$",
"puppetModules",
",",
"$",
"group",
")",
"{",
"$",
"availableClasses",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"puppetModules",
")",
")",
"{",
"foreach",
"(",
"$",
"puppetModules",
"as",
"$",
"puppetModule",
")",
"{",
"if",
"(",
"$",
"puppetModule",
"->",
"hasClasses",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"puppetModule",
"->",
"getClasses",
"(",
")",
"as",
"$",
"puppetClass",
")",
"{",
"$",
"groupClass",
"=",
"$",
"group",
"->",
"getClassByName",
"(",
"$",
"puppetClass",
"->",
"getName",
"(",
")",
")",
";",
"if",
"(",
"$",
"groupClass",
"!=",
"null",
")",
"{",
"if",
"(",
"$",
"puppetClass",
"->",
"hasParametersTemplates",
"(",
")",
")",
"{",
"$",
"this",
"->",
"groupClassHydrator",
"->",
"hydrate",
"(",
"$",
"puppetClass",
"->",
"getParametersTemplates",
"(",
")",
",",
"$",
"groupClass",
")",
";",
"}",
"}",
"else",
"{",
"$",
"availableClasses",
"[",
"$",
"puppetModule",
"->",
"getName",
"(",
")",
"]",
"[",
"]",
"=",
"$",
"puppetClass",
"->",
"getName",
"(",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"$",
"group",
"->",
"setAvailableClasses",
"(",
"$",
"availableClasses",
")",
";",
"}"
] | Hydrate group with the provided puppet modules data.
@param PuppetModule[] $puppetModules
@param GroupInterface $group
@return GroupInterface | [
"Hydrate",
"group",
"with",
"the",
"provided",
"puppet",
"modules",
"data",
"."
] | train | https://github.com/kambalabs/KmbPmProxy/blob/b4c664ae8b6f29e4e8768461ed99e1b0b80bde18/src/KmbPmProxy/Hydrator/GroupHydrator.php#L38-L58 |
chanhong/pdolite | src/PdoLite.php | PdoLite.getInstance | public static function getInstance( ) {
if(!self::$objInstance){
self::$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
self::$objInstance = new PDO(PDOLITE_DB_DSN, PDOLITE_DB_USER, PDOLITE_DB_PASS, self::$options);
}
return self::$objInstance;
} | php | public static function getInstance( ) {
if(!self::$objInstance){
self::$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
self::$objInstance = new PDO(PDOLITE_DB_DSN, PDOLITE_DB_USER, PDOLITE_DB_PASS, self::$options);
}
return self::$objInstance;
} | [
"public",
"static",
"function",
"getInstance",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"objInstance",
")",
"{",
"self",
"::",
"$",
"options",
"=",
"array",
"(",
"PDO",
"::",
"ATTR_ERRMODE",
"=>",
"PDO",
"::",
"ERRMODE_EXCEPTION",
")",
";",
"self",
"::",
"$",
"objInstance",
"=",
"new",
"PDO",
"(",
"PDOLITE_DB_DSN",
",",
"PDOLITE_DB_USER",
",",
"PDOLITE_DB_PASS",
",",
"self",
"::",
"$",
"options",
")",
";",
"}",
"return",
"self",
"::",
"$",
"objInstance",
";",
"}"
] | /*
Returns DB instance or create initial connection
@param
@return $objInstance; | [
"/",
"*",
"Returns",
"DB",
"instance",
"or",
"create",
"initial",
"connection"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L55-L66 |
chanhong/pdolite | src/PdoLite.php | PdoLite.backTrace | public static function backTrace() {
$str = "<br />[backTrace]";
foreach (debug_backtrace() as $row) {
$str .= "<br />FILE: "
. $row['file'] . " FUNC: " . $row['function']
. " LINE: " . $row['line'] . " ARGS: "
. print_r($row['args'], true);
}
return $str;
} | php | public static function backTrace() {
$str = "<br />[backTrace]";
foreach (debug_backtrace() as $row) {
$str .= "<br />FILE: "
. $row['file'] . " FUNC: " . $row['function']
. " LINE: " . $row['line'] . " ARGS: "
. print_r($row['args'], true);
}
return $str;
} | [
"public",
"static",
"function",
"backTrace",
"(",
")",
"{",
"$",
"str",
"=",
"\"<br />[backTrace]\"",
";",
"foreach",
"(",
"debug_backtrace",
"(",
")",
"as",
"$",
"row",
")",
"{",
"$",
"str",
".=",
"\"<br />FILE: \"",
".",
"$",
"row",
"[",
"'file'",
"]",
".",
"\" FUNC: \"",
".",
"$",
"row",
"[",
"'function'",
"]",
".",
"\" LINE: \"",
".",
"$",
"row",
"[",
"'line'",
"]",
".",
"\" ARGS: \"",
".",
"print_r",
"(",
"$",
"row",
"[",
"'args'",
"]",
",",
"true",
")",
";",
"}",
"return",
"$",
"str",
";",
"}"
] | /*
Backtrace errors
@param
@return $str; | [
"/",
"*",
"Backtrace",
"errors"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L95-L105 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbConnect | public static function dbConnect($dsn, $user="", $passwd="", $options=array()) {
try {
if (!self::$objInstance){
if (!empty($dsn)) {
defined('PDOLITE_DB_DSN') or define('PDOLITE_DB_DSN', $dsn);
defined('PDOLITE_DB_USER') or define('PDOLITE_DB_USER', $user);
defined('PDOLITE_DB_PASS') or define('PDOLITE_DB_PASS', $passwd);
}
if (empty($options)) {
self::$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
} else {
self::$options = $options;
};
self::$objInstance = self::getInstance();
}
return self::$objInstance;
} catch (PDOException $e) {
die(self::dbError($dsn));
}
} | php | public static function dbConnect($dsn, $user="", $passwd="", $options=array()) {
try {
if (!self::$objInstance){
if (!empty($dsn)) {
defined('PDOLITE_DB_DSN') or define('PDOLITE_DB_DSN', $dsn);
defined('PDOLITE_DB_USER') or define('PDOLITE_DB_USER', $user);
defined('PDOLITE_DB_PASS') or define('PDOLITE_DB_PASS', $passwd);
}
if (empty($options)) {
self::$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
} else {
self::$options = $options;
};
self::$objInstance = self::getInstance();
}
return self::$objInstance;
} catch (PDOException $e) {
die(self::dbError($dsn));
}
} | [
"public",
"static",
"function",
"dbConnect",
"(",
"$",
"dsn",
",",
"$",
"user",
"=",
"\"\"",
",",
"$",
"passwd",
"=",
"\"\"",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"objInstance",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"dsn",
")",
")",
"{",
"defined",
"(",
"'PDOLITE_DB_DSN'",
")",
"or",
"define",
"(",
"'PDOLITE_DB_DSN'",
",",
"$",
"dsn",
")",
";",
"defined",
"(",
"'PDOLITE_DB_USER'",
")",
"or",
"define",
"(",
"'PDOLITE_DB_USER'",
",",
"$",
"user",
")",
";",
"defined",
"(",
"'PDOLITE_DB_PASS'",
")",
"or",
"define",
"(",
"'PDOLITE_DB_PASS'",
",",
"$",
"passwd",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"options",
")",
")",
"{",
"self",
"::",
"$",
"options",
"=",
"array",
"(",
"PDO",
"::",
"ATTR_PERSISTENT",
"=>",
"true",
",",
"PDO",
"::",
"ATTR_ERRMODE",
"=>",
"PDO",
"::",
"ERRMODE_EXCEPTION",
")",
";",
"}",
"else",
"{",
"self",
"::",
"$",
"options",
"=",
"$",
"options",
";",
"}",
";",
"self",
"::",
"$",
"objInstance",
"=",
"self",
"::",
"getInstance",
"(",
")",
";",
"}",
"return",
"self",
"::",
"$",
"objInstance",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"dsn",
")",
")",
";",
"}",
"}"
] | /*
Returns DB instance or create initial connection
@param
@return $objInstance; | [
"/",
"*",
"Returns",
"DB",
"instance",
"or",
"create",
"initial",
"connection"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L122-L145 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbQuery | public static function dbQuery($sql) {
try {
return self::query($sql);
} catch (PDOException $e) {
die(self::dbError($sql));
}
} | php | public static function dbQuery($sql) {
try {
return self::query($sql);
} catch (PDOException $e) {
die(self::dbError($sql));
}
} | [
"public",
"static",
"function",
"dbQuery",
"(",
"$",
"sql",
")",
"{",
"try",
"{",
"return",
"self",
"::",
"query",
"(",
"$",
"sql",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"sql",
")",
")",
";",
"}",
"}"
] | /*
alias to PDO query
@param $sql
@return object of rows | [
"/",
"*",
"alias",
"to",
"PDO",
"query"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L152-L159 |
chanhong/pdolite | src/PdoLite.php | PdoLite.getLastId | public static function getLastId($table, $field) {
try {
$sql = 'SELECT max(' . $field . ') as lastid FROM ' . $table;
list($lastid) = self::dbFetch(self::query($sql), "num"); // cause warning when use assoc array
return (int) $lastid;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | php | public static function getLastId($table, $field) {
try {
$sql = 'SELECT max(' . $field . ') as lastid FROM ' . $table;
list($lastid) = self::dbFetch(self::query($sql), "num"); // cause warning when use assoc array
return (int) $lastid;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | [
"public",
"static",
"function",
"getLastId",
"(",
"$",
"table",
",",
"$",
"field",
")",
"{",
"try",
"{",
"$",
"sql",
"=",
"'SELECT max('",
".",
"$",
"field",
".",
"') as lastid FROM '",
".",
"$",
"table",
";",
"list",
"(",
"$",
"lastid",
")",
"=",
"self",
"::",
"dbFetch",
"(",
"self",
"::",
"query",
"(",
"$",
"sql",
")",
",",
"\"num\"",
")",
";",
"// cause warning when use assoc array\r",
"return",
"(",
"int",
")",
"$",
"lastid",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"echo",
"$",
"e",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"}"
] | /*
call query and dbFetch num to get lastID
@param $table, $field
@return $integer | [
"/",
"*",
"call",
"query",
"and",
"dbFetch",
"num",
"to",
"get",
"lastID"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L167-L176 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbFetch | public static function dbFetch($qhandle, $atype = "assoc") {
try {
if (is_object($qhandle)) {
$type = self::getPDOFetchType($atype);
return $qhandle->fetch($type);
}
} catch (PDOException $e) {
die(self::dbError(__METHOD__));
}
} | php | public static function dbFetch($qhandle, $atype = "assoc") {
try {
if (is_object($qhandle)) {
$type = self::getPDOFetchType($atype);
return $qhandle->fetch($type);
}
} catch (PDOException $e) {
die(self::dbError(__METHOD__));
}
} | [
"public",
"static",
"function",
"dbFetch",
"(",
"$",
"qhandle",
",",
"$",
"atype",
"=",
"\"assoc\"",
")",
"{",
"try",
"{",
"if",
"(",
"is_object",
"(",
"$",
"qhandle",
")",
")",
"{",
"$",
"type",
"=",
"self",
"::",
"getPDOFetchType",
"(",
"$",
"atype",
")",
";",
"return",
"$",
"qhandle",
"->",
"fetch",
"(",
"$",
"type",
")",
";",
"}",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"__METHOD__",
")",
")",
";",
"}",
"}"
] | /*
Alias to fetch to use with while ($row = Pdolite::dbFetch($res, "both")) {}
@param $qhandle, $atype (both, assoc or array, num or blank)
@return $array of FETCH_BOTH | [
"/",
"*",
"Alias",
"to",
"fetch",
"to",
"use",
"with",
"while",
"(",
"$row",
"=",
"Pdolite",
"::",
"dbFetch",
"(",
"$res",
"both",
"))",
"{}"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L213-L223 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbQ2Array | public static function dbQ2Array($sql, $atype = "assoc", $fetch = "fetch") {
try {
$myrows = array();
$res = self::query($sql);
if (is_object($res)) {
If (strtolower($fetch) == "all") {
$type = self::getPDOFetchType($atype);
return $res->fetchAll($type);
} else {
while ($myrow = self::dbFetch($res, $atype)) {
// use [] so the resulting array will be the same as fetchAll
$myrows[] = $myrow;
}
return $myrows;
}
}
} catch (PDOException $e) {
die(self::dbError($sql));
}
} | php | public static function dbQ2Array($sql, $atype = "assoc", $fetch = "fetch") {
try {
$myrows = array();
$res = self::query($sql);
if (is_object($res)) {
If (strtolower($fetch) == "all") {
$type = self::getPDOFetchType($atype);
return $res->fetchAll($type);
} else {
while ($myrow = self::dbFetch($res, $atype)) {
// use [] so the resulting array will be the same as fetchAll
$myrows[] = $myrow;
}
return $myrows;
}
}
} catch (PDOException $e) {
die(self::dbError($sql));
}
} | [
"public",
"static",
"function",
"dbQ2Array",
"(",
"$",
"sql",
",",
"$",
"atype",
"=",
"\"assoc\"",
",",
"$",
"fetch",
"=",
"\"fetch\"",
")",
"{",
"try",
"{",
"$",
"myrows",
"=",
"array",
"(",
")",
";",
"$",
"res",
"=",
"self",
"::",
"query",
"(",
"$",
"sql",
")",
";",
"if",
"(",
"is_object",
"(",
"$",
"res",
")",
")",
"{",
"If",
"(",
"strtolower",
"(",
"$",
"fetch",
")",
"==",
"\"all\"",
")",
"{",
"$",
"type",
"=",
"self",
"::",
"getPDOFetchType",
"(",
"$",
"atype",
")",
"",
";",
"return",
"$",
"res",
"->",
"fetchAll",
"(",
"$",
"type",
")",
";",
"}",
"else",
"{",
"while",
"(",
"$",
"myrow",
"=",
"self",
"::",
"dbFetch",
"(",
"$",
"res",
",",
"$",
"atype",
")",
")",
"{",
"// use [] so the resulting array will be the same as fetchAll\r",
"$",
"myrows",
"[",
"]",
"=",
"$",
"myrow",
";",
"}",
"return",
"$",
"myrows",
";",
"}",
"}",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"sql",
")",
")",
";",
"}",
"}"
] | /*
call query and dbFetch (slower but less memory)
@param $sql $atype
@return nested array of rows | [
"/",
"*",
"call",
"query",
"and",
"dbFetch",
"(",
"slower",
"but",
"less",
"memory",
")"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L281-L301 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbQ2ArrayAll | public static function dbQ2ArrayAll($sql, $atype = "assoc") {
try {
$res = self::query($sql);
if (is_object($res)) {
$type = self::getPDOFetchType($atype);
return $res->fetchAll($type);
}
} catch (PDOException $e) {
die(self::dbError($sql));
}
} | php | public static function dbQ2ArrayAll($sql, $atype = "assoc") {
try {
$res = self::query($sql);
if (is_object($res)) {
$type = self::getPDOFetchType($atype);
return $res->fetchAll($type);
}
} catch (PDOException $e) {
die(self::dbError($sql));
}
} | [
"public",
"static",
"function",
"dbQ2ArrayAll",
"(",
"$",
"sql",
",",
"$",
"atype",
"=",
"\"assoc\"",
")",
"{",
"try",
"{",
"$",
"res",
"=",
"self",
"::",
"query",
"(",
"$",
"sql",
")",
";",
"if",
"(",
"is_object",
"(",
"$",
"res",
")",
")",
"{",
"$",
"type",
"=",
"self",
"::",
"getPDOFetchType",
"(",
"$",
"atype",
")",
";",
"return",
"$",
"res",
"->",
"fetchAll",
"(",
"$",
"type",
")",
";",
"}",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"sql",
")",
")",
";",
"}",
"}"
] | /*
call query and fetchAll (faster but more memory)
@param $sql
@return nested array of rows | [
"/",
"*",
"call",
"query",
"and",
"fetchAll",
"(",
"faster",
"but",
"more",
"memory",
")"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L308-L319 |
chanhong/pdolite | src/PdoLite.php | PdoLite.fieldsKey | public static function fieldsKey($table, $filter="id") {
try {
$row = (array) self::findRow("select * from ".$table, "assoc");
// remove array element base on filter if _none_ no filter
if (strtolower($filter)!="_none_") {
// default is to filter id field
unset($row[$filter]);
}
return array_keys($row);
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | php | public static function fieldsKey($table, $filter="id") {
try {
$row = (array) self::findRow("select * from ".$table, "assoc");
// remove array element base on filter if _none_ no filter
if (strtolower($filter)!="_none_") {
// default is to filter id field
unset($row[$filter]);
}
return array_keys($row);
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | [
"public",
"static",
"function",
"fieldsKey",
"(",
"$",
"table",
",",
"$",
"filter",
"=",
"\"id\"",
")",
"{",
"try",
"{",
"$",
"row",
"=",
"(",
"array",
")",
"self",
"::",
"findRow",
"(",
"\"select * from \"",
".",
"$",
"table",
",",
"\"assoc\"",
")",
";",
"// remove array element base on filter if _none_ no filter\r",
"if",
"(",
"strtolower",
"(",
"$",
"filter",
")",
"!=",
"\"_none_\"",
")",
"{",
"// default is to filter id field\r",
"unset",
"(",
"$",
"row",
"[",
"$",
"filter",
"]",
")",
";",
"}",
"return",
"array_keys",
"(",
"$",
"row",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"echo",
"$",
"e",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"}"
] | /*
get one row from table
@param $table $filter
@return assoc array of fields | [
"/",
"*",
"get",
"one",
"row",
"from",
"table"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L377-L390 |
chanhong/pdolite | src/PdoLite.php | PdoLite.schema | public static function schema($table, $filter="id") {
try {
return array_flip(self::fieldsKey($table, $filter));
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | php | public static function schema($table, $filter="id") {
try {
return array_flip(self::fieldsKey($table, $filter));
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | [
"public",
"static",
"function",
"schema",
"(",
"$",
"table",
",",
"$",
"filter",
"=",
"\"id\"",
")",
"{",
"try",
"{",
"return",
"array_flip",
"(",
"self",
"::",
"fieldsKey",
"(",
"$",
"table",
",",
"$",
"filter",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"echo",
"$",
"e",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"}"
] | /*
flip fields key into array
@param $table $filter
@return assoc array of fields Array ( [name] => 0 [biography] => 1 ) | [
"/",
"*",
"flip",
"fields",
"key",
"into",
"array"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L397-L404 |
chanhong/pdolite | src/PdoLite.php | PdoLite.aIntersec | public static function aIntersec($iArray, $allowArray = array()) {
try {
$return = $iArray;
// if empty do not filter the array
if (!empty($allowArray)) {
$return = array_intersect_key($iArray, array_flip($allowArray));
}
return $return;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | php | public static function aIntersec($iArray, $allowArray = array()) {
try {
$return = $iArray;
// if empty do not filter the array
if (!empty($allowArray)) {
$return = array_intersect_key($iArray, array_flip($allowArray));
}
return $return;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | [
"public",
"static",
"function",
"aIntersec",
"(",
"$",
"iArray",
",",
"$",
"allowArray",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"$",
"return",
"=",
"$",
"iArray",
";",
"// if empty do not filter the array\r",
"if",
"(",
"!",
"empty",
"(",
"$",
"allowArray",
")",
")",
"{",
"$",
"return",
"=",
"array_intersect_key",
"(",
"$",
"iArray",
",",
"array_flip",
"(",
"$",
"allowArray",
")",
")",
";",
"}",
"return",
"$",
"return",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"echo",
"$",
"e",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"}"
] | /*
get array elements match from both array
@param $iArray, $allowArray
@return assoc array of fields | [
"/",
"*",
"get",
"array",
"elements",
"match",
"from",
"both",
"array"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L411-L424 |
chanhong/pdolite | src/PdoLite.php | PdoLite.schemaBasedArray | public static function schemaBasedArray($tname, $iArray) {
if (empty($tname) or empty($iArray)) return array();
$fields = self::fieldsKey($tname);
$carray = array_merge(array_flip($fields), $iArray);
return self::aIntersec($carray, $fields);
} | php | public static function schemaBasedArray($tname, $iArray) {
if (empty($tname) or empty($iArray)) return array();
$fields = self::fieldsKey($tname);
$carray = array_merge(array_flip($fields), $iArray);
return self::aIntersec($carray, $fields);
} | [
"public",
"static",
"function",
"schemaBasedArray",
"(",
"$",
"tname",
",",
"$",
"iArray",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tname",
")",
"or",
"empty",
"(",
"$",
"iArray",
")",
")",
"return",
"array",
"(",
")",
";",
"$",
"fields",
"=",
"self",
"::",
"fieldsKey",
"(",
"$",
"tname",
")",
";",
"$",
"carray",
"=",
"array_merge",
"(",
"array_flip",
"(",
"$",
"fields",
")",
",",
"$",
"iArray",
")",
";",
"return",
"self",
"::",
"aIntersec",
"(",
"$",
"carray",
",",
"$",
"fields",
")",
";",
"}"
] | /* filterBySchema might be better, to decide delete this later (TODO)
merge and intersec array with schema
@param table, $array
@return array of assoc | [
"/",
"*",
"filterBySchema",
"might",
"be",
"better",
"to",
"decide",
"delete",
"this",
"later",
"(",
"TODO",
")",
"merge",
"and",
"intersec",
"array",
"with",
"schema"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L431-L438 |
chanhong/pdolite | src/PdoLite.php | PdoLite.filterBySchema | public static function filterBySchema($tname, $iArray) {
try {
$fields = self::schema($tname,"_none_");
// diff in array with schma fields
$diffs = array_diff_key($iArray, $fields);
// remove unwanted fields
foreach ($diffs as $k=>$v) {
unset($iArray[$k]);
}
return $iArray;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | php | public static function filterBySchema($tname, $iArray) {
try {
$fields = self::schema($tname,"_none_");
// diff in array with schma fields
$diffs = array_diff_key($iArray, $fields);
// remove unwanted fields
foreach ($diffs as $k=>$v) {
unset($iArray[$k]);
}
return $iArray;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | [
"public",
"static",
"function",
"filterBySchema",
"(",
"$",
"tname",
",",
"$",
"iArray",
")",
"{",
"try",
"{",
"$",
"fields",
"=",
"self",
"::",
"schema",
"(",
"$",
"tname",
",",
"\"_none_\"",
")",
";",
"// diff in array with schma fields\r",
"$",
"diffs",
"=",
"array_diff_key",
"(",
"$",
"iArray",
",",
"$",
"fields",
")",
";",
"// remove unwanted fields\r",
"foreach",
"(",
"$",
"diffs",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"unset",
"(",
"$",
"iArray",
"[",
"$",
"k",
"]",
")",
";",
"}",
"return",
"$",
"iArray",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"echo",
"$",
"e",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"}"
] | /*
filter out fields not match schema fields
@param table, $fldArray
@return filtered field Array ( [name] => some name [biography] => some bio ) | [
"/",
"*",
"filter",
"out",
"fields",
"not",
"match",
"schema",
"fields"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L445-L460 |
chanhong/pdolite | src/PdoLite.php | PdoLite.escapeQuote | public static function escapeQuote($iArray) {
// clean \' into single quote before double it
(!empty($iArray))
? $ret = str_replace("'", "''", str_replace("\'", "'", $iArray))
: $ret = "";
return $ret;
} | php | public static function escapeQuote($iArray) {
// clean \' into single quote before double it
(!empty($iArray))
? $ret = str_replace("'", "''", str_replace("\'", "'", $iArray))
: $ret = "";
return $ret;
} | [
"public",
"static",
"function",
"escapeQuote",
"(",
"$",
"iArray",
")",
"{",
"// clean \\' into single quote before double it\r",
"(",
"!",
"empty",
"(",
"$",
"iArray",
")",
")",
"?",
"$",
"ret",
"=",
"str_replace",
"(",
"\"'\"",
",",
"\"''\"",
",",
"str_replace",
"(",
"\"\\'\"",
",",
"\"'\"",
",",
"$",
"iArray",
")",
")",
":",
"$",
"ret",
"=",
"\"\"",
";",
"return",
"$",
"ret",
";",
"}"
] | /*
escape quote before insert to database
@param $array
@return string with escape quote | [
"/",
"*",
"escape",
"quote",
"before",
"insert",
"to",
"database"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L484-L491 |
chanhong/pdolite | src/PdoLite.php | PdoLite.debug | public static function debug($iVar, $iStr = "", $iFormat = "") {
$preText = $dTrace = "";
if (!empty($iStr) and strtolower($iStr) == "dtrace") {
$dTrace = "dtrace";
}
if (!empty($iStr) and strtolower($iStr) <> "dtrace") {
$preText = "[-" . strtoupper($iStr) . "-] ";
}
$fstr = "$preText%s";
if (!empty($iVar)) {
if (is_array($iVar) or ( is_object($iVar))) {
$iVar = print_r($iVar, true);
}
} else {
$iVar = ' Var is empty!';
}
switch (strtolower($iFormat)) {
case "pre":
$fstr = "<pre>$preText%s</pre>";
break;
case "p":
case "br":
$fstr = "<$iFormat />$preText%s";
break;
default:
$fstr = " $fstr";
}
if (!empty($dTrace)) {
$dTrace = self::backTrace();
}
$ret = sprintf($fstr, $iVar) . $dTrace;
return $ret;
} | php | public static function debug($iVar, $iStr = "", $iFormat = "") {
$preText = $dTrace = "";
if (!empty($iStr) and strtolower($iStr) == "dtrace") {
$dTrace = "dtrace";
}
if (!empty($iStr) and strtolower($iStr) <> "dtrace") {
$preText = "[-" . strtoupper($iStr) . "-] ";
}
$fstr = "$preText%s";
if (!empty($iVar)) {
if (is_array($iVar) or ( is_object($iVar))) {
$iVar = print_r($iVar, true);
}
} else {
$iVar = ' Var is empty!';
}
switch (strtolower($iFormat)) {
case "pre":
$fstr = "<pre>$preText%s</pre>";
break;
case "p":
case "br":
$fstr = "<$iFormat />$preText%s";
break;
default:
$fstr = " $fstr";
}
if (!empty($dTrace)) {
$dTrace = self::backTrace();
}
$ret = sprintf($fstr, $iVar) . $dTrace;
return $ret;
} | [
"public",
"static",
"function",
"debug",
"(",
"$",
"iVar",
",",
"$",
"iStr",
"=",
"\"\"",
",",
"$",
"iFormat",
"=",
"\"\"",
")",
"{",
"$",
"preText",
"=",
"$",
"dTrace",
"=",
"\"\"",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"iStr",
")",
"and",
"strtolower",
"(",
"$",
"iStr",
")",
"==",
"\"dtrace\"",
")",
"{",
"$",
"dTrace",
"=",
"\"dtrace\"",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"iStr",
")",
"and",
"strtolower",
"(",
"$",
"iStr",
")",
"<>",
"\"dtrace\"",
")",
"{",
"$",
"preText",
"=",
"\"[-\"",
".",
"strtoupper",
"(",
"$",
"iStr",
")",
".",
"\"-] \"",
";",
"}",
"$",
"fstr",
"=",
"\"$preText%s\"",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"iVar",
")",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"iVar",
")",
"or",
"(",
"is_object",
"(",
"$",
"iVar",
")",
")",
")",
"{",
"$",
"iVar",
"=",
"print_r",
"(",
"$",
"iVar",
",",
"true",
")",
";",
"}",
"}",
"else",
"{",
"$",
"iVar",
"=",
"' Var is empty!'",
";",
"}",
"switch",
"(",
"strtolower",
"(",
"$",
"iFormat",
")",
")",
"{",
"case",
"\"pre\"",
":",
"$",
"fstr",
"=",
"\"<pre>$preText%s</pre>\"",
";",
"break",
";",
"case",
"\"p\"",
":",
"case",
"\"br\"",
":",
"$",
"fstr",
"=",
"\"<$iFormat />$preText%s\"",
";",
"break",
";",
"default",
":",
"$",
"fstr",
"=",
"\" $fstr\"",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"dTrace",
")",
")",
"{",
"$",
"dTrace",
"=",
"self",
"::",
"backTrace",
"(",
")",
";",
"}",
"$",
"ret",
"=",
"sprintf",
"(",
"$",
"fstr",
",",
"$",
"iVar",
")",
".",
"$",
"dTrace",
";",
"return",
"$",
"ret",
";",
"}"
] | /*
print debug message
@param $ivar $istr $iformat
@return string | [
"/",
"*",
"print",
"debug",
"message"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L520-L553 |
chanhong/pdolite | src/PdoLite.php | PdoLite.a2sUpdate | public static function a2sUpdate($iArray, $defaultArray = array()) {
$str = "";
// self::pln($iArray,"ns");
while (list($key, $val) = each($iArray)) {
// self::pln(gettype($val),"t=$key");
// override value from $defaultArray value of the same key
if (empty($val) and isset($defaultArray[$key])) {
// set to value of $defaultArray when value is empty
$val = $defaultArray[$key];
// catch the case of integer val=0
} elseif (isset($val) and empty($val) and gettype($val)<>"string") {
$val = $val;
} else {
$val = self::escapeQuote($val);
}
// concat fields list for sql update
// use single quote to work around sqlsrv error
$str .= $key . " ='" . $val . "', ";
// self::pln($str,"vs");
}
// return maker= 'Name', acct= '15',
return substr($str, 0, strlen($str) - 2); // take out comma and space
} | php | public static function a2sUpdate($iArray, $defaultArray = array()) {
$str = "";
// self::pln($iArray,"ns");
while (list($key, $val) = each($iArray)) {
// self::pln(gettype($val),"t=$key");
// override value from $defaultArray value of the same key
if (empty($val) and isset($defaultArray[$key])) {
// set to value of $defaultArray when value is empty
$val = $defaultArray[$key];
// catch the case of integer val=0
} elseif (isset($val) and empty($val) and gettype($val)<>"string") {
$val = $val;
} else {
$val = self::escapeQuote($val);
}
// concat fields list for sql update
// use single quote to work around sqlsrv error
$str .= $key . " ='" . $val . "', ";
// self::pln($str,"vs");
}
// return maker= 'Name', acct= '15',
return substr($str, 0, strlen($str) - 2); // take out comma and space
} | [
"public",
"static",
"function",
"a2sUpdate",
"(",
"$",
"iArray",
",",
"$",
"defaultArray",
"=",
"array",
"(",
")",
")",
"{",
"$",
"str",
"=",
"\"\"",
";",
"// self::pln($iArray,\"ns\");\r",
"while",
"(",
"list",
"(",
"$",
"key",
",",
"$",
"val",
")",
"=",
"each",
"(",
"$",
"iArray",
")",
")",
"{",
"// self::pln(gettype($val),\"t=$key\");\r",
"// override value from $defaultArray value of the same key\r",
"if",
"(",
"empty",
"(",
"$",
"val",
")",
"and",
"isset",
"(",
"$",
"defaultArray",
"[",
"$",
"key",
"]",
")",
")",
"{",
"// set to value of $defaultArray when value is empty\r",
"$",
"val",
"=",
"$",
"defaultArray",
"[",
"$",
"key",
"]",
";",
"// catch the case of integer val=0\r",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"val",
")",
"and",
"empty",
"(",
"$",
"val",
")",
"and",
"gettype",
"(",
"$",
"val",
")",
"<>",
"\"string\"",
")",
"{",
"$",
"val",
"=",
"$",
"val",
";",
"}",
"else",
"{",
"$",
"val",
"=",
"self",
"::",
"escapeQuote",
"(",
"$",
"val",
")",
";",
"}",
"// concat fields list for sql update\r",
"// use single quote to work around sqlsrv error\r",
"$",
"str",
".=",
"$",
"key",
".",
"\" ='\"",
".",
"$",
"val",
".",
"\"', \"",
";",
"// self::pln($str,\"vs\");\r",
"}",
"// return maker= 'Name', acct= '15',\r",
"return",
"substr",
"(",
"$",
"str",
",",
"0",
",",
"strlen",
"(",
"$",
"str",
")",
"-",
"2",
")",
";",
"// take out comma and space\r",
"}"
] | /*
array to fields list for sql update
@param $array $checkNumArray
@return string | [
"/",
"*",
"array",
"to",
"fields",
"list",
"for",
"sql",
"update"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L571-L594 |
chanhong/pdolite | src/PdoLite.php | PdoLite.a2sInsert | public static function a2sInsert($iArray, $defaultArray = array()) {
$nameStr = $valStr = "";
// self::pln($iArray,"ns");
while (list($key, $val) = each($iArray)) {
// self::pln(gettype($val),"t=$key");
// use single quote to work around sqlsrv error
// override value from $defaultArray value of the same key
if (empty($val) and isset($defaultArray[$key])) {
$valStr .= "'" . $defaultArray[$key] . "', ";
// catch the case of integer val=0
} elseif (isset($val) and empty($val) and gettype($val)<>"string") {
$valStr .= "'$val', ";
} elseif (!empty($val)) {
$valStr .= "'" . self::escapeQuote($val). "', ";
// catch the case of null in date field
} else {
$valStr .= "null, ";
}
}
$nameStr = implode(", ", array_keys($iArray));
// self::pln($nameStr,"ns");
// self::pln($valStr,"vs");
// take out comma and space
$valStr = substr($valStr, 0, strlen($valStr) - 2);
return "($nameStr) VALUES ($valStr)";
} | php | public static function a2sInsert($iArray, $defaultArray = array()) {
$nameStr = $valStr = "";
// self::pln($iArray,"ns");
while (list($key, $val) = each($iArray)) {
// self::pln(gettype($val),"t=$key");
// use single quote to work around sqlsrv error
// override value from $defaultArray value of the same key
if (empty($val) and isset($defaultArray[$key])) {
$valStr .= "'" . $defaultArray[$key] . "', ";
// catch the case of integer val=0
} elseif (isset($val) and empty($val) and gettype($val)<>"string") {
$valStr .= "'$val', ";
} elseif (!empty($val)) {
$valStr .= "'" . self::escapeQuote($val). "', ";
// catch the case of null in date field
} else {
$valStr .= "null, ";
}
}
$nameStr = implode(", ", array_keys($iArray));
// self::pln($nameStr,"ns");
// self::pln($valStr,"vs");
// take out comma and space
$valStr = substr($valStr, 0, strlen($valStr) - 2);
return "($nameStr) VALUES ($valStr)";
} | [
"public",
"static",
"function",
"a2sInsert",
"(",
"$",
"iArray",
",",
"$",
"defaultArray",
"=",
"array",
"(",
")",
")",
"{",
"$",
"nameStr",
"=",
"$",
"valStr",
"=",
"\"\"",
";",
"// self::pln($iArray,\"ns\");\r",
"while",
"(",
"list",
"(",
"$",
"key",
",",
"$",
"val",
")",
"=",
"each",
"(",
"$",
"iArray",
")",
")",
"{",
"// self::pln(gettype($val),\"t=$key\");\r",
"// use single quote to work around sqlsrv error\r",
"// override value from $defaultArray value of the same key\r",
"if",
"(",
"empty",
"(",
"$",
"val",
")",
"and",
"isset",
"(",
"$",
"defaultArray",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"valStr",
".=",
"\"'\"",
".",
"$",
"defaultArray",
"[",
"$",
"key",
"]",
".",
"\"', \"",
";",
"// catch the case of integer val=0\r",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"val",
")",
"and",
"empty",
"(",
"$",
"val",
")",
"and",
"gettype",
"(",
"$",
"val",
")",
"<>",
"\"string\"",
")",
"{",
"$",
"valStr",
".=",
"\"'$val', \"",
";",
"}",
"elseif",
"(",
"!",
"empty",
"(",
"$",
"val",
")",
")",
"{",
"$",
"valStr",
".=",
"\"'\"",
".",
"self",
"::",
"escapeQuote",
"(",
"$",
"val",
")",
".",
"\"', \"",
";",
"// catch the case of null in date field\r",
"}",
"else",
"{",
"$",
"valStr",
".=",
"\"null, \"",
";",
"}",
"}",
"$",
"nameStr",
"=",
"implode",
"(",
"\", \"",
",",
"array_keys",
"(",
"$",
"iArray",
")",
")",
";",
"// self::pln($nameStr,\"ns\");\r",
"// self::pln($valStr,\"vs\");\r",
"// take out comma and space\r",
"$",
"valStr",
"=",
"substr",
"(",
"$",
"valStr",
",",
"0",
",",
"strlen",
"(",
"$",
"valStr",
")",
"-",
"2",
")",
";",
"return",
"\"($nameStr) VALUES ($valStr)\"",
";",
"}"
] | /*
array to sql insert statement
@param $array
@return string (title, maker) VALUES ("Title","Maker") | [
"/",
"*",
"array",
"to",
"sql",
"insert",
"statement"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L601-L626 |
chanhong/pdolite | src/PdoLite.php | PdoLite.qbSelect | public static function qbSelect($tname, $options=array()) {
if (empty($tname)) return;
$one = self::getSUDIOptions("select", $tname, $options);
(!empty($one['where']))
? $where = " WHERE " . $one['where']
: $where = "";
(empty($one['fl']))
? $iFldList = "*"
: $iFldList = $one['fl']
;
return "SELECT " . $iFldList
. " FROM ". $tname
. $where . ";"
;
} | php | public static function qbSelect($tname, $options=array()) {
if (empty($tname)) return;
$one = self::getSUDIOptions("select", $tname, $options);
(!empty($one['where']))
? $where = " WHERE " . $one['where']
: $where = "";
(empty($one['fl']))
? $iFldList = "*"
: $iFldList = $one['fl']
;
return "SELECT " . $iFldList
. " FROM ". $tname
. $where . ";"
;
} | [
"public",
"static",
"function",
"qbSelect",
"(",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tname",
")",
")",
"return",
";",
"$",
"one",
"=",
"self",
"::",
"getSUDIOptions",
"(",
"\"select\"",
",",
"$",
"tname",
",",
"$",
"options",
")",
";",
"(",
"!",
"empty",
"(",
"$",
"one",
"[",
"'where'",
"]",
")",
")",
"?",
"$",
"where",
"=",
"\" WHERE \"",
".",
"$",
"one",
"[",
"'where'",
"]",
":",
"$",
"where",
"=",
"\"\"",
";",
"(",
"empty",
"(",
"$",
"one",
"[",
"'fl'",
"]",
")",
")",
"?",
"$",
"iFldList",
"=",
"\"*\"",
":",
"$",
"iFldList",
"=",
"$",
"one",
"[",
"'fl'",
"]",
";",
"return",
"\"SELECT \"",
".",
"$",
"iFldList",
".",
"\" FROM \"",
".",
"$",
"tname",
".",
"$",
"where",
".",
"\";\"",
";",
"}"
] | /*
build select statement (fieldlist must be already single quote safe)
@param table, $iFldList, $where
@return string | [
"/",
"*",
"build",
"select",
"statement",
"(",
"fieldlist",
"must",
"be",
"already",
"single",
"quote",
"safe",
")"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L634-L653 |
chanhong/pdolite | src/PdoLite.php | PdoLite.qbInsert | public static function qbInsert($tname, $options) {
if (empty($tname) or empty($options['fl'])) return;
$one = self::getSUDIOptions("insert", $tname, $options);
return "INSERT INTO $tname " . $one['fl'] . ";"
;
} | php | public static function qbInsert($tname, $options) {
if (empty($tname) or empty($options['fl'])) return;
$one = self::getSUDIOptions("insert", $tname, $options);
return "INSERT INTO $tname " . $one['fl'] . ";"
;
} | [
"public",
"static",
"function",
"qbInsert",
"(",
"$",
"tname",
",",
"$",
"options",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tname",
")",
"or",
"empty",
"(",
"$",
"options",
"[",
"'fl'",
"]",
")",
")",
"return",
";",
"$",
"one",
"=",
"self",
"::",
"getSUDIOptions",
"(",
"\"insert\"",
",",
"$",
"tname",
",",
"$",
"options",
")",
";",
"return",
"\"INSERT INTO $tname \"",
".",
"$",
"one",
"[",
"'fl'",
"]",
".",
"\";\"",
";",
"}"
] | /*
build insert statement (fieldlist must be already single quote safe)
@param table, $iFldList
@return string | [
"/",
"*",
"build",
"insert",
"statement",
"(",
"fieldlist",
"must",
"be",
"already",
"single",
"quote",
"safe",
")"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L660-L666 |
chanhong/pdolite | src/PdoLite.php | PdoLite.qbUpdate | public static function qbUpdate($tname, $options) {
if (empty($tname) or empty($options['fl'])) return;
$one = self::getSUDIOptions("update", $tname, $options);
(!empty($one['where']))
? $where = " WHERE " . $one['where']
: $where = "";
return "UPDATE $tname"
. " SET " . $one['fl']
. $where . ";"
;
} | php | public static function qbUpdate($tname, $options) {
if (empty($tname) or empty($options['fl'])) return;
$one = self::getSUDIOptions("update", $tname, $options);
(!empty($one['where']))
? $where = " WHERE " . $one['where']
: $where = "";
return "UPDATE $tname"
. " SET " . $one['fl']
. $where . ";"
;
} | [
"public",
"static",
"function",
"qbUpdate",
"(",
"$",
"tname",
",",
"$",
"options",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"tname",
")",
"or",
"empty",
"(",
"$",
"options",
"[",
"'fl'",
"]",
")",
")",
"return",
";",
"$",
"one",
"=",
"self",
"::",
"getSUDIOptions",
"(",
"\"update\"",
",",
"$",
"tname",
",",
"$",
"options",
")",
";",
"(",
"!",
"empty",
"(",
"$",
"one",
"[",
"'where'",
"]",
")",
")",
"?",
"$",
"where",
"=",
"\" WHERE \"",
".",
"$",
"one",
"[",
"'where'",
"]",
":",
"$",
"where",
"=",
"\"\"",
";",
"return",
"\"UPDATE $tname\"",
".",
"\" SET \"",
".",
"$",
"one",
"[",
"'fl'",
"]",
".",
"$",
"where",
".",
"\";\"",
";",
"}"
] | /*
build update statement (fieldlist must be already single quote safe)
@param table, $iFldList, $where
@return string | [
"/",
"*",
"build",
"update",
"statement",
"(",
"fieldlist",
"must",
"be",
"already",
"single",
"quote",
"safe",
")"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L685-L699 |
chanhong/pdolite | src/PdoLite.php | PdoLite.getSUDIOptions | public static function getSUDIOptions($opr, $tname, $options=array()) {
try {
$fldList = "";
$iFldList = self::getKeyVal($options, 'fl');
$where = self::getKeyVal($options, 'where');
$otype = self::getKeyVal($options, 'type');
$defaultArray = self::getKeyVal($options, 'default');
switch (strtolower($opr)) {
case "update":
if (!empty($iFldList) and is_array($iFldList)) {
$fldList = self::a2sUpdate(self::filterBySchema($tname, $iFldList), $defaultArray);
}
break;
case "insert":
if (!empty($iFldList) and is_string($iFldList)) {
// fields list then flip the array to key
$iFldList = array_flip(explode(",", str_replace(' ','',$iFldList)));
}
if (!empty($iFldList) and is_array($iFldList)) {
$fldList = self::a2sInsert(self::filterBySchema($tname, $iFldList), $defaultArray);
}
break;
case "select":
defailt :
if (!empty($iFldList) and is_string($iFldList)) {
// fields list then flip the array to key
$iFldList = array_flip(explode(",", str_replace(' ','',$iFldList)));
}
if (!empty($iFldList) and is_array($iFldList)) {
$fldList = self::a2sSelect(self::filterBySchema($tname, $iFldList));
}
}
return ['fl'=>$fldList, 'where'=>$where, 'type'=>$otype];
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | php | public static function getSUDIOptions($opr, $tname, $options=array()) {
try {
$fldList = "";
$iFldList = self::getKeyVal($options, 'fl');
$where = self::getKeyVal($options, 'where');
$otype = self::getKeyVal($options, 'type');
$defaultArray = self::getKeyVal($options, 'default');
switch (strtolower($opr)) {
case "update":
if (!empty($iFldList) and is_array($iFldList)) {
$fldList = self::a2sUpdate(self::filterBySchema($tname, $iFldList), $defaultArray);
}
break;
case "insert":
if (!empty($iFldList) and is_string($iFldList)) {
// fields list then flip the array to key
$iFldList = array_flip(explode(",", str_replace(' ','',$iFldList)));
}
if (!empty($iFldList) and is_array($iFldList)) {
$fldList = self::a2sInsert(self::filterBySchema($tname, $iFldList), $defaultArray);
}
break;
case "select":
defailt :
if (!empty($iFldList) and is_string($iFldList)) {
// fields list then flip the array to key
$iFldList = array_flip(explode(",", str_replace(' ','',$iFldList)));
}
if (!empty($iFldList) and is_array($iFldList)) {
$fldList = self::a2sSelect(self::filterBySchema($tname, $iFldList));
}
}
return ['fl'=>$fldList, 'where'=>$where, 'type'=>$otype];
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | [
"public",
"static",
"function",
"getSUDIOptions",
"(",
"$",
"opr",
",",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"$",
"fldList",
"=",
"\"\"",
";",
"$",
"iFldList",
"=",
"self",
"::",
"getKeyVal",
"(",
"$",
"options",
",",
"'fl'",
")",
";",
"$",
"where",
"=",
"self",
"::",
"getKeyVal",
"(",
"$",
"options",
",",
"'where'",
")",
";",
"$",
"otype",
"=",
"self",
"::",
"getKeyVal",
"(",
"$",
"options",
",",
"'type'",
")",
";",
"$",
"defaultArray",
"=",
"self",
"::",
"getKeyVal",
"(",
"$",
"options",
",",
"'default'",
")",
";",
"switch",
"(",
"strtolower",
"(",
"$",
"opr",
")",
")",
"{",
"case",
"\"update\"",
":",
"if",
"(",
"!",
"empty",
"(",
"$",
"iFldList",
")",
"and",
"is_array",
"(",
"$",
"iFldList",
")",
")",
"{",
"$",
"fldList",
"=",
"self",
"::",
"a2sUpdate",
"(",
"self",
"::",
"filterBySchema",
"(",
"$",
"tname",
",",
"$",
"iFldList",
")",
",",
"$",
"defaultArray",
")",
";",
"}",
"break",
";",
"case",
"\"insert\"",
":",
"if",
"(",
"!",
"empty",
"(",
"$",
"iFldList",
")",
"and",
"is_string",
"(",
"$",
"iFldList",
")",
")",
"{",
"// fields list then flip the array to key\r",
"$",
"iFldList",
"=",
"array_flip",
"(",
"explode",
"(",
"\",\"",
",",
"str_replace",
"(",
"' '",
",",
"''",
",",
"$",
"iFldList",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"iFldList",
")",
"and",
"is_array",
"(",
"$",
"iFldList",
")",
")",
"{",
"$",
"fldList",
"=",
"self",
"::",
"a2sInsert",
"(",
"self",
"::",
"filterBySchema",
"(",
"$",
"tname",
",",
"$",
"iFldList",
")",
",",
"$",
"defaultArray",
")",
";",
"}",
"break",
";",
"case",
"\"select\"",
":",
"defailt",
":",
"if",
"(",
"!",
"empty",
"(",
"$",
"iFldList",
")",
"and",
"is_string",
"(",
"$",
"iFldList",
")",
")",
"{",
"// fields list then flip the array to key\r",
"$",
"iFldList",
"=",
"array_flip",
"(",
"explode",
"(",
"\",\"",
",",
"str_replace",
"(",
"' '",
",",
"''",
",",
"$",
"iFldList",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"iFldList",
")",
"and",
"is_array",
"(",
"$",
"iFldList",
")",
")",
"{",
"$",
"fldList",
"=",
"self",
"::",
"a2sSelect",
"(",
"self",
"::",
"filterBySchema",
"(",
"$",
"tname",
",",
"$",
"iFldList",
")",
")",
";",
"}",
"}",
"return",
"[",
"'fl'",
"=>",
"$",
"fldList",
",",
"'where'",
"=>",
"$",
"where",
",",
"'type'",
"=>",
"$",
"otype",
"]",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"tname",
")",
")",
";",
"}",
"}"
] | /*
get SUDI options
@param table, $iFldList, $where
@return string | [
"/",
"*",
"get",
"SUDI",
"options"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L707-L747 |
chanhong/pdolite | src/PdoLite.php | PdoLite.select | public static function select($tname, $options=array()) {
try {
$otype = self::getKeyVal($options, 'type', 'assoc');
$all = self::getKeyVal($options, 'all');
$sql = self::qbSelect($tname, $options);
if (strtolower($all)=="all") {
$return = self::rows2arrayAll($sql, $otype);
} else {
$return = self::rows2Array($sql, $otype);
}
return $return;
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | php | public static function select($tname, $options=array()) {
try {
$otype = self::getKeyVal($options, 'type', 'assoc');
$all = self::getKeyVal($options, 'all');
$sql = self::qbSelect($tname, $options);
if (strtolower($all)=="all") {
$return = self::rows2arrayAll($sql, $otype);
} else {
$return = self::rows2Array($sql, $otype);
}
return $return;
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | [
"public",
"static",
"function",
"select",
"(",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"$",
"otype",
"=",
"self",
"::",
"getKeyVal",
"(",
"$",
"options",
",",
"'type'",
",",
"'assoc'",
")",
";",
"$",
"all",
"=",
"self",
"::",
"getKeyVal",
"(",
"$",
"options",
",",
"'all'",
")",
";",
"$",
"sql",
"=",
"self",
"::",
"qbSelect",
"(",
"$",
"tname",
",",
"$",
"options",
")",
";",
"if",
"(",
"strtolower",
"(",
"$",
"all",
")",
"==",
"\"all\"",
")",
"{",
"$",
"return",
"=",
"self",
"::",
"rows2arrayAll",
"(",
"$",
"sql",
",",
"$",
"otype",
")",
";",
"}",
"else",
"{",
"$",
"return",
"=",
"self",
"::",
"rows2Array",
"(",
"$",
"sql",
",",
"$",
"otype",
")",
";",
"}",
"return",
"$",
"return",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"tname",
")",
")",
";",
"}",
"}"
] | /*
select record set
@param table, $options
@return record set of array ['type'] | [
"/",
"*",
"select",
"record",
"set"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L754-L769 |
chanhong/pdolite | src/PdoLite.php | PdoLite.insert | public static function insert($tname, $options=array()) {
try {
return PdoLite::exec(self::qbInsert($tname, $options));
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | php | public static function insert($tname, $options=array()) {
try {
return PdoLite::exec(self::qbInsert($tname, $options));
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | [
"public",
"static",
"function",
"insert",
"(",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"return",
"PdoLite",
"::",
"exec",
"(",
"self",
"::",
"qbInsert",
"(",
"$",
"tname",
",",
"$",
"options",
")",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"tname",
")",
")",
";",
"}",
"}"
] | /*
insert record
@param table, $options
@return status | [
"/",
"*",
"insert",
"record"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L776-L783 |
chanhong/pdolite | src/PdoLite.php | PdoLite.delete | public static function delete($tname, $options=array()) {
try {
return PdoLite::exec(self::qbDelete($tname, $options));
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | php | public static function delete($tname, $options=array()) {
try {
return PdoLite::exec(self::qbDelete($tname, $options));
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | [
"public",
"static",
"function",
"delete",
"(",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"return",
"PdoLite",
"::",
"exec",
"(",
"self",
"::",
"qbDelete",
"(",
"$",
"tname",
",",
"$",
"options",
")",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"tname",
")",
")",
";",
"}",
"}"
] | /*
delete record
@param table, $options
@return status | [
"/",
"*",
"delete",
"record"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L790-L797 |
chanhong/pdolite | src/PdoLite.php | PdoLite.update | public static function update($tname, $options=array()) {
try {
return PdoLite::exec(self::qbUpdate($tname, $options));
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | php | public static function update($tname, $options=array()) {
try {
return PdoLite::exec(self::qbUpdate($tname, $options));
} catch (PDOException $e) {
die(self::dbError($tname));
}
} | [
"public",
"static",
"function",
"update",
"(",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"return",
"PdoLite",
"::",
"exec",
"(",
"self",
"::",
"qbUpdate",
"(",
"$",
"tname",
",",
"$",
"options",
")",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"die",
"(",
"self",
"::",
"dbError",
"(",
"$",
"tname",
")",
")",
";",
"}",
"}"
] | /*
update record
@param table, $options
@return status | [
"/",
"*",
"update",
"record"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L804-L811 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbField | public static function dbField($table, $field, $where) {
$fldValue = "";
$row = self::dbRow($table, ['type'=>'num', 'fl'=>$field, 'where'=>$where]);
if (!empty($row)) {
list($fldValue) = $row;
}
return $fldValue;
} | php | public static function dbField($table, $field, $where) {
$fldValue = "";
$row = self::dbRow($table, ['type'=>'num', 'fl'=>$field, 'where'=>$where]);
if (!empty($row)) {
list($fldValue) = $row;
}
return $fldValue;
} | [
"public",
"static",
"function",
"dbField",
"(",
"$",
"table",
",",
"$",
"field",
",",
"$",
"where",
")",
"{",
"$",
"fldValue",
"=",
"\"\"",
";",
"$",
"row",
"=",
"self",
"::",
"dbRow",
"(",
"$",
"table",
",",
"[",
"'type'",
"=>",
"'num'",
",",
"'fl'",
"=>",
"$",
"field",
",",
"'where'",
"=>",
"$",
"where",
"]",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"row",
")",
")",
"{",
"list",
"(",
"$",
"fldValue",
")",
"=",
"$",
"row",
";",
"}",
"return",
"$",
"fldValue",
";",
"}"
] | /*
call dbRow to get value of table field
@param $table, $field, $where
@return field value | [
"/",
"*",
"call",
"dbRow",
"to",
"get",
"value",
"of",
"table",
"field"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L819-L827 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbRow | public static function dbRow($tname, $options=array()) {
try {
$row = array();
$defArray = ['type'=>'assoc', 'all'=>'all'];
// options array will override the default array
$coptions = array_merge($defArray, $options);
$rows = self::select($tname, $coptions);
if (!empty($rows)) {
$row = array_shift($rows); // get top one array
}
return $row;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | php | public static function dbRow($tname, $options=array()) {
try {
$row = array();
$defArray = ['type'=>'assoc', 'all'=>'all'];
// options array will override the default array
$coptions = array_merge($defArray, $options);
$rows = self::select($tname, $coptions);
if (!empty($rows)) {
$row = array_shift($rows); // get top one array
}
return $row;
} catch (Exception $e) {
echo $e->getTraceAsString();
}
} | [
"public",
"static",
"function",
"dbRow",
"(",
"$",
"tname",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"$",
"row",
"=",
"array",
"(",
")",
";",
"$",
"defArray",
"=",
"[",
"'type'",
"=>",
"'assoc'",
",",
"'all'",
"=>",
"'all'",
"]",
";",
"// options array will override the default array\r",
"$",
"coptions",
"=",
"array_merge",
"(",
"$",
"defArray",
",",
"$",
"options",
")",
";",
"$",
"rows",
"=",
"self",
"::",
"select",
"(",
"$",
"tname",
",",
"$",
"coptions",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"rows",
")",
")",
"{",
"$",
"row",
"=",
"array_shift",
"(",
"$",
"rows",
")",
";",
"// get top one array\r",
"}",
"return",
"$",
"row",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"echo",
"$",
"e",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"}"
] | /*
call select to get one row
@param $table, $field, $where
@return field value | [
"/",
"*",
"call",
"select",
"to",
"get",
"one",
"row"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L834-L849 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbtypeSqlStr2Date | public function dbtypeSqlStr2Date($one) {
if (empty($one['fieldname'])) return;
if (empty($one['dbtype'])) {
$one['dbtype'] = "pdo-mysql";
}
if (empty($one['format'])) {
$one['format'] = "%m/%d/%y";
}
switch (strtolower($one['dbtype'])) {
case "pdo-sqlsrv":
$ret = "CONVERT(DATETIME, ".$one['fieldname'].")";
break;
default:
case "pdo-mysql":
$ret = "STR_TO_DATE(".$one['fieldname'].", '".$one['format']."')";
break;
}
return $ret;
} | php | public function dbtypeSqlStr2Date($one) {
if (empty($one['fieldname'])) return;
if (empty($one['dbtype'])) {
$one['dbtype'] = "pdo-mysql";
}
if (empty($one['format'])) {
$one['format'] = "%m/%d/%y";
}
switch (strtolower($one['dbtype'])) {
case "pdo-sqlsrv":
$ret = "CONVERT(DATETIME, ".$one['fieldname'].")";
break;
default:
case "pdo-mysql":
$ret = "STR_TO_DATE(".$one['fieldname'].", '".$one['format']."')";
break;
}
return $ret;
} | [
"public",
"function",
"dbtypeSqlStr2Date",
"(",
"$",
"one",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'fieldname'",
"]",
")",
")",
"return",
";",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'dbtype'",
"]",
")",
")",
"{",
"$",
"one",
"[",
"'dbtype'",
"]",
"=",
"\"pdo-mysql\"",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'format'",
"]",
")",
")",
"{",
"$",
"one",
"[",
"'format'",
"]",
"=",
"\"%m/%d/%y\"",
";",
"}",
"switch",
"(",
"strtolower",
"(",
"$",
"one",
"[",
"'dbtype'",
"]",
")",
")",
"{",
"case",
"\"pdo-sqlsrv\"",
":",
"$",
"ret",
"=",
"\"CONVERT(DATETIME, \"",
".",
"$",
"one",
"[",
"'fieldname'",
"]",
".",
"\")\"",
";",
"break",
";",
"default",
":",
"case",
"\"pdo-mysql\"",
":",
"$",
"ret",
"=",
"\"STR_TO_DATE(\"",
".",
"$",
"one",
"[",
"'fieldname'",
"]",
".",
"\", '\"",
".",
"$",
"one",
"[",
"'format'",
"]",
".",
"\"')\"",
";",
"break",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | /*
get query string for string to date based on dbtype such as 'pdo-mysql' or 'pdo-sqlsrv'
@param array('dbtype'=>'pdo-mysql','fieldname'=>'first', 'format'=>'%d/%d/%y')
@return string
sqlite date string must be in ths format "%Y-%m-%d" such '2017-12-01' then use date between | [
"/",
"*",
"get",
"query",
"string",
"for",
"string",
"to",
"date",
"based",
"on",
"dbtype",
"such",
"as",
"pdo",
"-",
"mysql",
"or",
"pdo",
"-",
"sqlsrv"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L857-L879 |
chanhong/pdolite | src/PdoLite.php | PdoLite.dbtypeSqlSelectRange | public function dbtypeSqlSelectRange($one) {
if (empty($one['tbl']) or empty($one['where'])) return;
if (empty($one['dbtype'])) {
$one['dbtype'] = "pdo-mysql";
}
if (empty($one['fl'])) {
$one['fl'] = "*";
}
if (empty($one['start'])) {
$one['start'] = 0;
}
if (empty($one['limit'])) {
$one['limit'] = 1;
}
switch (strtolower($one['dbtype'])) {
case "pdo-sqlsrv":
// require > SQL 2012
$ret = "SELECT ".$one['fl']
. " FROM ".$one['tbl']
. " WHERE ".$one['where']
. " OFFSET ".$one['start']." ROWS "
. " FETCH NEXT ".$one['limit']." ROWS ONLY"
;
break;
case "sqlite":
$ret = "SELECT ".$one['fl']
. " FROM ".$one['tbl']
. " WHERE ".$one['where']." LIMIT ".$one['start'].", ".$one['limit'].";"
;
break;
default:
case "pdo-mysql":
$ret = "SELECT ".$one['fl'].", @rownum:=@rownum+1 RowNumber "
. " FROM ".$one['tbl'].", (SELECT @rownum:=0) r "
. " WHERE ".$one['where']." LIMIT ".$one['limit']." OFFSET ".$one['start'].";"
;
break;
}
return $ret;
} | php | public function dbtypeSqlSelectRange($one) {
if (empty($one['tbl']) or empty($one['where'])) return;
if (empty($one['dbtype'])) {
$one['dbtype'] = "pdo-mysql";
}
if (empty($one['fl'])) {
$one['fl'] = "*";
}
if (empty($one['start'])) {
$one['start'] = 0;
}
if (empty($one['limit'])) {
$one['limit'] = 1;
}
switch (strtolower($one['dbtype'])) {
case "pdo-sqlsrv":
// require > SQL 2012
$ret = "SELECT ".$one['fl']
. " FROM ".$one['tbl']
. " WHERE ".$one['where']
. " OFFSET ".$one['start']." ROWS "
. " FETCH NEXT ".$one['limit']." ROWS ONLY"
;
break;
case "sqlite":
$ret = "SELECT ".$one['fl']
. " FROM ".$one['tbl']
. " WHERE ".$one['where']." LIMIT ".$one['start'].", ".$one['limit'].";"
;
break;
default:
case "pdo-mysql":
$ret = "SELECT ".$one['fl'].", @rownum:=@rownum+1 RowNumber "
. " FROM ".$one['tbl'].", (SELECT @rownum:=0) r "
. " WHERE ".$one['where']." LIMIT ".$one['limit']." OFFSET ".$one['start'].";"
;
break;
}
return $ret;
} | [
"public",
"function",
"dbtypeSqlSelectRange",
"(",
"$",
"one",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'tbl'",
"]",
")",
"or",
"empty",
"(",
"$",
"one",
"[",
"'where'",
"]",
")",
")",
"return",
";",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'dbtype'",
"]",
")",
")",
"{",
"$",
"one",
"[",
"'dbtype'",
"]",
"=",
"\"pdo-mysql\"",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'fl'",
"]",
")",
")",
"{",
"$",
"one",
"[",
"'fl'",
"]",
"=",
"\"*\"",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'start'",
"]",
")",
")",
"{",
"$",
"one",
"[",
"'start'",
"]",
"=",
"0",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"one",
"[",
"'limit'",
"]",
")",
")",
"{",
"$",
"one",
"[",
"'limit'",
"]",
"=",
"1",
";",
"}",
"switch",
"(",
"strtolower",
"(",
"$",
"one",
"[",
"'dbtype'",
"]",
")",
")",
"{",
"case",
"\"pdo-sqlsrv\"",
":",
"// require > SQL 2012 \r",
"$",
"ret",
"=",
"\"SELECT \"",
".",
"$",
"one",
"[",
"'fl'",
"]",
".",
"\" FROM \"",
".",
"$",
"one",
"[",
"'tbl'",
"]",
".",
"\" WHERE \"",
".",
"$",
"one",
"[",
"'where'",
"]",
".",
"\" OFFSET \"",
".",
"$",
"one",
"[",
"'start'",
"]",
".",
"\" ROWS \"",
".",
"\" FETCH NEXT \"",
".",
"$",
"one",
"[",
"'limit'",
"]",
".",
"\" ROWS ONLY\"",
";",
"break",
";",
"case",
"\"sqlite\"",
":",
"$",
"ret",
"=",
"\"SELECT \"",
".",
"$",
"one",
"[",
"'fl'",
"]",
".",
"\" FROM \"",
".",
"$",
"one",
"[",
"'tbl'",
"]",
".",
"\" WHERE \"",
".",
"$",
"one",
"[",
"'where'",
"]",
".",
"\" LIMIT \"",
".",
"$",
"one",
"[",
"'start'",
"]",
".",
"\", \"",
".",
"$",
"one",
"[",
"'limit'",
"]",
".",
"\";\"",
";",
"break",
";",
"default",
":",
"case",
"\"pdo-mysql\"",
":",
"$",
"ret",
"=",
"\"SELECT \"",
".",
"$",
"one",
"[",
"'fl'",
"]",
".",
"\", @rownum:=@rownum+1 RowNumber \"",
".",
"\" FROM \"",
".",
"$",
"one",
"[",
"'tbl'",
"]",
".",
"\", (SELECT @rownum:=0) r \"",
".",
"\" WHERE \"",
".",
"$",
"one",
"[",
"'where'",
"]",
".",
"\" LIMIT \"",
".",
"$",
"one",
"[",
"'limit'",
"]",
".",
"\" OFFSET \"",
".",
"$",
"one",
"[",
"'start'",
"]",
".",
"\";\"",
";",
"break",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | /*
get query string for select date range based on dbtype such as 'pdo-mysql' or 'pdo-sqlsrv' MUST have order by in WHERE to work
@param array('dbtype'=>'pdo-mysql','tbl'=>'tname', ,'fl'=>'*', 'where'=>'id=1 order by id', 'start'=>1, 'limit'=>10)
@return string | [
"/",
"*",
"get",
"query",
"string",
"for",
"select",
"date",
"range",
"based",
"on",
"dbtype",
"such",
"as",
"pdo",
"-",
"mysql",
"or",
"pdo",
"-",
"sqlsrv",
"MUST",
"have",
"order",
"by",
"in",
"WHERE",
"to",
"work"
] | train | https://github.com/chanhong/pdolite/blob/93f35e6df25db2f0a03ff8fed751ddac1439b68a/src/PdoLite.php#L886-L931 |
dmitrya2e/filtration-bundle | Manager/FilterSuperManager.php | FilterSuperManager.addFilter | public function addFilter(CollectionInterface $collection, $typeAlias, $name, array $options = [])
{
$filter = $this->filterCreator->create($typeAlias, $name, $options);
$collection->addFilter($filter);
return $filter;
} | php | public function addFilter(CollectionInterface $collection, $typeAlias, $name, array $options = [])
{
$filter = $this->filterCreator->create($typeAlias, $name, $options);
$collection->addFilter($filter);
return $filter;
} | [
"public",
"function",
"addFilter",
"(",
"CollectionInterface",
"$",
"collection",
",",
"$",
"typeAlias",
",",
"$",
"name",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"filter",
"=",
"$",
"this",
"->",
"filterCreator",
"->",
"create",
"(",
"$",
"typeAlias",
",",
"$",
"name",
",",
"$",
"options",
")",
";",
"$",
"collection",
"->",
"addFilter",
"(",
"$",
"filter",
")",
";",
"return",
"$",
"filter",
";",
"}"
] | Adds a filter to the collection.
@param CollectionInterface $collection The filter collection
@param string $typeAlias The alias of the filter service definition
@param string $name The internal name of the filter
@param array $options (Optional) The options of the filter
@see \Da2e\FiltrationBundle\Filter\Creator\FilterCreatorInterface::create() for complete documentation
@see \Da2e\FiltrationBundle\Filter\Collection\CollectionInterface::addFilter() for complete documentation
@return FilterInterface | [
"Adds",
"a",
"filter",
"to",
"the",
"collection",
"."
] | train | https://github.com/dmitrya2e/filtration-bundle/blob/fed5764af4e43871835744fb84957b2a76e9a215/Manager/FilterSuperManager.php#L114-L120 |
dmitrya2e/filtration-bundle | Manager/FilterSuperManager.php | FilterSuperManager.createForm | public function createForm(
CollectionInterface $collection,
array $rootFormBuilderOptions = [],
array $filterFormBuilderOptions = [],
Request $request = null
) {
$form = $this->formCreator->create($collection, $rootFormBuilderOptions, $filterFormBuilderOptions);
if ($request !== null) {
$form->handleRequest($request);
}
return $form;
} | php | public function createForm(
CollectionInterface $collection,
array $rootFormBuilderOptions = [],
array $filterFormBuilderOptions = [],
Request $request = null
) {
$form = $this->formCreator->create($collection, $rootFormBuilderOptions, $filterFormBuilderOptions);
if ($request !== null) {
$form->handleRequest($request);
}
return $form;
} | [
"public",
"function",
"createForm",
"(",
"CollectionInterface",
"$",
"collection",
",",
"array",
"$",
"rootFormBuilderOptions",
"=",
"[",
"]",
",",
"array",
"$",
"filterFormBuilderOptions",
"=",
"[",
"]",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"formCreator",
"->",
"create",
"(",
"$",
"collection",
",",
"$",
"rootFormBuilderOptions",
",",
"$",
"filterFormBuilderOptions",
")",
";",
"if",
"(",
"$",
"request",
"!==",
"null",
")",
"{",
"$",
"form",
"->",
"handleRequest",
"(",
"$",
"request",
")",
";",
"}",
"return",
"$",
"form",
";",
"}"
] | Creates a filtration form (unnamed).
@param CollectionInterface $collection The filter collection
@param array $rootFormBuilderOptions (Optional)
@param array $filterFormBuilderOptions (Optional)
@param Request|null $request (Optional) If passed Request object,
FormInterface::handleRequest() will be executed
@see \Da2e\FiltrationBundle\Form\Creator\FormCreatorInterface::create() for complete documentation
@return \Symfony\Component\Form\FormInterface | [
"Creates",
"a",
"filtration",
"form",
"(",
"unnamed",
")",
"."
] | train | https://github.com/dmitrya2e/filtration-bundle/blob/fed5764af4e43871835744fb84957b2a76e9a215/Manager/FilterSuperManager.php#L135-L148 |
dmitrya2e/filtration-bundle | Manager/FilterSuperManager.php | FilterSuperManager.createNamedForm | public function createNamedForm(
$name,
CollectionInterface $collection,
array $rootFormBuilderOptions = [],
array $filterFormBuilderOptions = [],
Request $request = null
) {
$form = $this->formCreator->createNamed($name, $collection, $rootFormBuilderOptions, $filterFormBuilderOptions);
if ($request !== null) {
$form->handleRequest($request);
}
return $form;
} | php | public function createNamedForm(
$name,
CollectionInterface $collection,
array $rootFormBuilderOptions = [],
array $filterFormBuilderOptions = [],
Request $request = null
) {
$form = $this->formCreator->createNamed($name, $collection, $rootFormBuilderOptions, $filterFormBuilderOptions);
if ($request !== null) {
$form->handleRequest($request);
}
return $form;
} | [
"public",
"function",
"createNamedForm",
"(",
"$",
"name",
",",
"CollectionInterface",
"$",
"collection",
",",
"array",
"$",
"rootFormBuilderOptions",
"=",
"[",
"]",
",",
"array",
"$",
"filterFormBuilderOptions",
"=",
"[",
"]",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"formCreator",
"->",
"createNamed",
"(",
"$",
"name",
",",
"$",
"collection",
",",
"$",
"rootFormBuilderOptions",
",",
"$",
"filterFormBuilderOptions",
")",
";",
"if",
"(",
"$",
"request",
"!==",
"null",
")",
"{",
"$",
"form",
"->",
"handleRequest",
"(",
"$",
"request",
")",
";",
"}",
"return",
"$",
"form",
";",
"}"
] | Creates a filtration named form.
@param string $name The name of the root form
@param CollectionInterface $collection The filter collection
@param array $rootFormBuilderOptions (Optional)
@param array $filterFormBuilderOptions (Optional)
@param Request|null $request (Optional) If passed Request object,
FormInterface::handleRequest() will be executed
@see \Da2e\FiltrationBundle\Form\Creator\FormCreatorInterface::createNamed() for complete documentation
@return \Symfony\Component\Form\FormInterface | [
"Creates",
"a",
"filtration",
"named",
"form",
"."
] | train | https://github.com/dmitrya2e/filtration-bundle/blob/fed5764af4e43871835744fb84957b2a76e9a215/Manager/FilterSuperManager.php#L164-L178 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.index | public function index($trashed = false)
{
$this->authorize(UsersPolicy::PERMISSION_LIST);
$users = $this->user->with('roles')->protectAdmins()->when($trashed, function ($query) {
return $query->onlyTrashed();
})->paginate(30);
$title = trans('auth::users.titles.users-list').($trashed ? ' - '.trans('core::generals.trashed') : '');
$this->setTitle($title);
$this->addBreadcrumb($title);
return $this->view('admin.users.index', compact('trashed', 'users'));
} | php | public function index($trashed = false)
{
$this->authorize(UsersPolicy::PERMISSION_LIST);
$users = $this->user->with('roles')->protectAdmins()->when($trashed, function ($query) {
return $query->onlyTrashed();
})->paginate(30);
$title = trans('auth::users.titles.users-list').($trashed ? ' - '.trans('core::generals.trashed') : '');
$this->setTitle($title);
$this->addBreadcrumb($title);
return $this->view('admin.users.index', compact('trashed', 'users'));
} | [
"public",
"function",
"index",
"(",
"$",
"trashed",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_LIST",
")",
";",
"$",
"users",
"=",
"$",
"this",
"->",
"user",
"->",
"with",
"(",
"'roles'",
")",
"->",
"protectAdmins",
"(",
")",
"->",
"when",
"(",
"$",
"trashed",
",",
"function",
"(",
"$",
"query",
")",
"{",
"return",
"$",
"query",
"->",
"onlyTrashed",
"(",
")",
";",
"}",
")",
"->",
"paginate",
"(",
"30",
")",
";",
"$",
"title",
"=",
"trans",
"(",
"'auth::users.titles.users-list'",
")",
".",
"(",
"$",
"trashed",
"?",
"' - '",
".",
"trans",
"(",
"'core::generals.trashed'",
")",
":",
"''",
")",
";",
"$",
"this",
"->",
"setTitle",
"(",
"$",
"title",
")",
";",
"$",
"this",
"->",
"addBreadcrumb",
"(",
"$",
"title",
")",
";",
"return",
"$",
"this",
"->",
"view",
"(",
"'admin.users.index'",
",",
"compact",
"(",
"'trashed'",
",",
"'users'",
")",
")",
";",
"}"
] | List the users.
@param bool $trashed
@return \Illuminate\View\View | [
"List",
"the",
"users",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L71-L84 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.listByRole | public function listByRole(Role $role, $trashed = false)
{
$this->authorize(UsersPolicy::PERMISSION_LIST);
$users = $role->users()->with('roles')
->protectAdmins()
->paginate(30);
$title = trans('auth::users.titles.users-list')." - {$role->name} Role". ($trashed ? ' - '.trans('core::generals.trashed') : '');
$this->setTitle($title);
$this->addBreadcrumb($title);
return $this->view('admin.users.list', compact('trashed', 'users'));
} | php | public function listByRole(Role $role, $trashed = false)
{
$this->authorize(UsersPolicy::PERMISSION_LIST);
$users = $role->users()->with('roles')
->protectAdmins()
->paginate(30);
$title = trans('auth::users.titles.users-list')." - {$role->name} Role". ($trashed ? ' - '.trans('core::generals.trashed') : '');
$this->setTitle($title);
$this->addBreadcrumb($title);
return $this->view('admin.users.list', compact('trashed', 'users'));
} | [
"public",
"function",
"listByRole",
"(",
"Role",
"$",
"role",
",",
"$",
"trashed",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_LIST",
")",
";",
"$",
"users",
"=",
"$",
"role",
"->",
"users",
"(",
")",
"->",
"with",
"(",
"'roles'",
")",
"->",
"protectAdmins",
"(",
")",
"->",
"paginate",
"(",
"30",
")",
";",
"$",
"title",
"=",
"trans",
"(",
"'auth::users.titles.users-list'",
")",
".",
"\" - {$role->name} Role\"",
".",
"(",
"$",
"trashed",
"?",
"' - '",
".",
"trans",
"(",
"'core::generals.trashed'",
")",
":",
"''",
")",
";",
"$",
"this",
"->",
"setTitle",
"(",
"$",
"title",
")",
";",
"$",
"this",
"->",
"addBreadcrumb",
"(",
"$",
"title",
")",
";",
"return",
"$",
"this",
"->",
"view",
"(",
"'admin.users.list'",
",",
"compact",
"(",
"'trashed'",
",",
"'users'",
")",
")",
";",
"}"
] | List the users by a role.
@param \Arcanesoft\Contracts\Auth\Models\Role $role
@param bool $trashed
@return \Illuminate\View\View | [
"List",
"the",
"users",
"by",
"a",
"role",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L104-L117 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.create | public function create(Role $role)
{
$this->authorize(UsersPolicy::PERMISSION_CREATE);
$roles = $role->all();
$this->setTitle($title = trans('auth::users.titles.create-user'));
$this->addBreadcrumb($title);
return $this->view('admin.users.create', compact('roles'));
} | php | public function create(Role $role)
{
$this->authorize(UsersPolicy::PERMISSION_CREATE);
$roles = $role->all();
$this->setTitle($title = trans('auth::users.titles.create-user'));
$this->addBreadcrumb($title);
return $this->view('admin.users.create', compact('roles'));
} | [
"public",
"function",
"create",
"(",
"Role",
"$",
"role",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_CREATE",
")",
";",
"$",
"roles",
"=",
"$",
"role",
"->",
"all",
"(",
")",
";",
"$",
"this",
"->",
"setTitle",
"(",
"$",
"title",
"=",
"trans",
"(",
"'auth::users.titles.create-user'",
")",
")",
";",
"$",
"this",
"->",
"addBreadcrumb",
"(",
"$",
"title",
")",
";",
"return",
"$",
"this",
"->",
"view",
"(",
"'admin.users.create'",
",",
"compact",
"(",
"'roles'",
")",
")",
";",
"}"
] | Show the create a new user form.
@param \Arcanesoft\Contracts\Auth\Models\Role $role
@return \Illuminate\View\View | [
"Show",
"the",
"create",
"a",
"new",
"user",
"form",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L126-L136 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.store | public function store(CreateUserRequest $request, User $user)
{
$this->authorize(UsersPolicy::PERMISSION_CREATE);
$user->fill($request->getValidatedData());
$user->is_active = true;
$user->save();
$user->roles()->sync($request->get('roles'));
$this->transNotification('created', ['name' => $user->full_name], $user->toArray());
return redirect()->route('admin::auth.users.index');
} | php | public function store(CreateUserRequest $request, User $user)
{
$this->authorize(UsersPolicy::PERMISSION_CREATE);
$user->fill($request->getValidatedData());
$user->is_active = true;
$user->save();
$user->roles()->sync($request->get('roles'));
$this->transNotification('created', ['name' => $user->full_name], $user->toArray());
return redirect()->route('admin::auth.users.index');
} | [
"public",
"function",
"store",
"(",
"CreateUserRequest",
"$",
"request",
",",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_CREATE",
")",
";",
"$",
"user",
"->",
"fill",
"(",
"$",
"request",
"->",
"getValidatedData",
"(",
")",
")",
";",
"$",
"user",
"->",
"is_active",
"=",
"true",
";",
"$",
"user",
"->",
"save",
"(",
")",
";",
"$",
"user",
"->",
"roles",
"(",
")",
"->",
"sync",
"(",
"$",
"request",
"->",
"get",
"(",
"'roles'",
")",
")",
";",
"$",
"this",
"->",
"transNotification",
"(",
"'created'",
",",
"[",
"'name'",
"=>",
"$",
"user",
"->",
"full_name",
"]",
",",
"$",
"user",
"->",
"toArray",
"(",
")",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"route",
"(",
"'admin::auth.users.index'",
")",
";",
"}"
] | Store the new user.
@param \Arcanesoft\Auth\Http\Requests\Admin\Users\CreateUserRequest $request
@param \Arcanesoft\Contracts\Auth\Models\User $user
@return \Illuminate\Http\RedirectResponse | [
"Store",
"the",
"new",
"user",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L146-L158 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.show | public function show(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_SHOW);
$user->load(['roles', 'roles.permissions']);
$this->setTitle($title = trans('auth::users.titles.user-details'));
$this->addBreadcrumb($title);
return $this->view('admin.users.show', compact('user'));
} | php | public function show(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_SHOW);
$user->load(['roles', 'roles.permissions']);
$this->setTitle($title = trans('auth::users.titles.user-details'));
$this->addBreadcrumb($title);
return $this->view('admin.users.show', compact('user'));
} | [
"public",
"function",
"show",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_SHOW",
")",
";",
"$",
"user",
"->",
"load",
"(",
"[",
"'roles'",
",",
"'roles.permissions'",
"]",
")",
";",
"$",
"this",
"->",
"setTitle",
"(",
"$",
"title",
"=",
"trans",
"(",
"'auth::users.titles.user-details'",
")",
")",
";",
"$",
"this",
"->",
"addBreadcrumb",
"(",
"$",
"title",
")",
";",
"return",
"$",
"this",
"->",
"view",
"(",
"'admin.users.show'",
",",
"compact",
"(",
"'user'",
")",
")",
";",
"}"
] | Show the user's details.
@param \Arcanesoft\Contracts\Auth\Models\User $user
@return \Illuminate\View\View | [
"Show",
"the",
"user",
"s",
"details",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L167-L177 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.edit | public function edit(User $user, Role $role)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
$user->load(['roles', 'roles.permissions']);
$roles = $role->all();
$this->setTitle($title = trans('auth::users.titles.edit-user'));
$this->addBreadcrumb($title);
return $this->view('admin.users.edit', compact('user', 'roles'));
} | php | public function edit(User $user, Role $role)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
$user->load(['roles', 'roles.permissions']);
$roles = $role->all();
$this->setTitle($title = trans('auth::users.titles.edit-user'));
$this->addBreadcrumb($title);
return $this->view('admin.users.edit', compact('user', 'roles'));
} | [
"public",
"function",
"edit",
"(",
"User",
"$",
"user",
",",
"Role",
"$",
"role",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_UPDATE",
")",
";",
"$",
"user",
"->",
"load",
"(",
"[",
"'roles'",
",",
"'roles.permissions'",
"]",
")",
";",
"$",
"roles",
"=",
"$",
"role",
"->",
"all",
"(",
")",
";",
"$",
"this",
"->",
"setTitle",
"(",
"$",
"title",
"=",
"trans",
"(",
"'auth::users.titles.edit-user'",
")",
")",
";",
"$",
"this",
"->",
"addBreadcrumb",
"(",
"$",
"title",
")",
";",
"return",
"$",
"this",
"->",
"view",
"(",
"'admin.users.edit'",
",",
"compact",
"(",
"'user'",
",",
"'roles'",
")",
")",
";",
"}"
] | Show the edit the user form.
@param \Arcanesoft\Contracts\Auth\Models\User $user
@param \Arcanesoft\Contracts\Auth\Models\Role $role
@return \Illuminate\View\View | [
"Show",
"the",
"edit",
"the",
"user",
"form",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L187-L198 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.update | public function update(UpdateUserRequest $request, User $user)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
$user->update($request->getValidatedData());
$user->roles()->sync($request->get('roles'));
$this->transNotification('updated', ['name' => $user->full_name], $user->toArray());
return redirect()->route('admin::auth.users.show', [$user->hashed_id]);
} | php | public function update(UpdateUserRequest $request, User $user)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
$user->update($request->getValidatedData());
$user->roles()->sync($request->get('roles'));
$this->transNotification('updated', ['name' => $user->full_name], $user->toArray());
return redirect()->route('admin::auth.users.show', [$user->hashed_id]);
} | [
"public",
"function",
"update",
"(",
"UpdateUserRequest",
"$",
"request",
",",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_UPDATE",
")",
";",
"$",
"user",
"->",
"update",
"(",
"$",
"request",
"->",
"getValidatedData",
"(",
")",
")",
";",
"$",
"user",
"->",
"roles",
"(",
")",
"->",
"sync",
"(",
"$",
"request",
"->",
"get",
"(",
"'roles'",
")",
")",
";",
"$",
"this",
"->",
"transNotification",
"(",
"'updated'",
",",
"[",
"'name'",
"=>",
"$",
"user",
"->",
"full_name",
"]",
",",
"$",
"user",
"->",
"toArray",
"(",
")",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"route",
"(",
"'admin::auth.users.show'",
",",
"[",
"$",
"user",
"->",
"hashed_id",
"]",
")",
";",
"}"
] | Update the user.
@param \Arcanesoft\Auth\Http\Requests\Admin\Users\UpdateUserRequest $request
@param \Arcanesoft\Contracts\Auth\Models\User $user
@return \Illuminate\Http\RedirectResponse | [
"Update",
"the",
"user",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L208-L218 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.activate | public function activate(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
try {
($active = $user->isActive()) ? $user->deactivate() : $user->activate();
$message = $this->transNotification(
$active ? 'disabled' : 'enabled',
['name' => $user->full_name],
$user->toArray()
);
return $this->jsonResponseSuccess(compact('message'));
}
catch (\Exception $e) {
return $this->jsonResponseError(['message' => $e->getMessage()], 500);
}
} | php | public function activate(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
try {
($active = $user->isActive()) ? $user->deactivate() : $user->activate();
$message = $this->transNotification(
$active ? 'disabled' : 'enabled',
['name' => $user->full_name],
$user->toArray()
);
return $this->jsonResponseSuccess(compact('message'));
}
catch (\Exception $e) {
return $this->jsonResponseError(['message' => $e->getMessage()], 500);
}
} | [
"public",
"function",
"activate",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_UPDATE",
")",
";",
"try",
"{",
"(",
"$",
"active",
"=",
"$",
"user",
"->",
"isActive",
"(",
")",
")",
"?",
"$",
"user",
"->",
"deactivate",
"(",
")",
":",
"$",
"user",
"->",
"activate",
"(",
")",
";",
"$",
"message",
"=",
"$",
"this",
"->",
"transNotification",
"(",
"$",
"active",
"?",
"'disabled'",
":",
"'enabled'",
",",
"[",
"'name'",
"=>",
"$",
"user",
"->",
"full_name",
"]",
",",
"$",
"user",
"->",
"toArray",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"jsonResponseSuccess",
"(",
"compact",
"(",
"'message'",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"jsonResponseError",
"(",
"[",
"'message'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
",",
"500",
")",
";",
"}",
"}"
] | Activate/Disable a user.
@param \Arcanesoft\Contracts\Auth\Models\User $user
@return \Illuminate\Http\JsonResponse | [
"Activate",
"/",
"Disable",
"a",
"user",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L227-L245 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.restore | public function restore(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
try {
$user->restore();
$message = $this->transNotification('restored', ['name' => $user->full_name], $user->toArray());
return $this->jsonResponseSuccess(compact('message'));
}
catch (\Exception $e) {
return $this->jsonResponseError(['message' => $e->getMessage()], 500);
}
} | php | public function restore(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_UPDATE);
try {
$user->restore();
$message = $this->transNotification('restored', ['name' => $user->full_name], $user->toArray());
return $this->jsonResponseSuccess(compact('message'));
}
catch (\Exception $e) {
return $this->jsonResponseError(['message' => $e->getMessage()], 500);
}
} | [
"public",
"function",
"restore",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_UPDATE",
")",
";",
"try",
"{",
"$",
"user",
"->",
"restore",
"(",
")",
";",
"$",
"message",
"=",
"$",
"this",
"->",
"transNotification",
"(",
"'restored'",
",",
"[",
"'name'",
"=>",
"$",
"user",
"->",
"full_name",
"]",
",",
"$",
"user",
"->",
"toArray",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"jsonResponseSuccess",
"(",
"compact",
"(",
"'message'",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"jsonResponseError",
"(",
"[",
"'message'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
",",
"500",
")",
";",
"}",
"}"
] | Restore the trashed user.
@param \Arcanesoft\Contracts\Auth\Models\User $user
@return \Illuminate\Http\JsonResponse | [
"Restore",
"the",
"trashed",
"user",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L254-L268 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.delete | public function delete(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_DELETE);
try {
($trashed = $user->trashed()) ? $user->forceDelete() : $user->delete();
$message = $this->transNotification(
$trashed ? 'deleted' : 'trashed',
['name' => $user->full_name],
$user->toArray()
);
return $this->jsonResponseSuccess(compact('message'));
}
catch(\Exception $e) {
return $this->jsonResponseError(['message' => $e->getMessage()], 500);
}
} | php | public function delete(User $user)
{
$this->authorize(UsersPolicy::PERMISSION_DELETE);
try {
($trashed = $user->trashed()) ? $user->forceDelete() : $user->delete();
$message = $this->transNotification(
$trashed ? 'deleted' : 'trashed',
['name' => $user->full_name],
$user->toArray()
);
return $this->jsonResponseSuccess(compact('message'));
}
catch(\Exception $e) {
return $this->jsonResponseError(['message' => $e->getMessage()], 500);
}
} | [
"public",
"function",
"delete",
"(",
"User",
"$",
"user",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"UsersPolicy",
"::",
"PERMISSION_DELETE",
")",
";",
"try",
"{",
"(",
"$",
"trashed",
"=",
"$",
"user",
"->",
"trashed",
"(",
")",
")",
"?",
"$",
"user",
"->",
"forceDelete",
"(",
")",
":",
"$",
"user",
"->",
"delete",
"(",
")",
";",
"$",
"message",
"=",
"$",
"this",
"->",
"transNotification",
"(",
"$",
"trashed",
"?",
"'deleted'",
":",
"'trashed'",
",",
"[",
"'name'",
"=>",
"$",
"user",
"->",
"full_name",
"]",
",",
"$",
"user",
"->",
"toArray",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"jsonResponseSuccess",
"(",
"compact",
"(",
"'message'",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"jsonResponseError",
"(",
"[",
"'message'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
",",
"500",
")",
";",
"}",
"}"
] | Delete a user.
@param \Arcanesoft\Contracts\Auth\Models\User $user
@return \Illuminate\Http\JsonResponse | [
"Delete",
"a",
"user",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L277-L295 |
ARCANESOFT/Auth | src/Http/Controllers/Admin/UsersController.php | UsersController.impersonate | public function impersonate(User $user, Impersonator $impersonator)
{
/** @var \Arcanedev\LaravelImpersonator\Contracts\Impersonatable $user */
if ( ! $impersonator->start(auth()->user(), $user)) {
$this->notifyDanger(
trans('auth::users.messages.impersonation-failed.message'),
trans('auth::users.messages.impersonation-failed.title')
);
return redirect()->back();
}
return redirect()->to('/');
} | php | public function impersonate(User $user, Impersonator $impersonator)
{
/** @var \Arcanedev\LaravelImpersonator\Contracts\Impersonatable $user */
if ( ! $impersonator->start(auth()->user(), $user)) {
$this->notifyDanger(
trans('auth::users.messages.impersonation-failed.message'),
trans('auth::users.messages.impersonation-failed.title')
);
return redirect()->back();
}
return redirect()->to('/');
} | [
"public",
"function",
"impersonate",
"(",
"User",
"$",
"user",
",",
"Impersonator",
"$",
"impersonator",
")",
"{",
"/** @var \\Arcanedev\\LaravelImpersonator\\Contracts\\Impersonatable $user */",
"if",
"(",
"!",
"$",
"impersonator",
"->",
"start",
"(",
"auth",
"(",
")",
"->",
"user",
"(",
")",
",",
"$",
"user",
")",
")",
"{",
"$",
"this",
"->",
"notifyDanger",
"(",
"trans",
"(",
"'auth::users.messages.impersonation-failed.message'",
")",
",",
"trans",
"(",
"'auth::users.messages.impersonation-failed.title'",
")",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"}",
"return",
"redirect",
"(",
")",
"->",
"to",
"(",
"'/'",
")",
";",
"}"
] | Impersonate a user.
@param \Arcanesoft\Contracts\Auth\Models\User $user
@param \Arcanedev\LaravelImpersonator\Contracts\Impersonator $impersonator
@return \Illuminate\Http\RedirectResponse | [
"Impersonate",
"a",
"user",
"."
] | train | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Controllers/Admin/UsersController.php#L305-L318 |
native5/native5-sdk-client-php | src/Native5/Route/Router.php | Router.route | public function route()
{
global $app;
$controllerName = $this->_command->getControllerName();
if (!$this->routeExists($controllerName)) {
$controllerName = 'error';
}
include 'controllers/'.$controllerName.'.php';
// Only log analytics data for non-login pages here
if (strcasecmp($controllerName, 'login') !== 0) {
if($app->getConfiguration()->logAnalytics() == true) {
$analyticsData = array();
$analyticsData['time'] = time();
$analyticsData['session'] = session_id();
$analyticsData['page'] = $controllerName;
$GLOBALS['routeLogger']->info(json_encode($analyticsData));
}
}
$controllerClass = $controllerName.'Controller';
$controller = new $controllerClass($this->_command);
//$controller->addPreProcessor();
try {
$params = $controller->getParams();
$request = new HttpRequest($params);
$request->parse();
$controller->execute($request);
} catch(MissingParamsException $mpe) {
$response = new HttpResponse();
$response->addHeader('HTTP/1.1 400 Bad Request');
$response->send();
} catch(ServiceException $sxe) {
$response = new HttpResponse();
$response->sendError($sxe->getMessage());
} catch(ClientException $cxe) {
$response = new HttpResponse();
$response->sendError($cxe->getMessage(), $cxe->getCode());
}
} | php | public function route()
{
global $app;
$controllerName = $this->_command->getControllerName();
if (!$this->routeExists($controllerName)) {
$controllerName = 'error';
}
include 'controllers/'.$controllerName.'.php';
// Only log analytics data for non-login pages here
if (strcasecmp($controllerName, 'login') !== 0) {
if($app->getConfiguration()->logAnalytics() == true) {
$analyticsData = array();
$analyticsData['time'] = time();
$analyticsData['session'] = session_id();
$analyticsData['page'] = $controllerName;
$GLOBALS['routeLogger']->info(json_encode($analyticsData));
}
}
$controllerClass = $controllerName.'Controller';
$controller = new $controllerClass($this->_command);
//$controller->addPreProcessor();
try {
$params = $controller->getParams();
$request = new HttpRequest($params);
$request->parse();
$controller->execute($request);
} catch(MissingParamsException $mpe) {
$response = new HttpResponse();
$response->addHeader('HTTP/1.1 400 Bad Request');
$response->send();
} catch(ServiceException $sxe) {
$response = new HttpResponse();
$response->sendError($sxe->getMessage());
} catch(ClientException $cxe) {
$response = new HttpResponse();
$response->sendError($cxe->getMessage(), $cxe->getCode());
}
} | [
"public",
"function",
"route",
"(",
")",
"{",
"global",
"$",
"app",
";",
"$",
"controllerName",
"=",
"$",
"this",
"->",
"_command",
"->",
"getControllerName",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"routeExists",
"(",
"$",
"controllerName",
")",
")",
"{",
"$",
"controllerName",
"=",
"'error'",
";",
"}",
"include",
"'controllers/'",
".",
"$",
"controllerName",
".",
"'.php'",
";",
"// Only log analytics data for non-login pages here",
"if",
"(",
"strcasecmp",
"(",
"$",
"controllerName",
",",
"'login'",
")",
"!==",
"0",
")",
"{",
"if",
"(",
"$",
"app",
"->",
"getConfiguration",
"(",
")",
"->",
"logAnalytics",
"(",
")",
"==",
"true",
")",
"{",
"$",
"analyticsData",
"=",
"array",
"(",
")",
";",
"$",
"analyticsData",
"[",
"'time'",
"]",
"=",
"time",
"(",
")",
";",
"$",
"analyticsData",
"[",
"'session'",
"]",
"=",
"session_id",
"(",
")",
";",
"$",
"analyticsData",
"[",
"'page'",
"]",
"=",
"$",
"controllerName",
";",
"$",
"GLOBALS",
"[",
"'routeLogger'",
"]",
"->",
"info",
"(",
"json_encode",
"(",
"$",
"analyticsData",
")",
")",
";",
"}",
"}",
"$",
"controllerClass",
"=",
"$",
"controllerName",
".",
"'Controller'",
";",
"$",
"controller",
"=",
"new",
"$",
"controllerClass",
"(",
"$",
"this",
"->",
"_command",
")",
";",
"//$controller->addPreProcessor();",
"try",
"{",
"$",
"params",
"=",
"$",
"controller",
"->",
"getParams",
"(",
")",
";",
"$",
"request",
"=",
"new",
"HttpRequest",
"(",
"$",
"params",
")",
";",
"$",
"request",
"->",
"parse",
"(",
")",
";",
"$",
"controller",
"->",
"execute",
"(",
"$",
"request",
")",
";",
"}",
"catch",
"(",
"MissingParamsException",
"$",
"mpe",
")",
"{",
"$",
"response",
"=",
"new",
"HttpResponse",
"(",
")",
";",
"$",
"response",
"->",
"addHeader",
"(",
"'HTTP/1.1 400 Bad Request'",
")",
";",
"$",
"response",
"->",
"send",
"(",
")",
";",
"}",
"catch",
"(",
"ServiceException",
"$",
"sxe",
")",
"{",
"$",
"response",
"=",
"new",
"HttpResponse",
"(",
")",
";",
"$",
"response",
"->",
"sendError",
"(",
"$",
"sxe",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ClientException",
"$",
"cxe",
")",
"{",
"$",
"response",
"=",
"new",
"HttpResponse",
"(",
")",
";",
"$",
"response",
"->",
"sendError",
"(",
"$",
"cxe",
"->",
"getMessage",
"(",
")",
",",
"$",
"cxe",
"->",
"getCode",
"(",
")",
")",
";",
"}",
"}"
] | route
@access public
@return void | [
"route"
] | train | https://github.com/native5/native5-sdk-client-php/blob/e1f598cf27654d81bb5facace1990b737242a2f9/src/Native5/Route/Router.php#L81-L122 |
OxfordInfoLabs/kinikit-core | src/Util/StringUtils.php | StringUtils.matchesWildcardPattern | public static function matchesWildcardPattern($predicateString, $pattern) {
// Only do a fuzzy match if at least a single * character found.
if (is_numeric(strpos($pattern, "*"))) {
$pattern = str_replace("\\*", "(.*)", preg_quote($pattern, "/"));
$regex = "/" . $pattern . "/";
return preg_match($regex, $predicateString) > 0;
} else {
return $predicateString == $pattern;
}
} | php | public static function matchesWildcardPattern($predicateString, $pattern) {
// Only do a fuzzy match if at least a single * character found.
if (is_numeric(strpos($pattern, "*"))) {
$pattern = str_replace("\\*", "(.*)", preg_quote($pattern, "/"));
$regex = "/" . $pattern . "/";
return preg_match($regex, $predicateString) > 0;
} else {
return $predicateString == $pattern;
}
} | [
"public",
"static",
"function",
"matchesWildcardPattern",
"(",
"$",
"predicateString",
",",
"$",
"pattern",
")",
"{",
"// Only do a fuzzy match if at least a single * character found.",
"if",
"(",
"is_numeric",
"(",
"strpos",
"(",
"$",
"pattern",
",",
"\"*\"",
")",
")",
")",
"{",
"$",
"pattern",
"=",
"str_replace",
"(",
"\"\\\\*\"",
",",
"\"(.*)\"",
",",
"preg_quote",
"(",
"$",
"pattern",
",",
"\"/\"",
")",
")",
";",
"$",
"regex",
"=",
"\"/\"",
".",
"$",
"pattern",
".",
"\"/\"",
";",
"return",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"predicateString",
")",
">",
"0",
";",
"}",
"else",
"{",
"return",
"$",
"predicateString",
"==",
"$",
"pattern",
";",
"}",
"}"
] | Return a boolean indicating whether the passed string matches the supplied pattern
which may contain * wildcards
@param string $predicateString
@param string $pattern | [
"Return",
"a",
"boolean",
"indicating",
"whether",
"the",
"passed",
"string",
"matches",
"the",
"supplied",
"pattern",
"which",
"may",
"contain",
"*",
"wildcards"
] | train | https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/StringUtils.php#L20-L32 |
OxfordInfoLabs/kinikit-core | src/Util/StringUtils.php | StringUtils.generateRandomString | public static function generateRandomString($numberOfChars, $includeCaps = true, $includeNumbers = true, $includeSymbols = false) {
$possibleChars = range(97, 122);
// If include caps, add in capital letters
if ($includeCaps) $possibleChars = array_merge($possibleChars, range(65, 90));
if ($includeNumbers) $possibleChars = array_merge($possibleChars, range(48, 57));
if ($includeSymbols) $possibleChars = array_merge($possibleChars, array(33, 64, 35, 43, 61, 42, 63));
$string = "";
for ($i = 0; $i < $numberOfChars; $i++) {
$string .= chr($possibleChars[rand(0, sizeof($possibleChars) - 1)]);
}
return $string;
} | php | public static function generateRandomString($numberOfChars, $includeCaps = true, $includeNumbers = true, $includeSymbols = false) {
$possibleChars = range(97, 122);
// If include caps, add in capital letters
if ($includeCaps) $possibleChars = array_merge($possibleChars, range(65, 90));
if ($includeNumbers) $possibleChars = array_merge($possibleChars, range(48, 57));
if ($includeSymbols) $possibleChars = array_merge($possibleChars, array(33, 64, 35, 43, 61, 42, 63));
$string = "";
for ($i = 0; $i < $numberOfChars; $i++) {
$string .= chr($possibleChars[rand(0, sizeof($possibleChars) - 1)]);
}
return $string;
} | [
"public",
"static",
"function",
"generateRandomString",
"(",
"$",
"numberOfChars",
",",
"$",
"includeCaps",
"=",
"true",
",",
"$",
"includeNumbers",
"=",
"true",
",",
"$",
"includeSymbols",
"=",
"false",
")",
"{",
"$",
"possibleChars",
"=",
"range",
"(",
"97",
",",
"122",
")",
";",
"// If include caps, add in capital letters",
"if",
"(",
"$",
"includeCaps",
")",
"$",
"possibleChars",
"=",
"array_merge",
"(",
"$",
"possibleChars",
",",
"range",
"(",
"65",
",",
"90",
")",
")",
";",
"if",
"(",
"$",
"includeNumbers",
")",
"$",
"possibleChars",
"=",
"array_merge",
"(",
"$",
"possibleChars",
",",
"range",
"(",
"48",
",",
"57",
")",
")",
";",
"if",
"(",
"$",
"includeSymbols",
")",
"$",
"possibleChars",
"=",
"array_merge",
"(",
"$",
"possibleChars",
",",
"array",
"(",
"33",
",",
"64",
",",
"35",
",",
"43",
",",
"61",
",",
"42",
",",
"63",
")",
")",
";",
"$",
"string",
"=",
"\"\"",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"numberOfChars",
";",
"$",
"i",
"++",
")",
"{",
"$",
"string",
".=",
"chr",
"(",
"$",
"possibleChars",
"[",
"rand",
"(",
"0",
",",
"sizeof",
"(",
"$",
"possibleChars",
")",
"-",
"1",
")",
"]",
")",
";",
"}",
"return",
"$",
"string",
";",
"}"
] | Generate a random string of the given length (for e.g. passwords etc).
Optional flags allow for capital letters, numbers and symbols
@param $numberOfChars
@param bool $includeSymbols | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"given",
"length",
"(",
"for",
"e",
".",
"g",
".",
"passwords",
"etc",
")",
".",
"Optional",
"flags",
"allow",
"for",
"capital",
"letters",
"numbers",
"and",
"symbols"
] | train | https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/StringUtils.php#L42-L59 |
CaliCastle/socialite | src/Two/AbstractProvider.php | AbstractProvider.redirect | public function redirect()
{
$state = null;
if ($this->usesState()) {
$this->request->getSession()->set('state', $state = Str::random(40));
}
return new RedirectResponse($this->getAuthUrl($state));
} | php | public function redirect()
{
$state = null;
if ($this->usesState()) {
$this->request->getSession()->set('state', $state = Str::random(40));
}
return new RedirectResponse($this->getAuthUrl($state));
} | [
"public",
"function",
"redirect",
"(",
")",
"{",
"$",
"state",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"usesState",
"(",
")",
")",
"{",
"$",
"this",
"->",
"request",
"->",
"getSession",
"(",
")",
"->",
"set",
"(",
"'state'",
",",
"$",
"state",
"=",
"Str",
"::",
"random",
"(",
"40",
")",
")",
";",
"}",
"return",
"new",
"RedirectResponse",
"(",
"$",
"this",
"->",
"getAuthUrl",
"(",
"$",
"state",
")",
")",
";",
"}"
] | Redirect the user of the application to the provider's authentication screen.
@return \Symfony\Component\HttpFoundation\RedirectResponse | [
"Redirect",
"the",
"user",
"of",
"the",
"application",
"to",
"the",
"provider",
"s",
"authentication",
"screen",
"."
] | train | https://github.com/CaliCastle/socialite/blob/68acdf290c7e3afbc3db08b3a197230a3f6b0370/src/Two/AbstractProvider.php#L129-L138 |
CaliCastle/socialite | src/Two/AbstractProvider.php | AbstractProvider.user | public function user()
{
if ($this->hasInvalidState()) {
throw new InvalidStateException;
}
$user = $this->mapUserToObject($this->getUserByToken(
$token = $this->getAccessToken($this->getCode())
));
return $user->setToken($token);
} | php | public function user()
{
if ($this->hasInvalidState()) {
throw new InvalidStateException;
}
$user = $this->mapUserToObject($this->getUserByToken(
$token = $this->getAccessToken($this->getCode())
));
return $user->setToken($token);
} | [
"public",
"function",
"user",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasInvalidState",
"(",
")",
")",
"{",
"throw",
"new",
"InvalidStateException",
";",
"}",
"$",
"user",
"=",
"$",
"this",
"->",
"mapUserToObject",
"(",
"$",
"this",
"->",
"getUserByToken",
"(",
"$",
"token",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
"$",
"this",
"->",
"getCode",
"(",
")",
")",
")",
")",
";",
"return",
"$",
"user",
"->",
"setToken",
"(",
"$",
"token",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/CaliCastle/socialite/blob/68acdf290c7e3afbc3db08b3a197230a3f6b0370/src/Two/AbstractProvider.php#L188-L199 |
CaliCastle/socialite | src/Two/AbstractProvider.php | AbstractProvider.hasInvalidState | protected function hasInvalidState()
{
if ($this->isStateless()) {
return false;
}
$state = $this->request->getSession()->pull('state');
return !(strlen($state) > 0 && $this->request->input('state') === $state);
} | php | protected function hasInvalidState()
{
if ($this->isStateless()) {
return false;
}
$state = $this->request->getSession()->pull('state');
return !(strlen($state) > 0 && $this->request->input('state') === $state);
} | [
"protected",
"function",
"hasInvalidState",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isStateless",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"state",
"=",
"$",
"this",
"->",
"request",
"->",
"getSession",
"(",
")",
"->",
"pull",
"(",
"'state'",
")",
";",
"return",
"!",
"(",
"strlen",
"(",
"$",
"state",
")",
">",
"0",
"&&",
"$",
"this",
"->",
"request",
"->",
"input",
"(",
"'state'",
")",
"===",
"$",
"state",
")",
";",
"}"
] | Determine if the current request / session has a mismatching "state".
@return bool | [
"Determine",
"if",
"the",
"current",
"request",
"/",
"session",
"has",
"a",
"mismatching",
"state",
"."
] | train | https://github.com/CaliCastle/socialite/blob/68acdf290c7e3afbc3db08b3a197230a3f6b0370/src/Two/AbstractProvider.php#L219-L228 |
squareproton/Bond | src/Bond/Pg/Catalog.php | Catalog.getEnum | private function getEnum()
{
$enumResult = $this->db->query(
new Raw( <<<SQL
SELECT
t.typname as name,
n.nspname as schema,
array_agg( e.enumlabel ORDER BY e.enumsortorder ) as labels
FROM
pg_enum e
INNER JOIN
pg_type t ON e.enumtypid = t.oid
INNER JOIN
pg_namespace n ON t.typnamespace = n.oid
WHERE
n.nspname = ANY( current_schemas(false) )
GROUP BY
t.typname, t.oid, n.nspname
ORDER BY
schema, t.typname ASC
SQL
)
);
$output = [];
foreach( $enumResult->fetch(Result::FLATTEN_PREVENT | Result::TYPE_DETECT) as $data ) {
$output[$data['name']] = $data['labels'];
}
return new Enum($output);
} | php | private function getEnum()
{
$enumResult = $this->db->query(
new Raw( <<<SQL
SELECT
t.typname as name,
n.nspname as schema,
array_agg( e.enumlabel ORDER BY e.enumsortorder ) as labels
FROM
pg_enum e
INNER JOIN
pg_type t ON e.enumtypid = t.oid
INNER JOIN
pg_namespace n ON t.typnamespace = n.oid
WHERE
n.nspname = ANY( current_schemas(false) )
GROUP BY
t.typname, t.oid, n.nspname
ORDER BY
schema, t.typname ASC
SQL
)
);
$output = [];
foreach( $enumResult->fetch(Result::FLATTEN_PREVENT | Result::TYPE_DETECT) as $data ) {
$output[$data['name']] = $data['labels'];
}
return new Enum($output);
} | [
"private",
"function",
"getEnum",
"(",
")",
"{",
"$",
"enumResult",
"=",
"$",
"this",
"->",
"db",
"->",
"query",
"(",
"new",
"Raw",
"(",
" <<<SQL\n SELECT\n t.typname as name,\n n.nspname as schema,\n array_agg( e.enumlabel ORDER BY e.enumsortorder ) as labels\n FROM\n pg_enum e\n INNER JOIN\n pg_type t ON e.enumtypid = t.oid\n INNER JOIN\n pg_namespace n ON t.typnamespace = n.oid\n WHERE\n n.nspname = ANY( current_schemas(false) )\n GROUP BY\n t.typname, t.oid, n.nspname\n ORDER BY\n schema, t.typname ASC\nSQL",
")",
")",
";",
"$",
"output",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"enumResult",
"->",
"fetch",
"(",
"Result",
"::",
"FLATTEN_PREVENT",
"|",
"Result",
"::",
"TYPE_DETECT",
")",
"as",
"$",
"data",
")",
"{",
"$",
"output",
"[",
"$",
"data",
"[",
"'name'",
"]",
"]",
"=",
"$",
"data",
"[",
"'labels'",
"]",
";",
"}",
"return",
"new",
"Enum",
"(",
"$",
"output",
")",
";",
"}"
] | Get array of enum's and their values from the database
@param Bond\Pg
@return array | [
"Get",
"array",
"of",
"enum",
"s",
"and",
"their",
"values",
"from",
"the",
"database"
] | train | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/Catalog.php#L75-L107 |
squareproton/Bond | src/Bond/Pg/Catalog.php | Catalog.loadReferences | private function loadReferences()
{
// References defined in pg_catalog
$sql = new Raw('SELECT * FROM dev."vAttributeReferences" WHERE "isInherited" = false');
$sql = new Raw( <<<SQL
-- Based on. http://code.google.com/p/pgutils/ but very heavily modified
-- Potentially inheritance aware/compensating. Be careful. Use the unit tests.
WITH "vRelationDescendants" as (
SELECT
c.oid,
c.relname,
(
WITH RECURSIVE
q( oid ) AS
(
SELECT
crd.oid
FROM
pg_class crd
WHERE
crd.oid = c.oid
UNION ALL
SELECT i.inhrelid FROM q INNER JOIN pg_inherits i ON q.oid = i.inhparent
)
SELECT oid FROM q WHERE oid = c.oid
) as childoid
FROM
pg_class c
INNER JOIN
pg_namespace n ON n.oid = c.relnamespace
ORDER BY
n.nspname, c.relname
), "vAttributeReferences" as (
SELECT
fkr.oid <> fkrd.oid AS "isInheritedSource",
pkr.oid <> pkrd.oid AS "isInheritedTarget",
( fkr.oid <> fkrd.oid OR pkr.oid <> pkrd.oid ) as "isInherited",
fkn.nspname AS fk_namespace,
fkr.relname AS fk_relation,
fkr.oid AS fk_oid,
fka.attname AS fk_column,
fka.attnum as "fk_attnum",
-- initByData
fkr.oid::text || '.' || fka.attnum::text AS fk_key,
(
EXISTS (
SELECT
pg_index.indexrelid,
pg_index.indrelid,
pg_index.indkey,
pg_index.indclass,
pg_index.indnatts,
pg_index.indisunique,
pg_index.indisprimary,
pg_index.indisclustered,
pg_index.indexprs,
pg_index.indpred
FROM
pg_index
WHERE
pg_index.indrelid = fkr.oid AND pg_index.indkey[0] = fka.attnum
)
) AS fk_indexed,
pkn.nspname AS pk_namespace,
pkr.relname AS pk_relation,
pkr.oid AS pk_oid,
pka.attname AS pk_column,
pka.attnum as "pk_attnum",
-- initByData
pkr.oid::text || '.' || pka.attnum::text AS pk_key,
(
EXISTS (
SELECT
pg_index.indexrelid,
pg_index.indrelid,
pg_index.indkey,
pg_index.indclass,
pg_index.indnatts,
pg_index.indisunique,
pg_index.indisprimary,
pg_index.indisclustered,
pg_index.indexprs,
pg_index.indpred
FROM
pg_index
WHERE
pg_index.indrelid = pkr.oid AND
pg_index.indkey[0] = pka.attnum
)
) AS pk_indexed,
c.confupdtype::text || c.confdeltype::text AS ud,
cn.nspname AS c_namespace,
c.conname AS c_name
FROM (
(
(
(
(
(
(
pg_constraint c
JOIN
pg_namespace cn ON cn.oid = c.connamespace
)
INNER JOIN
"vRelationDescendants" as fkrd ON c.conrelid = fkrd.oid
INNER JOIN
pg_class fkr ON fkr.oid = fkrd.childoid
)
JOIN
pg_namespace fkn ON fkn.oid = fkr.relnamespace
)
JOIN
pg_attribute fka ON fka.attrelid = c.conrelid AND fka.attnum = ANY (c.conkey)
)
INNER JOIN
"vRelationDescendants" as pkrd ON c.confrelid = pkrd.oid
INNER JOIN
pg_class pkr ON pkr.oid = pkrd.childoid
)
JOIN
pg_namespace pkn ON pkn.oid = pkr.relnamespace
)
JOIN
pg_attribute pka ON pka.attrelid = c.confrelid AND pka.attnum = ANY (c.confkey)
)
WHERE
c.contype = 'f'::"char" AND
fkn.nspname = ANY( current_schemas(false) ) AND
pkn.nspname = ANY( current_schemas(false) )
)
SELECT * FROM "vAttributeReferences" WHERE "isInherited" = false
SQL
);
$relationships = $this->db->query($sql);
foreach( $relationships as $relationship ) {
$fk = $this->pgAttributes->findOneByKey($relationship['fk_key']);
$pk = $this->pgAttributes->findOneByKey($relationship['pk_key']);
if( !$fk or !$pk ) {
d_pr( $relationship );
die();
}
$fk->addReference($pk);
}
// look for normality defined relationships
$profiler = new Profiler( __FUNCTION__ );
$profiler->log();
foreach( $this->pgClasses as $relation ) {
$tags = $relation->getTags();
if( isset( $tags['references'] ) ) {
foreach( $tags['references'] as $reference ) {
$reference = array_map( 'trim', explode( '=', $reference) );
$reference[1] = explode( '.', $reference[1] );
$fk = $relation->getAttributeByName($reference[0]);
// referencing
$pkTable = $this->pgClasses->findOneByName($reference[1][0]);
$pk = $pkTable->getAttributeByName($reference[1][1]);
$fk->addReference($pk);
}
}
}
// echo $profiler->log()->output();
} | php | private function loadReferences()
{
// References defined in pg_catalog
$sql = new Raw('SELECT * FROM dev."vAttributeReferences" WHERE "isInherited" = false');
$sql = new Raw( <<<SQL
-- Based on. http://code.google.com/p/pgutils/ but very heavily modified
-- Potentially inheritance aware/compensating. Be careful. Use the unit tests.
WITH "vRelationDescendants" as (
SELECT
c.oid,
c.relname,
(
WITH RECURSIVE
q( oid ) AS
(
SELECT
crd.oid
FROM
pg_class crd
WHERE
crd.oid = c.oid
UNION ALL
SELECT i.inhrelid FROM q INNER JOIN pg_inherits i ON q.oid = i.inhparent
)
SELECT oid FROM q WHERE oid = c.oid
) as childoid
FROM
pg_class c
INNER JOIN
pg_namespace n ON n.oid = c.relnamespace
ORDER BY
n.nspname, c.relname
), "vAttributeReferences" as (
SELECT
fkr.oid <> fkrd.oid AS "isInheritedSource",
pkr.oid <> pkrd.oid AS "isInheritedTarget",
( fkr.oid <> fkrd.oid OR pkr.oid <> pkrd.oid ) as "isInherited",
fkn.nspname AS fk_namespace,
fkr.relname AS fk_relation,
fkr.oid AS fk_oid,
fka.attname AS fk_column,
fka.attnum as "fk_attnum",
-- initByData
fkr.oid::text || '.' || fka.attnum::text AS fk_key,
(
EXISTS (
SELECT
pg_index.indexrelid,
pg_index.indrelid,
pg_index.indkey,
pg_index.indclass,
pg_index.indnatts,
pg_index.indisunique,
pg_index.indisprimary,
pg_index.indisclustered,
pg_index.indexprs,
pg_index.indpred
FROM
pg_index
WHERE
pg_index.indrelid = fkr.oid AND pg_index.indkey[0] = fka.attnum
)
) AS fk_indexed,
pkn.nspname AS pk_namespace,
pkr.relname AS pk_relation,
pkr.oid AS pk_oid,
pka.attname AS pk_column,
pka.attnum as "pk_attnum",
-- initByData
pkr.oid::text || '.' || pka.attnum::text AS pk_key,
(
EXISTS (
SELECT
pg_index.indexrelid,
pg_index.indrelid,
pg_index.indkey,
pg_index.indclass,
pg_index.indnatts,
pg_index.indisunique,
pg_index.indisprimary,
pg_index.indisclustered,
pg_index.indexprs,
pg_index.indpred
FROM
pg_index
WHERE
pg_index.indrelid = pkr.oid AND
pg_index.indkey[0] = pka.attnum
)
) AS pk_indexed,
c.confupdtype::text || c.confdeltype::text AS ud,
cn.nspname AS c_namespace,
c.conname AS c_name
FROM (
(
(
(
(
(
(
pg_constraint c
JOIN
pg_namespace cn ON cn.oid = c.connamespace
)
INNER JOIN
"vRelationDescendants" as fkrd ON c.conrelid = fkrd.oid
INNER JOIN
pg_class fkr ON fkr.oid = fkrd.childoid
)
JOIN
pg_namespace fkn ON fkn.oid = fkr.relnamespace
)
JOIN
pg_attribute fka ON fka.attrelid = c.conrelid AND fka.attnum = ANY (c.conkey)
)
INNER JOIN
"vRelationDescendants" as pkrd ON c.confrelid = pkrd.oid
INNER JOIN
pg_class pkr ON pkr.oid = pkrd.childoid
)
JOIN
pg_namespace pkn ON pkn.oid = pkr.relnamespace
)
JOIN
pg_attribute pka ON pka.attrelid = c.confrelid AND pka.attnum = ANY (c.confkey)
)
WHERE
c.contype = 'f'::"char" AND
fkn.nspname = ANY( current_schemas(false) ) AND
pkn.nspname = ANY( current_schemas(false) )
)
SELECT * FROM "vAttributeReferences" WHERE "isInherited" = false
SQL
);
$relationships = $this->db->query($sql);
foreach( $relationships as $relationship ) {
$fk = $this->pgAttributes->findOneByKey($relationship['fk_key']);
$pk = $this->pgAttributes->findOneByKey($relationship['pk_key']);
if( !$fk or !$pk ) {
d_pr( $relationship );
die();
}
$fk->addReference($pk);
}
// look for normality defined relationships
$profiler = new Profiler( __FUNCTION__ );
$profiler->log();
foreach( $this->pgClasses as $relation ) {
$tags = $relation->getTags();
if( isset( $tags['references'] ) ) {
foreach( $tags['references'] as $reference ) {
$reference = array_map( 'trim', explode( '=', $reference) );
$reference[1] = explode( '.', $reference[1] );
$fk = $relation->getAttributeByName($reference[0]);
// referencing
$pkTable = $this->pgClasses->findOneByName($reference[1][0]);
$pk = $pkTable->getAttributeByName($reference[1][1]);
$fk->addReference($pk);
}
}
}
// echo $profiler->log()->output();
} | [
"private",
"function",
"loadReferences",
"(",
")",
"{",
"// References defined in pg_catalog",
"$",
"sql",
"=",
"new",
"Raw",
"(",
"'SELECT * FROM dev.\"vAttributeReferences\" WHERE \"isInherited\" = false'",
")",
";",
"$",
"sql",
"=",
"new",
"Raw",
"(",
" <<<SQL\n-- Based on. http://code.google.com/p/pgutils/ but very heavily modified\n-- Potentially inheritance aware/compensating. Be careful. Use the unit tests.\nWITH \"vRelationDescendants\" as (\n SELECT\n c.oid,\n c.relname,\n (\n WITH RECURSIVE\n q( oid ) AS\n (\n SELECT\n crd.oid\n FROM\n pg_class crd\n WHERE\n crd.oid = c.oid\n\n UNION ALL\n\n SELECT i.inhrelid FROM q INNER JOIN pg_inherits i ON q.oid = i.inhparent\n )\n SELECT oid FROM q WHERE oid = c.oid\n ) as childoid\n FROM\n pg_class c\n INNER JOIN\n pg_namespace n ON n.oid = c.relnamespace\n ORDER BY\n n.nspname, c.relname\n), \"vAttributeReferences\" as (\n SELECT\n fkr.oid <> fkrd.oid AS \"isInheritedSource\",\n pkr.oid <> pkrd.oid AS \"isInheritedTarget\",\n ( fkr.oid <> fkrd.oid OR pkr.oid <> pkrd.oid ) as \"isInherited\",\n\n fkn.nspname AS fk_namespace,\n fkr.relname AS fk_relation,\n fkr.oid AS fk_oid,\n fka.attname AS fk_column,\n fka.attnum as \"fk_attnum\",\n\n -- initByData\n fkr.oid::text || '.' || fka.attnum::text AS fk_key,\n\n (\n EXISTS (\n SELECT\n pg_index.indexrelid,\n pg_index.indrelid,\n pg_index.indkey,\n pg_index.indclass,\n pg_index.indnatts,\n pg_index.indisunique,\n pg_index.indisprimary,\n pg_index.indisclustered,\n pg_index.indexprs,\n pg_index.indpred\n FROM\n pg_index\n WHERE\n pg_index.indrelid = fkr.oid AND pg_index.indkey[0] = fka.attnum\n )\n ) AS fk_indexed,\n pkn.nspname AS pk_namespace,\n pkr.relname AS pk_relation,\n pkr.oid AS pk_oid,\n pka.attname AS pk_column,\n pka.attnum as \"pk_attnum\",\n\n -- initByData\n pkr.oid::text || '.' || pka.attnum::text AS pk_key,\n\n (\n EXISTS (\n SELECT\n pg_index.indexrelid,\n pg_index.indrelid,\n pg_index.indkey,\n pg_index.indclass,\n pg_index.indnatts,\n pg_index.indisunique,\n pg_index.indisprimary,\n pg_index.indisclustered,\n pg_index.indexprs,\n pg_index.indpred\n FROM\n pg_index\n WHERE\n pg_index.indrelid = pkr.oid AND\n pg_index.indkey[0] = pka.attnum\n )\n ) AS pk_indexed,\n c.confupdtype::text || c.confdeltype::text AS ud,\n cn.nspname AS c_namespace,\n c.conname AS c_name\n FROM (\n (\n (\n (\n (\n (\n (\n pg_constraint c\n JOIN\n pg_namespace cn ON cn.oid = c.connamespace\n )\n INNER JOIN\n \"vRelationDescendants\" as fkrd ON c.conrelid = fkrd.oid\n INNER JOIN\n pg_class fkr ON fkr.oid = fkrd.childoid\n )\n JOIN\n pg_namespace fkn ON fkn.oid = fkr.relnamespace\n )\n JOIN\n pg_attribute fka ON fka.attrelid = c.conrelid AND fka.attnum = ANY (c.conkey)\n )\n INNER JOIN\n \"vRelationDescendants\" as pkrd ON c.confrelid = pkrd.oid\n INNER JOIN\n pg_class pkr ON pkr.oid = pkrd.childoid\n )\n JOIN\n pg_namespace pkn ON pkn.oid = pkr.relnamespace\n )\n JOIN\n pg_attribute pka ON pka.attrelid = c.confrelid AND pka.attnum = ANY (c.confkey)\n )\n WHERE\n c.contype = 'f'::\"char\" AND\n fkn.nspname = ANY( current_schemas(false) ) AND\n pkn.nspname = ANY( current_schemas(false) )\n)\nSELECT * FROM \"vAttributeReferences\" WHERE \"isInherited\" = false\nSQL",
")",
";",
"$",
"relationships",
"=",
"$",
"this",
"->",
"db",
"->",
"query",
"(",
"$",
"sql",
")",
";",
"foreach",
"(",
"$",
"relationships",
"as",
"$",
"relationship",
")",
"{",
"$",
"fk",
"=",
"$",
"this",
"->",
"pgAttributes",
"->",
"findOneByKey",
"(",
"$",
"relationship",
"[",
"'fk_key'",
"]",
")",
";",
"$",
"pk",
"=",
"$",
"this",
"->",
"pgAttributes",
"->",
"findOneByKey",
"(",
"$",
"relationship",
"[",
"'pk_key'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"fk",
"or",
"!",
"$",
"pk",
")",
"{",
"d_pr",
"(",
"$",
"relationship",
")",
";",
"die",
"(",
")",
";",
"}",
"$",
"fk",
"->",
"addReference",
"(",
"$",
"pk",
")",
";",
"}",
"// look for normality defined relationships",
"$",
"profiler",
"=",
"new",
"Profiler",
"(",
"__FUNCTION__",
")",
";",
"$",
"profiler",
"->",
"log",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"pgClasses",
"as",
"$",
"relation",
")",
"{",
"$",
"tags",
"=",
"$",
"relation",
"->",
"getTags",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"tags",
"[",
"'references'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"tags",
"[",
"'references'",
"]",
"as",
"$",
"reference",
")",
"{",
"$",
"reference",
"=",
"array_map",
"(",
"'trim'",
",",
"explode",
"(",
"'='",
",",
"$",
"reference",
")",
")",
";",
"$",
"reference",
"[",
"1",
"]",
"=",
"explode",
"(",
"'.'",
",",
"$",
"reference",
"[",
"1",
"]",
")",
";",
"$",
"fk",
"=",
"$",
"relation",
"->",
"getAttributeByName",
"(",
"$",
"reference",
"[",
"0",
"]",
")",
";",
"// referencing",
"$",
"pkTable",
"=",
"$",
"this",
"->",
"pgClasses",
"->",
"findOneByName",
"(",
"$",
"reference",
"[",
"1",
"]",
"[",
"0",
"]",
")",
";",
"$",
"pk",
"=",
"$",
"pkTable",
"->",
"getAttributeByName",
"(",
"$",
"reference",
"[",
"1",
"]",
"[",
"1",
"]",
")",
";",
"$",
"fk",
"->",
"addReference",
"(",
"$",
"pk",
")",
";",
"}",
"}",
"}",
"// echo $profiler->log()->output();",
"}"
] | See, http://www.postgresql.org/docs/8.4/interactive/catalog-pg-constraint.html
@return bool. Populate the static variables $this->references $this->isReferencedBy | [
"See",
"http",
":",
"//",
"www",
".",
"postgresql",
".",
"org",
"/",
"docs",
"/",
"8",
".",
"4",
"/",
"interactive",
"/",
"catalog",
"-",
"pg",
"-",
"constraint",
".",
"html"
] | train | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/Catalog.php#L113-L303 |
Sectorr/Core | Sectorr/Core/Input/Input.php | Input.exists | public static function exists($type = 'post')
{
switch ($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
} | php | public static function exists($type = 'post')
{
switch ($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
} | [
"public",
"static",
"function",
"exists",
"(",
"$",
"type",
"=",
"'post'",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'post'",
":",
"return",
"(",
"!",
"empty",
"(",
"$",
"_POST",
")",
")",
"?",
"true",
":",
"false",
";",
"break",
";",
"case",
"'get'",
":",
"return",
"(",
"!",
"empty",
"(",
"$",
"_GET",
")",
")",
"?",
"true",
":",
"false",
";",
"break",
";",
"default",
":",
"return",
"false",
";",
"break",
";",
"}",
"}"
] | Check the given request type exists.
@param string $type
@return bool | [
"Check",
"the",
"given",
"request",
"type",
"exists",
"."
] | train | https://github.com/Sectorr/Core/blob/31df852dc6cc61642b0b87d9f0ae56c8e7da5a27/Sectorr/Core/Input/Input.php#L24-L37 |
Sectorr/Core | Sectorr/Core/Input/Input.php | Input.get | public static function get($item)
{
if (isset($_POST[$item])) {
return $_POST[$item];
} elseif (isset($_GET[$item])) {
return $_GET[$item];
} else {
return '';
}
} | php | public static function get($item)
{
if (isset($_POST[$item])) {
return $_POST[$item];
} elseif (isset($_GET[$item])) {
return $_GET[$item];
} else {
return '';
}
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"item",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_POST",
"[",
"$",
"item",
"]",
")",
")",
"{",
"return",
"$",
"_POST",
"[",
"$",
"item",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"_GET",
"[",
"$",
"item",
"]",
")",
")",
"{",
"return",
"$",
"_GET",
"[",
"$",
"item",
"]",
";",
"}",
"else",
"{",
"return",
"''",
";",
"}",
"}"
] | Returns the given input item.
@param $item
@return string | [
"Returns",
"the",
"given",
"input",
"item",
"."
] | train | https://github.com/Sectorr/Core/blob/31df852dc6cc61642b0b87d9f0ae56c8e7da5a27/Sectorr/Core/Input/Input.php#L45-L54 |
Subsets and Splits