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
|
---|---|---|---|---|---|---|---|---|---|---|
nabab/bbn | src/bbn/db.php | db.update_ignore | public function update_ignore($table, array $values = null, array $where = null): ?int
{
return $this->update($table, $values, $where, true);
} | php | public function update_ignore($table, array $values = null, array $where = null): ?int
{
return $this->update($table, $values, $where, true);
} | [
"public",
"function",
"update_ignore",
"(",
"$",
"table",
",",
"array",
"$",
"values",
"=",
"null",
",",
"array",
"$",
"where",
"=",
"null",
")",
":",
"?",
"int",
"{",
"return",
"$",
"this",
"->",
"update",
"(",
"$",
"table",
",",
"$",
"values",
",",
"$",
"where",
",",
"true",
")",
";",
"}"
] | If exist delete row(s) in a table, else ignore.
<code>
$this->db->delete_ignore(
"table_users",
['id' => '20']
);
</code>
@param string|array $table The table name or the configuration array.
@param array $values
@param array $where The "where" condition.
@return int The number of rows deleted. | [
"If",
"exist",
"delete",
"row",
"(",
"s",
")",
"in",
"a",
"table",
"else",
"ignore",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3016-L3019 |
nabab/bbn | src/bbn/db.php | db.delete | public function delete($table, array $where = null, bool $ignore = false): ?int
{
$cfg = \is_array($table) ? $table : [
'tables' => [$table],
'where' => $where,
'ignore' => $ignore
];
$cfg['kind'] = 'DELETE';
return $this->_exec($cfg);
} | php | public function delete($table, array $where = null, bool $ignore = false): ?int
{
$cfg = \is_array($table) ? $table : [
'tables' => [$table],
'where' => $where,
'ignore' => $ignore
];
$cfg['kind'] = 'DELETE';
return $this->_exec($cfg);
} | [
"public",
"function",
"delete",
"(",
"$",
"table",
",",
"array",
"$",
"where",
"=",
"null",
",",
"bool",
"$",
"ignore",
"=",
"false",
")",
":",
"?",
"int",
"{",
"$",
"cfg",
"=",
"\\",
"is_array",
"(",
"$",
"table",
")",
"?",
"$",
"table",
":",
"[",
"'tables'",
"=>",
"[",
"$",
"table",
"]",
",",
"'where'",
"=>",
"$",
"where",
",",
"'ignore'",
"=>",
"$",
"ignore",
"]",
";",
"$",
"cfg",
"[",
"'kind'",
"]",
"=",
"'DELETE'",
";",
"return",
"$",
"this",
"->",
"_exec",
"(",
"$",
"cfg",
")",
";",
"}"
] | Deletes row(s) in a table.
<code>
$this->db->delete("table_users", ['id' => '32']);
</code>
@param string|array $table The table name or the configuration array.
@param array $where The "where" condition.
@param bool $ignore default: false.
@return int The number of rows deleted. | [
"Deletes",
"row",
"(",
"s",
")",
"in",
"a",
"table",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3034-L3043 |
nabab/bbn | src/bbn/db.php | db.delete_ignore | public function delete_ignore($table, array $where = null): ?int
{
return $this->delete(\is_array($table) ? array_merge($table, ['ignore' => true]) : $table, $where, true);
} | php | public function delete_ignore($table, array $where = null): ?int
{
return $this->delete(\is_array($table) ? array_merge($table, ['ignore' => true]) : $table, $where, true);
} | [
"public",
"function",
"delete_ignore",
"(",
"$",
"table",
",",
"array",
"$",
"where",
"=",
"null",
")",
":",
"?",
"int",
"{",
"return",
"$",
"this",
"->",
"delete",
"(",
"\\",
"is_array",
"(",
"$",
"table",
")",
"?",
"array_merge",
"(",
"$",
"table",
",",
"[",
"'ignore'",
"=>",
"true",
"]",
")",
":",
"$",
"table",
",",
"$",
"where",
",",
"true",
")",
";",
"}"
] | If exist delete row(s) in a table, else ignore.
<code>
$this->db->delete_ignore(
"table_users",
['id' => '20']
);
</code>
@param string|array $table The table name or the configuration array.
@param array $where The "where" condition.
@return int The number of rows deleted. | [
"If",
"exist",
"delete",
"row",
"(",
"s",
")",
"in",
"a",
"table",
"else",
"ignore",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3060-L3063 |
nabab/bbn | src/bbn/db.php | db.insert_ignore | public function insert_ignore($table, array $values = null): ?int
{
return $this->insert(\is_array($table) ? array_merge($table, ['ignore' => true]) : $table, $values, true);
} | php | public function insert_ignore($table, array $values = null): ?int
{
return $this->insert(\is_array($table) ? array_merge($table, ['ignore' => true]) : $table, $values, true);
} | [
"public",
"function",
"insert_ignore",
"(",
"$",
"table",
",",
"array",
"$",
"values",
"=",
"null",
")",
":",
"?",
"int",
"{",
"return",
"$",
"this",
"->",
"insert",
"(",
"\\",
"is_array",
"(",
"$",
"table",
")",
"?",
"array_merge",
"(",
"$",
"table",
",",
"[",
"'ignore'",
"=>",
"true",
"]",
")",
":",
"$",
"table",
",",
"$",
"values",
",",
"true",
")",
";",
"}"
] | If not exist inserts row(s) in a table, else ignore.
<code>
$this->db->insert_ignore(
"table_users",
[
['id' => '19', 'name' => 'Frank'],
['id' => '20', 'name' => 'Ted'],
]
);
</code>
@param string|array $table The table name or the configuration array.
@param array $values The row(s) values.
@return int The number of rows inserted. | [
"If",
"not",
"exist",
"inserts",
"row",
"(",
"s",
")",
"in",
"a",
"table",
"else",
"ignore",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3083-L3086 |
nabab/bbn | src/bbn/db.php | db.fetchColumn | public function fetchColumn($query, int $num = 0)
{
if ( $r = $this->query(...\func_get_args()) ){
return $r->fetchColumn($num);
}
return false;
} | php | public function fetchColumn($query, int $num = 0)
{
if ( $r = $this->query(...\func_get_args()) ){
return $r->fetchColumn($num);
}
return false;
} | [
"public",
"function",
"fetchColumn",
"(",
"$",
"query",
",",
"int",
"$",
"num",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"r",
"=",
"$",
"this",
"->",
"query",
"(",
"...",
"\\",
"func_get_args",
"(",
")",
")",
")",
"{",
"return",
"$",
"r",
"->",
"fetchColumn",
"(",
"$",
"num",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Transposition of the original fetchColumn method, but with the query included. Return an arra or false if no result
@todo confusion between result's index and this->query arguments(IMPORTANT). Missing the example because the function doesn't work
@param $query
@param int $num
@return mixed | [
"Transposition",
"of",
"the",
"original",
"fetchColumn",
"method",
"but",
"with",
"the",
"query",
"included",
".",
"Return",
"an",
"arra",
"or",
"false",
"if",
"no",
"result",
"@todo",
"confusion",
"between",
"result",
"s",
"index",
"and",
"this",
"-",
">",
"query",
"arguments",
"(",
"IMPORTANT",
")",
".",
"Missing",
"the",
"example",
"because",
"the",
"function",
"doesn",
"t",
"work"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3171-L3177 |
nabab/bbn | src/bbn/db.php | db.query | public function query($statement)
{
if ( $this->check() ){
$args = \func_get_args();
// If fancy is false we just use the regular PDO query function
if ( !$this->fancy ){
return parent::query(...$args);
}
// The function can be called directly with func_get_args()
while ( (\count($args) === 1) && \is_array($args[0]) ){
$args = $args[0];
}
if ( !empty($args[0]) && \is_string($args[0]) ){
// The first argument is the statement
$statement = trim(array_shift($args));
$hash = $this->_make_hash($statement);
// Sending a hash as second argument from helper functions will bind it to the saved statement
if (
count($args) &&
\is_string($args[0]) &&
(strpos($args[0], $this->hash_contour) === 0) &&
(\strlen($args[0]) === (32 + 2*\strlen($this->hash_contour))) &&
(substr($args[0],-\strlen($this->hash_contour)) === $this->hash_contour)
){
$hash_sent = array_shift($args);
}
$driver_options = [];
if (
count($args) &&
\is_array($args[0])
){
// Case where drivers are arguments
if ( !array_key_exists(0, $args[0]) ){
$driver_options = array_shift($args);
}
// Case where values are in a single argument
else if ( \count($args) === 1 ){
$args = $args[0];
}
}
/** @var array $params Will become the property last_params each time a query is executed */
$params = [
'statement' => $statement,
'values' => [],
'last' => microtime(true)
];
$num_values = 0;
foreach ( $args as $i => $arg ){
if ( !\is_array($arg) ){
$params['values'][] = $arg;
$num_values++;
}
else if ( isset($arg[2]) ){
$params['values'][] = $arg[2];
$num_values++;
}
}
if ( !isset($this->queries[$hash]) ){
/** @var int $placeholders The number of placeholders in the statement */
$placeholders = 0;
if ( $sequences = $this->parse_query($statement) ){
/* Or looking for question marks */
$sequences = array_keys($sequences);
preg_match_all('/(\?)/', $statement, $exp);
$placeholders = isset($exp[1]) && \is_array($exp[1]) ? \count($exp[1]) : 0;
while ( $sequences[0] === 'OPTIONS' ){
array_shift($sequences);
}
$params['kind'] = $sequences[0];
$params['union'] = isset($sequences['UNION']);
$params['write'] = \in_array($params['kind'], self::$write_kinds, true);
$params['structure'] = \in_array($params['kind'], self::$structure_kinds, true);
}
else if ( ($this->engine === 'sqlite') && (strpos($statement, 'PRAGMA') === 0) ){
$params['kind'] = 'PRAGMA';
}
else{
die(\defined('BBN_IS_DEV') && BBN_IS_DEV ? "Impossible to parse the query $statement" : 'Impossible to parse the query');
}
// This will add to the queries array
$this->_add_query(
$hash,
$statement,
$params['kind'],
$placeholders,
$driver_options);
if ( !empty($hash_sent) ){
$this->queries[$hash_sent] = $hash;
}
}
// The hash of the hash for retrieving a query based on the helper's config's hash
else if ( \is_string($this->queries[$hash]) ){
$hash = $this->queries[$hash];
}
$q =& $this->queries[$hash];
/* If the number of values is inferior to the number of placeholders we fill the values with the last given value */
if ( !empty($params['values']) && ($num_values < $q['placeholders']) ){
$params['values'] = array_merge(
$params['values'],
array_fill($num_values, $q['placeholders'] - $num_values, end($params['values']))
);
$num_values = \count($params['values']);
}
/* The number of values must match the number of placeholders to bind */
if ( $num_values !== $q['placeholders'] ){
$this->error('Incorrect arguments count (your values: '.$num_values.', in the statement: '.$q['placeholders']."\n\n".$statement."\n\n".'start of values'.print_r($params['values'], 1).'Arguments:'.print_r(\func_get_args(),true));
exit;
}
$q['num']++;
$q['last'] = microtime(true);
if ( $q['exe_time'] === 0 ){
$time = $q['last'];
}
// That will always contains the parameters of the last query done
$this->last_params = $params;
// Adds to $debug_queries if in debug mode and defines $last_query
$this->add_statement($q['sql']);
// If the statement is a structure modifier we need to clear the cache
if ( $q['structure'] ){
foreach ( $this->queries as $k => $v ){
if ( $k !== $hash ){
unset($this->queries[$k]);
}
}
/** @todo Clear the cache */
}
try{
// This is a writing statement, it will execute the statement and return the number of affected rows
if ( $q['write'] ){
// A prepared query already exists for the writing
/** @var db\query */
if ( $q['prepared'] ){
$r = $q['prepared']->init($this->last_params['values'])->execute();
}
// If there are no values we can assume the statement doesn't need to be prepared and is just executed
else if ( $num_values === 0 ){
// Native PDO function which returns the number of affected rows
$r = $this->exec($q['sql']);
}
// Preparing the query
else{
// Native PDO function which will use db\query as base class
/** @var db\query */
$q['prepared'] = $this->prepare($q['sql'], $q['options']);
$r = $q['prepared']->execute();
}
}
// This is a reading statement, it will prepare the statement and return a query object
else{
if ( !$q['prepared'] ){
// Native PDO function which will use db\query as base class
$q['prepared'] = $this->prepare($q['sql'], $driver_options);
}
else{
// Returns the same db\query object
$q['prepared']->init($this->last_params['values']);
}
}
if ( !empty($time) && ($q['exe_time'] === 0) ){
$q['exe_time'] = microtime(true) - $time;
}
}
catch (\PDOException $e ){
$this->error($e);
}
if ( $this->check() ){
// So if read statement returns the query object
if ( !$q['write'] ){
return $q['prepared'];
}
// If it is a write statement returns the number of affected rows
if ( $q['prepared'] && $q['write'] ){
$r = $q['prepared']->rowCount();
}
// If it is an insert statement we (try to) set the last inserted ID
if ( ($q['kind'] === 'INSERT') && $r ){
$this->set_last_insert_id();
}
return $r ?? false;
}
}
}
return false;
} | php | public function query($statement)
{
if ( $this->check() ){
$args = \func_get_args();
// If fancy is false we just use the regular PDO query function
if ( !$this->fancy ){
return parent::query(...$args);
}
// The function can be called directly with func_get_args()
while ( (\count($args) === 1) && \is_array($args[0]) ){
$args = $args[0];
}
if ( !empty($args[0]) && \is_string($args[0]) ){
// The first argument is the statement
$statement = trim(array_shift($args));
$hash = $this->_make_hash($statement);
// Sending a hash as second argument from helper functions will bind it to the saved statement
if (
count($args) &&
\is_string($args[0]) &&
(strpos($args[0], $this->hash_contour) === 0) &&
(\strlen($args[0]) === (32 + 2*\strlen($this->hash_contour))) &&
(substr($args[0],-\strlen($this->hash_contour)) === $this->hash_contour)
){
$hash_sent = array_shift($args);
}
$driver_options = [];
if (
count($args) &&
\is_array($args[0])
){
// Case where drivers are arguments
if ( !array_key_exists(0, $args[0]) ){
$driver_options = array_shift($args);
}
// Case where values are in a single argument
else if ( \count($args) === 1 ){
$args = $args[0];
}
}
/** @var array $params Will become the property last_params each time a query is executed */
$params = [
'statement' => $statement,
'values' => [],
'last' => microtime(true)
];
$num_values = 0;
foreach ( $args as $i => $arg ){
if ( !\is_array($arg) ){
$params['values'][] = $arg;
$num_values++;
}
else if ( isset($arg[2]) ){
$params['values'][] = $arg[2];
$num_values++;
}
}
if ( !isset($this->queries[$hash]) ){
/** @var int $placeholders The number of placeholders in the statement */
$placeholders = 0;
if ( $sequences = $this->parse_query($statement) ){
/* Or looking for question marks */
$sequences = array_keys($sequences);
preg_match_all('/(\?)/', $statement, $exp);
$placeholders = isset($exp[1]) && \is_array($exp[1]) ? \count($exp[1]) : 0;
while ( $sequences[0] === 'OPTIONS' ){
array_shift($sequences);
}
$params['kind'] = $sequences[0];
$params['union'] = isset($sequences['UNION']);
$params['write'] = \in_array($params['kind'], self::$write_kinds, true);
$params['structure'] = \in_array($params['kind'], self::$structure_kinds, true);
}
else if ( ($this->engine === 'sqlite') && (strpos($statement, 'PRAGMA') === 0) ){
$params['kind'] = 'PRAGMA';
}
else{
die(\defined('BBN_IS_DEV') && BBN_IS_DEV ? "Impossible to parse the query $statement" : 'Impossible to parse the query');
}
// This will add to the queries array
$this->_add_query(
$hash,
$statement,
$params['kind'],
$placeholders,
$driver_options);
if ( !empty($hash_sent) ){
$this->queries[$hash_sent] = $hash;
}
}
// The hash of the hash for retrieving a query based on the helper's config's hash
else if ( \is_string($this->queries[$hash]) ){
$hash = $this->queries[$hash];
}
$q =& $this->queries[$hash];
/* If the number of values is inferior to the number of placeholders we fill the values with the last given value */
if ( !empty($params['values']) && ($num_values < $q['placeholders']) ){
$params['values'] = array_merge(
$params['values'],
array_fill($num_values, $q['placeholders'] - $num_values, end($params['values']))
);
$num_values = \count($params['values']);
}
/* The number of values must match the number of placeholders to bind */
if ( $num_values !== $q['placeholders'] ){
$this->error('Incorrect arguments count (your values: '.$num_values.', in the statement: '.$q['placeholders']."\n\n".$statement."\n\n".'start of values'.print_r($params['values'], 1).'Arguments:'.print_r(\func_get_args(),true));
exit;
}
$q['num']++;
$q['last'] = microtime(true);
if ( $q['exe_time'] === 0 ){
$time = $q['last'];
}
// That will always contains the parameters of the last query done
$this->last_params = $params;
// Adds to $debug_queries if in debug mode and defines $last_query
$this->add_statement($q['sql']);
// If the statement is a structure modifier we need to clear the cache
if ( $q['structure'] ){
foreach ( $this->queries as $k => $v ){
if ( $k !== $hash ){
unset($this->queries[$k]);
}
}
/** @todo Clear the cache */
}
try{
// This is a writing statement, it will execute the statement and return the number of affected rows
if ( $q['write'] ){
// A prepared query already exists for the writing
/** @var db\query */
if ( $q['prepared'] ){
$r = $q['prepared']->init($this->last_params['values'])->execute();
}
// If there are no values we can assume the statement doesn't need to be prepared and is just executed
else if ( $num_values === 0 ){
// Native PDO function which returns the number of affected rows
$r = $this->exec($q['sql']);
}
// Preparing the query
else{
// Native PDO function which will use db\query as base class
/** @var db\query */
$q['prepared'] = $this->prepare($q['sql'], $q['options']);
$r = $q['prepared']->execute();
}
}
// This is a reading statement, it will prepare the statement and return a query object
else{
if ( !$q['prepared'] ){
// Native PDO function which will use db\query as base class
$q['prepared'] = $this->prepare($q['sql'], $driver_options);
}
else{
// Returns the same db\query object
$q['prepared']->init($this->last_params['values']);
}
}
if ( !empty($time) && ($q['exe_time'] === 0) ){
$q['exe_time'] = microtime(true) - $time;
}
}
catch (\PDOException $e ){
$this->error($e);
}
if ( $this->check() ){
// So if read statement returns the query object
if ( !$q['write'] ){
return $q['prepared'];
}
// If it is a write statement returns the number of affected rows
if ( $q['prepared'] && $q['write'] ){
$r = $q['prepared']->rowCount();
}
// If it is an insert statement we (try to) set the last inserted ID
if ( ($q['kind'] === 'INSERT') && $r ){
$this->set_last_insert_id();
}
return $r ?? false;
}
}
}
return false;
} | [
"public",
"function",
"query",
"(",
"$",
"statement",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"check",
"(",
")",
")",
"{",
"$",
"args",
"=",
"\\",
"func_get_args",
"(",
")",
";",
"// If fancy is false we just use the regular PDO query function",
"if",
"(",
"!",
"$",
"this",
"->",
"fancy",
")",
"{",
"return",
"parent",
"::",
"query",
"(",
"...",
"$",
"args",
")",
";",
"}",
"// The function can be called directly with func_get_args()",
"while",
"(",
"(",
"\\",
"count",
"(",
"$",
"args",
")",
"===",
"1",
")",
"&&",
"\\",
"is_array",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"$",
"args",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
"[",
"0",
"]",
")",
"&&",
"\\",
"is_string",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"// The first argument is the statement",
"$",
"statement",
"=",
"trim",
"(",
"array_shift",
"(",
"$",
"args",
")",
")",
";",
"$",
"hash",
"=",
"$",
"this",
"->",
"_make_hash",
"(",
"$",
"statement",
")",
";",
"// Sending a hash as second argument from helper functions will bind it to the saved statement",
"if",
"(",
"count",
"(",
"$",
"args",
")",
"&&",
"\\",
"is_string",
"(",
"$",
"args",
"[",
"0",
"]",
")",
"&&",
"(",
"strpos",
"(",
"$",
"args",
"[",
"0",
"]",
",",
"$",
"this",
"->",
"hash_contour",
")",
"===",
"0",
")",
"&&",
"(",
"\\",
"strlen",
"(",
"$",
"args",
"[",
"0",
"]",
")",
"===",
"(",
"32",
"+",
"2",
"*",
"\\",
"strlen",
"(",
"$",
"this",
"->",
"hash_contour",
")",
")",
")",
"&&",
"(",
"substr",
"(",
"$",
"args",
"[",
"0",
"]",
",",
"-",
"\\",
"strlen",
"(",
"$",
"this",
"->",
"hash_contour",
")",
")",
"===",
"$",
"this",
"->",
"hash_contour",
")",
")",
"{",
"$",
"hash_sent",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"}",
"$",
"driver_options",
"=",
"[",
"]",
";",
"if",
"(",
"count",
"(",
"$",
"args",
")",
"&&",
"\\",
"is_array",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"// Case where drivers are arguments",
"if",
"(",
"!",
"array_key_exists",
"(",
"0",
",",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"$",
"driver_options",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"}",
"// Case where values are in a single argument",
"else",
"if",
"(",
"\\",
"count",
"(",
"$",
"args",
")",
"===",
"1",
")",
"{",
"$",
"args",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"}",
"}",
"/** @var array $params Will become the property last_params each time a query is executed */",
"$",
"params",
"=",
"[",
"'statement'",
"=>",
"$",
"statement",
",",
"'values'",
"=>",
"[",
"]",
",",
"'last'",
"=>",
"microtime",
"(",
"true",
")",
"]",
";",
"$",
"num_values",
"=",
"0",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"i",
"=>",
"$",
"arg",
")",
"{",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"arg",
")",
")",
"{",
"$",
"params",
"[",
"'values'",
"]",
"[",
"]",
"=",
"$",
"arg",
";",
"$",
"num_values",
"++",
";",
"}",
"else",
"if",
"(",
"isset",
"(",
"$",
"arg",
"[",
"2",
"]",
")",
")",
"{",
"$",
"params",
"[",
"'values'",
"]",
"[",
"]",
"=",
"$",
"arg",
"[",
"2",
"]",
";",
"$",
"num_values",
"++",
";",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"queries",
"[",
"$",
"hash",
"]",
")",
")",
"{",
"/** @var int $placeholders The number of placeholders in the statement */",
"$",
"placeholders",
"=",
"0",
";",
"if",
"(",
"$",
"sequences",
"=",
"$",
"this",
"->",
"parse_query",
"(",
"$",
"statement",
")",
")",
"{",
"/* Or looking for question marks */",
"$",
"sequences",
"=",
"array_keys",
"(",
"$",
"sequences",
")",
";",
"preg_match_all",
"(",
"'/(\\?)/'",
",",
"$",
"statement",
",",
"$",
"exp",
")",
";",
"$",
"placeholders",
"=",
"isset",
"(",
"$",
"exp",
"[",
"1",
"]",
")",
"&&",
"\\",
"is_array",
"(",
"$",
"exp",
"[",
"1",
"]",
")",
"?",
"\\",
"count",
"(",
"$",
"exp",
"[",
"1",
"]",
")",
":",
"0",
";",
"while",
"(",
"$",
"sequences",
"[",
"0",
"]",
"===",
"'OPTIONS'",
")",
"{",
"array_shift",
"(",
"$",
"sequences",
")",
";",
"}",
"$",
"params",
"[",
"'kind'",
"]",
"=",
"$",
"sequences",
"[",
"0",
"]",
";",
"$",
"params",
"[",
"'union'",
"]",
"=",
"isset",
"(",
"$",
"sequences",
"[",
"'UNION'",
"]",
")",
";",
"$",
"params",
"[",
"'write'",
"]",
"=",
"\\",
"in_array",
"(",
"$",
"params",
"[",
"'kind'",
"]",
",",
"self",
"::",
"$",
"write_kinds",
",",
"true",
")",
";",
"$",
"params",
"[",
"'structure'",
"]",
"=",
"\\",
"in_array",
"(",
"$",
"params",
"[",
"'kind'",
"]",
",",
"self",
"::",
"$",
"structure_kinds",
",",
"true",
")",
";",
"}",
"else",
"if",
"(",
"(",
"$",
"this",
"->",
"engine",
"===",
"'sqlite'",
")",
"&&",
"(",
"strpos",
"(",
"$",
"statement",
",",
"'PRAGMA'",
")",
"===",
"0",
")",
")",
"{",
"$",
"params",
"[",
"'kind'",
"]",
"=",
"'PRAGMA'",
";",
"}",
"else",
"{",
"die",
"(",
"\\",
"defined",
"(",
"'BBN_IS_DEV'",
")",
"&&",
"BBN_IS_DEV",
"?",
"\"Impossible to parse the query $statement\"",
":",
"'Impossible to parse the query'",
")",
";",
"}",
"// This will add to the queries array",
"$",
"this",
"->",
"_add_query",
"(",
"$",
"hash",
",",
"$",
"statement",
",",
"$",
"params",
"[",
"'kind'",
"]",
",",
"$",
"placeholders",
",",
"$",
"driver_options",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"hash_sent",
")",
")",
"{",
"$",
"this",
"->",
"queries",
"[",
"$",
"hash_sent",
"]",
"=",
"$",
"hash",
";",
"}",
"}",
"// The hash of the hash for retrieving a query based on the helper's config's hash",
"else",
"if",
"(",
"\\",
"is_string",
"(",
"$",
"this",
"->",
"queries",
"[",
"$",
"hash",
"]",
")",
")",
"{",
"$",
"hash",
"=",
"$",
"this",
"->",
"queries",
"[",
"$",
"hash",
"]",
";",
"}",
"$",
"q",
"=",
"&",
"$",
"this",
"->",
"queries",
"[",
"$",
"hash",
"]",
";",
"/* If the number of values is inferior to the number of placeholders we fill the values with the last given value */",
"if",
"(",
"!",
"empty",
"(",
"$",
"params",
"[",
"'values'",
"]",
")",
"&&",
"(",
"$",
"num_values",
"<",
"$",
"q",
"[",
"'placeholders'",
"]",
")",
")",
"{",
"$",
"params",
"[",
"'values'",
"]",
"=",
"array_merge",
"(",
"$",
"params",
"[",
"'values'",
"]",
",",
"array_fill",
"(",
"$",
"num_values",
",",
"$",
"q",
"[",
"'placeholders'",
"]",
"-",
"$",
"num_values",
",",
"end",
"(",
"$",
"params",
"[",
"'values'",
"]",
")",
")",
")",
";",
"$",
"num_values",
"=",
"\\",
"count",
"(",
"$",
"params",
"[",
"'values'",
"]",
")",
";",
"}",
"/* The number of values must match the number of placeholders to bind */",
"if",
"(",
"$",
"num_values",
"!==",
"$",
"q",
"[",
"'placeholders'",
"]",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"'Incorrect arguments count (your values: '",
".",
"$",
"num_values",
".",
"', in the statement: '",
".",
"$",
"q",
"[",
"'placeholders'",
"]",
".",
"\"\\n\\n\"",
".",
"$",
"statement",
".",
"\"\\n\\n\"",
".",
"'start of values'",
".",
"print_r",
"(",
"$",
"params",
"[",
"'values'",
"]",
",",
"1",
")",
".",
"'Arguments:'",
".",
"print_r",
"(",
"\\",
"func_get_args",
"(",
")",
",",
"true",
")",
")",
";",
"exit",
";",
"}",
"$",
"q",
"[",
"'num'",
"]",
"++",
";",
"$",
"q",
"[",
"'last'",
"]",
"=",
"microtime",
"(",
"true",
")",
";",
"if",
"(",
"$",
"q",
"[",
"'exe_time'",
"]",
"===",
"0",
")",
"{",
"$",
"time",
"=",
"$",
"q",
"[",
"'last'",
"]",
";",
"}",
"// That will always contains the parameters of the last query done",
"$",
"this",
"->",
"last_params",
"=",
"$",
"params",
";",
"// Adds to $debug_queries if in debug mode and defines $last_query",
"$",
"this",
"->",
"add_statement",
"(",
"$",
"q",
"[",
"'sql'",
"]",
")",
";",
"// If the statement is a structure modifier we need to clear the cache",
"if",
"(",
"$",
"q",
"[",
"'structure'",
"]",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"queries",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"$",
"k",
"!==",
"$",
"hash",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"queries",
"[",
"$",
"k",
"]",
")",
";",
"}",
"}",
"/** @todo Clear the cache */",
"}",
"try",
"{",
"// This is a writing statement, it will execute the statement and return the number of affected rows",
"if",
"(",
"$",
"q",
"[",
"'write'",
"]",
")",
"{",
"// A prepared query already exists for the writing",
"/** @var db\\query */",
"if",
"(",
"$",
"q",
"[",
"'prepared'",
"]",
")",
"{",
"$",
"r",
"=",
"$",
"q",
"[",
"'prepared'",
"]",
"->",
"init",
"(",
"$",
"this",
"->",
"last_params",
"[",
"'values'",
"]",
")",
"->",
"execute",
"(",
")",
";",
"}",
"// If there are no values we can assume the statement doesn't need to be prepared and is just executed",
"else",
"if",
"(",
"$",
"num_values",
"===",
"0",
")",
"{",
"// Native PDO function which returns the number of affected rows",
"$",
"r",
"=",
"$",
"this",
"->",
"exec",
"(",
"$",
"q",
"[",
"'sql'",
"]",
")",
";",
"}",
"// Preparing the query",
"else",
"{",
"// Native PDO function which will use db\\query as base class",
"/** @var db\\query */",
"$",
"q",
"[",
"'prepared'",
"]",
"=",
"$",
"this",
"->",
"prepare",
"(",
"$",
"q",
"[",
"'sql'",
"]",
",",
"$",
"q",
"[",
"'options'",
"]",
")",
";",
"$",
"r",
"=",
"$",
"q",
"[",
"'prepared'",
"]",
"->",
"execute",
"(",
")",
";",
"}",
"}",
"// This is a reading statement, it will prepare the statement and return a query object",
"else",
"{",
"if",
"(",
"!",
"$",
"q",
"[",
"'prepared'",
"]",
")",
"{",
"// Native PDO function which will use db\\query as base class",
"$",
"q",
"[",
"'prepared'",
"]",
"=",
"$",
"this",
"->",
"prepare",
"(",
"$",
"q",
"[",
"'sql'",
"]",
",",
"$",
"driver_options",
")",
";",
"}",
"else",
"{",
"// Returns the same db\\query object",
"$",
"q",
"[",
"'prepared'",
"]",
"->",
"init",
"(",
"$",
"this",
"->",
"last_params",
"[",
"'values'",
"]",
")",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"time",
")",
"&&",
"(",
"$",
"q",
"[",
"'exe_time'",
"]",
"===",
"0",
")",
")",
"{",
"$",
"q",
"[",
"'exe_time'",
"]",
"=",
"microtime",
"(",
"true",
")",
"-",
"$",
"time",
";",
"}",
"}",
"catch",
"(",
"\\",
"PDOException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"$",
"e",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"check",
"(",
")",
")",
"{",
"// So if read statement returns the query object",
"if",
"(",
"!",
"$",
"q",
"[",
"'write'",
"]",
")",
"{",
"return",
"$",
"q",
"[",
"'prepared'",
"]",
";",
"}",
"// If it is a write statement returns the number of affected rows",
"if",
"(",
"$",
"q",
"[",
"'prepared'",
"]",
"&&",
"$",
"q",
"[",
"'write'",
"]",
")",
"{",
"$",
"r",
"=",
"$",
"q",
"[",
"'prepared'",
"]",
"->",
"rowCount",
"(",
")",
";",
"}",
"// If it is an insert statement we (try to) set the last inserted ID",
"if",
"(",
"(",
"$",
"q",
"[",
"'kind'",
"]",
"===",
"'INSERT'",
")",
"&&",
"$",
"r",
")",
"{",
"$",
"this",
"->",
"set_last_insert_id",
"(",
")",
";",
"}",
"return",
"$",
"r",
"??",
"false",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Executes a writing statement and return the number of affected rows or return a query object for the reading * statement
@todo far vedere a thomams perche non funziona in lettura
```php
\bbn\x::dump($db->query("DELETE FROM table_users WHERE name LIKE '%lucy%'"));
// (int) 3
\bbn\x::dump($db->query("SELECT * FROM table_users WHERE name = 'John"));
// (bbn\db\query) Object
```
@param array|string $statement
@return int|db\query | [
"Executes",
"a",
"writing",
"statement",
"and",
"return",
"the",
"number",
"of",
"affected",
"rows",
"or",
"return",
"a",
"query",
"object",
"for",
"the",
"reading",
"*",
"statement",
"@todo",
"far",
"vedere",
"a",
"thomams",
"perche",
"non",
"funziona",
"in",
"lettura"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3216-L3406 |
nabab/bbn | src/bbn/db.php | db.tfn | public function tfn(string $table, bool $escaped = false): ?string
{
return $this->table_full_name($table, $escaped);
} | php | public function tfn(string $table, bool $escaped = false): ?string
{
return $this->table_full_name($table, $escaped);
} | [
"public",
"function",
"tfn",
"(",
"string",
"$",
"table",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"table_full_name",
"(",
"$",
"table",
",",
"$",
"escaped",
")",
";",
"}"
] | Return table's simple name.
(similar to {@link table_simple_name()})
```php
\bbn\x::dump($db->tsn("work_db.table_users"));
// (string) table_users
\bbn\x::dump($db->tsn("work_db.table_users", true));
// (string) `table_users`
```
@param string $table The table's name
@param bool $escaped If set to true the returned string will be escaped.
@return null|string | [
"Return",
"table",
"s",
"simple",
"name",
".",
"(",
"similar",
"to",
"{",
"@link",
"table_simple_name",
"()",
"}",
")"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3432-L3435 |
nabab/bbn | src/bbn/db.php | db.tsn | public function tsn(string $table, bool $escaped = false): ?string
{
return $this->table_simple_name($table, $escaped);
} | php | public function tsn(string $table, bool $escaped = false): ?string
{
return $this->table_simple_name($table, $escaped);
} | [
"public",
"function",
"tsn",
"(",
"string",
"$",
"table",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"table_simple_name",
"(",
"$",
"table",
",",
"$",
"escaped",
")",
";",
"}"
] | Return table's simple name.
(similar to {@link table_simple_name()})
```php
\bbn\x::dump($db->tsn("work_db.table_users"));
// (string) table_users
\bbn\x::dump($db->tsn("work_db.table_users", true));
// (string) `table_users`
```
@param string $table The table's name
@param bool $escaped If set to true the returned string will be escaped.
@return null|string | [
"Return",
"table",
"s",
"simple",
"name",
".",
"(",
"similar",
"to",
"{",
"@link",
"table_simple_name",
"()",
"}",
")"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3452-L3455 |
nabab/bbn | src/bbn/db.php | db.cfn | public function cfn(string $col, $table = null, bool $escaped = false): ?string
{
return $this->col_full_name($col, $table, $escaped);
} | php | public function cfn(string $col, $table = null, bool $escaped = false): ?string
{
return $this->col_full_name($col, $table, $escaped);
} | [
"public",
"function",
"cfn",
"(",
"string",
"$",
"col",
",",
"$",
"table",
"=",
"null",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"col_full_name",
"(",
"$",
"col",
",",
"$",
"table",
",",
"$",
"escaped",
")",
";",
"}"
] | Return column's full name.
(similar to {@link col_full_name()})
```php
\bbn\x::dump($db->cfn("name", "table_users"));
// (string) table_users.name
\bbn\x::dump($db->cfn("name", "table_users", true));
// (string) \`table_users\`.\`name\`
```
@param string $col The column's name (escaped or not).
@param string $table The table's name (escaped or not).
@param bool $escaped If set to true the returned string will be escaped.
@return null|string | [
"Return",
"column",
"s",
"full",
"name",
".",
"(",
"similar",
"to",
"{",
"@link",
"col_full_name",
"()",
"}",
")"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3473-L3476 |
nabab/bbn | src/bbn/db.php | db.csn | public function csn(string $col, bool $escaped = false): ?string
{
return $this->col_simple_name($col, $escaped);
} | php | public function csn(string $col, bool $escaped = false): ?string
{
return $this->col_simple_name($col, $escaped);
} | [
"public",
"function",
"csn",
"(",
"string",
"$",
"col",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"col_simple_name",
"(",
"$",
"col",
",",
"$",
"escaped",
")",
";",
"}"
] | Return the column's simple name.
(similar to {@link col_simple_name()})
```php
\bbn\x::dump($db->csn("table_users.name"));
// (string) name
\bbn\x::dump($db->csn("table_users.name", true));
// (string) `name`
```
@param string $col The column's complete name (escaped or not)
@param bool $escaped If set to true the returned string will be escaped.
@return null|string | [
"Return",
"the",
"column",
"s",
"simple",
"name",
".",
"(",
"similar",
"to",
"{",
"@link",
"col_simple_name",
"()",
"}",
")"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3493-L3496 |
nabab/bbn | src/bbn/db.php | db.change | public function change(string $db): self
{
if ( $this->language->change($db) ){
$this->current = $db;
}
return $this;
} | php | public function change(string $db): self
{
if ( $this->language->change($db) ){
$this->current = $db;
}
return $this;
} | [
"public",
"function",
"change",
"(",
"string",
"$",
"db",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"language",
"->",
"change",
"(",
"$",
"db",
")",
")",
"{",
"$",
"this",
"->",
"current",
"=",
"$",
"db",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Changes the database used to the given one.
```php
$db = new db();
x::dump($db->change('db_example'));
// (db)
```
@param string $db The database's name
@return self | [
"Changes",
"the",
"database",
"used",
"to",
"the",
"given",
"one",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3543-L3549 |
nabab/bbn | src/bbn/db.php | db.table_full_name | public function table_full_name(string $table, bool $escaped = false): ?string
{
return $this->language->table_full_name($table, $escaped);
} | php | public function table_full_name(string $table, bool $escaped = false): ?string
{
return $this->language->table_full_name($table, $escaped);
} | [
"public",
"function",
"table_full_name",
"(",
"string",
"$",
"table",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"table_full_name",
"(",
"$",
"table",
",",
"$",
"escaped",
")",
";",
"}"
] | Return table's full name.
```php
bbn\x::dump($db->table_full_name("table_users"));
// (String) db_example.table_users
bbn\x::dump($db->table_full_name("table_users", true));
// (String) `db_example`.`table_users`
```
@param string $table The table's name (escaped or not).
@param bool $escaped If set to true the returned string will be escaped.
@return string | false | [
"Return",
"table",
"s",
"full",
"name",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3581-L3584 |
nabab/bbn | src/bbn/db.php | db.table_simple_name | public function table_simple_name(string $table, bool $escaped = false): ?string
{
return $this->language->table_simple_name($table, $escaped);
} | php | public function table_simple_name(string $table, bool $escaped = false): ?string
{
return $this->language->table_simple_name($table, $escaped);
} | [
"public",
"function",
"table_simple_name",
"(",
"string",
"$",
"table",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"table_simple_name",
"(",
"$",
"table",
",",
"$",
"escaped",
")",
";",
"}"
] | Return table's simple name.
```php
\bbn\x::dump($db->table_simple_name("example_db.table_users"));
// (string) table_users
\bbn\x::dump($db->table_simple_name("example.table_users", true));
// (string) `table_users`
```
@param string $table The table's name (escaped or not)
@param bool $escaped If set to true the returned string will be escaped
@return string | false | [
"Return",
"table",
"s",
"simple",
"name",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3628-L3631 |
nabab/bbn | src/bbn/db.php | db.col_full_name | public function col_full_name(string $col, $table = '', $escaped = false): ?string
{
return $this->language->col_full_name($col, $table, $escaped);
} | php | public function col_full_name(string $col, $table = '', $escaped = false): ?string
{
return $this->language->col_full_name($col, $table, $escaped);
} | [
"public",
"function",
"col_full_name",
"(",
"string",
"$",
"col",
",",
"$",
"table",
"=",
"''",
",",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"col_full_name",
"(",
"$",
"col",
",",
"$",
"table",
",",
"$",
"escaped",
")",
";",
"}"
] | Return column's full name.
```php
\bbn\x::dump($db->col_full_name("name", "table_users"));
// (string) table_users.name
\bbn\x::dump($db->col_full_name("name", "table_users", true));
// (string) \`table_users\`.\`name\`
```
@param string $col The column's name (escaped or not)
@param string $table The table's name (escaped or not)
@param bool $escaped If set to true the returned string will be escaped
@return string | false | [
"Return",
"column",
"s",
"full",
"name",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3648-L3651 |
nabab/bbn | src/bbn/db.php | db.col_simple_name | public function col_simple_name(string $col, bool $escaped = false): ?string
{
return $this->language->col_simple_name($col, $escaped);
} | php | public function col_simple_name(string $col, bool $escaped = false): ?string
{
return $this->language->col_simple_name($col, $escaped);
} | [
"public",
"function",
"col_simple_name",
"(",
"string",
"$",
"col",
",",
"bool",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"col_simple_name",
"(",
"$",
"col",
",",
"$",
"escaped",
")",
";",
"}"
] | Return the column's simple name.
```php
\bbn\x::dump($db->col_simple_name("table_users.name"));
// (string) name
\bbn\x::dump($db->col_simple_name("table_users.name", true));
// (string) `name`
```
@param string $col The column's complete name (escaped or not).
@param bool $escaped If set to true the returned string will be escaped.
@return string | false | [
"Return",
"the",
"column",
"s",
"simple",
"name",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3667-L3670 |
nabab/bbn | src/bbn/db.php | db.get_tables | public function get_tables(string $database=''): ?array
{
if ( empty($database) ){
$database = $this->current;
}
return $this->_get_cache($database, 'tables');
} | php | public function get_tables(string $database=''): ?array
{
if ( empty($database) ){
$database = $this->current;
}
return $this->_get_cache($database, 'tables');
} | [
"public",
"function",
"get_tables",
"(",
"string",
"$",
"database",
"=",
"''",
")",
":",
"?",
"array",
"{",
"if",
"(",
"empty",
"(",
"$",
"database",
")",
")",
"{",
"$",
"database",
"=",
"$",
"this",
"->",
"current",
";",
"}",
"return",
"$",
"this",
"->",
"_get_cache",
"(",
"$",
"database",
",",
"'tables'",
")",
";",
"}"
] | Return tables' names of a database as an array.
```php
\bbn\x::dump($db->get_tables('db_example'));
/*
(array) [
"clients",
"columns",
"cron",
"journal",
"dbs",
"examples",
"history",
"hosts",
"keys",
"mails",
"medias",
"notes",
"medias",
"versions"
]
```
@param string $database Database name
@return null|array | [
"Return",
"tables",
"names",
"of",
"a",
"database",
"as",
"an",
"array",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3753-L3759 |
nabab/bbn | src/bbn/db.php | db.get_keys | public function get_keys(string $table): ?array
{
if ( $tmp = $this->_get_cache($table) ){
return [
'keys' => $tmp['keys'],
'cols' => $tmp['cols']
];
}
return null;
} | php | public function get_keys(string $table): ?array
{
if ( $tmp = $this->_get_cache($table) ){
return [
'keys' => $tmp['keys'],
'cols' => $tmp['cols']
];
}
return null;
} | [
"public",
"function",
"get_keys",
"(",
"string",
"$",
"table",
")",
":",
"?",
"array",
"{",
"if",
"(",
"$",
"tmp",
"=",
"$",
"this",
"->",
"_get_cache",
"(",
"$",
"table",
")",
")",
"{",
"return",
"[",
"'keys'",
"=>",
"$",
"tmp",
"[",
"'keys'",
"]",
",",
"'cols'",
"=>",
"$",
"tmp",
"[",
"'cols'",
"]",
"]",
";",
"}",
"return",
"null",
";",
"}"
] | Return the table's keys as an array indexed with the fields names.
```php
\bbn\x::dump($db->get_keys("table_users"));
/*
(array)[
"keys" => [
"PRIMARY" => [
"columns" => [
"id",
],
"ref_db" => null,
"ref_table" => null,
"ref_column" => null,
"unique" => 1,
],
"number" => [
"columns" => [
"number",
],
"ref_db" => null,
"ref_table" => null,
"ref_column" => null,
"unique" => 1,
],
],
"cols" => [
"id" => [
"PRIMARY",
],
"number" => [
"number",
],
],
]
```
@param string $table The table's name
@return null|array | [
"Return",
"the",
"table",
"s",
"keys",
"as",
"an",
"array",
"indexed",
"with",
"the",
"fields",
"names",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3862-L3871 |
nabab/bbn | src/bbn/db.php | db.get_insert | public function get_insert(array $cfg): string
{
$cfg['kind'] = 'INSERT';
return $this->language->get_insert($this->process_cfg($cfg));
} | php | public function get_insert(array $cfg): string
{
$cfg['kind'] = 'INSERT';
return $this->language->get_insert($this->process_cfg($cfg));
} | [
"public",
"function",
"get_insert",
"(",
"array",
"$",
"cfg",
")",
":",
"string",
"{",
"$",
"cfg",
"[",
"'kind'",
"]",
"=",
"'INSERT'",
";",
"return",
"$",
"this",
"->",
"language",
"->",
"get_insert",
"(",
"$",
"this",
"->",
"process_cfg",
"(",
"$",
"cfg",
")",
")",
";",
"}"
] | Returns the SQL code for an INSERT statement.
```php
\bbn\x::dump($db->get_insert([
'tables' => ['table_users'],
'fields' => ['name','surname']
]));
/*
(string)
INSERT INTO `db_example`.`table_users` (
`name`, `surname`)
VALUES (?, ?)
```
@param array $cfg The configuration array
@return string | [
"Returns",
"the",
"SQL",
"code",
"for",
"an",
"INSERT",
"statement",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3922-L3926 |
nabab/bbn | src/bbn/db.php | db.get_update | public function get_update(array $cfg): string
{
$cfg['kind'] = 'UPDATE';
return $this->language->get_update($this->process_cfg($cfg));
} | php | public function get_update(array $cfg): string
{
$cfg['kind'] = 'UPDATE';
return $this->language->get_update($this->process_cfg($cfg));
} | [
"public",
"function",
"get_update",
"(",
"array",
"$",
"cfg",
")",
":",
"string",
"{",
"$",
"cfg",
"[",
"'kind'",
"]",
"=",
"'UPDATE'",
";",
"return",
"$",
"this",
"->",
"language",
"->",
"get_update",
"(",
"$",
"this",
"->",
"process_cfg",
"(",
"$",
"cfg",
")",
")",
";",
"}"
] | Returns the SQL code for an UPDATE statement.
```php
\bbn\x::dump($db->get_update([
'tables' => ['table_users'],
'fields' => ['name','surname']
]));
/*
(string)
UPDATE `db_example`.`table_users`
SET `table_users`.`name` = ?,
`table_users`.`surname` = ?
```
@param array $cfg The configuration array
@return string | [
"Returns",
"the",
"SQL",
"code",
"for",
"an",
"UPDATE",
"statement",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3946-L3950 |
nabab/bbn | src/bbn/db.php | db.get_delete | public function get_delete(array $cfg): string
{
$cfg['kind'] = 'DELETE';
return $this->language->get_delete($this->process_cfg($cfg));
} | php | public function get_delete(array $cfg): string
{
$cfg['kind'] = 'DELETE';
return $this->language->get_delete($this->process_cfg($cfg));
} | [
"public",
"function",
"get_delete",
"(",
"array",
"$",
"cfg",
")",
":",
"string",
"{",
"$",
"cfg",
"[",
"'kind'",
"]",
"=",
"'DELETE'",
";",
"return",
"$",
"this",
"->",
"language",
"->",
"get_delete",
"(",
"$",
"this",
"->",
"process_cfg",
"(",
"$",
"cfg",
")",
")",
";",
"}"
] | Returns the SQL code for a DELETE statement.
```php
\bbn\x::dump($db->get_delete('table_users',['id'=>1]));
// (string) DELETE FROM `db_example`.`table_users` * WHERE 1 AND `table_users`.`id` = ?
```
@param array $cfg The configuration array
@return string | [
"Returns",
"the",
"SQL",
"code",
"for",
"a",
"DELETE",
"statement",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L3963-L3967 |
nabab/bbn | src/bbn/db.php | db.create_index | public function create_index(string $table, $column, bool $unique = false, $length = null): bool
{
return $this->language->create_index($table, $column, $unique);
} | php | public function create_index(string $table, $column, bool $unique = false, $length = null): bool
{
return $this->language->create_index($table, $column, $unique);
} | [
"public",
"function",
"create_index",
"(",
"string",
"$",
"table",
",",
"$",
"column",
",",
"bool",
"$",
"unique",
"=",
"false",
",",
"$",
"length",
"=",
"null",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"create_index",
"(",
"$",
"table",
",",
"$",
"column",
",",
"$",
"unique",
")",
";",
"}"
] | Creates an index on one or more column(s) of the table
@todo return data
```php
\bbn\x::dump($db->create_db_index('table_users','id_group'));
// (void)
```
@param string $table
@param string|array $column
@param bool $unique
@param null $length
@return bool | [
"Creates",
"an",
"index",
"on",
"one",
"or",
"more",
"column",
"(",
"s",
")",
"of",
"the",
"table"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L4090-L4093 |
nabab/bbn | src/bbn/db.php | db.delete_index | public function delete_index(string $table, string $key): bool
{
return $this->language->delete_index($table, $key);
} | php | public function delete_index(string $table, string $key): bool
{
return $this->language->delete_index($table, $key);
} | [
"public",
"function",
"delete_index",
"(",
"string",
"$",
"table",
",",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"delete_index",
"(",
"$",
"table",
",",
"$",
"key",
")",
";",
"}"
] | Deletes index on a column of the table.
@todo far vedere a thomas perchè non funziona/return data
```php
\bbn\x::dump($db->delete_db_index('table_users','id_group'));
// (void)
```
@param string $table The table's name.
@param string $key The key's name.
@return bool | [
"Deletes",
"index",
"on",
"a",
"column",
"of",
"the",
"table",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L4109-L4112 |
nabab/bbn | src/bbn/db.php | db.create_user | public function create_user(string $user, string $pass, string $db = null): bool
{
return $this->language->create_user($user, $pass, $db);
} | php | public function create_user(string $user, string $pass, string $db = null): bool
{
return $this->language->create_user($user, $pass, $db);
} | [
"public",
"function",
"create_user",
"(",
"string",
"$",
"user",
",",
"string",
"$",
"pass",
",",
"string",
"$",
"db",
"=",
"null",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"create_user",
"(",
"$",
"user",
",",
"$",
"pass",
",",
"$",
"db",
")",
";",
"}"
] | Creates an user for a specific db.
@todo return data
```php
\bbn\x::dump($db->create_db_user('Michael','22101980','db_example'));
// (void)
```
@param string $user
@param string $pass
@param string $db
@return bool | [
"Creates",
"an",
"user",
"for",
"a",
"specific",
"db",
".",
"@todo",
"return",
"data"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L4128-L4131 |
nabab/bbn | src/bbn/db.php | db.get_users | public function get_users(string $user = '', string $host = ''): ?array
{
return $this->language->get_users($user, $host);
} | php | public function get_users(string $user = '', string $host = ''): ?array
{
return $this->language->get_users($user, $host);
} | [
"public",
"function",
"get_users",
"(",
"string",
"$",
"user",
"=",
"''",
",",
"string",
"$",
"host",
"=",
"''",
")",
":",
"?",
"array",
"{",
"return",
"$",
"this",
"->",
"language",
"->",
"get_users",
"(",
"$",
"user",
",",
"$",
"host",
")",
";",
"}"
] | Return an array including privileges of a specific db_user or all db_users.
@todo far vedere a th la descrizione
```php
\bbn\x::dump($db->get_users('Michael'));
/* (array) [
"GRANT USAGE ON *.* TO 'Michael'@''",
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON `db_example`.* TO 'Michael'@''"
]
```
@param string $user. The user's name, without params will return all privileges of all db_users
@param string $host. The host
@return array | [
"Return",
"an",
"array",
"including",
"privileges",
"of",
"a",
"specific",
"db_user",
"or",
"all",
"db_users",
".",
"@todo",
"far",
"vedere",
"a",
"th",
"la",
"descrizione"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db.php#L4167-L4170 |
chubbyphp/chubbyphp-negotiation | src/ContentTypeNegotiator.php | ContentTypeNegotiator.negotiate | public function negotiate(Request $request)
{
if ([] === $this->supportedMediaTypes) {
return null;
}
if (!$request->hasHeader('Content-Type')) {
return null;
}
return $this->compareAgainstSupportedMediaTypes($request->getHeaderLine('Content-Type'));
} | php | public function negotiate(Request $request)
{
if ([] === $this->supportedMediaTypes) {
return null;
}
if (!$request->hasHeader('Content-Type')) {
return null;
}
return $this->compareAgainstSupportedMediaTypes($request->getHeaderLine('Content-Type'));
} | [
"public",
"function",
"negotiate",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"[",
"]",
"===",
"$",
"this",
"->",
"supportedMediaTypes",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"$",
"request",
"->",
"hasHeader",
"(",
"'Content-Type'",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"compareAgainstSupportedMediaTypes",
"(",
"$",
"request",
"->",
"getHeaderLine",
"(",
"'Content-Type'",
")",
")",
";",
"}"
] | @param Request $request
@return NegotiatedValueInterface|null | [
"@param",
"Request",
"$request"
] | train | https://github.com/chubbyphp/chubbyphp-negotiation/blob/f4f8a10f2f067ecd868db9177c81f00428c42049/src/ContentTypeNegotiator.php#L40-L51 |
chubbyphp/chubbyphp-negotiation | src/ContentTypeNegotiator.php | ContentTypeNegotiator.compareAgainstSupportedMediaTypes | private function compareAgainstSupportedMediaTypes(string $header)
{
if (false !== strpos($header, ',')) {
return null;
}
$headerValueParts = explode(';', $header);
$mediaType = trim(array_shift($headerValueParts));
$attributes = [];
foreach ($headerValueParts as $attribute) {
list($attributeKey, $attributeValue) = explode('=', $attribute);
$attributes[trim($attributeKey)] = trim($attributeValue);
}
if (in_array($mediaType, $this->supportedMediaTypes, true)) {
return new NegotiatedValue($mediaType, $attributes);
}
return null;
} | php | private function compareAgainstSupportedMediaTypes(string $header)
{
if (false !== strpos($header, ',')) {
return null;
}
$headerValueParts = explode(';', $header);
$mediaType = trim(array_shift($headerValueParts));
$attributes = [];
foreach ($headerValueParts as $attribute) {
list($attributeKey, $attributeValue) = explode('=', $attribute);
$attributes[trim($attributeKey)] = trim($attributeValue);
}
if (in_array($mediaType, $this->supportedMediaTypes, true)) {
return new NegotiatedValue($mediaType, $attributes);
}
return null;
} | [
"private",
"function",
"compareAgainstSupportedMediaTypes",
"(",
"string",
"$",
"header",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"header",
",",
"','",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"headerValueParts",
"=",
"explode",
"(",
"';'",
",",
"$",
"header",
")",
";",
"$",
"mediaType",
"=",
"trim",
"(",
"array_shift",
"(",
"$",
"headerValueParts",
")",
")",
";",
"$",
"attributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"headerValueParts",
"as",
"$",
"attribute",
")",
"{",
"list",
"(",
"$",
"attributeKey",
",",
"$",
"attributeValue",
")",
"=",
"explode",
"(",
"'='",
",",
"$",
"attribute",
")",
";",
"$",
"attributes",
"[",
"trim",
"(",
"$",
"attributeKey",
")",
"]",
"=",
"trim",
"(",
"$",
"attributeValue",
")",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"mediaType",
",",
"$",
"this",
"->",
"supportedMediaTypes",
",",
"true",
")",
")",
"{",
"return",
"new",
"NegotiatedValue",
"(",
"$",
"mediaType",
",",
"$",
"attributes",
")",
";",
"}",
"return",
"null",
";",
"}"
] | @param string $header
@return NegotiatedValueInterface|null | [
"@param",
"string",
"$header"
] | train | https://github.com/chubbyphp/chubbyphp-negotiation/blob/f4f8a10f2f067ecd868db9177c81f00428c42049/src/ContentTypeNegotiator.php#L58-L77 |
phPoirot/psr7 | HttpServerRequest.php | HttpServerRequest.getQueryParams | function getQueryParams()
{
if ($this->queryParams == null) {
$uriQuery = $this->getUri()->getQuery();
if (!empty($uriQuery))
parse_str($uriQuery, $this->queryParams);
}
return $this->queryParams;
} | php | function getQueryParams()
{
if ($this->queryParams == null) {
$uriQuery = $this->getUri()->getQuery();
if (!empty($uriQuery))
parse_str($uriQuery, $this->queryParams);
}
return $this->queryParams;
} | [
"function",
"getQueryParams",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"queryParams",
"==",
"null",
")",
"{",
"$",
"uriQuery",
"=",
"$",
"this",
"->",
"getUri",
"(",
")",
"->",
"getQuery",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"uriQuery",
")",
")",
"parse_str",
"(",
"$",
"uriQuery",
",",
"$",
"this",
"->",
"queryParams",
")",
";",
"}",
"return",
"$",
"this",
"->",
"queryParams",
";",
"}"
] | Retrieve query string arguments.
Retrieves the deserialized query string arguments, if any.
Note: the query params might not be in sync with the URI or server
params. If you need to ensure you are only getting the original
values, you may need to parse the query string from `getUri()->getQuery()`
or from the `QUERY_STRING` server param.
@return array | [
"Retrieve",
"query",
"string",
"arguments",
"."
] | train | https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpServerRequest.php#L119-L128 |
phPoirot/psr7 | HttpServerRequest.php | HttpServerRequest.withoutAttribute | function withoutAttribute($name)
{
if (! isset($this->attributes[$name]))
return clone $this;
$new = clone $this;
unset($new->attributes[$name]);
return $new;
} | php | function withoutAttribute($name)
{
if (! isset($this->attributes[$name]))
return clone $this;
$new = clone $this;
unset($new->attributes[$name]);
return $new;
} | [
"function",
"withoutAttribute",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
")",
"return",
"clone",
"$",
"this",
";",
"$",
"new",
"=",
"clone",
"$",
"this",
";",
"unset",
"(",
"$",
"new",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
";",
"return",
"$",
"new",
";",
"}"
] | Return an instance that removes the specified derived request attribute.
This method allows removing a single derived request attribute as
described in getAttributes().
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that removes
the attribute.
@see getAttributes()
@param string $name The attribute name.
@return HttpServerRequest | [
"Return",
"an",
"instance",
"that",
"removes",
"the",
"specified",
"derived",
"request",
"attribute",
"."
] | train | https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpServerRequest.php#L330-L338 |
phPoirot/psr7 | HttpServerRequest.php | HttpServerRequest._assertValidateUploadedFiles | protected function _assertValidateUploadedFiles(array $uploadedFiles)
{
foreach ($uploadedFiles as $file) {
if (is_array($file)) {
$this->_assertValidateUploadedFiles($file);
continue;
}
if (! $file instanceof UploadedFileInterface) {
throw new \InvalidArgumentException('Invalid uploaded files structure');
}
}
} | php | protected function _assertValidateUploadedFiles(array $uploadedFiles)
{
foreach ($uploadedFiles as $file) {
if (is_array($file)) {
$this->_assertValidateUploadedFiles($file);
continue;
}
if (! $file instanceof UploadedFileInterface) {
throw new \InvalidArgumentException('Invalid uploaded files structure');
}
}
} | [
"protected",
"function",
"_assertValidateUploadedFiles",
"(",
"array",
"$",
"uploadedFiles",
")",
"{",
"foreach",
"(",
"$",
"uploadedFiles",
"as",
"$",
"file",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"_assertValidateUploadedFiles",
"(",
"$",
"file",
")",
";",
"continue",
";",
"}",
"if",
"(",
"!",
"$",
"file",
"instanceof",
"UploadedFileInterface",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid uploaded files structure'",
")",
";",
"}",
"}",
"}"
] | Recursively validate the structure in an uploaded files array.
@param array $uploadedFiles
@throws \InvalidArgumentException | [
"Recursively",
"validate",
"the",
"structure",
"in",
"an",
"uploaded",
"files",
"array",
"."
] | train | https://github.com/phPoirot/psr7/blob/e90295e806dc2eb0cc422f315075f673c63a0780/HttpServerRequest.php#L366-L378 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.setLimits | public function setLimits($offset, $limit, $max = 0, $cutoff = 0)
{
$this->sphinx->setLimits($offset, $limit, $max, $cutoff);
} | php | public function setLimits($offset, $limit, $max = 0, $cutoff = 0)
{
$this->sphinx->setLimits($offset, $limit, $max, $cutoff);
} | [
"public",
"function",
"setLimits",
"(",
"$",
"offset",
",",
"$",
"limit",
",",
"$",
"max",
"=",
"0",
",",
"$",
"cutoff",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"setLimits",
"(",
"$",
"offset",
",",
"$",
"limit",
",",
"$",
"max",
",",
"$",
"cutoff",
")",
";",
"}"
] | Set limits on the range and number of results returned.
@param int $offset The number of results to seek past.
@param int $limit The number of results to return.
@param int $max The maximum number of matches to retrieve.
@param int $cutoff The cutoff to stop searching at. | [
"Set",
"limits",
"on",
"the",
"range",
"and",
"number",
"of",
"results",
"returned",
"."
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L89-L92 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.setFilter | public function setFilter($attribute, $values, $exclude = false)
{
$this->sphinx->setFilter($attribute, $values, $exclude);
} | php | public function setFilter($attribute, $values, $exclude = false)
{
$this->sphinx->setFilter($attribute, $values, $exclude);
} | [
"public",
"function",
"setFilter",
"(",
"$",
"attribute",
",",
"$",
"values",
",",
"$",
"exclude",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"setFilter",
"(",
"$",
"attribute",
",",
"$",
"values",
",",
"$",
"exclude",
")",
";",
"}"
] | Set the desired search filter.
@param string $attribute The attribute to filter.
@param array $values The values to filter.
@param bool $exclude Is this an exclusion filter? | [
"Set",
"the",
"desired",
"search",
"filter",
"."
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L116-L119 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.search | public function search($query, array $indexes, array $options = array(), $escapeQuery = true)
{
if ($escapeQuery) {
$query = $this->sphinx->escapeString($query);
}
/**
* Build the list of indexes to be queried.
*/
$indexNames = '';
foreach ($indexes as &$label) {
if (isset($this->indexes[$label])) {
$indexNames .= $this->indexes[$label] . ' ';
}
}
$indexNames = trim($indexNames);
/**
* If no valid indexes were specified, return an empty result set.
*/
if (empty($indexNames)) {
return array();
}
/**
* Set the offset and limit for the returned results.
*/
if (isset($options['result_offset']) && isset($options['result_limit'])) {
$this->sphinx->setLimits($options['result_offset'], $options['result_limit']);
}
/**
* Weight the individual fields.
*/
if (isset($options['field_weights'])) {
$this->sphinx->setFieldWeights($options['field_weights']);
}
/**
* Perform the query.
*/
$results = $this->sphinx->query($query, $indexNames);
if ($results === false || $results['status'] !== SEARCHD_OK) {
if(is_array($results) && $results['status'] === SEARCHD_WARNING) {
$errorText = $this->sphinx->getLastWarning();
} else {
$errorText = $this->sphinx->getLastError();
}
throw new \RuntimeException(sprintf(
'Searching index "%s" for "%s" failed with message "%s".',
$label,
$query,
$errorText
));
}
return $results;
} | php | public function search($query, array $indexes, array $options = array(), $escapeQuery = true)
{
if ($escapeQuery) {
$query = $this->sphinx->escapeString($query);
}
/**
* Build the list of indexes to be queried.
*/
$indexNames = '';
foreach ($indexes as &$label) {
if (isset($this->indexes[$label])) {
$indexNames .= $this->indexes[$label] . ' ';
}
}
$indexNames = trim($indexNames);
/**
* If no valid indexes were specified, return an empty result set.
*/
if (empty($indexNames)) {
return array();
}
/**
* Set the offset and limit for the returned results.
*/
if (isset($options['result_offset']) && isset($options['result_limit'])) {
$this->sphinx->setLimits($options['result_offset'], $options['result_limit']);
}
/**
* Weight the individual fields.
*/
if (isset($options['field_weights'])) {
$this->sphinx->setFieldWeights($options['field_weights']);
}
/**
* Perform the query.
*/
$results = $this->sphinx->query($query, $indexNames);
if ($results === false || $results['status'] !== SEARCHD_OK) {
if(is_array($results) && $results['status'] === SEARCHD_WARNING) {
$errorText = $this->sphinx->getLastWarning();
} else {
$errorText = $this->sphinx->getLastError();
}
throw new \RuntimeException(sprintf(
'Searching index "%s" for "%s" failed with message "%s".',
$label,
$query,
$errorText
));
}
return $results;
} | [
"public",
"function",
"search",
"(",
"$",
"query",
",",
"array",
"$",
"indexes",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
",",
"$",
"escapeQuery",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"escapeQuery",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"sphinx",
"->",
"escapeString",
"(",
"$",
"query",
")",
";",
"}",
"/**\n * Build the list of indexes to be queried.\n */",
"$",
"indexNames",
"=",
"''",
";",
"foreach",
"(",
"$",
"indexes",
"as",
"&",
"$",
"label",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"indexes",
"[",
"$",
"label",
"]",
")",
")",
"{",
"$",
"indexNames",
".=",
"$",
"this",
"->",
"indexes",
"[",
"$",
"label",
"]",
".",
"' '",
";",
"}",
"}",
"$",
"indexNames",
"=",
"trim",
"(",
"$",
"indexNames",
")",
";",
"/**\n * If no valid indexes were specified, return an empty result set.\n */",
"if",
"(",
"empty",
"(",
"$",
"indexNames",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"/**\n * Set the offset and limit for the returned results.\n */",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'result_offset'",
"]",
")",
"&&",
"isset",
"(",
"$",
"options",
"[",
"'result_limit'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"setLimits",
"(",
"$",
"options",
"[",
"'result_offset'",
"]",
",",
"$",
"options",
"[",
"'result_limit'",
"]",
")",
";",
"}",
"/**\n * Weight the individual fields.\n */",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'field_weights'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"setFieldWeights",
"(",
"$",
"options",
"[",
"'field_weights'",
"]",
")",
";",
"}",
"/**\n * Perform the query.\n */",
"$",
"results",
"=",
"$",
"this",
"->",
"sphinx",
"->",
"query",
"(",
"$",
"query",
",",
"$",
"indexNames",
")",
";",
"if",
"(",
"$",
"results",
"===",
"false",
"||",
"$",
"results",
"[",
"'status'",
"]",
"!==",
"SEARCHD_OK",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"results",
")",
"&&",
"$",
"results",
"[",
"'status'",
"]",
"===",
"SEARCHD_WARNING",
")",
"{",
"$",
"errorText",
"=",
"$",
"this",
"->",
"sphinx",
"->",
"getLastWarning",
"(",
")",
";",
"}",
"else",
"{",
"$",
"errorText",
"=",
"$",
"this",
"->",
"sphinx",
"->",
"getLastError",
"(",
")",
";",
"}",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Searching index \"%s\" for \"%s\" failed with message \"%s\".'",
",",
"$",
"label",
",",
"$",
"query",
",",
"$",
"errorText",
")",
")",
";",
"}",
"return",
"$",
"results",
";",
"}"
] | Search for the specified query string.
@param string $query The query string that we are searching for.
@param array $indexes The indexes to perform the search on.
@param array $options The options for the query.
@param bool $escapeQuery Should the query string be escaped?
@return array|bool The results of the search.
@throws \RuntimeException | [
"Search",
"for",
"the",
"specified",
"query",
"string",
"."
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L140-L200 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.addQuery | public function addQuery($query, array $indexes)
{
$indexNames = '';
foreach ($indexes as &$label) {
if (isset($this->indexes[$label])) {
$indexNames .= $this->indexes[$label] . ' ';
}
}
if (!empty($indexNames)) {
$this->sphinx->addQuery($query, $indexNames);
}
} | php | public function addQuery($query, array $indexes)
{
$indexNames = '';
foreach ($indexes as &$label) {
if (isset($this->indexes[$label])) {
$indexNames .= $this->indexes[$label] . ' ';
}
}
if (!empty($indexNames)) {
$this->sphinx->addQuery($query, $indexNames);
}
} | [
"public",
"function",
"addQuery",
"(",
"$",
"query",
",",
"array",
"$",
"indexes",
")",
"{",
"$",
"indexNames",
"=",
"''",
";",
"foreach",
"(",
"$",
"indexes",
"as",
"&",
"$",
"label",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"indexes",
"[",
"$",
"label",
"]",
")",
")",
"{",
"$",
"indexNames",
".=",
"$",
"this",
"->",
"indexes",
"[",
"$",
"label",
"]",
".",
"' '",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"indexNames",
")",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"addQuery",
"(",
"$",
"query",
",",
"$",
"indexNames",
")",
";",
"}",
"}"
] | Adds a query to a multi-query batch using current settings.
@param string $query The query string that we are searching for.
@param array $indexes The indexes to perform the search on. | [
"Adds",
"a",
"query",
"to",
"a",
"multi",
"-",
"query",
"batch",
"using",
"current",
"settings",
"."
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L208-L220 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.getSnippet | public function getSnippet($text, $index, $terms, $options = array())
{
$results = $this->getSnippets(array($text), $index, $terms, $options);
if ($results) {
return $results[0];
}
return false;
} | php | public function getSnippet($text, $index, $terms, $options = array())
{
$results = $this->getSnippets(array($text), $index, $terms, $options);
if ($results) {
return $results[0];
}
return false;
} | [
"public",
"function",
"getSnippet",
"(",
"$",
"text",
",",
"$",
"index",
",",
"$",
"terms",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"results",
"=",
"$",
"this",
"->",
"getSnippets",
"(",
"array",
"(",
"$",
"text",
")",
",",
"$",
"index",
",",
"$",
"terms",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"results",
")",
"{",
"return",
"$",
"results",
"[",
"0",
"]",
";",
"}",
"return",
"false",
";",
"}"
] | Get snippet for text
@param string $text Text to process
@param string $index Search index
@param string $terms Words for highlight
@param array $options Generate snippet option
@return string|false | [
"Get",
"snippet",
"for",
"text"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L242-L251 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.getSnippets | public function getSnippets($text, $index, $terms, $options = array())
{
return $this->sphinx->BuildExcerpts($text, $index, $terms, $options);
} | php | public function getSnippets($text, $index, $terms, $options = array())
{
return $this->sphinx->BuildExcerpts($text, $index, $terms, $options);
} | [
"public",
"function",
"getSnippets",
"(",
"$",
"text",
",",
"$",
"index",
",",
"$",
"terms",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"sphinx",
"->",
"BuildExcerpts",
"(",
"$",
"text",
",",
"$",
"index",
",",
"$",
"terms",
",",
"$",
"options",
")",
";",
"}"
] | Get snippets for array of text
@param array $text Array of text to process
@param string $index Search index
@param string $terms Words for highlight
@param array $options Generate snippet option
@return array|false | [
"Get",
"snippets",
"for",
"array",
"of",
"text"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L263-L266 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.resetAll | public function resetAll()
{
$this->sphinx->ResetFilters();
$this->sphinx->ResetGroupBy();
$this->sphinx->ResetOverrides();
$this->sphinx->SetSortMode(SPH_SORT_RELEVANCE);
$this->resetLimits();
} | php | public function resetAll()
{
$this->sphinx->ResetFilters();
$this->sphinx->ResetGroupBy();
$this->sphinx->ResetOverrides();
$this->sphinx->SetSortMode(SPH_SORT_RELEVANCE);
$this->resetLimits();
} | [
"public",
"function",
"resetAll",
"(",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"ResetFilters",
"(",
")",
";",
"$",
"this",
"->",
"sphinx",
"->",
"ResetGroupBy",
"(",
")",
";",
"$",
"this",
"->",
"sphinx",
"->",
"ResetOverrides",
"(",
")",
";",
"$",
"this",
"->",
"sphinx",
"->",
"SetSortMode",
"(",
"SPH_SORT_RELEVANCE",
")",
";",
"$",
"this",
"->",
"resetLimits",
"(",
")",
";",
"}"
] | Reset filters, group by, overrides, limits | [
"Reset",
"filters",
"group",
"by",
"overrides",
"limits"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L271-L278 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.setGeoAnchor | public function setGeoAnchor($attrLat, $attrLong, $lat, $long)
{
$this->sphinx->SetGeoAnchor($attrLat, $attrLong, $lat, $long);
} | php | public function setGeoAnchor($attrLat, $attrLong, $lat, $long)
{
$this->sphinx->SetGeoAnchor($attrLat, $attrLong, $lat, $long);
} | [
"public",
"function",
"setGeoAnchor",
"(",
"$",
"attrLat",
",",
"$",
"attrLong",
",",
"$",
"lat",
",",
"$",
"long",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"SetGeoAnchor",
"(",
"$",
"attrLat",
",",
"$",
"attrLong",
",",
"$",
"lat",
",",
"$",
"long",
")",
";",
"}"
] | Set geo anchor for geosphere distance calculations (filters and sorting)
@param string $attrLat Attribute name for latitude
@param string $attrLong Attribute name for longitude
@param float $lat Point latitude, must be in radians
@param float $long Point longitude, must be in radians
@link http://www.sanisoft.com/blog/2011/05/02/geo-distance-search-in-sphinx/ | [
"Set",
"geo",
"anchor",
"for",
"geosphere",
"distance",
"calculations",
"(",
"filters",
"and",
"sorting",
")"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L298-L301 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.setFilterFloatRange | public function setFilterFloatRange($attribute, $min, $max, $exclude = false)
{
$this->sphinx->SetFilterFloatRange($attribute, $min, $max, $exclude);
} | php | public function setFilterFloatRange($attribute, $min, $max, $exclude = false)
{
$this->sphinx->SetFilterFloatRange($attribute, $min, $max, $exclude);
} | [
"public",
"function",
"setFilterFloatRange",
"(",
"$",
"attribute",
",",
"$",
"min",
",",
"$",
"max",
",",
"$",
"exclude",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"SetFilterFloatRange",
"(",
"$",
"attribute",
",",
"$",
"min",
",",
"$",
"max",
",",
"$",
"exclude",
")",
";",
"}"
] | Set float range filter
@param string $attribute Attribute name
@param float $min Min range value
@param float $max Max range value
@param bool $exclude Is this an exclusion filter? | [
"Set",
"float",
"range",
"filter"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L311-L314 |
verdet23/SphinxSearchBundle | Services/Search/SphinxSearch.php | SphinxSearch.setFilterRange | public function setFilterRange($attribute, $min, $max, $exclude = false)
{
$this->sphinx->SetFilterRange($attribute, $min, $max, $exclude);
} | php | public function setFilterRange($attribute, $min, $max, $exclude = false)
{
$this->sphinx->SetFilterRange($attribute, $min, $max, $exclude);
} | [
"public",
"function",
"setFilterRange",
"(",
"$",
"attribute",
",",
"$",
"min",
",",
"$",
"max",
",",
"$",
"exclude",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"sphinx",
"->",
"SetFilterRange",
"(",
"$",
"attribute",
",",
"$",
"min",
",",
"$",
"max",
",",
"$",
"exclude",
")",
";",
"}"
] | Set range filter
@param string $attribute Attribute name
@param float $min Min range value
@param float $max Max range value
@param bool $exclude Is this an exclusion filter? | [
"Set",
"range",
"filter"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Search/SphinxSearch.php#L324-L327 |
websoftwares/MonologZMQHandler | src/Handler/ZMQHandler.php | ZMQHandler.write | protected function write(array $record)
{
if ($this->multipart) {
$this->zmqSocket->send($record['channel'],$this->zmqMode);
$this->zmqSocket->send($record['formatted']);
} else {
$this->zmqSocket->send($record["formatted"],$this->zmqMode);
}
} | php | protected function write(array $record)
{
if ($this->multipart) {
$this->zmqSocket->send($record['channel'],$this->zmqMode);
$this->zmqSocket->send($record['formatted']);
} else {
$this->zmqSocket->send($record["formatted"],$this->zmqMode);
}
} | [
"protected",
"function",
"write",
"(",
"array",
"$",
"record",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"multipart",
")",
"{",
"$",
"this",
"->",
"zmqSocket",
"->",
"send",
"(",
"$",
"record",
"[",
"'channel'",
"]",
",",
"$",
"this",
"->",
"zmqMode",
")",
";",
"$",
"this",
"->",
"zmqSocket",
"->",
"send",
"(",
"$",
"record",
"[",
"'formatted'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"zmqSocket",
"->",
"send",
"(",
"$",
"record",
"[",
"\"formatted\"",
"]",
",",
"$",
"this",
"->",
"zmqMode",
")",
";",
"}",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/websoftwares/MonologZMQHandler/blob/3960af4ab91610bfdaafa6d4daad26bb5c615f02/src/Handler/ZMQHandler.php#L63-L71 |
verdet23/SphinxSearchBundle | Services/Indexer/Indexer.php | Indexer.rotateAll | public function rotateAll()
{
$pb = $this->prepareProcessBuilder();
$pb->add('--all');
$indexer = $pb->getProcess();
$indexer->run();
if (strstr($indexer->getOutput(), 'FATAL:') || strstr($indexer->getOutput(), 'ERROR:')) {
throw new \RuntimeException(sprintf('Error rotating indexes: "%s".', rtrim($indexer->getOutput())));
}
} | php | public function rotateAll()
{
$pb = $this->prepareProcessBuilder();
$pb->add('--all');
$indexer = $pb->getProcess();
$indexer->run();
if (strstr($indexer->getOutput(), 'FATAL:') || strstr($indexer->getOutput(), 'ERROR:')) {
throw new \RuntimeException(sprintf('Error rotating indexes: "%s".', rtrim($indexer->getOutput())));
}
} | [
"public",
"function",
"rotateAll",
"(",
")",
"{",
"$",
"pb",
"=",
"$",
"this",
"->",
"prepareProcessBuilder",
"(",
")",
";",
"$",
"pb",
"->",
"add",
"(",
"'--all'",
")",
";",
"$",
"indexer",
"=",
"$",
"pb",
"->",
"getProcess",
"(",
")",
";",
"$",
"indexer",
"->",
"run",
"(",
")",
";",
"if",
"(",
"strstr",
"(",
"$",
"indexer",
"->",
"getOutput",
"(",
")",
",",
"'FATAL:'",
")",
"||",
"strstr",
"(",
"$",
"indexer",
"->",
"getOutput",
"(",
")",
",",
"'ERROR:'",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Error rotating indexes: \"%s\".'",
",",
"rtrim",
"(",
"$",
"indexer",
"->",
"getOutput",
"(",
")",
")",
")",
")",
";",
"}",
"}"
] | Rebuild and rotate all indexes. | [
"Rebuild",
"and",
"rotate",
"all",
"indexes",
"."
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Indexer/Indexer.php#L51-L63 |
verdet23/SphinxSearchBundle | Services/Indexer/Indexer.php | Indexer.rotate | public function rotate($indexes)
{
$pb = $this->prepareProcessBuilder();
if (is_array($indexes)) {
foreach ($indexes as &$label) {
if (isset($this->indexes[$label])) {
$pb->add($this->indexes[$label]);
}
}
} elseif (is_string($indexes)) {
if (isset($this->indexes[$indexes])) {
$pb->add($this->indexes[$indexes]);
}
} else {
throw new \RuntimeException(sprintf(
'Indexes can only be an array or string, %s given.',
gettype($indexes)
));
}
$indexer = $pb->getProcess();
$indexer->run();
if (strstr($indexer->getOutput(), 'FATAL:') || strstr($indexer->getOutput(), 'ERROR:')) {
throw new \RuntimeException(sprintf('Error rotating indexes: "%s".', rtrim($indexer->getOutput())));
}
} | php | public function rotate($indexes)
{
$pb = $this->prepareProcessBuilder();
if (is_array($indexes)) {
foreach ($indexes as &$label) {
if (isset($this->indexes[$label])) {
$pb->add($this->indexes[$label]);
}
}
} elseif (is_string($indexes)) {
if (isset($this->indexes[$indexes])) {
$pb->add($this->indexes[$indexes]);
}
} else {
throw new \RuntimeException(sprintf(
'Indexes can only be an array or string, %s given.',
gettype($indexes)
));
}
$indexer = $pb->getProcess();
$indexer->run();
if (strstr($indexer->getOutput(), 'FATAL:') || strstr($indexer->getOutput(), 'ERROR:')) {
throw new \RuntimeException(sprintf('Error rotating indexes: "%s".', rtrim($indexer->getOutput())));
}
} | [
"public",
"function",
"rotate",
"(",
"$",
"indexes",
")",
"{",
"$",
"pb",
"=",
"$",
"this",
"->",
"prepareProcessBuilder",
"(",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"indexes",
")",
")",
"{",
"foreach",
"(",
"$",
"indexes",
"as",
"&",
"$",
"label",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"indexes",
"[",
"$",
"label",
"]",
")",
")",
"{",
"$",
"pb",
"->",
"add",
"(",
"$",
"this",
"->",
"indexes",
"[",
"$",
"label",
"]",
")",
";",
"}",
"}",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"indexes",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"indexes",
"[",
"$",
"indexes",
"]",
")",
")",
"{",
"$",
"pb",
"->",
"add",
"(",
"$",
"this",
"->",
"indexes",
"[",
"$",
"indexes",
"]",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Indexes can only be an array or string, %s given.'",
",",
"gettype",
"(",
"$",
"indexes",
")",
")",
")",
";",
"}",
"$",
"indexer",
"=",
"$",
"pb",
"->",
"getProcess",
"(",
")",
";",
"$",
"indexer",
"->",
"run",
"(",
")",
";",
"if",
"(",
"strstr",
"(",
"$",
"indexer",
"->",
"getOutput",
"(",
")",
",",
"'FATAL:'",
")",
"||",
"strstr",
"(",
"$",
"indexer",
"->",
"getOutput",
"(",
")",
",",
"'ERROR:'",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Error rotating indexes: \"%s\".'",
",",
"rtrim",
"(",
"$",
"indexer",
"->",
"getOutput",
"(",
")",
")",
")",
")",
";",
"}",
"}"
] | Rebuild and rotate the specified index(es).
@param array|string $indexes The index(es) to rotate.
@throws \RuntimeException | [
"Rebuild",
"and",
"rotate",
"the",
"specified",
"index",
"(",
"es",
")",
"."
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Indexer/Indexer.php#L72-L100 |
verdet23/SphinxSearchBundle | Services/Indexer/Indexer.php | Indexer.prepareProcessBuilder | protected function prepareProcessBuilder()
{
$pb = new ProcessBuilder();
$pb->inheritEnvironmentVariables();
if ($this->sudo) {
$pb->add('sudo');
}
$pb->add($this->bin);
if ($this->config) {
$pb->add('--config')
->add($this->config);
}
$pb->add('--rotate');
return $pb;
} | php | protected function prepareProcessBuilder()
{
$pb = new ProcessBuilder();
$pb->inheritEnvironmentVariables();
if ($this->sudo) {
$pb->add('sudo');
}
$pb->add($this->bin);
if ($this->config) {
$pb->add('--config')
->add($this->config);
}
$pb->add('--rotate');
return $pb;
} | [
"protected",
"function",
"prepareProcessBuilder",
"(",
")",
"{",
"$",
"pb",
"=",
"new",
"ProcessBuilder",
"(",
")",
";",
"$",
"pb",
"->",
"inheritEnvironmentVariables",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"sudo",
")",
"{",
"$",
"pb",
"->",
"add",
"(",
"'sudo'",
")",
";",
"}",
"$",
"pb",
"->",
"add",
"(",
"$",
"this",
"->",
"bin",
")",
";",
"if",
"(",
"$",
"this",
"->",
"config",
")",
"{",
"$",
"pb",
"->",
"add",
"(",
"'--config'",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"config",
")",
";",
"}",
"$",
"pb",
"->",
"add",
"(",
"'--rotate'",
")",
";",
"return",
"$",
"pb",
";",
"}"
] | Prepare process builder
@return ProcessBuilder | [
"Prepare",
"process",
"builder"
] | train | https://github.com/verdet23/SphinxSearchBundle/blob/6452cc3a5fab83647b6c08574164249fb8f03b05/Services/Indexer/Indexer.php#L129-L146 |
skeeks-cms/cms-import-csv-shop-content | src/ImportCsvShopContentHandler.php | ImportCsvShopContentHandler.getChildrenColumnNumber | public function getChildrenColumnNumber($code)
{
if (in_array($code, $this->matchingChild))
{
foreach ($this->matchingChild as $number => $codeValue)
{
if ($codeValue == $code)
{
return (int) $number;
}
}
}
return null;
} | php | public function getChildrenColumnNumber($code)
{
if (in_array($code, $this->matchingChild))
{
foreach ($this->matchingChild as $number => $codeValue)
{
if ($codeValue == $code)
{
return (int) $number;
}
}
}
return null;
} | [
"public",
"function",
"getChildrenColumnNumber",
"(",
"$",
"code",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"code",
",",
"$",
"this",
"->",
"matchingChild",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"matchingChild",
"as",
"$",
"number",
"=>",
"$",
"codeValue",
")",
"{",
"if",
"(",
"$",
"codeValue",
"==",
"$",
"code",
")",
"{",
"return",
"(",
"int",
")",
"$",
"number",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | @param $code
@return int|null | [
"@param",
"$code"
] | train | https://github.com/skeeks-cms/cms-import-csv-shop-content/blob/9a523f92f6a2d03161a98c3098abfb6b01e60f53/src/ImportCsvShopContentHandler.php#L228-L242 |
skeeks-cms/cms-import-csv-shop-content | src/ImportCsvShopContentHandler.php | ImportCsvShopContentHandler.getChildrenValue | public function getChildrenValue($code, $row = [])
{
$number = $this->getChildrenColumnNumber($code);
if ($number !== null)
{
return $row[$number];
}
return null;
} | php | public function getChildrenValue($code, $row = [])
{
$number = $this->getChildrenColumnNumber($code);
if ($number !== null)
{
return $row[$number];
}
return null;
} | [
"public",
"function",
"getChildrenValue",
"(",
"$",
"code",
",",
"$",
"row",
"=",
"[",
"]",
")",
"{",
"$",
"number",
"=",
"$",
"this",
"->",
"getChildrenColumnNumber",
"(",
"$",
"code",
")",
";",
"if",
"(",
"$",
"number",
"!==",
"null",
")",
"{",
"return",
"$",
"row",
"[",
"$",
"number",
"]",
";",
"}",
"return",
"null",
";",
"}"
] | @param $code
@param array $row
@return null | [
"@param",
"$code",
"@param",
"array",
"$row"
] | train | https://github.com/skeeks-cms/cms-import-csv-shop-content/blob/9a523f92f6a2d03161a98c3098abfb6b01e60f53/src/ImportCsvShopContentHandler.php#L250-L260 |
skeeks-cms/cms-import-csv-shop-content | src/ImportCsvShopContentHandler.php | ImportCsvShopContentHandler.import | public function import($number, $row)
{
$result = new CsvImportRowResult();
/**
* @var $element ShopCmsContentElement
*/
try
{
$isUpdate = false;
$element = null;
$isChildren = false;
//Если есть настроен дочерний контент, если задано поле связи с родителем, и поле задано у родителя
if ($this->matchingChild && $this->parentRelationField && $this->getChildrenColumnNumber('relation') !== null)
{
//Эта строка торговое предложение
if ($relation = $this->getChildrenValue('relation', $row))
{
$isChildren = true;
}
}
if ($isChildren)
{
$isUpdate = false;
$element = $this->_initElement($number, $row, $this->childrenCmsContent->id, ShopCmsContentElement::className());
if (!$element->isNewRecord)
{
$isUpdate = true;
} else
{
//Нужно свзять предложение с товаром
$relationValue = $this->getChildrenValue('relation', $row);
$parentElement = $this->getElement($this->parentRelationField, $relationValue);
if (!$parentElement)
{
throw new Exception('Торговое предложение, не найден товар к которому привязать.');
} else
{
$element->parent_content_element_id = $parentElement->id;
$element->name = $parentElement->name;
}
}
foreach ($this->matchingChild as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
$this->_initModelByField($element, $fieldName, $row[$number]);
}
}
$relation = $this->getChildrenValue('relation', $row);
$element->validate();
//$element->relatedPropertiesModel->validate();
if (!$element->errors && !$element->relatedPropertiesModel->errors)
{
$element->save();
if (!$element->relatedPropertiesModel->save(false))
{
throw new Exception('Не сохранены дополнительные данные');
};
$imageUrl = $this->getValue('image', $row);
if ($imageUrl && !$element->image)
{
$file = \Yii::$app->storage->upload($imageUrl, [
'name' => $element->name
]);
$element->link('image', $file);
}
$shopProduct = $element->shopProduct;
if (!$shopProduct)
{
$shopProduct = new ShopProduct();
$shopProduct->baseProductPriceValue = 0;
$shopProduct->baseProductPriceCurrency = "RUB";
$shopProduct->id = $element->id;
$shopProduct->product_type = ShopProduct::TYPE_OFFERS;
$shopProduct->save();
}
foreach ($this->matchingChild as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
try
{
$this->_initModelByFieldAfterSave($element, $fieldName, $row[$number]);
} catch (\Exception $e)
{
throw new Exception('Ошибка созранения поля: ' . $fieldName . $e->getMessage());
}
}
}
$result->message = $isUpdate === true ? "Торговое предложение обновлено" : 'Торговое предложение создано' ;
$rp = $element->relatedPropertiesModel;
$rp->initAllProperties();
$rp = Json::encode($rp->toArray());
//$rp = '';
$result->html = <<<HTML
Товар: <a href="{$element->parentContentElement->url}" data-pjax="0" target="_blank">{$element->parentContentElement->id} (предложение: {$element->id})</a> $rp
HTML;
} else
{
$result->success = false;
$result->message = 'Ошибка';
$result->html = Json::encode($element->errors) . "<br />" . Json::encode($element->relatedPropertiesModel->errors);
}
} else
{
$isUpdate = false;
$element = $this->_initElement($number, $row, $this->content_id, ShopCmsContentElement::className());
foreach ($this->matching as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
$this->_initModelByField($element, $fieldName, $row[$number]);
}
}
if (!$element->isNewRecord)
{
$isUpdate = true;
}
$element->validate();
//$element->relatedPropertiesModel->validate();
if (!$element->errors && !$element->relatedPropertiesModel->errors)
{
/*print_r($element->toArray());
print_r((new \ReflectionClass($element))->getName());
die();*/
$element->save();
if (!$element->relatedPropertiesModel->save(false))
{
throw new Exception('Не сохранены дополнительные данные');
};
$imageUrl = $this->getValue('image', $row);
if ($imageUrl && !$element->image)
{
$file = \Yii::$app->storage->upload($imageUrl, [
'name' => $element->name
]);
$element->link('image', $file);
}
$shopProduct = $element->shopProduct;
if (!$shopProduct)
{
$shopProduct = new ShopProduct();
$shopProduct->baseProductPriceValue = 0;
$shopProduct->baseProductPriceCurrency = "RUB";
$shopProduct->id = $element->id;
$shopProduct->product_type = ShopProduct::TYPE_OFFERS;
$shopProduct->save();
}
$element->refresh();
foreach ($this->matching as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
try
{
$this->_initModelByFieldAfterSave($element, $fieldName, $row[$number]);
} catch (\Exception $e)
{
throw new Exception('Ошибка сохранения поля: ' . $fieldName . ": " . $e->getMessage());
}
}
}
$result->message = $isUpdate === true ? "Товар обновлен" : 'Товар создан' ;
$element->relatedPropertiesModel->initAllProperties();
$rp = Json::encode($element->relatedPropertiesModel->toArray());
$rp = '';
$result->html = <<<HTML
Товар: <a href="{$element->url}" data-pjax="0" target="_blank">{$element->id}</a> $rp
HTML;
} else
{
$result->success = false;
$result->message = 'Ошибка';
$result->html = Json::encode($element->errors) . "<br />" . Json::encode($element->relatedPropertiesModel->errors);
}
}
unset($element);
} catch (\Exception $e)
{
throw $e;
$result->success = false;
$result->message = "Ошибка: " . $e->getMessage();
}
return $result;
} | php | public function import($number, $row)
{
$result = new CsvImportRowResult();
/**
* @var $element ShopCmsContentElement
*/
try
{
$isUpdate = false;
$element = null;
$isChildren = false;
//Если есть настроен дочерний контент, если задано поле связи с родителем, и поле задано у родителя
if ($this->matchingChild && $this->parentRelationField && $this->getChildrenColumnNumber('relation') !== null)
{
//Эта строка торговое предложение
if ($relation = $this->getChildrenValue('relation', $row))
{
$isChildren = true;
}
}
if ($isChildren)
{
$isUpdate = false;
$element = $this->_initElement($number, $row, $this->childrenCmsContent->id, ShopCmsContentElement::className());
if (!$element->isNewRecord)
{
$isUpdate = true;
} else
{
//Нужно свзять предложение с товаром
$relationValue = $this->getChildrenValue('relation', $row);
$parentElement = $this->getElement($this->parentRelationField, $relationValue);
if (!$parentElement)
{
throw new Exception('Торговое предложение, не найден товар к которому привязать.');
} else
{
$element->parent_content_element_id = $parentElement->id;
$element->name = $parentElement->name;
}
}
foreach ($this->matchingChild as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
$this->_initModelByField($element, $fieldName, $row[$number]);
}
}
$relation = $this->getChildrenValue('relation', $row);
$element->validate();
//$element->relatedPropertiesModel->validate();
if (!$element->errors && !$element->relatedPropertiesModel->errors)
{
$element->save();
if (!$element->relatedPropertiesModel->save(false))
{
throw new Exception('Не сохранены дополнительные данные');
};
$imageUrl = $this->getValue('image', $row);
if ($imageUrl && !$element->image)
{
$file = \Yii::$app->storage->upload($imageUrl, [
'name' => $element->name
]);
$element->link('image', $file);
}
$shopProduct = $element->shopProduct;
if (!$shopProduct)
{
$shopProduct = new ShopProduct();
$shopProduct->baseProductPriceValue = 0;
$shopProduct->baseProductPriceCurrency = "RUB";
$shopProduct->id = $element->id;
$shopProduct->product_type = ShopProduct::TYPE_OFFERS;
$shopProduct->save();
}
foreach ($this->matchingChild as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
try
{
$this->_initModelByFieldAfterSave($element, $fieldName, $row[$number]);
} catch (\Exception $e)
{
throw new Exception('Ошибка созранения поля: ' . $fieldName . $e->getMessage());
}
}
}
$result->message = $isUpdate === true ? "Торговое предложение обновлено" : 'Торговое предложение создано' ;
$rp = $element->relatedPropertiesModel;
$rp->initAllProperties();
$rp = Json::encode($rp->toArray());
//$rp = '';
$result->html = <<<HTML
Товар: <a href="{$element->parentContentElement->url}" data-pjax="0" target="_blank">{$element->parentContentElement->id} (предложение: {$element->id})</a> $rp
HTML;
} else
{
$result->success = false;
$result->message = 'Ошибка';
$result->html = Json::encode($element->errors) . "<br />" . Json::encode($element->relatedPropertiesModel->errors);
}
} else
{
$isUpdate = false;
$element = $this->_initElement($number, $row, $this->content_id, ShopCmsContentElement::className());
foreach ($this->matching as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
$this->_initModelByField($element, $fieldName, $row[$number]);
}
}
if (!$element->isNewRecord)
{
$isUpdate = true;
}
$element->validate();
//$element->relatedPropertiesModel->validate();
if (!$element->errors && !$element->relatedPropertiesModel->errors)
{
/*print_r($element->toArray());
print_r((new \ReflectionClass($element))->getName());
die();*/
$element->save();
if (!$element->relatedPropertiesModel->save(false))
{
throw new Exception('Не сохранены дополнительные данные');
};
$imageUrl = $this->getValue('image', $row);
if ($imageUrl && !$element->image)
{
$file = \Yii::$app->storage->upload($imageUrl, [
'name' => $element->name
]);
$element->link('image', $file);
}
$shopProduct = $element->shopProduct;
if (!$shopProduct)
{
$shopProduct = new ShopProduct();
$shopProduct->baseProductPriceValue = 0;
$shopProduct->baseProductPriceCurrency = "RUB";
$shopProduct->id = $element->id;
$shopProduct->product_type = ShopProduct::TYPE_OFFERS;
$shopProduct->save();
}
$element->refresh();
foreach ($this->matching as $number => $fieldName)
{
//Выбрано соответствие
if ($fieldName)
{
try
{
$this->_initModelByFieldAfterSave($element, $fieldName, $row[$number]);
} catch (\Exception $e)
{
throw new Exception('Ошибка сохранения поля: ' . $fieldName . ": " . $e->getMessage());
}
}
}
$result->message = $isUpdate === true ? "Товар обновлен" : 'Товар создан' ;
$element->relatedPropertiesModel->initAllProperties();
$rp = Json::encode($element->relatedPropertiesModel->toArray());
$rp = '';
$result->html = <<<HTML
Товар: <a href="{$element->url}" data-pjax="0" target="_blank">{$element->id}</a> $rp
HTML;
} else
{
$result->success = false;
$result->message = 'Ошибка';
$result->html = Json::encode($element->errors) . "<br />" . Json::encode($element->relatedPropertiesModel->errors);
}
}
unset($element);
} catch (\Exception $e)
{
throw $e;
$result->success = false;
$result->message = "Ошибка: " . $e->getMessage();
}
return $result;
} | [
"public",
"function",
"import",
"(",
"$",
"number",
",",
"$",
"row",
")",
"{",
"$",
"result",
"=",
"new",
"CsvImportRowResult",
"(",
")",
";",
"/**\n * @var $element ShopCmsContentElement\n */",
"try",
"{",
"$",
"isUpdate",
"=",
"false",
";",
"$",
"element",
"=",
"null",
";",
"$",
"isChildren",
"=",
"false",
";",
"//Если есть настроен дочерний контент, если задано поле связи с родителем, и поле задано у родителя",
"if",
"(",
"$",
"this",
"->",
"matchingChild",
"&&",
"$",
"this",
"->",
"parentRelationField",
"&&",
"$",
"this",
"->",
"getChildrenColumnNumber",
"(",
"'relation'",
")",
"!==",
"null",
")",
"{",
"//Эта строка торговое предложение",
"if",
"(",
"$",
"relation",
"=",
"$",
"this",
"->",
"getChildrenValue",
"(",
"'relation'",
",",
"$",
"row",
")",
")",
"{",
"$",
"isChildren",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"$",
"isChildren",
")",
"{",
"$",
"isUpdate",
"=",
"false",
";",
"$",
"element",
"=",
"$",
"this",
"->",
"_initElement",
"(",
"$",
"number",
",",
"$",
"row",
",",
"$",
"this",
"->",
"childrenCmsContent",
"->",
"id",
",",
"ShopCmsContentElement",
"::",
"className",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"element",
"->",
"isNewRecord",
")",
"{",
"$",
"isUpdate",
"=",
"true",
";",
"}",
"else",
"{",
"//Нужно свзять предложение с товаром",
"$",
"relationValue",
"=",
"$",
"this",
"->",
"getChildrenValue",
"(",
"'relation'",
",",
"$",
"row",
")",
";",
"$",
"parentElement",
"=",
"$",
"this",
"->",
"getElement",
"(",
"$",
"this",
"->",
"parentRelationField",
",",
"$",
"relationValue",
")",
";",
"if",
"(",
"!",
"$",
"parentElement",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Торговое предложение, не найден товар к которому привязать.');",
"",
"",
"}",
"else",
"{",
"$",
"element",
"->",
"parent_content_element_id",
"=",
"$",
"parentElement",
"->",
"id",
";",
"$",
"element",
"->",
"name",
"=",
"$",
"parentElement",
"->",
"name",
";",
"}",
"}",
"foreach",
"(",
"$",
"this",
"->",
"matchingChild",
"as",
"$",
"number",
"=>",
"$",
"fieldName",
")",
"{",
"//Выбрано соответствие",
"if",
"(",
"$",
"fieldName",
")",
"{",
"$",
"this",
"->",
"_initModelByField",
"(",
"$",
"element",
",",
"$",
"fieldName",
",",
"$",
"row",
"[",
"$",
"number",
"]",
")",
";",
"}",
"}",
"$",
"relation",
"=",
"$",
"this",
"->",
"getChildrenValue",
"(",
"'relation'",
",",
"$",
"row",
")",
";",
"$",
"element",
"->",
"validate",
"(",
")",
";",
"//$element->relatedPropertiesModel->validate();",
"if",
"(",
"!",
"$",
"element",
"->",
"errors",
"&&",
"!",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"errors",
")",
"{",
"$",
"element",
"->",
"save",
"(",
")",
";",
"if",
"(",
"!",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"save",
"(",
"false",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Не сохранены дополнительные данные');",
"",
"",
"}",
";",
"$",
"imageUrl",
"=",
"$",
"this",
"->",
"getValue",
"(",
"'image'",
",",
"$",
"row",
")",
";",
"if",
"(",
"$",
"imageUrl",
"&&",
"!",
"$",
"element",
"->",
"image",
")",
"{",
"$",
"file",
"=",
"\\",
"Yii",
"::",
"$",
"app",
"->",
"storage",
"->",
"upload",
"(",
"$",
"imageUrl",
",",
"[",
"'name'",
"=>",
"$",
"element",
"->",
"name",
"]",
")",
";",
"$",
"element",
"->",
"link",
"(",
"'image'",
",",
"$",
"file",
")",
";",
"}",
"$",
"shopProduct",
"=",
"$",
"element",
"->",
"shopProduct",
";",
"if",
"(",
"!",
"$",
"shopProduct",
")",
"{",
"$",
"shopProduct",
"=",
"new",
"ShopProduct",
"(",
")",
";",
"$",
"shopProduct",
"->",
"baseProductPriceValue",
"=",
"0",
";",
"$",
"shopProduct",
"->",
"baseProductPriceCurrency",
"=",
"\"RUB\"",
";",
"$",
"shopProduct",
"->",
"id",
"=",
"$",
"element",
"->",
"id",
";",
"$",
"shopProduct",
"->",
"product_type",
"=",
"ShopProduct",
"::",
"TYPE_OFFERS",
";",
"$",
"shopProduct",
"->",
"save",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"matchingChild",
"as",
"$",
"number",
"=>",
"$",
"fieldName",
")",
"{",
"//Выбрано соответствие",
"if",
"(",
"$",
"fieldName",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"_initModelByFieldAfterSave",
"(",
"$",
"element",
",",
"$",
"fieldName",
",",
"$",
"row",
"[",
"$",
"number",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Ошибка созранения поля: ' . $fieldName . $e->",
"e",
"M",
"essage())",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"}",
"}",
"}",
"$",
"result",
"->",
"message",
"=",
"$",
"isUpdate",
"===",
"true",
"?",
"\"Торговое предложение обновлено\" : 'Торговое предложение соз",
"а",
"о' ;",
"",
"$",
"rp",
"=",
"$",
"element",
"->",
"relatedPropertiesModel",
";",
"$",
"rp",
"->",
"initAllProperties",
"(",
")",
";",
"$",
"rp",
"=",
"Json",
"::",
"encode",
"(",
"$",
"rp",
"->",
"toArray",
"(",
")",
")",
";",
"//$rp = '';",
"$",
"result",
"->",
"html",
"=",
" <<<HTML\n Товар: <a href=\"{$element->parentContentElement->url}\" data-pjax=\"0\" target=\"_blank\">{$element->parentContentElement->id} (предложение: {$element->id})</a> $rp\nHTML",
";",
"}",
"else",
"{",
"$",
"result",
"->",
"success",
"=",
"false",
";",
"$",
"result",
"->",
"message",
"=",
"'Ошибка';",
"",
"$",
"result",
"->",
"html",
"=",
"Json",
"::",
"encode",
"(",
"$",
"element",
"->",
"errors",
")",
".",
"\"<br />\"",
".",
"Json",
"::",
"encode",
"(",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"errors",
")",
";",
"}",
"}",
"else",
"{",
"$",
"isUpdate",
"=",
"false",
";",
"$",
"element",
"=",
"$",
"this",
"->",
"_initElement",
"(",
"$",
"number",
",",
"$",
"row",
",",
"$",
"this",
"->",
"content_id",
",",
"ShopCmsContentElement",
"::",
"className",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"matching",
"as",
"$",
"number",
"=>",
"$",
"fieldName",
")",
"{",
"//Выбрано соответствие",
"if",
"(",
"$",
"fieldName",
")",
"{",
"$",
"this",
"->",
"_initModelByField",
"(",
"$",
"element",
",",
"$",
"fieldName",
",",
"$",
"row",
"[",
"$",
"number",
"]",
")",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"element",
"->",
"isNewRecord",
")",
"{",
"$",
"isUpdate",
"=",
"true",
";",
"}",
"$",
"element",
"->",
"validate",
"(",
")",
";",
"//$element->relatedPropertiesModel->validate();",
"if",
"(",
"!",
"$",
"element",
"->",
"errors",
"&&",
"!",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"errors",
")",
"{",
"/*print_r($element->toArray());\nprint_r((new \\ReflectionClass($element))->getName());\n die();*/",
"$",
"element",
"->",
"save",
"(",
")",
";",
"if",
"(",
"!",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"save",
"(",
"false",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Не сохранены дополнительные данные');",
"",
"",
"}",
";",
"$",
"imageUrl",
"=",
"$",
"this",
"->",
"getValue",
"(",
"'image'",
",",
"$",
"row",
")",
";",
"if",
"(",
"$",
"imageUrl",
"&&",
"!",
"$",
"element",
"->",
"image",
")",
"{",
"$",
"file",
"=",
"\\",
"Yii",
"::",
"$",
"app",
"->",
"storage",
"->",
"upload",
"(",
"$",
"imageUrl",
",",
"[",
"'name'",
"=>",
"$",
"element",
"->",
"name",
"]",
")",
";",
"$",
"element",
"->",
"link",
"(",
"'image'",
",",
"$",
"file",
")",
";",
"}",
"$",
"shopProduct",
"=",
"$",
"element",
"->",
"shopProduct",
";",
"if",
"(",
"!",
"$",
"shopProduct",
")",
"{",
"$",
"shopProduct",
"=",
"new",
"ShopProduct",
"(",
")",
";",
"$",
"shopProduct",
"->",
"baseProductPriceValue",
"=",
"0",
";",
"$",
"shopProduct",
"->",
"baseProductPriceCurrency",
"=",
"\"RUB\"",
";",
"$",
"shopProduct",
"->",
"id",
"=",
"$",
"element",
"->",
"id",
";",
"$",
"shopProduct",
"->",
"product_type",
"=",
"ShopProduct",
"::",
"TYPE_OFFERS",
";",
"$",
"shopProduct",
"->",
"save",
"(",
")",
";",
"}",
"$",
"element",
"->",
"refresh",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"matching",
"as",
"$",
"number",
"=>",
"$",
"fieldName",
")",
"{",
"//Выбрано соответствие",
"if",
"(",
"$",
"fieldName",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"_initModelByFieldAfterSave",
"(",
"$",
"element",
",",
"$",
"fieldName",
",",
"$",
"row",
"[",
"$",
"number",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Ошибка сохранения поля: ' . $fieldName . \": \"",
".",
"$",
"e->getMes",
"a",
"e())",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"}",
"}",
"}",
"$",
"result",
"->",
"message",
"=",
"$",
"isUpdate",
"===",
"true",
"?",
"\"Товар обновлен\" : 'Товар соз",
"а",
"' ;",
"",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"initAllProperties",
"(",
")",
";",
"$",
"rp",
"=",
"Json",
"::",
"encode",
"(",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"toArray",
"(",
")",
")",
";",
"$",
"rp",
"=",
"''",
";",
"$",
"result",
"->",
"html",
"=",
" <<<HTML\n Товар: <a href=\"{$element->url}\" data-pjax=\"0\" target=\"_blank\">{$element->id}</a> $rp\nHTML",
";",
"}",
"else",
"{",
"$",
"result",
"->",
"success",
"=",
"false",
";",
"$",
"result",
"->",
"message",
"=",
"'Ошибка';",
"",
"$",
"result",
"->",
"html",
"=",
"Json",
"::",
"encode",
"(",
"$",
"element",
"->",
"errors",
")",
".",
"\"<br />\"",
".",
"Json",
"::",
"encode",
"(",
"$",
"element",
"->",
"relatedPropertiesModel",
"->",
"errors",
")",
";",
"}",
"}",
"unset",
"(",
"$",
"element",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"$",
"e",
";",
"$",
"result",
"->",
"success",
"=",
"false",
";",
"$",
"result",
"->",
"message",
"=",
"\"Ошибка: \" . $e-",
"g",
"t",
"M",
"es",
"sage();",
"",
"",
"",
"}",
"return",
"$",
"result",
";",
"}"
] | @param $number
@param $row
@return CsvImportRowResult | [
"@param",
"$number",
"@param",
"$row"
] | train | https://github.com/skeeks-cms/cms-import-csv-shop-content/blob/9a523f92f6a2d03161a98c3098abfb6b01e60f53/src/ImportCsvShopContentHandler.php#L347-L583 |
heidelpay/PhpDoc | src/phpDocumentor/Descriptor/Builder/Reflector/ArgumentAssembler.php | ArgumentAssembler.create | public function create($data, $params = array())
{
$argumentDescriptor = new ArgumentDescriptor();
$argumentDescriptor->setName($data->getName());
$argumentDescriptor->setTypes(
$this->builder->buildDescriptor(
$data->getType() ? new Collection(array($data->getType())) : new Collection()
)
);
foreach ($params as $paramDescriptor) {
$this->overwriteTypeAndDescriptionFromParamTag($data, $paramDescriptor, $argumentDescriptor);
}
$argumentDescriptor->setDefault($data->getDefault());
$argumentDescriptor->setByReference($data->isByRef());
return $argumentDescriptor;
} | php | public function create($data, $params = array())
{
$argumentDescriptor = new ArgumentDescriptor();
$argumentDescriptor->setName($data->getName());
$argumentDescriptor->setTypes(
$this->builder->buildDescriptor(
$data->getType() ? new Collection(array($data->getType())) : new Collection()
)
);
foreach ($params as $paramDescriptor) {
$this->overwriteTypeAndDescriptionFromParamTag($data, $paramDescriptor, $argumentDescriptor);
}
$argumentDescriptor->setDefault($data->getDefault());
$argumentDescriptor->setByReference($data->isByRef());
return $argumentDescriptor;
} | [
"public",
"function",
"create",
"(",
"$",
"data",
",",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"argumentDescriptor",
"=",
"new",
"ArgumentDescriptor",
"(",
")",
";",
"$",
"argumentDescriptor",
"->",
"setName",
"(",
"$",
"data",
"->",
"getName",
"(",
")",
")",
";",
"$",
"argumentDescriptor",
"->",
"setTypes",
"(",
"$",
"this",
"->",
"builder",
"->",
"buildDescriptor",
"(",
"$",
"data",
"->",
"getType",
"(",
")",
"?",
"new",
"Collection",
"(",
"array",
"(",
"$",
"data",
"->",
"getType",
"(",
")",
")",
")",
":",
"new",
"Collection",
"(",
")",
")",
")",
";",
"foreach",
"(",
"$",
"params",
"as",
"$",
"paramDescriptor",
")",
"{",
"$",
"this",
"->",
"overwriteTypeAndDescriptionFromParamTag",
"(",
"$",
"data",
",",
"$",
"paramDescriptor",
",",
"$",
"argumentDescriptor",
")",
";",
"}",
"$",
"argumentDescriptor",
"->",
"setDefault",
"(",
"$",
"data",
"->",
"getDefault",
"(",
")",
")",
";",
"$",
"argumentDescriptor",
"->",
"setByReference",
"(",
"$",
"data",
"->",
"isByRef",
"(",
")",
")",
";",
"return",
"$",
"argumentDescriptor",
";",
"}"
] | Creates a Descriptor from the provided data.
@param ArgumentReflector $data
@param ParamDescriptor[] $params
@return ArgumentDescriptor | [
"Creates",
"a",
"Descriptor",
"from",
"the",
"provided",
"data",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/Builder/Reflector/ArgumentAssembler.php#L32-L50 |
heidelpay/PhpDoc | src/phpDocumentor/Descriptor/Builder/Reflector/ArgumentAssembler.php | ArgumentAssembler.overwriteTypeAndDescriptionFromParamTag | protected function overwriteTypeAndDescriptionFromParamTag(
ArgumentReflector $argument,
ParamDescriptor $paramDescriptor,
ArgumentDescriptor $argumentDescriptor
) {
if ($paramDescriptor->getVariableName() != $argument->getName()) {
return;
}
$argumentDescriptor->setDescription($paramDescriptor->getDescription());
$argumentDescriptor->setTypes(
$paramDescriptor->getTypes() ?: $this->builder->buildDescriptor(
new Collection(array($argument->getType() ?: 'mixed'))
)
);
} | php | protected function overwriteTypeAndDescriptionFromParamTag(
ArgumentReflector $argument,
ParamDescriptor $paramDescriptor,
ArgumentDescriptor $argumentDescriptor
) {
if ($paramDescriptor->getVariableName() != $argument->getName()) {
return;
}
$argumentDescriptor->setDescription($paramDescriptor->getDescription());
$argumentDescriptor->setTypes(
$paramDescriptor->getTypes() ?: $this->builder->buildDescriptor(
new Collection(array($argument->getType() ?: 'mixed'))
)
);
} | [
"protected",
"function",
"overwriteTypeAndDescriptionFromParamTag",
"(",
"ArgumentReflector",
"$",
"argument",
",",
"ParamDescriptor",
"$",
"paramDescriptor",
",",
"ArgumentDescriptor",
"$",
"argumentDescriptor",
")",
"{",
"if",
"(",
"$",
"paramDescriptor",
"->",
"getVariableName",
"(",
")",
"!=",
"$",
"argument",
"->",
"getName",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"argumentDescriptor",
"->",
"setDescription",
"(",
"$",
"paramDescriptor",
"->",
"getDescription",
"(",
")",
")",
";",
"$",
"argumentDescriptor",
"->",
"setTypes",
"(",
"$",
"paramDescriptor",
"->",
"getTypes",
"(",
")",
"?",
":",
"$",
"this",
"->",
"builder",
"->",
"buildDescriptor",
"(",
"new",
"Collection",
"(",
"array",
"(",
"$",
"argument",
"->",
"getType",
"(",
")",
"?",
":",
"'mixed'",
")",
")",
")",
")",
";",
"}"
] | Overwrites the type and description in the Argument Descriptor with that from the tag if the names match.
@param ArgumentReflector $argument
@param ParamDescriptor $paramDescriptor
@param ArgumentDescriptor $argumentDescriptor
@return void | [
"Overwrites",
"the",
"type",
"and",
"description",
"in",
"the",
"Argument",
"Descriptor",
"with",
"that",
"from",
"the",
"tag",
"if",
"the",
"names",
"match",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/Builder/Reflector/ArgumentAssembler.php#L61-L76 |
zhouyl/mellivora | Mellivora/Database/Migrations/Migrator.php | Migrator.runUp | protected function runUp($file, $batch, $pretend)
{
// First we will resolve a "real" instance of the migration class from this
// migration file name. Once we have the instances we can run the actual
// command such as "up" or "down", or we can just simulate the action.
$migration = $this->resolve(
$name = $this->getMigrationName($file)
);
if ($pretend) {
return $this->pretendToRun($migration, 'up');
}
$this->runMigration($migration, 'up');
// Once we have run a migrations class, we will log that it was run in this
// repository so that we don't try to run it next time we do a migration
// in the application. A migration repository keeps the migrate order.
$this->repository->log($name, $batch);
$this->note("<info>Migrated:</info> {$name}");
} | php | protected function runUp($file, $batch, $pretend)
{
// First we will resolve a "real" instance of the migration class from this
// migration file name. Once we have the instances we can run the actual
// command such as "up" or "down", or we can just simulate the action.
$migration = $this->resolve(
$name = $this->getMigrationName($file)
);
if ($pretend) {
return $this->pretendToRun($migration, 'up');
}
$this->runMigration($migration, 'up');
// Once we have run a migrations class, we will log that it was run in this
// repository so that we don't try to run it next time we do a migration
// in the application. A migration repository keeps the migrate order.
$this->repository->log($name, $batch);
$this->note("<info>Migrated:</info> {$name}");
} | [
"protected",
"function",
"runUp",
"(",
"$",
"file",
",",
"$",
"batch",
",",
"$",
"pretend",
")",
"{",
"// First we will resolve a \"real\" instance of the migration class from this",
"// migration file name. Once we have the instances we can run the actual",
"// command such as \"up\" or \"down\", or we can just simulate the action.",
"$",
"migration",
"=",
"$",
"this",
"->",
"resolve",
"(",
"$",
"name",
"=",
"$",
"this",
"->",
"getMigrationName",
"(",
"$",
"file",
")",
")",
";",
"if",
"(",
"$",
"pretend",
")",
"{",
"return",
"$",
"this",
"->",
"pretendToRun",
"(",
"$",
"migration",
",",
"'up'",
")",
";",
"}",
"$",
"this",
"->",
"runMigration",
"(",
"$",
"migration",
",",
"'up'",
")",
";",
"// Once we have run a migrations class, we will log that it was run in this",
"// repository so that we don't try to run it next time we do a migration",
"// in the application. A migration repository keeps the migrate order.",
"$",
"this",
"->",
"repository",
"->",
"log",
"(",
"$",
"name",
",",
"$",
"batch",
")",
";",
"$",
"this",
"->",
"note",
"(",
"\"<info>Migrated:</info> {$name}\"",
")",
";",
"}"
] | Run "up" a migration instance.
@param string $file
@param int $batch
@param bool $pretend
@return void | [
"Run",
"up",
"a",
"migration",
"instance",
"."
] | train | https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Migrations/Migrator.php#L156-L177 |
zhouyl/mellivora | Mellivora/Database/Migrations/Migrator.php | Migrator.getMigrationsForRollback | protected function getMigrationsForRollback(array $options)
{
if (($steps = Arr::get($options, 'step', 0)) > 0) {
return $this->repository->getMigrations($steps);
}
return $this->repository->getLast();
} | php | protected function getMigrationsForRollback(array $options)
{
if (($steps = Arr::get($options, 'step', 0)) > 0) {
return $this->repository->getMigrations($steps);
}
return $this->repository->getLast();
} | [
"protected",
"function",
"getMigrationsForRollback",
"(",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"(",
"$",
"steps",
"=",
"Arr",
"::",
"get",
"(",
"$",
"options",
",",
"'step'",
",",
"0",
")",
")",
">",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"repository",
"->",
"getMigrations",
"(",
"$",
"steps",
")",
";",
"}",
"return",
"$",
"this",
"->",
"repository",
"->",
"getLast",
"(",
")",
";",
"}"
] | Get the migrations for a rollback operation.
@param array $options
@return array | [
"Get",
"the",
"migrations",
"for",
"a",
"rollback",
"operation",
"."
] | train | https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Migrations/Migrator.php#L212-L219 |
kenphp/ken | src/Helpers/Url.php | Url.createAbsolute | public static function createAbsolute($url, array $params = array())
{
$url = self::addParams($url, $params);
$url = ltrim($url, '/');
$baseUrl = app()->request->getBaseUrl();
return $baseUrl.'/'.$url;
} | php | public static function createAbsolute($url, array $params = array())
{
$url = self::addParams($url, $params);
$url = ltrim($url, '/');
$baseUrl = app()->request->getBaseUrl();
return $baseUrl.'/'.$url;
} | [
"public",
"static",
"function",
"createAbsolute",
"(",
"$",
"url",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"url",
"=",
"self",
"::",
"addParams",
"(",
"$",
"url",
",",
"$",
"params",
")",
";",
"$",
"url",
"=",
"ltrim",
"(",
"$",
"url",
",",
"'/'",
")",
";",
"$",
"baseUrl",
"=",
"app",
"(",
")",
"->",
"request",
"->",
"getBaseUrl",
"(",
")",
";",
"return",
"$",
"baseUrl",
".",
"'/'",
".",
"$",
"url",
";",
"}"
] | Creates absolute url.
@param string $url
@param array $params Assosiative array in format [key => value ] for GET parameters
@return string | [
"Creates",
"absolute",
"url",
"."
] | train | https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Helpers/Url.php#L33-L40 |
kenphp/ken | src/Helpers/Url.php | Url.addParams | private static function addParams($url, array $params = array())
{
$cParams = count($params);
if ($cParams > 0) {
$url .= '?';
$idx = 1;
foreach ($params as $key => $value) {
$url .= $key.'='.$value;
if ($idx < $cParams) {
$url .= '&';
}
++$idx;
}
}
return $url;
} | php | private static function addParams($url, array $params = array())
{
$cParams = count($params);
if ($cParams > 0) {
$url .= '?';
$idx = 1;
foreach ($params as $key => $value) {
$url .= $key.'='.$value;
if ($idx < $cParams) {
$url .= '&';
}
++$idx;
}
}
return $url;
} | [
"private",
"static",
"function",
"addParams",
"(",
"$",
"url",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"cParams",
"=",
"count",
"(",
"$",
"params",
")",
";",
"if",
"(",
"$",
"cParams",
">",
"0",
")",
"{",
"$",
"url",
".=",
"'?'",
";",
"$",
"idx",
"=",
"1",
";",
"foreach",
"(",
"$",
"params",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"url",
".=",
"$",
"key",
".",
"'='",
".",
"$",
"value",
";",
"if",
"(",
"$",
"idx",
"<",
"$",
"cParams",
")",
"{",
"$",
"url",
".=",
"'&'",
";",
"}",
"++",
"$",
"idx",
";",
"}",
"}",
"return",
"$",
"url",
";",
"}"
] | Appends GET parameters to url.
@param string $url
@param array $params Assosiative array in format [key => value ] for GET parameters
@return string | [
"Appends",
"GET",
"parameters",
"to",
"url",
"."
] | train | https://github.com/kenphp/ken/blob/c454a86f0ab55c52c88e9bff5bc6fb4e7bd9e0eb/src/Helpers/Url.php#L50-L67 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php | ezcDbSchemaPersistentClassWriter.saveToFile | public function saveToFile( $dir, ezcDbSchema $dbSchema )
{
if ( !is_dir( $dir ) )
{
throw new ezcBaseFileNotFoundException( $dir, 'directory' );
}
if ( !is_writable( $dir ) )
{
throw new ezcBaseFilePermissionException( $dir, ezcBaseFileException::WRITE );
}
$schema = $dbSchema->getSchema();
foreach ( $schema as $tableName => $table )
{
$this->writeClass( $dir, $tableName, $table );
}
} | php | public function saveToFile( $dir, ezcDbSchema $dbSchema )
{
if ( !is_dir( $dir ) )
{
throw new ezcBaseFileNotFoundException( $dir, 'directory' );
}
if ( !is_writable( $dir ) )
{
throw new ezcBaseFilePermissionException( $dir, ezcBaseFileException::WRITE );
}
$schema = $dbSchema->getSchema();
foreach ( $schema as $tableName => $table )
{
$this->writeClass( $dir, $tableName, $table );
}
} | [
"public",
"function",
"saveToFile",
"(",
"$",
"dir",
",",
"ezcDbSchema",
"$",
"dbSchema",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"throw",
"new",
"ezcBaseFileNotFoundException",
"(",
"$",
"dir",
",",
"'directory'",
")",
";",
"}",
"if",
"(",
"!",
"is_writable",
"(",
"$",
"dir",
")",
")",
"{",
"throw",
"new",
"ezcBaseFilePermissionException",
"(",
"$",
"dir",
",",
"ezcBaseFileException",
"::",
"WRITE",
")",
";",
"}",
"$",
"schema",
"=",
"$",
"dbSchema",
"->",
"getSchema",
"(",
")",
";",
"foreach",
"(",
"$",
"schema",
"as",
"$",
"tableName",
"=>",
"$",
"table",
")",
"{",
"$",
"this",
"->",
"writeClass",
"(",
"$",
"dir",
",",
"$",
"tableName",
",",
"$",
"table",
")",
";",
"}",
"}"
] | Writes the schema definition in $dbSchema to files located in $dir.
This method dumps the given schema to PersistentObject definitions, which
will be located in the given directory.
@param string $dir The directory to store definitions in.
@param ezcDbSchema $dbSchema The schema object to create defs for.
@throws ezcBaseFileNotFoundException If the given directory could not be
found.
@throws ezcBaseFilePermissionException If the given directory is not
writable. | [
"Writes",
"the",
"schema",
"definition",
"in",
"$dbSchema",
"to",
"files",
"located",
"in",
"$dir",
".",
"This",
"method",
"dumps",
"the",
"given",
"schema",
"to",
"PersistentObject",
"definitions",
"which",
"will",
"be",
"located",
"in",
"the",
"given",
"directory",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php#L72-L90 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php | ezcDbSchemaPersistentClassWriter.writeAttributes | private function writeAttributes( $file, $fields )
{
foreach ( $fields as $fieldName => $field )
{
fwrite( $file, " /**\n" );
fwrite( $file, " * $fieldName\n" );
fwrite( $file, " *\n" );
fwrite( $file, " * @var {$this->translateType($field->type)}\n" );
fwrite( $file, " */\n" );
fwrite( $file, " private \$$fieldName;\n" );
}
} | php | private function writeAttributes( $file, $fields )
{
foreach ( $fields as $fieldName => $field )
{
fwrite( $file, " /**\n" );
fwrite( $file, " * $fieldName\n" );
fwrite( $file, " *\n" );
fwrite( $file, " * @var {$this->translateType($field->type)}\n" );
fwrite( $file, " */\n" );
fwrite( $file, " private \$$fieldName;\n" );
}
} | [
"private",
"function",
"writeAttributes",
"(",
"$",
"file",
",",
"$",
"fields",
")",
"{",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"fieldName",
"=>",
"$",
"field",
")",
"{",
"fwrite",
"(",
"$",
"file",
",",
"\" /**\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * $fieldName\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" *\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * @var {$this->translateType($field->type)}\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" */\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" private \\$$fieldName;\\n\"",
")",
";",
"}",
"}"
] | Writes the list of attributes.
@param resource $file
@param array $fields
@return void | [
"Writes",
"the",
"list",
"of",
"attributes",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php#L99-L110 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php | ezcDbSchemaPersistentClassWriter.writeSetState | private function writeSetState( $file )
{
fwrite( $file, " /**\n" );
fwrite( $file, " * Set the PersistentObject state.\n" );
fwrite( $file, " *\n" );
fwrite( $file, " * @param array(string=>mixed) \$state The state to set.\n" );
fwrite( $file, " * @return void\n" );
fwrite( $file, " */\n" );
fwrite( $file, " public function setState( array \$state )\n" );
fwrite( $file, " {\n" );
fwrite( $file, " foreach ( \$state as \$attribute => \$value )\n" );
fwrite( $file, " {\n" );
fwrite( $file, " \$this->\$attribute = \$value;\n" );
fwrite( $file, " }\n" );
fwrite( $file, " }\n" );
} | php | private function writeSetState( $file )
{
fwrite( $file, " /**\n" );
fwrite( $file, " * Set the PersistentObject state.\n" );
fwrite( $file, " *\n" );
fwrite( $file, " * @param array(string=>mixed) \$state The state to set.\n" );
fwrite( $file, " * @return void\n" );
fwrite( $file, " */\n" );
fwrite( $file, " public function setState( array \$state )\n" );
fwrite( $file, " {\n" );
fwrite( $file, " foreach ( \$state as \$attribute => \$value )\n" );
fwrite( $file, " {\n" );
fwrite( $file, " \$this->\$attribute = \$value;\n" );
fwrite( $file, " }\n" );
fwrite( $file, " }\n" );
} | [
"private",
"function",
"writeSetState",
"(",
"$",
"file",
")",
"{",
"fwrite",
"(",
"$",
"file",
",",
"\" /**\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * Set the PersistentObject state.\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" *\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * @param array(string=>mixed) \\$state The state to set.\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * @return void\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" */\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" public function setState( array \\$state )\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" {\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" foreach ( \\$state as \\$attribute => \\$value )\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" {\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" \\$this->\\$attribute = \\$value;\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" }\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" }\\n\"",
")",
";",
"}"
] | Writes the setState() method for the class.
@param resource $file
@return void | [
"Writes",
"the",
"setState",
"()",
"method",
"for",
"the",
"class",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php#L118-L133 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php | ezcDbSchemaPersistentClassWriter.writeGetState | private function writeGetState( $file, $fields )
{
fwrite( $file, " /**\n" );
fwrite( $file, " * Get the PersistentObject state.\n" );
fwrite( $file, " *\n" );
fwrite( $file, " * @return array(string=>mixed) The state of the object.\n" );
fwrite( $file, " */\n" );
fwrite( $file, " public function getState()\n" );
fwrite( $file, " {\n" );
fwrite( $file, " return array(\n" );
foreach ( $fields as $fieldName => $field )
{
fwrite( $file, " '$fieldName' => \$this->$fieldName,\n" );
}
fwrite( $file, " );\n" );
fwrite( $file, " }\n" );
} | php | private function writeGetState( $file, $fields )
{
fwrite( $file, " /**\n" );
fwrite( $file, " * Get the PersistentObject state.\n" );
fwrite( $file, " *\n" );
fwrite( $file, " * @return array(string=>mixed) The state of the object.\n" );
fwrite( $file, " */\n" );
fwrite( $file, " public function getState()\n" );
fwrite( $file, " {\n" );
fwrite( $file, " return array(\n" );
foreach ( $fields as $fieldName => $field )
{
fwrite( $file, " '$fieldName' => \$this->$fieldName,\n" );
}
fwrite( $file, " );\n" );
fwrite( $file, " }\n" );
} | [
"private",
"function",
"writeGetState",
"(",
"$",
"file",
",",
"$",
"fields",
")",
"{",
"fwrite",
"(",
"$",
"file",
",",
"\" /**\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * Get the PersistentObject state.\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" *\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * @return array(string=>mixed) The state of the object.\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" */\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" public function getState()\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" {\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" return array(\\n\"",
")",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"fieldName",
"=>",
"$",
"field",
")",
"{",
"fwrite",
"(",
"$",
"file",
",",
"\" '$fieldName' => \\$this->$fieldName,\\n\"",
")",
";",
"}",
"fwrite",
"(",
"$",
"file",
",",
"\" );\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" }\\n\"",
")",
";",
"}"
] | Writes the getState() method for the class.
@param resource $file
@param array $fields The table fields.
@return void | [
"Writes",
"the",
"getState",
"()",
"method",
"for",
"the",
"class",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php#L142-L158 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php | ezcDbSchemaPersistentClassWriter.writeClass | private function writeClass( $dir, $tableName, ezcDbSchemaTable $table )
{
$file = $this->openFile( $dir, $tableName );
fwrite( $file, "/**\n" );
fwrite( $file, " * Data class $tableName.\n" );
fwrite( $file, " * Class to be used with eZ Components PersistentObject.\n" );
fwrite( $file, " */\n" );
fwrite( $file, "class {$this->prefix}$tableName\n" );
fwrite( $file, "{\n" );
// attributes
$this->writeAttributes( $file, $table->fields );
fwrite( $file, "\n" );
// methods
$this->writeSetState( $file );
fwrite( $file, "\n" );
$this->writeGetState( $file, $table->fields );
fwrite( $file, "}\n" );
$this->closeFile( $file );
} | php | private function writeClass( $dir, $tableName, ezcDbSchemaTable $table )
{
$file = $this->openFile( $dir, $tableName );
fwrite( $file, "/**\n" );
fwrite( $file, " * Data class $tableName.\n" );
fwrite( $file, " * Class to be used with eZ Components PersistentObject.\n" );
fwrite( $file, " */\n" );
fwrite( $file, "class {$this->prefix}$tableName\n" );
fwrite( $file, "{\n" );
// attributes
$this->writeAttributes( $file, $table->fields );
fwrite( $file, "\n" );
// methods
$this->writeSetState( $file );
fwrite( $file, "\n" );
$this->writeGetState( $file, $table->fields );
fwrite( $file, "}\n" );
$this->closeFile( $file );
} | [
"private",
"function",
"writeClass",
"(",
"$",
"dir",
",",
"$",
"tableName",
",",
"ezcDbSchemaTable",
"$",
"table",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"openFile",
"(",
"$",
"dir",
",",
"$",
"tableName",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"/**\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * Data class $tableName.\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" * Class to be used with eZ Components PersistentObject.\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\" */\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"class {$this->prefix}$tableName\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"{\\n\"",
")",
";",
"// attributes ",
"$",
"this",
"->",
"writeAttributes",
"(",
"$",
"file",
",",
"$",
"table",
"->",
"fields",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"\\n\"",
")",
";",
"// methods",
"$",
"this",
"->",
"writeSetState",
"(",
"$",
"file",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"\\n\"",
")",
";",
"$",
"this",
"->",
"writeGetState",
"(",
"$",
"file",
",",
"$",
"table",
"->",
"fields",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"}\\n\"",
")",
";",
"$",
"this",
"->",
"closeFile",
"(",
"$",
"file",
")",
";",
"}"
] | Writes a PHP class.
This method writes a PHP class from a table definition.
@param string $dir The directory to write the defititions to.
@param string $tableName Name of the database table.
@param ezcDbSchemaTable $table The table definition. | [
"Writes",
"a",
"PHP",
"class",
".",
"This",
"method",
"writes",
"a",
"PHP",
"class",
"from",
"a",
"table",
"definition",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php#L168-L190 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php | ezcDbSchemaPersistentClassWriter.openFile | private function openFile( $dir, $name )
{
$filename = $dir . DIRECTORY_SEPARATOR . strtolower( $this->prefix ) . strtolower( $name ) . '.php';
// We do not want to overwrite files
if ( file_exists( $filename ) && ( $this->overwrite === false || is_writable( $filename ) === false ) )
{
throw new ezcBaseFileIoException( $filename, ezcBaseFileException::WRITE, "File already exists or is not writeable. Use --overwrite to ignore existance." );
}
$file = @fopen( $filename, 'w' );
if ( $file === false )
{
throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE );
}
fwrite( $file, "<?php\n" );
fwrite( $file, "// Autogenerated class file\n" );
fwrite( $file, "\n" );
return $file;
} | php | private function openFile( $dir, $name )
{
$filename = $dir . DIRECTORY_SEPARATOR . strtolower( $this->prefix ) . strtolower( $name ) . '.php';
// We do not want to overwrite files
if ( file_exists( $filename ) && ( $this->overwrite === false || is_writable( $filename ) === false ) )
{
throw new ezcBaseFileIoException( $filename, ezcBaseFileException::WRITE, "File already exists or is not writeable. Use --overwrite to ignore existance." );
}
$file = @fopen( $filename, 'w' );
if ( $file === false )
{
throw new ezcBaseFilePermissionException( $file, ezcBaseFileException::WRITE );
}
fwrite( $file, "<?php\n" );
fwrite( $file, "// Autogenerated class file\n" );
fwrite( $file, "\n" );
return $file;
} | [
"private",
"function",
"openFile",
"(",
"$",
"dir",
",",
"$",
"name",
")",
"{",
"$",
"filename",
"=",
"$",
"dir",
".",
"DIRECTORY_SEPARATOR",
".",
"strtolower",
"(",
"$",
"this",
"->",
"prefix",
")",
".",
"strtolower",
"(",
"$",
"name",
")",
".",
"'.php'",
";",
"// We do not want to overwrite files",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
"&&",
"(",
"$",
"this",
"->",
"overwrite",
"===",
"false",
"||",
"is_writable",
"(",
"$",
"filename",
")",
"===",
"false",
")",
")",
"{",
"throw",
"new",
"ezcBaseFileIoException",
"(",
"$",
"filename",
",",
"ezcBaseFileException",
"::",
"WRITE",
",",
"\"File already exists or is not writeable. Use --overwrite to ignore existance.\"",
")",
";",
"}",
"$",
"file",
"=",
"@",
"fopen",
"(",
"$",
"filename",
",",
"'w'",
")",
";",
"if",
"(",
"$",
"file",
"===",
"false",
")",
"{",
"throw",
"new",
"ezcBaseFilePermissionException",
"(",
"$",
"file",
",",
"ezcBaseFileException",
"::",
"WRITE",
")",
";",
"}",
"fwrite",
"(",
"$",
"file",
",",
"\"<?php\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"// Autogenerated class file\\n\"",
")",
";",
"fwrite",
"(",
"$",
"file",
",",
"\"\\n\"",
")",
";",
"return",
"$",
"file",
";",
"}"
] | Open a file for writing a PersistentObject definition to.
This method opens a file for writing a PersistentObject definition to
and writes the basic PHP open tag to it.
@param string $dir The diretory to open the file in.
@param string $name The table name.
@return resource(file) The file resource used for writing.
@throws ezcBaseFileIoException
if the file to write to already exists.
@throws ezcBaseFilePermissionException
if the file could not be opened for writing. | [
"Open",
"a",
"file",
"for",
"writing",
"a",
"PersistentObject",
"definition",
"to",
".",
"This",
"method",
"opens",
"a",
"file",
"for",
"writing",
"a",
"PersistentObject",
"definition",
"to",
"and",
"writes",
"the",
"basic",
"PHP",
"open",
"tag",
"to",
"it",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/persistent/class_writer.php#L206-L223 |
Laralum/Permissions | src/PermissionsChecker.php | PermissionsChecker.check | public static function check($permissions)
{
if (Schema::hasTable('laralum_permissions')) {
foreach ($permissions as $permission) {
if (!self::allCached()->contains('slug', $permission['slug'])) {
Cache::forget('laralum_permissions');
if (!self::allCached()->contains('slug', $permission['slug'])) {
Permission::create([
'name' => $permission['name'],
'slug' => $permission['slug'],
'description' => $permission['desc'],
]);
}
}
}
}
session(['laralum_permissions::mandatory' => array_merge(static::mandatory(), $permissions)]);
} | php | public static function check($permissions)
{
if (Schema::hasTable('laralum_permissions')) {
foreach ($permissions as $permission) {
if (!self::allCached()->contains('slug', $permission['slug'])) {
Cache::forget('laralum_permissions');
if (!self::allCached()->contains('slug', $permission['slug'])) {
Permission::create([
'name' => $permission['name'],
'slug' => $permission['slug'],
'description' => $permission['desc'],
]);
}
}
}
}
session(['laralum_permissions::mandatory' => array_merge(static::mandatory(), $permissions)]);
} | [
"public",
"static",
"function",
"check",
"(",
"$",
"permissions",
")",
"{",
"if",
"(",
"Schema",
"::",
"hasTable",
"(",
"'laralum_permissions'",
")",
")",
"{",
"foreach",
"(",
"$",
"permissions",
"as",
"$",
"permission",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"allCached",
"(",
")",
"->",
"contains",
"(",
"'slug'",
",",
"$",
"permission",
"[",
"'slug'",
"]",
")",
")",
"{",
"Cache",
"::",
"forget",
"(",
"'laralum_permissions'",
")",
";",
"if",
"(",
"!",
"self",
"::",
"allCached",
"(",
")",
"->",
"contains",
"(",
"'slug'",
",",
"$",
"permission",
"[",
"'slug'",
"]",
")",
")",
"{",
"Permission",
"::",
"create",
"(",
"[",
"'name'",
"=>",
"$",
"permission",
"[",
"'name'",
"]",
",",
"'slug'",
"=>",
"$",
"permission",
"[",
"'slug'",
"]",
",",
"'description'",
"=>",
"$",
"permission",
"[",
"'desc'",
"]",
",",
"]",
")",
";",
"}",
"}",
"}",
"}",
"session",
"(",
"[",
"'laralum_permissions::mandatory'",
"=>",
"array_merge",
"(",
"static",
"::",
"mandatory",
"(",
")",
",",
"$",
"permissions",
")",
"]",
")",
";",
"}"
] | Checks if the permisions exists and if they dont, they will be added.
@param array $permissions | [
"Checks",
"if",
"the",
"permisions",
"exists",
"and",
"if",
"they",
"dont",
"they",
"will",
"be",
"added",
"."
] | train | https://github.com/Laralum/Permissions/blob/79970ee7d1bff816ad4b9adee29067faead3f756/src/PermissionsChecker.php#L41-L58 |
ellipsephp/session-start | src/StartSessionMiddleware.php | StartSessionMiddleware.process | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Fail when session is disabled or has already started.
$this->failWhenDisabled();
$this->failWhenStarted();
// Try to retrieve the session id from the request cookies.
$cookies = $request->getCookieParams();
$session_id = $cookies[$this->name] ?? '';
if ($session_id != '') session_id($session_id);
// Handle the request when session_start is successful.
if (session_start(self::SESSION_OPTIONS)) {
session_name($this->name);
$response = $handler->handle($request);
$this->failWhenClosed();
$session_id = session_id();
session_write_close();
return $this->withSessionCookie($response, $session_id);
}
throw new SessionStartException;
} | php | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Fail when session is disabled or has already started.
$this->failWhenDisabled();
$this->failWhenStarted();
// Try to retrieve the session id from the request cookies.
$cookies = $request->getCookieParams();
$session_id = $cookies[$this->name] ?? '';
if ($session_id != '') session_id($session_id);
// Handle the request when session_start is successful.
if (session_start(self::SESSION_OPTIONS)) {
session_name($this->name);
$response = $handler->handle($request);
$this->failWhenClosed();
$session_id = session_id();
session_write_close();
return $this->withSessionCookie($response, $session_id);
}
throw new SessionStartException;
} | [
"public",
"function",
"process",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"RequestHandlerInterface",
"$",
"handler",
")",
":",
"ResponseInterface",
"{",
"// Fail when session is disabled or has already started.",
"$",
"this",
"->",
"failWhenDisabled",
"(",
")",
";",
"$",
"this",
"->",
"failWhenStarted",
"(",
")",
";",
"// Try to retrieve the session id from the request cookies.",
"$",
"cookies",
"=",
"$",
"request",
"->",
"getCookieParams",
"(",
")",
";",
"$",
"session_id",
"=",
"$",
"cookies",
"[",
"$",
"this",
"->",
"name",
"]",
"??",
"''",
";",
"if",
"(",
"$",
"session_id",
"!=",
"''",
")",
"session_id",
"(",
"$",
"session_id",
")",
";",
"// Handle the request when session_start is successful.",
"if",
"(",
"session_start",
"(",
"self",
"::",
"SESSION_OPTIONS",
")",
")",
"{",
"session_name",
"(",
"$",
"this",
"->",
"name",
")",
";",
"$",
"response",
"=",
"$",
"handler",
"->",
"handle",
"(",
"$",
"request",
")",
";",
"$",
"this",
"->",
"failWhenClosed",
"(",
")",
";",
"$",
"session_id",
"=",
"session_id",
"(",
")",
";",
"session_write_close",
"(",
")",
";",
"return",
"$",
"this",
"->",
"withSessionCookie",
"(",
"$",
"response",
",",
"$",
"session_id",
")",
";",
"}",
"throw",
"new",
"SessionStartException",
";",
"}"
] | Start the session, handle the request and add the session cookie to the
response.
@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Server\RequestHandlerInterface $handler
@return \Psr\Http\Message\ResponseInterface
@throws \Ellipse\Session\Exceptions\SessionStartException | [
"Start",
"the",
"session",
"handle",
"the",
"request",
"and",
"add",
"the",
"session",
"cookie",
"to",
"the",
"response",
"."
] | train | https://github.com/ellipsephp/session-start/blob/7272abfdc42bd8ffc1692c2a37114f6a187d4a24/src/StartSessionMiddleware.php#L66-L97 |
ellipsephp/session-start | src/StartSessionMiddleware.php | StartSessionMiddleware.withSessionCookie | private function withSessionCookie(ResponseInterface $response, string $session_id): ResponseInterface
{
// Merge session cookie options.
$default = session_get_cookie_params();
$default = array_change_key_case($default, CASE_LOWER);
$options = array_change_key_case($this->options, CASE_LOWER);
$options = array_merge($default, $options);
if ($options['lifetime'] < 0) $options['lifetime'] = 0;
// Create a session cookie and attach it to the response.
$cookie = SetCookie::create($this->name, $session_id)
->withMaxAge($options['lifetime'])
->withPath($options['path'])
->withDomain($options['domain'])
->withSecure($options['secure'])
->withHttpOnly($options['httponly']);
if ($options['lifetime'] > 0) {
$cookie = $cookie->withExpires(time() + $options['lifetime']);
}
return FigResponseCookies::set($response, $cookie);
} | php | private function withSessionCookie(ResponseInterface $response, string $session_id): ResponseInterface
{
// Merge session cookie options.
$default = session_get_cookie_params();
$default = array_change_key_case($default, CASE_LOWER);
$options = array_change_key_case($this->options, CASE_LOWER);
$options = array_merge($default, $options);
if ($options['lifetime'] < 0) $options['lifetime'] = 0;
// Create a session cookie and attach it to the response.
$cookie = SetCookie::create($this->name, $session_id)
->withMaxAge($options['lifetime'])
->withPath($options['path'])
->withDomain($options['domain'])
->withSecure($options['secure'])
->withHttpOnly($options['httponly']);
if ($options['lifetime'] > 0) {
$cookie = $cookie->withExpires(time() + $options['lifetime']);
}
return FigResponseCookies::set($response, $cookie);
} | [
"private",
"function",
"withSessionCookie",
"(",
"ResponseInterface",
"$",
"response",
",",
"string",
"$",
"session_id",
")",
":",
"ResponseInterface",
"{",
"// Merge session cookie options.",
"$",
"default",
"=",
"session_get_cookie_params",
"(",
")",
";",
"$",
"default",
"=",
"array_change_key_case",
"(",
"$",
"default",
",",
"CASE_LOWER",
")",
";",
"$",
"options",
"=",
"array_change_key_case",
"(",
"$",
"this",
"->",
"options",
",",
"CASE_LOWER",
")",
";",
"$",
"options",
"=",
"array_merge",
"(",
"$",
"default",
",",
"$",
"options",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'lifetime'",
"]",
"<",
"0",
")",
"$",
"options",
"[",
"'lifetime'",
"]",
"=",
"0",
";",
"// Create a session cookie and attach it to the response.",
"$",
"cookie",
"=",
"SetCookie",
"::",
"create",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"session_id",
")",
"->",
"withMaxAge",
"(",
"$",
"options",
"[",
"'lifetime'",
"]",
")",
"->",
"withPath",
"(",
"$",
"options",
"[",
"'path'",
"]",
")",
"->",
"withDomain",
"(",
"$",
"options",
"[",
"'domain'",
"]",
")",
"->",
"withSecure",
"(",
"$",
"options",
"[",
"'secure'",
"]",
")",
"->",
"withHttpOnly",
"(",
"$",
"options",
"[",
"'httponly'",
"]",
")",
";",
"if",
"(",
"$",
"options",
"[",
"'lifetime'",
"]",
">",
"0",
")",
"{",
"$",
"cookie",
"=",
"$",
"cookie",
"->",
"withExpires",
"(",
"time",
"(",
")",
"+",
"$",
"options",
"[",
"'lifetime'",
"]",
")",
";",
"}",
"return",
"FigResponseCookies",
"::",
"set",
"(",
"$",
"response",
",",
"$",
"cookie",
")",
";",
"}"
] | Attach a session cookie with the given sesison id to the given response.
@param \Psr\Http\Message\ResponseInterface $response
@param string $session_id
@return \Psr\Http\Message\ResponseInterface | [
"Attach",
"a",
"session",
"cookie",
"with",
"the",
"given",
"sesison",
"id",
"to",
"the",
"given",
"response",
"."
] | train | https://github.com/ellipsephp/session-start/blob/7272abfdc42bd8ffc1692c2a37114f6a187d4a24/src/StartSessionMiddleware.php#L151-L178 |
vaibhavpandeyvpz/sandesh | src/MessageAbstract.php | MessageAbstract.getHeaderLine | public function getHeaderLine($name)
{
$values = $this->getHeader($name);
if (count($values)) {
return implode(',', $values);
}
return '';
} | php | public function getHeaderLine($name)
{
$values = $this->getHeader($name);
if (count($values)) {
return implode(',', $values);
}
return '';
} | [
"public",
"function",
"getHeaderLine",
"(",
"$",
"name",
")",
"{",
"$",
"values",
"=",
"$",
"this",
"->",
"getHeader",
"(",
"$",
"name",
")",
";",
"if",
"(",
"count",
"(",
"$",
"values",
")",
")",
"{",
"return",
"implode",
"(",
"','",
",",
"$",
"values",
")",
";",
"}",
"return",
"''",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/vaibhavpandeyvpz/sandesh/blob/bea2d06c7cac099ed82da973c922859de4158de0/src/MessageAbstract.php#L66-L73 |
vaibhavpandeyvpz/sandesh | src/MessageAbstract.php | MessageAbstract.withAddedHeader | public function withAddedHeader($name, $value)
{
MessageValidations::assertHeaderName($name);
if ($this->hasHeader($name)) {
$name = $this->headerNames[strtolower($name)];
$value = is_array($value) ? $value : array($value);
array_walk($value, array(__NAMESPACE__ . '\\MessageValidations', 'assertHeaderValue'));
$clone = clone $this;
$clone->headers[$name] += array_merge($clone->headers[$name], $value);
return $clone;
} else {
return $this->withHeader($name, $value);
}
} | php | public function withAddedHeader($name, $value)
{
MessageValidations::assertHeaderName($name);
if ($this->hasHeader($name)) {
$name = $this->headerNames[strtolower($name)];
$value = is_array($value) ? $value : array($value);
array_walk($value, array(__NAMESPACE__ . '\\MessageValidations', 'assertHeaderValue'));
$clone = clone $this;
$clone->headers[$name] += array_merge($clone->headers[$name], $value);
return $clone;
} else {
return $this->withHeader($name, $value);
}
} | [
"public",
"function",
"withAddedHeader",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"MessageValidations",
"::",
"assertHeaderName",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasHeader",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"headerNames",
"[",
"strtolower",
"(",
"$",
"name",
")",
"]",
";",
"$",
"value",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"$",
"value",
":",
"array",
"(",
"$",
"value",
")",
";",
"array_walk",
"(",
"$",
"value",
",",
"array",
"(",
"__NAMESPACE__",
".",
"'\\\\MessageValidations'",
",",
"'assertHeaderValue'",
")",
")",
";",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"$",
"clone",
"->",
"headers",
"[",
"$",
"name",
"]",
"+=",
"array_merge",
"(",
"$",
"clone",
"->",
"headers",
"[",
"$",
"name",
"]",
",",
"$",
"value",
")",
";",
"return",
"$",
"clone",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"withHeader",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/vaibhavpandeyvpz/sandesh/blob/bea2d06c7cac099ed82da973c922859de4158de0/src/MessageAbstract.php#L102-L115 |
vaibhavpandeyvpz/sandesh | src/MessageAbstract.php | MessageAbstract.withHeader | public function withHeader($name, $value)
{
MessageValidations::assertHeaderName($name);
$value = is_array($value) ? $value : array($value);
array_walk($value, array(__NAMESPACE__ . '\\MessageValidations', 'assertHeaderValue'));
$clone = clone $this;
$clone->headerNames[strtolower($name)] = $name;
$clone->headers[$name] = $value;
return $clone;
} | php | public function withHeader($name, $value)
{
MessageValidations::assertHeaderName($name);
$value = is_array($value) ? $value : array($value);
array_walk($value, array(__NAMESPACE__ . '\\MessageValidations', 'assertHeaderValue'));
$clone = clone $this;
$clone->headerNames[strtolower($name)] = $name;
$clone->headers[$name] = $value;
return $clone;
} | [
"public",
"function",
"withHeader",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"MessageValidations",
"::",
"assertHeaderName",
"(",
"$",
"name",
")",
";",
"$",
"value",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"$",
"value",
":",
"array",
"(",
"$",
"value",
")",
";",
"array_walk",
"(",
"$",
"value",
",",
"array",
"(",
"__NAMESPACE__",
".",
"'\\\\MessageValidations'",
",",
"'assertHeaderValue'",
")",
")",
";",
"$",
"clone",
"=",
"clone",
"$",
"this",
";",
"$",
"clone",
"->",
"headerNames",
"[",
"strtolower",
"(",
"$",
"name",
")",
"]",
"=",
"$",
"name",
";",
"$",
"clone",
"->",
"headers",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"clone",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/vaibhavpandeyvpz/sandesh/blob/bea2d06c7cac099ed82da973c922859de4158de0/src/MessageAbstract.php#L130-L139 |
netvlies/NetvliesFormBundle | Controller/FormAdminController.php | FormAdminController.createResponse | protected function createResponse(PHPExcel $excel, $fileName)
{
$writer = new PHPExcel_Writer_Excel2007($excel);
ob_start();
$writer->save('php://output');
$content = ob_get_clean();
$response = new Response();
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$fileName.'"');
$response->headers->set('Cache-Control', 'max-age=0');
$response->setContent($content);
return $response;
} | php | protected function createResponse(PHPExcel $excel, $fileName)
{
$writer = new PHPExcel_Writer_Excel2007($excel);
ob_start();
$writer->save('php://output');
$content = ob_get_clean();
$response = new Response();
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$fileName.'"');
$response->headers->set('Cache-Control', 'max-age=0');
$response->setContent($content);
return $response;
} | [
"protected",
"function",
"createResponse",
"(",
"PHPExcel",
"$",
"excel",
",",
"$",
"fileName",
")",
"{",
"$",
"writer",
"=",
"new",
"PHPExcel_Writer_Excel2007",
"(",
"$",
"excel",
")",
";",
"ob_start",
"(",
")",
";",
"$",
"writer",
"->",
"save",
"(",
"'php://output'",
")",
";",
"$",
"content",
"=",
"ob_get_clean",
"(",
")",
";",
"$",
"response",
"=",
"new",
"Response",
"(",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Type'",
",",
"'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Disposition'",
",",
"'attachment;filename=\"'",
".",
"$",
"fileName",
".",
"'\"'",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Cache-Control'",
",",
"'max-age=0'",
")",
";",
"$",
"response",
"->",
"setContent",
"(",
"$",
"content",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Generates a response object for a PHPExcel object.
@param PHPExcel $excel
@param $fileName
@return Response | [
"Generates",
"a",
"response",
"object",
"for",
"a",
"PHPExcel",
"object",
"."
] | train | https://github.com/netvlies/NetvliesFormBundle/blob/93f9a3321d9925040111374e7c1014a6400a2d08/Controller/FormAdminController.php#L73-L86 |
ajant/SimpleArrayLibrary | src/Categories/Inspectors.php | Inspectors.hasAllValuesMultiDimensional | public static function hasAllValuesMultiDimensional(array $haystack, array $needles)
{
$return = true;
foreach ($needles as $needle) {
if (!in_array($needle, $haystack)) {
$return = false;
break;
}
}
return $return;
} | php | public static function hasAllValuesMultiDimensional(array $haystack, array $needles)
{
$return = true;
foreach ($needles as $needle) {
if (!in_array($needle, $haystack)) {
$return = false;
break;
}
}
return $return;
} | [
"public",
"static",
"function",
"hasAllValuesMultiDimensional",
"(",
"array",
"$",
"haystack",
",",
"array",
"$",
"needles",
")",
"{",
"$",
"return",
"=",
"true",
";",
"foreach",
"(",
"$",
"needles",
"as",
"$",
"needle",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"needle",
",",
"$",
"haystack",
")",
")",
"{",
"$",
"return",
"=",
"false",
";",
"break",
";",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] | Checks if $array's keys contain all of $subArray's values
@param array $haystack
@param array $needles
@return bool | [
"Checks",
"if",
"$array",
"s",
"keys",
"contain",
"all",
"of",
"$subArray",
"s",
"values"
] | train | https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Inspectors.php#L41-L52 |
ajant/SimpleArrayLibrary | src/Categories/Inspectors.php | Inspectors.haveSameKeys | public static function haveSameKeys(array $array1, array $array2)
{
return self::hasAllKeys($array1, array_keys($array2)) && self::hasAllKeys($array2, array_keys($array1)) ? true : false;
} | php | public static function haveSameKeys(array $array1, array $array2)
{
return self::hasAllKeys($array1, array_keys($array2)) && self::hasAllKeys($array2, array_keys($array1)) ? true : false;
} | [
"public",
"static",
"function",
"haveSameKeys",
"(",
"array",
"$",
"array1",
",",
"array",
"$",
"array2",
")",
"{",
"return",
"self",
"::",
"hasAllKeys",
"(",
"$",
"array1",
",",
"array_keys",
"(",
"$",
"array2",
")",
")",
"&&",
"self",
"::",
"hasAllKeys",
"(",
"$",
"array2",
",",
"array_keys",
"(",
"$",
"array1",
")",
")",
"?",
"true",
":",
"false",
";",
"}"
] | Checks if two arrays have all equal keys
@param array $array1
@param array $array2
@return boolean | [
"Checks",
"if",
"two",
"arrays",
"have",
"all",
"equal",
"keys"
] | train | https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Inspectors.php#L75-L78 |
ajant/SimpleArrayLibrary | src/Categories/Inspectors.php | Inspectors.haveSameValues | public static function haveSameValues($array1, $array2)
{
return self::hasAllValues($array1, $array2) && self::hasAllValues($array2, $array1) ? true : false;
} | php | public static function haveSameValues($array1, $array2)
{
return self::hasAllValues($array1, $array2) && self::hasAllValues($array2, $array1) ? true : false;
} | [
"public",
"static",
"function",
"haveSameValues",
"(",
"$",
"array1",
",",
"$",
"array2",
")",
"{",
"return",
"self",
"::",
"hasAllValues",
"(",
"$",
"array1",
",",
"$",
"array2",
")",
"&&",
"self",
"::",
"hasAllValues",
"(",
"$",
"array2",
",",
"$",
"array1",
")",
"?",
"true",
":",
"false",
";",
"}"
] | Check if two arrays have all equal values
@param array $array1
@param array $array2
@return bool | [
"Check",
"if",
"two",
"arrays",
"have",
"all",
"equal",
"values"
] | train | https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Inspectors.php#L88-L91 |
inhere/php-librarys | src/Utils/Token.php | Token.gen | public static function gen($password)
{
return crypt($password, self::$algo . self::$cost . '$' . self::uniqueSalt());
} | php | public static function gen($password)
{
return crypt($password, self::$algo . self::$cost . '$' . self::uniqueSalt());
} | [
"public",
"static",
"function",
"gen",
"(",
"$",
"password",
")",
"{",
"return",
"crypt",
"(",
"$",
"password",
",",
"self",
"::",
"$",
"algo",
".",
"self",
"::",
"$",
"cost",
".",
"'$'",
".",
"self",
"::",
"uniqueSalt",
"(",
")",
")",
";",
"}"
] | this will be used to generate a hash
@param $password
@return string | [
"this",
"will",
"be",
"used",
"to",
"generate",
"a",
"hash"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Utils/Token.php#L56-L59 |
inhere/php-librarys | src/Utils/Token.php | Token.GUid | public static function GUid(): string
{
mt_srand((double)microtime() * 10000);
$charId = strtolower(md5(uniqid(mt_rand(), true)));
// $hyphen = chr(45);
$uuid = substr($charId, 0, 8) .
substr($charId, 8, 4) .
substr($charId, 12, 4) .
substr($charId, 16, 4) .
substr($charId, 20, 12);
return $uuid;
} | php | public static function GUid(): string
{
mt_srand((double)microtime() * 10000);
$charId = strtolower(md5(uniqid(mt_rand(), true)));
// $hyphen = chr(45);
$uuid = substr($charId, 0, 8) .
substr($charId, 8, 4) .
substr($charId, 12, 4) .
substr($charId, 16, 4) .
substr($charId, 20, 12);
return $uuid;
} | [
"public",
"static",
"function",
"GUid",
"(",
")",
":",
"string",
"{",
"mt_srand",
"(",
"(",
"double",
")",
"microtime",
"(",
")",
"*",
"10000",
")",
";",
"$",
"charId",
"=",
"strtolower",
"(",
"md5",
"(",
"uniqid",
"(",
"mt_rand",
"(",
")",
",",
"true",
")",
")",
")",
";",
"// $hyphen = chr(45);",
"$",
"uuid",
"=",
"substr",
"(",
"$",
"charId",
",",
"0",
",",
"8",
")",
".",
"substr",
"(",
"$",
"charId",
",",
"8",
",",
"4",
")",
".",
"substr",
"(",
"$",
"charId",
",",
"12",
",",
"4",
")",
".",
"substr",
"(",
"$",
"charId",
",",
"16",
",",
"4",
")",
".",
"substr",
"(",
"$",
"charId",
",",
"20",
",",
"12",
")",
";",
"return",
"$",
"uuid",
";",
"}"
] | 生成guid
@return string | [
"生成guid"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Utils/Token.php#L156-L169 |
dstuecken/notify | src/Handler/LoggerHandler.php | LoggerHandler.handle | public function handle(NotificationInterface $notification, $level)
{
return $this->logger->log($level, $notification->message());
} | php | public function handle(NotificationInterface $notification, $level)
{
return $this->logger->log($level, $notification->message());
} | [
"public",
"function",
"handle",
"(",
"NotificationInterface",
"$",
"notification",
",",
"$",
"level",
")",
"{",
"return",
"$",
"this",
"->",
"logger",
"->",
"log",
"(",
"$",
"level",
",",
"$",
"notification",
"->",
"message",
"(",
")",
")",
";",
"}"
] | Handle a notification
@return bool | [
"Handle",
"a",
"notification"
] | train | https://github.com/dstuecken/notify/blob/abccf0a6a272caf66baea74323f18e2212c6e11e/src/Handler/LoggerHandler.php#L32-L35 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/CoversTag.php | CoversTag.process | public function process(\DOMDocument $xml)
{
$xpath = new \DOMXPath($xml);
$nodes = $xpath->query('//tag[@name=\'covers\']');
/** @var \DOMElement $node */
foreach ($nodes as $node) {
$refers = $node->getAttribute('refers');
$refers_array = explode('::', $refers);
// determine the type so we know where to put the @coveredby tag on
$type = 'class';
if (isset($refers_array[1])) {
// starts with $ = property, ends with () = method,
// otherwise constant
$type = $refers_array[1][0] == '$' ? 'property' : 'constant';
$type = substr($refers_array[1], -2) == '()' ? 'method' : $type;
}
switch ($type) {
case 'class':
// escape single quotes in the class name
$xpath_refers = 'concat(\''.str_replace(
array("'", '"'),
array('\', "\'", \'', '\', \'"\' , \''),
$refers
) . "', '')";
$qry = '/project/file/class[full_name=' . $xpath_refers . ']';
break;
default:
$class_name = $refers_array[0];
// escape single quotes in the class name
$xpath_class_name = 'concat(\''.str_replace(
array("'", '"'),
array('\', "\'", \'', '\', \'"\' , \''),
$class_name
) . "', '')";
// escape single quotes in the method name
$xpath_method_name = 'concat(\''.str_replace(
array("'", '"'),
array('\', "\'", \'', '\', \'"\' , \''),
rtrim($refers_array[1], '()')
) . "', '')";
$qry = '/project/file/class[full_name=' . $xpath_class_name
. ']/'.$type.'[name=' . $xpath_method_name .']';
break;
}
/** @noinspection PhpUsageOfSilenceOperatorInspection as there is no pre-validation possible */
$referral_nodes = @$xpath->query($qry);
// if the query is wrong; output a Critical error and continue to
// the next @covers
if ($referral_nodes === false) {
// $this->log(
// 'An XPath error occurs while processing @covers, the query used was: ' . $qry,
// LogLevel::CRITICAL
// );
continue;
}
// check if the result is unique; if not we error and continue
// to the next @covers
if ($referral_nodes->length > 1) {
continue;
}
// if there is one matching element; link them together
if ($referral_nodes->length > 0) {
/** @var \DOMElement $referral */
$referral = $referral_nodes->item(0);
$docblock = $referral->getElementsByTagName('docblock');
if ($docblock->length < 1) {
$docblock = new \DOMElement('docblock');
$referral->appendChild($docblock);
} else {
$docblock = $docblock->item(0);
}
$used_by = new \DOMElement('tag');
$docblock->appendChild($used_by);
$used_by->setAttribute('name', 'used_by');
$used_by->setAttribute('line', '');
// gather the name of the referring element and set that as refers
// attribute
if ($node->parentNode->parentNode->nodeName == 'class') {
// if the element where the @covers is in is a class; nothing
// more than the class name need to returned
$referral_name = $node->parentNode->parentNode
->getElementsByTagName('full_name')->item(0)->nodeValue;
} else {
$referral_class_name = null;
if ($node->parentNode->parentNode->nodeName == 'method') {
// gather the name of the class where the @covers is in
$referral_class_name = $node->parentNode->parentNode
->parentNode->getElementsByTagName('full_name')->item(0)
->nodeValue;
}
// gather the name of the subelement of the class where
// the @covers is in
$referral_name = $node->parentNode->parentNode
->getElementsByTagName('name')->item(0)->nodeValue;
// if it is a method; suffix with ()
if ($node->parentNode->parentNode->nodeName == 'method'
|| $node->parentNode->parentNode->nodeName == 'function'
) {
$referral_name .= '()';
}
// only prefix class name if this is a class member
if ($referral_class_name) {
$referral_name = $referral_class_name . '::'
. $referral_name;
}
}
$used_by->setAttribute('description', $referral_name);
$used_by->setAttribute('refers', $referral_name);
}
}
return $xml;
} | php | public function process(\DOMDocument $xml)
{
$xpath = new \DOMXPath($xml);
$nodes = $xpath->query('//tag[@name=\'covers\']');
/** @var \DOMElement $node */
foreach ($nodes as $node) {
$refers = $node->getAttribute('refers');
$refers_array = explode('::', $refers);
// determine the type so we know where to put the @coveredby tag on
$type = 'class';
if (isset($refers_array[1])) {
// starts with $ = property, ends with () = method,
// otherwise constant
$type = $refers_array[1][0] == '$' ? 'property' : 'constant';
$type = substr($refers_array[1], -2) == '()' ? 'method' : $type;
}
switch ($type) {
case 'class':
// escape single quotes in the class name
$xpath_refers = 'concat(\''.str_replace(
array("'", '"'),
array('\', "\'", \'', '\', \'"\' , \''),
$refers
) . "', '')";
$qry = '/project/file/class[full_name=' . $xpath_refers . ']';
break;
default:
$class_name = $refers_array[0];
// escape single quotes in the class name
$xpath_class_name = 'concat(\''.str_replace(
array("'", '"'),
array('\', "\'", \'', '\', \'"\' , \''),
$class_name
) . "', '')";
// escape single quotes in the method name
$xpath_method_name = 'concat(\''.str_replace(
array("'", '"'),
array('\', "\'", \'', '\', \'"\' , \''),
rtrim($refers_array[1], '()')
) . "', '')";
$qry = '/project/file/class[full_name=' . $xpath_class_name
. ']/'.$type.'[name=' . $xpath_method_name .']';
break;
}
/** @noinspection PhpUsageOfSilenceOperatorInspection as there is no pre-validation possible */
$referral_nodes = @$xpath->query($qry);
// if the query is wrong; output a Critical error and continue to
// the next @covers
if ($referral_nodes === false) {
// $this->log(
// 'An XPath error occurs while processing @covers, the query used was: ' . $qry,
// LogLevel::CRITICAL
// );
continue;
}
// check if the result is unique; if not we error and continue
// to the next @covers
if ($referral_nodes->length > 1) {
continue;
}
// if there is one matching element; link them together
if ($referral_nodes->length > 0) {
/** @var \DOMElement $referral */
$referral = $referral_nodes->item(0);
$docblock = $referral->getElementsByTagName('docblock');
if ($docblock->length < 1) {
$docblock = new \DOMElement('docblock');
$referral->appendChild($docblock);
} else {
$docblock = $docblock->item(0);
}
$used_by = new \DOMElement('tag');
$docblock->appendChild($used_by);
$used_by->setAttribute('name', 'used_by');
$used_by->setAttribute('line', '');
// gather the name of the referring element and set that as refers
// attribute
if ($node->parentNode->parentNode->nodeName == 'class') {
// if the element where the @covers is in is a class; nothing
// more than the class name need to returned
$referral_name = $node->parentNode->parentNode
->getElementsByTagName('full_name')->item(0)->nodeValue;
} else {
$referral_class_name = null;
if ($node->parentNode->parentNode->nodeName == 'method') {
// gather the name of the class where the @covers is in
$referral_class_name = $node->parentNode->parentNode
->parentNode->getElementsByTagName('full_name')->item(0)
->nodeValue;
}
// gather the name of the subelement of the class where
// the @covers is in
$referral_name = $node->parentNode->parentNode
->getElementsByTagName('name')->item(0)->nodeValue;
// if it is a method; suffix with ()
if ($node->parentNode->parentNode->nodeName == 'method'
|| $node->parentNode->parentNode->nodeName == 'function'
) {
$referral_name .= '()';
}
// only prefix class name if this is a class member
if ($referral_class_name) {
$referral_name = $referral_class_name . '::'
. $referral_name;
}
}
$used_by->setAttribute('description', $referral_name);
$used_by->setAttribute('refers', $referral_name);
}
}
return $xml;
} | [
"public",
"function",
"process",
"(",
"\\",
"DOMDocument",
"$",
"xml",
")",
"{",
"$",
"xpath",
"=",
"new",
"\\",
"DOMXPath",
"(",
"$",
"xml",
")",
";",
"$",
"nodes",
"=",
"$",
"xpath",
"->",
"query",
"(",
"'//tag[@name=\\'covers\\']'",
")",
";",
"/** @var \\DOMElement $node */",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"$",
"refers",
"=",
"$",
"node",
"->",
"getAttribute",
"(",
"'refers'",
")",
";",
"$",
"refers_array",
"=",
"explode",
"(",
"'::'",
",",
"$",
"refers",
")",
";",
"// determine the type so we know where to put the @coveredby tag on",
"$",
"type",
"=",
"'class'",
";",
"if",
"(",
"isset",
"(",
"$",
"refers_array",
"[",
"1",
"]",
")",
")",
"{",
"// starts with $ = property, ends with () = method,",
"// otherwise constant",
"$",
"type",
"=",
"$",
"refers_array",
"[",
"1",
"]",
"[",
"0",
"]",
"==",
"'$'",
"?",
"'property'",
":",
"'constant'",
";",
"$",
"type",
"=",
"substr",
"(",
"$",
"refers_array",
"[",
"1",
"]",
",",
"-",
"2",
")",
"==",
"'()'",
"?",
"'method'",
":",
"$",
"type",
";",
"}",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'class'",
":",
"// escape single quotes in the class name",
"$",
"xpath_refers",
"=",
"'concat(\\''",
".",
"str_replace",
"(",
"array",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"array",
"(",
"'\\', \"\\'\", \\''",
",",
"'\\', \\'\"\\' , \\''",
")",
",",
"$",
"refers",
")",
".",
"\"', '')\"",
";",
"$",
"qry",
"=",
"'/project/file/class[full_name='",
".",
"$",
"xpath_refers",
".",
"']'",
";",
"break",
";",
"default",
":",
"$",
"class_name",
"=",
"$",
"refers_array",
"[",
"0",
"]",
";",
"// escape single quotes in the class name",
"$",
"xpath_class_name",
"=",
"'concat(\\''",
".",
"str_replace",
"(",
"array",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"array",
"(",
"'\\', \"\\'\", \\''",
",",
"'\\', \\'\"\\' , \\''",
")",
",",
"$",
"class_name",
")",
".",
"\"', '')\"",
";",
"// escape single quotes in the method name",
"$",
"xpath_method_name",
"=",
"'concat(\\''",
".",
"str_replace",
"(",
"array",
"(",
"\"'\"",
",",
"'\"'",
")",
",",
"array",
"(",
"'\\', \"\\'\", \\''",
",",
"'\\', \\'\"\\' , \\''",
")",
",",
"rtrim",
"(",
"$",
"refers_array",
"[",
"1",
"]",
",",
"'()'",
")",
")",
".",
"\"', '')\"",
";",
"$",
"qry",
"=",
"'/project/file/class[full_name='",
".",
"$",
"xpath_class_name",
".",
"']/'",
".",
"$",
"type",
".",
"'[name='",
".",
"$",
"xpath_method_name",
".",
"']'",
";",
"break",
";",
"}",
"/** @noinspection PhpUsageOfSilenceOperatorInspection as there is no pre-validation possible */",
"$",
"referral_nodes",
"=",
"@",
"$",
"xpath",
"->",
"query",
"(",
"$",
"qry",
")",
";",
"// if the query is wrong; output a Critical error and continue to",
"// the next @covers",
"if",
"(",
"$",
"referral_nodes",
"===",
"false",
")",
"{",
"// $this->log(",
"// 'An XPath error occurs while processing @covers, the query used was: ' . $qry,",
"// LogLevel::CRITICAL",
"// );",
"continue",
";",
"}",
"// check if the result is unique; if not we error and continue",
"// to the next @covers",
"if",
"(",
"$",
"referral_nodes",
"->",
"length",
">",
"1",
")",
"{",
"continue",
";",
"}",
"// if there is one matching element; link them together",
"if",
"(",
"$",
"referral_nodes",
"->",
"length",
">",
"0",
")",
"{",
"/** @var \\DOMElement $referral */",
"$",
"referral",
"=",
"$",
"referral_nodes",
"->",
"item",
"(",
"0",
")",
";",
"$",
"docblock",
"=",
"$",
"referral",
"->",
"getElementsByTagName",
"(",
"'docblock'",
")",
";",
"if",
"(",
"$",
"docblock",
"->",
"length",
"<",
"1",
")",
"{",
"$",
"docblock",
"=",
"new",
"\\",
"DOMElement",
"(",
"'docblock'",
")",
";",
"$",
"referral",
"->",
"appendChild",
"(",
"$",
"docblock",
")",
";",
"}",
"else",
"{",
"$",
"docblock",
"=",
"$",
"docblock",
"->",
"item",
"(",
"0",
")",
";",
"}",
"$",
"used_by",
"=",
"new",
"\\",
"DOMElement",
"(",
"'tag'",
")",
";",
"$",
"docblock",
"->",
"appendChild",
"(",
"$",
"used_by",
")",
";",
"$",
"used_by",
"->",
"setAttribute",
"(",
"'name'",
",",
"'used_by'",
")",
";",
"$",
"used_by",
"->",
"setAttribute",
"(",
"'line'",
",",
"''",
")",
";",
"// gather the name of the referring element and set that as refers",
"// attribute",
"if",
"(",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"nodeName",
"==",
"'class'",
")",
"{",
"// if the element where the @covers is in is a class; nothing",
"// more than the class name need to returned",
"$",
"referral_name",
"=",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"getElementsByTagName",
"(",
"'full_name'",
")",
"->",
"item",
"(",
"0",
")",
"->",
"nodeValue",
";",
"}",
"else",
"{",
"$",
"referral_class_name",
"=",
"null",
";",
"if",
"(",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"nodeName",
"==",
"'method'",
")",
"{",
"// gather the name of the class where the @covers is in",
"$",
"referral_class_name",
"=",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"parentNode",
"->",
"getElementsByTagName",
"(",
"'full_name'",
")",
"->",
"item",
"(",
"0",
")",
"->",
"nodeValue",
";",
"}",
"// gather the name of the subelement of the class where",
"// the @covers is in",
"$",
"referral_name",
"=",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"getElementsByTagName",
"(",
"'name'",
")",
"->",
"item",
"(",
"0",
")",
"->",
"nodeValue",
";",
"// if it is a method; suffix with ()",
"if",
"(",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"nodeName",
"==",
"'method'",
"||",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
"->",
"nodeName",
"==",
"'function'",
")",
"{",
"$",
"referral_name",
".=",
"'()'",
";",
"}",
"// only prefix class name if this is a class member",
"if",
"(",
"$",
"referral_class_name",
")",
"{",
"$",
"referral_name",
"=",
"$",
"referral_class_name",
".",
"'::'",
".",
"$",
"referral_name",
";",
"}",
"}",
"$",
"used_by",
"->",
"setAttribute",
"(",
"'description'",
",",
"$",
"referral_name",
")",
";",
"$",
"used_by",
"->",
"setAttribute",
"(",
"'refers'",
",",
"$",
"referral_name",
")",
";",
"}",
"}",
"return",
"$",
"xml",
";",
"}"
] | Find all return tags that contain 'self' or '$this' and replace those
terms for the name of the current class' type.
@param \DOMDocument $xml Structure source to apply behaviour onto.
@todo split method into submethods
@return \DOMDocument | [
"Find",
"all",
"return",
"tags",
"that",
"contain",
"self",
"or",
"$this",
"and",
"replace",
"those",
"terms",
"for",
"the",
"name",
"of",
"the",
"current",
"class",
"type",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/CoversTag.php#L29-L159 |
WellCommerce/AppBundle | Validator/UniqueUsernameValidator.php | UniqueUsernameValidator.validate | public function validate($entity, Constraint $constraint)
{
if (!$entity instanceof ClientDetails) {
throw new \InvalidArgumentException('Expected instance of ClientDetails');
}
$username = $entity->getUsername();
$result = $this->clientRepository->findOneBy(['clientDetails.username' => $username]);
if (null === $result) {
return;
}
if ($this->context instanceof ExecutionContextInterface) {
$this->context
->buildViolation($constraint->message)
->setParameter('{{ url }}', $this->routerHelper->generateUrl('front.client.login'))
->atPath('username')
->setInvalidValue($username)
->addViolation();
}
} | php | public function validate($entity, Constraint $constraint)
{
if (!$entity instanceof ClientDetails) {
throw new \InvalidArgumentException('Expected instance of ClientDetails');
}
$username = $entity->getUsername();
$result = $this->clientRepository->findOneBy(['clientDetails.username' => $username]);
if (null === $result) {
return;
}
if ($this->context instanceof ExecutionContextInterface) {
$this->context
->buildViolation($constraint->message)
->setParameter('{{ url }}', $this->routerHelper->generateUrl('front.client.login'))
->atPath('username')
->setInvalidValue($username)
->addViolation();
}
} | [
"public",
"function",
"validate",
"(",
"$",
"entity",
",",
"Constraint",
"$",
"constraint",
")",
"{",
"if",
"(",
"!",
"$",
"entity",
"instanceof",
"ClientDetails",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Expected instance of ClientDetails'",
")",
";",
"}",
"$",
"username",
"=",
"$",
"entity",
"->",
"getUsername",
"(",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"clientRepository",
"->",
"findOneBy",
"(",
"[",
"'clientDetails.username'",
"=>",
"$",
"username",
"]",
")",
";",
"if",
"(",
"null",
"===",
"$",
"result",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"context",
"instanceof",
"ExecutionContextInterface",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"buildViolation",
"(",
"$",
"constraint",
"->",
"message",
")",
"->",
"setParameter",
"(",
"'{{ url }}'",
",",
"$",
"this",
"->",
"routerHelper",
"->",
"generateUrl",
"(",
"'front.client.login'",
")",
")",
"->",
"atPath",
"(",
"'username'",
")",
"->",
"setInvalidValue",
"(",
"$",
"username",
")",
"->",
"addViolation",
"(",
")",
";",
"}",
"}"
] | Validate the route entity
@param mixed $entity
@param Constraint $constraint | [
"Validate",
"the",
"route",
"entity"
] | train | https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Validator/UniqueUsernameValidator.php#L56-L77 |
ekuiter/feature-php | FeaturePhp/Collaboration/Composer.php | Composer.getComposerMap | public static function getComposerMap() {
$composerMap = array();
foreach (self::getComposers() as $composer)
$composerMap[call_user_func(array($composer, "getKind"))] = $composer;
return $composerMap;
} | php | public static function getComposerMap() {
$composerMap = array();
foreach (self::getComposers() as $composer)
$composerMap[call_user_func(array($composer, "getKind"))] = $composer;
return $composerMap;
} | [
"public",
"static",
"function",
"getComposerMap",
"(",
")",
"{",
"$",
"composerMap",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"self",
"::",
"getComposers",
"(",
")",
"as",
"$",
"composer",
")",
"$",
"composerMap",
"[",
"call_user_func",
"(",
"array",
"(",
"$",
"composer",
",",
"\"getKind\"",
")",
")",
"]",
"=",
"$",
"composer",
";",
"return",
"$",
"composerMap",
";",
"}"
] | Returns a map from all composer kinds to class names.
@return string[] | [
"Returns",
"a",
"map",
"from",
"all",
"composer",
"kinds",
"to",
"class",
"names",
"."
] | train | https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Collaboration/Composer.php#L37-L42 |
ekuiter/feature-php | FeaturePhp/Collaboration/Composer.php | Composer.fromKind | public static function fromKind($kind) {
$composerMap = self::getComposerMap();
if (!array_key_exists($kind, $composerMap))
throw new ComposerException("no composer found for \"$kind\"");
$class = $composerMap[$kind];
return new $class();
} | php | public static function fromKind($kind) {
$composerMap = self::getComposerMap();
if (!array_key_exists($kind, $composerMap))
throw new ComposerException("no composer found for \"$kind\"");
$class = $composerMap[$kind];
return new $class();
} | [
"public",
"static",
"function",
"fromKind",
"(",
"$",
"kind",
")",
"{",
"$",
"composerMap",
"=",
"self",
"::",
"getComposerMap",
"(",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"kind",
",",
"$",
"composerMap",
")",
")",
"throw",
"new",
"ComposerException",
"(",
"\"no composer found for \\\"$kind\\\"\"",
")",
";",
"$",
"class",
"=",
"$",
"composerMap",
"[",
"$",
"kind",
"]",
";",
"return",
"new",
"$",
"class",
"(",
")",
";",
"}"
] | Creates a composer from a kind.
@param string $kind
@return Composer | [
"Creates",
"a",
"composer",
"from",
"a",
"kind",
"."
] | train | https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Collaboration/Composer.php#L49-L55 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.routes | public function routes()
{
Route::get('countries/{id}', function ($id) {
$request = request();
return CountryStore::country($id, $request);
})->name('country');
Route::get('countries', function () {
$request = request();
return CountryStore::countries($request);
})->name('countries');
Route::get('administrative_areas/{id}', function ($id) {
$request = request();
return CountryStore::administrativeArea($id, $request);
})->name('administrative_area');
Route::get('cities/{city_id}', function ($city_id) {
$request = request();
return CountryStore::city($city_id, $request);
})->name('city');
} | php | public function routes()
{
Route::get('countries/{id}', function ($id) {
$request = request();
return CountryStore::country($id, $request);
})->name('country');
Route::get('countries', function () {
$request = request();
return CountryStore::countries($request);
})->name('countries');
Route::get('administrative_areas/{id}', function ($id) {
$request = request();
return CountryStore::administrativeArea($id, $request);
})->name('administrative_area');
Route::get('cities/{city_id}', function ($city_id) {
$request = request();
return CountryStore::city($city_id, $request);
})->name('city');
} | [
"public",
"function",
"routes",
"(",
")",
"{",
"Route",
"::",
"get",
"(",
"'countries/{id}'",
",",
"function",
"(",
"$",
"id",
")",
"{",
"$",
"request",
"=",
"request",
"(",
")",
";",
"return",
"CountryStore",
"::",
"country",
"(",
"$",
"id",
",",
"$",
"request",
")",
";",
"}",
")",
"->",
"name",
"(",
"'country'",
")",
";",
"Route",
"::",
"get",
"(",
"'countries'",
",",
"function",
"(",
")",
"{",
"$",
"request",
"=",
"request",
"(",
")",
";",
"return",
"CountryStore",
"::",
"countries",
"(",
"$",
"request",
")",
";",
"}",
")",
"->",
"name",
"(",
"'countries'",
")",
";",
"Route",
"::",
"get",
"(",
"'administrative_areas/{id}'",
",",
"function",
"(",
"$",
"id",
")",
"{",
"$",
"request",
"=",
"request",
"(",
")",
";",
"return",
"CountryStore",
"::",
"administrativeArea",
"(",
"$",
"id",
",",
"$",
"request",
")",
";",
"}",
")",
"->",
"name",
"(",
"'administrative_area'",
")",
";",
"Route",
"::",
"get",
"(",
"'cities/{city_id}'",
",",
"function",
"(",
"$",
"city_id",
")",
"{",
"$",
"request",
"=",
"request",
"(",
")",
";",
"return",
"CountryStore",
"::",
"city",
"(",
"$",
"city_id",
",",
"$",
"request",
")",
";",
"}",
")",
"->",
"name",
"(",
"'city'",
")",
";",
"}"
] | Set routes for country API
@return void | [
"Set",
"routes",
"for",
"country",
"API"
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L21-L42 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.country | public function country($country_id, Request $request = null)
{
$country = Country::with('zone')->find($country_id);
if ($request) {
$included = [];
$query = $country->getInlcudeResources($request->include);
if ($query) {
$collection = new Collection(
$query,
str_singular($request->include)
);
$included = $collection->toArray();
}
$links = $request ? ['self' => $request->url()] : [];
return $this->respondWithItem(
$country,
'country',
$links,
$included
);
}
return $country;
} | php | public function country($country_id, Request $request = null)
{
$country = Country::with('zone')->find($country_id);
if ($request) {
$included = [];
$query = $country->getInlcudeResources($request->include);
if ($query) {
$collection = new Collection(
$query,
str_singular($request->include)
);
$included = $collection->toArray();
}
$links = $request ? ['self' => $request->url()] : [];
return $this->respondWithItem(
$country,
'country',
$links,
$included
);
}
return $country;
} | [
"public",
"function",
"country",
"(",
"$",
"country_id",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"country",
"=",
"Country",
"::",
"with",
"(",
"'zone'",
")",
"->",
"find",
"(",
"$",
"country_id",
")",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"included",
"=",
"[",
"]",
";",
"$",
"query",
"=",
"$",
"country",
"->",
"getInlcudeResources",
"(",
"$",
"request",
"->",
"include",
")",
";",
"if",
"(",
"$",
"query",
")",
"{",
"$",
"collection",
"=",
"new",
"Collection",
"(",
"$",
"query",
",",
"str_singular",
"(",
"$",
"request",
"->",
"include",
")",
")",
";",
"$",
"included",
"=",
"$",
"collection",
"->",
"toArray",
"(",
")",
";",
"}",
"$",
"links",
"=",
"$",
"request",
"?",
"[",
"'self'",
"=>",
"$",
"request",
"->",
"url",
"(",
")",
"]",
":",
"[",
"]",
";",
"return",
"$",
"this",
"->",
"respondWithItem",
"(",
"$",
"country",
",",
"'country'",
",",
"$",
"links",
",",
"$",
"included",
")",
";",
"}",
"return",
"$",
"country",
";",
"}"
] | Get Country item. Optional include administrative areas
@param int $country_id
@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\Country item | [
"Get",
"Country",
"item",
".",
"Optional",
"include",
"administrative",
"areas"
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L51-L74 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.countries | public function countries(Request $request = null)
{
$query = Country::with('zone');
if ($request) {
$resource = new Collection($query, 'country', $request);
return $this->respondWithCollection($resource);
}
return $query->get();
} | php | public function countries(Request $request = null)
{
$query = Country::with('zone');
if ($request) {
$resource = new Collection($query, 'country', $request);
return $this->respondWithCollection($resource);
}
return $query->get();
} | [
"public",
"function",
"countries",
"(",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"query",
"=",
"Country",
"::",
"with",
"(",
"'zone'",
")",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"resource",
"=",
"new",
"Collection",
"(",
"$",
"query",
",",
"'country'",
",",
"$",
"request",
")",
";",
"return",
"$",
"this",
"->",
"respondWithCollection",
"(",
"$",
"resource",
")",
";",
"}",
"return",
"$",
"query",
"->",
"get",
"(",
")",
";",
"}"
] | Get Country list
@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\Country collection | [
"Get",
"Country",
"list"
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L82-L91 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.administrativeArea | public function administrativeArea($admin_area_id, Request $request = null)
{
$admin_area = AdministrativeArea::find($admin_area_id);
if ($request) {
$included = [];
if (
$request->has('include') &&
AdministrativeArea::isIncludable($request->include)
) {
$cities = $admin_area->cities()->getQuery();
$cities_included = new Collection($cities, 'city');
$included = $cities_included->toArray();
}
$links = $request ? ['self' => $request->url()] : [];
return $this->respondWithItem(
$admin_area,
'administrative_area',
$links,
$included
);
}
return $admin_area;
} | php | public function administrativeArea($admin_area_id, Request $request = null)
{
$admin_area = AdministrativeArea::find($admin_area_id);
if ($request) {
$included = [];
if (
$request->has('include') &&
AdministrativeArea::isIncludable($request->include)
) {
$cities = $admin_area->cities()->getQuery();
$cities_included = new Collection($cities, 'city');
$included = $cities_included->toArray();
}
$links = $request ? ['self' => $request->url()] : [];
return $this->respondWithItem(
$admin_area,
'administrative_area',
$links,
$included
);
}
return $admin_area;
} | [
"public",
"function",
"administrativeArea",
"(",
"$",
"admin_area_id",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"admin_area",
"=",
"AdministrativeArea",
"::",
"find",
"(",
"$",
"admin_area_id",
")",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"included",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"request",
"->",
"has",
"(",
"'include'",
")",
"&&",
"AdministrativeArea",
"::",
"isIncludable",
"(",
"$",
"request",
"->",
"include",
")",
")",
"{",
"$",
"cities",
"=",
"$",
"admin_area",
"->",
"cities",
"(",
")",
"->",
"getQuery",
"(",
")",
";",
"$",
"cities_included",
"=",
"new",
"Collection",
"(",
"$",
"cities",
",",
"'city'",
")",
";",
"$",
"included",
"=",
"$",
"cities_included",
"->",
"toArray",
"(",
")",
";",
"}",
"$",
"links",
"=",
"$",
"request",
"?",
"[",
"'self'",
"=>",
"$",
"request",
"->",
"url",
"(",
")",
"]",
":",
"[",
"]",
";",
"return",
"$",
"this",
"->",
"respondWithItem",
"(",
"$",
"admin_area",
",",
"'administrative_area'",
",",
"$",
"links",
",",
"$",
"included",
")",
";",
"}",
"return",
"$",
"admin_area",
";",
"}"
] | Get Administrative area item, optional include cities
@param int $admin_area_id
@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\AdministrativeArea item | [
"Get",
"Administrative",
"area",
"item",
"optional",
"include",
"cities"
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L100-L123 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.administrativeAreas | public function administrativeAreas($country_id, Request $request = null)
{
$query = AdministrativeArea::where('country_id', $country_id)
->with('country');
if ($request) {
$resource = new Collection($query, 'administrative_area', $request);
return $this->respondWithCollection($resource);
}
return $query->get();
} | php | public function administrativeAreas($country_id, Request $request = null)
{
$query = AdministrativeArea::where('country_id', $country_id)
->with('country');
if ($request) {
$resource = new Collection($query, 'administrative_area', $request);
return $this->respondWithCollection($resource);
}
return $query->get();
} | [
"public",
"function",
"administrativeAreas",
"(",
"$",
"country_id",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"query",
"=",
"AdministrativeArea",
"::",
"where",
"(",
"'country_id'",
",",
"$",
"country_id",
")",
"->",
"with",
"(",
"'country'",
")",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"resource",
"=",
"new",
"Collection",
"(",
"$",
"query",
",",
"'administrative_area'",
",",
"$",
"request",
")",
";",
"return",
"$",
"this",
"->",
"respondWithCollection",
"(",
"$",
"resource",
")",
";",
"}",
"return",
"$",
"query",
"->",
"get",
"(",
")",
";",
"}"
] | Get Administrative areas collection of a country given
@param int $country_id
@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\AdministrativeArea collection | [
"Get",
"Administrative",
"areas",
"collection",
"of",
"a",
"country",
"given"
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L132-L142 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.city | public function city($city_id, Request $request = null)
{
$city = City::find($city_id);
if ($request) {
$included = [];
$query = $city->getInlcudeResources($request->include);
if ($query) {
$collection = new Collection($query, $request->include);
$included = $collection->toArray();
}
$links = $request ? ['self' => $request->url()] : [];
return $this->respondWithItem($city, 'city', $links, $included);
}
return $city;
} | php | public function city($city_id, Request $request = null)
{
$city = City::find($city_id);
if ($request) {
$included = [];
$query = $city->getInlcudeResources($request->include);
if ($query) {
$collection = new Collection($query, $request->include);
$included = $collection->toArray();
}
$links = $request ? ['self' => $request->url()] : [];
return $this->respondWithItem($city, 'city', $links, $included);
}
return $city;
} | [
"public",
"function",
"city",
"(",
"$",
"city_id",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"city",
"=",
"City",
"::",
"find",
"(",
"$",
"city_id",
")",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"included",
"=",
"[",
"]",
";",
"$",
"query",
"=",
"$",
"city",
"->",
"getInlcudeResources",
"(",
"$",
"request",
"->",
"include",
")",
";",
"if",
"(",
"$",
"query",
")",
"{",
"$",
"collection",
"=",
"new",
"Collection",
"(",
"$",
"query",
",",
"$",
"request",
"->",
"include",
")",
";",
"$",
"included",
"=",
"$",
"collection",
"->",
"toArray",
"(",
")",
";",
"}",
"$",
"links",
"=",
"$",
"request",
"?",
"[",
"'self'",
"=>",
"$",
"request",
"->",
"url",
"(",
")",
"]",
":",
"[",
"]",
";",
"return",
"$",
"this",
"->",
"respondWithItem",
"(",
"$",
"city",
",",
"'city'",
",",
"$",
"links",
",",
"$",
"included",
")",
";",
"}",
"return",
"$",
"city",
";",
"}"
] | Get city item, optional include administrative division.
@param int $city_id
@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\City item | [
"Get",
"city",
"item",
"optional",
"include",
"administrative",
"division",
"."
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L151-L166 |
jnaxo/country-codes | src/CountryStore.php | CountryStore.cities | public function cities($country_id, Request $request = null)
{
$query = City::with([
'administrativeArea' => function ($q) use ($country_id) {
$q->where('country_id', $country_id);
}
])
->with('administrativeArea.country');
if ($request) {
$resource = new Collection($query, 'city', $request);
return $this->respondWithCollection($resource);
}
return $query->get();
} | php | public function cities($country_id, Request $request = null)
{
$query = City::with([
'administrativeArea' => function ($q) use ($country_id) {
$q->where('country_id', $country_id);
}
])
->with('administrativeArea.country');
if ($request) {
$resource = new Collection($query, 'city', $request);
return $this->respondWithCollection($resource);
}
return $query->get();
} | [
"public",
"function",
"cities",
"(",
"$",
"country_id",
",",
"Request",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"query",
"=",
"City",
"::",
"with",
"(",
"[",
"'administrativeArea'",
"=>",
"function",
"(",
"$",
"q",
")",
"use",
"(",
"$",
"country_id",
")",
"{",
"$",
"q",
"->",
"where",
"(",
"'country_id'",
",",
"$",
"country_id",
")",
";",
"}",
"]",
")",
"->",
"with",
"(",
"'administrativeArea.country'",
")",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"resource",
"=",
"new",
"Collection",
"(",
"$",
"query",
",",
"'city'",
",",
"$",
"request",
")",
";",
"return",
"$",
"this",
"->",
"respondWithCollection",
"(",
"$",
"resource",
")",
";",
"}",
"return",
"$",
"query",
"->",
"get",
"(",
")",
";",
"}"
] | Get country cities
@param int $country_id
@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\City collection | [
"Get",
"country",
"cities"
] | train | https://github.com/jnaxo/country-codes/blob/ab1f24886e1b49eef5fd4b4eb4fb37aa7faeacd9/src/CountryStore.php#L175-L189 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php | AreAllArgumentsValidValidator.validate | public function validate($value, Constraint $constraint)
{
if (! $value instanceof MethodDescriptor
&& ! $value instanceof FunctionDescriptor
) {
throw new ConstraintDefinitionException(
'The Functions\AreAllArgumentsValid validator may only be used on function or method objects'
);
}
$this->constraint = $constraint;
$this->initValueObject($value);
$violation = $this->processArgumentValidation();
if ($violation) {
return $violation;
}
$this->checkParamsExists();
} | php | public function validate($value, Constraint $constraint)
{
if (! $value instanceof MethodDescriptor
&& ! $value instanceof FunctionDescriptor
) {
throw new ConstraintDefinitionException(
'The Functions\AreAllArgumentsValid validator may only be used on function or method objects'
);
}
$this->constraint = $constraint;
$this->initValueObject($value);
$violation = $this->processArgumentValidation();
if ($violation) {
return $violation;
}
$this->checkParamsExists();
} | [
"public",
"function",
"validate",
"(",
"$",
"value",
",",
"Constraint",
"$",
"constraint",
")",
"{",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"MethodDescriptor",
"&&",
"!",
"$",
"value",
"instanceof",
"FunctionDescriptor",
")",
"{",
"throw",
"new",
"ConstraintDefinitionException",
"(",
"'The Functions\\AreAllArgumentsValid validator may only be used on function or method objects'",
")",
";",
"}",
"$",
"this",
"->",
"constraint",
"=",
"$",
"constraint",
";",
"$",
"this",
"->",
"initValueObject",
"(",
"$",
"value",
")",
";",
"$",
"violation",
"=",
"$",
"this",
"->",
"processArgumentValidation",
"(",
")",
";",
"if",
"(",
"$",
"violation",
")",
"{",
"return",
"$",
"violation",
";",
"}",
"$",
"this",
"->",
"checkParamsExists",
"(",
")",
";",
"}"
] | @see \Symfony\Component\Validator\ConstraintValidatorInterface::validate()
@throws ConstraintDefinitionException | [
"@see",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Validator",
"\\",
"ConstraintValidatorInterface",
"::",
"validate",
"()"
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php#L44-L64 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php | AreAllArgumentsValidValidator.checkArgumentInDocBlock | protected function checkArgumentInDocBlock()
{
$validator = new IsArgumentInDocBlockValidator();
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new IsArgumentInDocBlock);
} | php | protected function checkArgumentInDocBlock()
{
$validator = new IsArgumentInDocBlockValidator();
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new IsArgumentInDocBlock);
} | [
"protected",
"function",
"checkArgumentInDocBlock",
"(",
")",
"{",
"$",
"validator",
"=",
"new",
"IsArgumentInDocBlockValidator",
"(",
")",
";",
"$",
"validator",
"->",
"initialize",
"(",
"$",
"this",
"->",
"context",
")",
";",
"return",
"$",
"validator",
"->",
"validate",
"(",
"$",
"this",
"->",
"validationValue",
",",
"new",
"IsArgumentInDocBlock",
")",
";",
"}"
] | Check if argument is inside docblock. | [
"Check",
"if",
"argument",
"is",
"inside",
"docblock",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php#L111-L117 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php | AreAllArgumentsValidValidator.checkArgumentNameMatchParam | protected function checkArgumentNameMatchParam()
{
$validator = new DoesArgumentNameMatchParamValidator;
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new DoesArgumentNameMatchParam);
} | php | protected function checkArgumentNameMatchParam()
{
$validator = new DoesArgumentNameMatchParamValidator;
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new DoesArgumentNameMatchParam);
} | [
"protected",
"function",
"checkArgumentNameMatchParam",
"(",
")",
"{",
"$",
"validator",
"=",
"new",
"DoesArgumentNameMatchParamValidator",
";",
"$",
"validator",
"->",
"initialize",
"(",
"$",
"this",
"->",
"context",
")",
";",
"return",
"$",
"validator",
"->",
"validate",
"(",
"$",
"this",
"->",
"validationValue",
",",
"new",
"DoesArgumentNameMatchParam",
")",
";",
"}"
] | Check if argument matches parameter. | [
"Check",
"if",
"argument",
"matches",
"parameter",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php#L122-L128 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php | AreAllArgumentsValidValidator.checkArgumentTypehintMatchParam | protected function checkArgumentTypehintMatchParam()
{
$validator = new DoesArgumentTypehintMatchParamValidator;
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new DoesArgumentTypehintMatchParam);
} | php | protected function checkArgumentTypehintMatchParam()
{
$validator = new DoesArgumentTypehintMatchParamValidator;
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new DoesArgumentTypehintMatchParam);
} | [
"protected",
"function",
"checkArgumentTypehintMatchParam",
"(",
")",
"{",
"$",
"validator",
"=",
"new",
"DoesArgumentTypehintMatchParamValidator",
";",
"$",
"validator",
"->",
"initialize",
"(",
"$",
"this",
"->",
"context",
")",
";",
"return",
"$",
"validator",
"->",
"validate",
"(",
"$",
"this",
"->",
"validationValue",
",",
"new",
"DoesArgumentTypehintMatchParam",
")",
";",
"}"
] | Check if argument typehint matches parameter. | [
"Check",
"if",
"argument",
"typehint",
"matches",
"parameter",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php#L133-L139 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php | AreAllArgumentsValidValidator.checkParamsExists | protected function checkParamsExists()
{
$validator = new DoesParamsExistsValidator();
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new DoesParamsExists);
} | php | protected function checkParamsExists()
{
$validator = new DoesParamsExistsValidator();
$validator->initialize($this->context);
return $validator->validate($this->validationValue, new DoesParamsExists);
} | [
"protected",
"function",
"checkParamsExists",
"(",
")",
"{",
"$",
"validator",
"=",
"new",
"DoesParamsExistsValidator",
"(",
")",
";",
"$",
"validator",
"->",
"initialize",
"(",
"$",
"this",
"->",
"context",
")",
";",
"return",
"$",
"validator",
"->",
"validate",
"(",
"$",
"this",
"->",
"validationValue",
",",
"new",
"DoesParamsExists",
")",
";",
"}"
] | Check if parameter exists for argument.
@param Collection $params
@param Collection $arguments | [
"Check",
"if",
"parameter",
"exists",
"for",
"argument",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Functions/AreAllArgumentsValidValidator.php#L147-L153 |
inhere/php-librarys | src/Components/EnvDetector.php | EnvDetector.getEnvNameByHost | public static function getEnvNameByHost(string $defaultEnv = null, string $hostname = null): string
{
$hostname = $hostname ?: gethostname();
if (!$hostname) {
return $defaultEnv;
}
foreach (self::$host2env as $kw => $env) {
if (false !== strpos($hostname, $kw)) {
return $env;
}
}
return $defaultEnv;
} | php | public static function getEnvNameByHost(string $defaultEnv = null, string $hostname = null): string
{
$hostname = $hostname ?: gethostname();
if (!$hostname) {
return $defaultEnv;
}
foreach (self::$host2env as $kw => $env) {
if (false !== strpos($hostname, $kw)) {
return $env;
}
}
return $defaultEnv;
} | [
"public",
"static",
"function",
"getEnvNameByHost",
"(",
"string",
"$",
"defaultEnv",
"=",
"null",
",",
"string",
"$",
"hostname",
"=",
"null",
")",
":",
"string",
"{",
"$",
"hostname",
"=",
"$",
"hostname",
"?",
":",
"gethostname",
"(",
")",
";",
"if",
"(",
"!",
"$",
"hostname",
")",
"{",
"return",
"$",
"defaultEnv",
";",
"}",
"foreach",
"(",
"self",
"::",
"$",
"host2env",
"as",
"$",
"kw",
"=>",
"$",
"env",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"hostname",
",",
"$",
"kw",
")",
")",
"{",
"return",
"$",
"env",
";",
"}",
"}",
"return",
"$",
"defaultEnv",
";",
"}"
] | get Env Name By Host
@param null|string $hostname
@param string $defaultEnv
@return string | [
"get",
"Env",
"Name",
"By",
"Host"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/EnvDetector.php#L49-L64 |
inhere/php-librarys | src/Components/EnvDetector.php | EnvDetector.getEnvNameByDomain | public static function getEnvNameByDomain(string $defaultEnv = null, string $domain = null): string
{
$domain = $domain ?: PhpHelper::serverParam('HTTP_HOST');
if (!$domain) {
return $defaultEnv;
}
foreach (self::$domain2env as $kw => $env) {
if (false !== strpos($domain, $kw)) {
return $env;
}
}
return $defaultEnv;
} | php | public static function getEnvNameByDomain(string $defaultEnv = null, string $domain = null): string
{
$domain = $domain ?: PhpHelper::serverParam('HTTP_HOST');
if (!$domain) {
return $defaultEnv;
}
foreach (self::$domain2env as $kw => $env) {
if (false !== strpos($domain, $kw)) {
return $env;
}
}
return $defaultEnv;
} | [
"public",
"static",
"function",
"getEnvNameByDomain",
"(",
"string",
"$",
"defaultEnv",
"=",
"null",
",",
"string",
"$",
"domain",
"=",
"null",
")",
":",
"string",
"{",
"$",
"domain",
"=",
"$",
"domain",
"?",
":",
"PhpHelper",
"::",
"serverParam",
"(",
"'HTTP_HOST'",
")",
";",
"if",
"(",
"!",
"$",
"domain",
")",
"{",
"return",
"$",
"defaultEnv",
";",
"}",
"foreach",
"(",
"self",
"::",
"$",
"domain2env",
"as",
"$",
"kw",
"=>",
"$",
"env",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"domain",
",",
"$",
"kw",
")",
")",
"{",
"return",
"$",
"env",
";",
"}",
"}",
"return",
"$",
"defaultEnv",
";",
"}"
] | get Env Name By Domain
@param string $defaultEnv
@param null|string $domain
@return string | [
"get",
"Env",
"Name",
"By",
"Domain"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/EnvDetector.php#L72-L87 |
Isset/pushnotification | src/PushNotification/Type/Windows/WindowsConnection.php | WindowsConnection.sendAndReceive | public function sendAndReceive(Message $message): Response
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><wp:Notification xmlns:wp="WPNotification" />');
$toast = $xml->addChild('wp:Toast');
foreach ($message->getMessage() as $element => $value) {
$toast->addChild($element, htmlspecialchars($value, ENT_XML1 | ENT_QUOTES));
}
$response = new ConnectionResponseImpl();
$request = new Request('POST', $message->getIdentifier(), [], $xml->asXML());
try {
$clientResponse = $this->client->send($request);
// check against headers? X-NotificationStatus / X-SubscriptionStatus / X-DeviceConnectionStatus
// @see https://msdn.microsoft.com/en-us/library/windows/apps/ff941100(v=vs.105).aspx
$response->setResponse($clientResponse->getBody()->getContents());
} catch (RequestException $e) {
$response->setErrorResponse($e);
}
return $response;
} | php | public function sendAndReceive(Message $message): Response
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><wp:Notification xmlns:wp="WPNotification" />');
$toast = $xml->addChild('wp:Toast');
foreach ($message->getMessage() as $element => $value) {
$toast->addChild($element, htmlspecialchars($value, ENT_XML1 | ENT_QUOTES));
}
$response = new ConnectionResponseImpl();
$request = new Request('POST', $message->getIdentifier(), [], $xml->asXML());
try {
$clientResponse = $this->client->send($request);
// check against headers? X-NotificationStatus / X-SubscriptionStatus / X-DeviceConnectionStatus
// @see https://msdn.microsoft.com/en-us/library/windows/apps/ff941100(v=vs.105).aspx
$response->setResponse($clientResponse->getBody()->getContents());
} catch (RequestException $e) {
$response->setErrorResponse($e);
}
return $response;
} | [
"public",
"function",
"sendAndReceive",
"(",
"Message",
"$",
"message",
")",
":",
"Response",
"{",
"$",
"xml",
"=",
"new",
"\\",
"SimpleXMLElement",
"(",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\" />'",
")",
";",
"$",
"toast",
"=",
"$",
"xml",
"->",
"addChild",
"(",
"'wp:Toast'",
")",
";",
"foreach",
"(",
"$",
"message",
"->",
"getMessage",
"(",
")",
"as",
"$",
"element",
"=>",
"$",
"value",
")",
"{",
"$",
"toast",
"->",
"addChild",
"(",
"$",
"element",
",",
"htmlspecialchars",
"(",
"$",
"value",
",",
"ENT_XML1",
"|",
"ENT_QUOTES",
")",
")",
";",
"}",
"$",
"response",
"=",
"new",
"ConnectionResponseImpl",
"(",
")",
";",
"$",
"request",
"=",
"new",
"Request",
"(",
"'POST'",
",",
"$",
"message",
"->",
"getIdentifier",
"(",
")",
",",
"[",
"]",
",",
"$",
"xml",
"->",
"asXML",
"(",
")",
")",
";",
"try",
"{",
"$",
"clientResponse",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"$",
"request",
")",
";",
"// check against headers? X-NotificationStatus / X-SubscriptionStatus / X-DeviceConnectionStatus",
"// @see https://msdn.microsoft.com/en-us/library/windows/apps/ff941100(v=vs.105).aspx",
"$",
"response",
"->",
"setResponse",
"(",
"$",
"clientResponse",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
")",
";",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"$",
"response",
"->",
"setErrorResponse",
"(",
"$",
"e",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | @param Message $message
@throws ConnectionException
@throws ConnectionHandlerException
@return Response | [
"@param",
"Message",
"$message"
] | train | https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Type/Windows/WindowsConnection.php#L75-L95 |
WellCommerce/StandardEditionBundle | DataFixtures/ORM/LoadUserData.php | LoadUserData.load | public function load(ObjectManager $manager)
{
if (!$this->isEnabled()) {
return;
}
$role = new Role();
$role->setName('admin');
$role->setRole('ROLE_ADMIN');
$manager->persist($role);
$this->setReference('default_role', $role);
$group = new UserGroup();
$group->setName('Administration');
$group->setPermissions($this->getPermissions($group));
$manager->persist($group);
$this->setReference('default_group', $group);
$user = new User();
$user->setFirstName('John');
$user->setLastName('Doe');
$user->setUsername('admin');
$user->setEmail('[email protected]');
$user->setEnabled(1);
$user->setPassword('admin');
$user->addRole($role);
$user->getGroups()->add($group);
$user->setApiKey($this->container->get('security.helper')->generateRandomPassword());
$manager->persist($user);
$manager->flush();
} | php | public function load(ObjectManager $manager)
{
if (!$this->isEnabled()) {
return;
}
$role = new Role();
$role->setName('admin');
$role->setRole('ROLE_ADMIN');
$manager->persist($role);
$this->setReference('default_role', $role);
$group = new UserGroup();
$group->setName('Administration');
$group->setPermissions($this->getPermissions($group));
$manager->persist($group);
$this->setReference('default_group', $group);
$user = new User();
$user->setFirstName('John');
$user->setLastName('Doe');
$user->setUsername('admin');
$user->setEmail('[email protected]');
$user->setEnabled(1);
$user->setPassword('admin');
$user->addRole($role);
$user->getGroups()->add($group);
$user->setApiKey($this->container->get('security.helper')->generateRandomPassword());
$manager->persist($user);
$manager->flush();
} | [
"public",
"function",
"load",
"(",
"ObjectManager",
"$",
"manager",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"role",
"=",
"new",
"Role",
"(",
")",
";",
"$",
"role",
"->",
"setName",
"(",
"'admin'",
")",
";",
"$",
"role",
"->",
"setRole",
"(",
"'ROLE_ADMIN'",
")",
";",
"$",
"manager",
"->",
"persist",
"(",
"$",
"role",
")",
";",
"$",
"this",
"->",
"setReference",
"(",
"'default_role'",
",",
"$",
"role",
")",
";",
"$",
"group",
"=",
"new",
"UserGroup",
"(",
")",
";",
"$",
"group",
"->",
"setName",
"(",
"'Administration'",
")",
";",
"$",
"group",
"->",
"setPermissions",
"(",
"$",
"this",
"->",
"getPermissions",
"(",
"$",
"group",
")",
")",
";",
"$",
"manager",
"->",
"persist",
"(",
"$",
"group",
")",
";",
"$",
"this",
"->",
"setReference",
"(",
"'default_group'",
",",
"$",
"group",
")",
";",
"$",
"user",
"=",
"new",
"User",
"(",
")",
";",
"$",
"user",
"->",
"setFirstName",
"(",
"'John'",
")",
";",
"$",
"user",
"->",
"setLastName",
"(",
"'Doe'",
")",
";",
"$",
"user",
"->",
"setUsername",
"(",
"'admin'",
")",
";",
"$",
"user",
"->",
"setEmail",
"(",
"'[email protected]'",
")",
";",
"$",
"user",
"->",
"setEnabled",
"(",
"1",
")",
";",
"$",
"user",
"->",
"setPassword",
"(",
"'admin'",
")",
";",
"$",
"user",
"->",
"addRole",
"(",
"$",
"role",
")",
";",
"$",
"user",
"->",
"getGroups",
"(",
")",
"->",
"add",
"(",
"$",
"group",
")",
";",
"$",
"user",
"->",
"setApiKey",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'security.helper'",
")",
"->",
"generateRandomPassword",
"(",
")",
")",
";",
"$",
"manager",
"->",
"persist",
"(",
"$",
"user",
")",
";",
"$",
"manager",
"->",
"flush",
"(",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/WellCommerce/StandardEditionBundle/blob/6367bd20bbb6bde37c710a6ba87ae72b5f05f61e/DataFixtures/ORM/LoadUserData.php#L33-L66 |
zhouyl/mellivora | Mellivora/View/Concerns/ManagesComponents.php | ManagesComponents.slot | public function slot($name, $content = null)
{
if (count(func_get_args()) === 2) {
$this->slots[$this->currentComponent()][$name] = $content;
} else {
if (ob_start()) {
$this->slots[$this->currentComponent()][$name] = '';
$this->slotStack[$this->currentComponent()][] = $name;
}
}
} | php | public function slot($name, $content = null)
{
if (count(func_get_args()) === 2) {
$this->slots[$this->currentComponent()][$name] = $content;
} else {
if (ob_start()) {
$this->slots[$this->currentComponent()][$name] = '';
$this->slotStack[$this->currentComponent()][] = $name;
}
}
} | [
"public",
"function",
"slot",
"(",
"$",
"name",
",",
"$",
"content",
"=",
"null",
")",
"{",
"if",
"(",
"count",
"(",
"func_get_args",
"(",
")",
")",
"===",
"2",
")",
"{",
"$",
"this",
"->",
"slots",
"[",
"$",
"this",
"->",
"currentComponent",
"(",
")",
"]",
"[",
"$",
"name",
"]",
"=",
"$",
"content",
";",
"}",
"else",
"{",
"if",
"(",
"ob_start",
"(",
")",
")",
"{",
"$",
"this",
"->",
"slots",
"[",
"$",
"this",
"->",
"currentComponent",
"(",
")",
"]",
"[",
"$",
"name",
"]",
"=",
"''",
";",
"$",
"this",
"->",
"slotStack",
"[",
"$",
"this",
"->",
"currentComponent",
"(",
")",
"]",
"[",
"]",
"=",
"$",
"name",
";",
"}",
"}",
"}"
] | Start the slot rendering process.
@param string $name
@param null|string $content
@return void | [
"Start",
"the",
"slot",
"rendering",
"process",
"."
] | train | https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/View/Concerns/ManagesComponents.php#L92-L103 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/Traits/TimestampTrait.php | TimestampTrait.initTimestampTrait | protected static function initTimestampTrait()
{
$update_timestamps = isset(static::$update_timestamps) ? (array) static::$update_timestamps : ['updated_at'];
$insert_timestamps = isset(static::$insert_timestamps) ? static::$insert_timestamps : ['created_at'];
$insert_timestamps = array_merge($update_timestamps, $insert_timestamps);
static::addEventCallBack('insert', function ($entity) use ($insert_timestamps) {
foreach ($insert_timestamps as $field) {
if (!$entity->getRaw($field)) {
$entity->setRaw($field, new DateTime());
}
}
});
static::addEventCallBack('update', function ($entity) use ($update_timestamps) {
if ($entity->isModified()) {
foreach ($update_timestamps as $field) {
$entity->setRaw($field, new DateTime());
}
}
});
} | php | protected static function initTimestampTrait()
{
$update_timestamps = isset(static::$update_timestamps) ? (array) static::$update_timestamps : ['updated_at'];
$insert_timestamps = isset(static::$insert_timestamps) ? static::$insert_timestamps : ['created_at'];
$insert_timestamps = array_merge($update_timestamps, $insert_timestamps);
static::addEventCallBack('insert', function ($entity) use ($insert_timestamps) {
foreach ($insert_timestamps as $field) {
if (!$entity->getRaw($field)) {
$entity->setRaw($field, new DateTime());
}
}
});
static::addEventCallBack('update', function ($entity) use ($update_timestamps) {
if ($entity->isModified()) {
foreach ($update_timestamps as $field) {
$entity->setRaw($field, new DateTime());
}
}
});
} | [
"protected",
"static",
"function",
"initTimestampTrait",
"(",
")",
"{",
"$",
"update_timestamps",
"=",
"isset",
"(",
"static",
"::",
"$",
"update_timestamps",
")",
"?",
"(",
"array",
")",
"static",
"::",
"$",
"update_timestamps",
":",
"[",
"'updated_at'",
"]",
";",
"$",
"insert_timestamps",
"=",
"isset",
"(",
"static",
"::",
"$",
"insert_timestamps",
")",
"?",
"static",
"::",
"$",
"insert_timestamps",
":",
"[",
"'created_at'",
"]",
";",
"$",
"insert_timestamps",
"=",
"array_merge",
"(",
"$",
"update_timestamps",
",",
"$",
"insert_timestamps",
")",
";",
"static",
"::",
"addEventCallBack",
"(",
"'insert'",
",",
"function",
"(",
"$",
"entity",
")",
"use",
"(",
"$",
"insert_timestamps",
")",
"{",
"foreach",
"(",
"$",
"insert_timestamps",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"$",
"entity",
"->",
"getRaw",
"(",
"$",
"field",
")",
")",
"{",
"$",
"entity",
"->",
"setRaw",
"(",
"$",
"field",
",",
"new",
"DateTime",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"static",
"::",
"addEventCallBack",
"(",
"'update'",
",",
"function",
"(",
"$",
"entity",
")",
"use",
"(",
"$",
"update_timestamps",
")",
"{",
"if",
"(",
"$",
"entity",
"->",
"isModified",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"update_timestamps",
"as",
"$",
"field",
")",
"{",
"$",
"entity",
"->",
"setRaw",
"(",
"$",
"field",
",",
"new",
"DateTime",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | configure the timestamps with $insert_timestamps and
$update_timestamps
protected static $insert_timestamps = [
'createdAt',
'timeCreated',
];
OR
protected static $insert_timestamps = 'createdAt';
protected static $update_timestamps = [
'updatedAt',
'timeUpdated',
];
OR
protected static $update_timestamps = 'updatedAt'; | [
"configure",
"the",
"timestamps",
"with",
"$insert_timestamps",
"and",
"$update_timestamps"
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/Traits/TimestampTrait.php#L32-L54 |
Visithor/visithor | src/Visithor/Renderer/PrettyRenderer.php | PrettyRenderer.render | public function render(
OutputInterface $output,
Url $url,
$HTTPCode,
$success
) {
$color = $success
? '<bg=green> </bg=green>'
: '<bg=red> </bg=red>';
$HTTPCode = (200 == $HTTPCode)
? '<fg=green>200</fg=green>'
: $HTTPCode;
$options = '<fg=cyan>' . json_encode($url->getOptions()) . '</fg=cyan>';
$output->writeln($color . ' [' . $HTTPCode . '] ' . $url->getPath() . ' ' . $options);
return $this;
} | php | public function render(
OutputInterface $output,
Url $url,
$HTTPCode,
$success
) {
$color = $success
? '<bg=green> </bg=green>'
: '<bg=red> </bg=red>';
$HTTPCode = (200 == $HTTPCode)
? '<fg=green>200</fg=green>'
: $HTTPCode;
$options = '<fg=cyan>' . json_encode($url->getOptions()) . '</fg=cyan>';
$output->writeln($color . ' [' . $HTTPCode . '] ' . $url->getPath() . ' ' . $options);
return $this;
} | [
"public",
"function",
"render",
"(",
"OutputInterface",
"$",
"output",
",",
"Url",
"$",
"url",
",",
"$",
"HTTPCode",
",",
"$",
"success",
")",
"{",
"$",
"color",
"=",
"$",
"success",
"?",
"'<bg=green> </bg=green>'",
":",
"'<bg=red> </bg=red>'",
";",
"$",
"HTTPCode",
"=",
"(",
"200",
"==",
"$",
"HTTPCode",
")",
"?",
"'<fg=green>200</fg=green>'",
":",
"$",
"HTTPCode",
";",
"$",
"options",
"=",
"'<fg=cyan>'",
".",
"json_encode",
"(",
"$",
"url",
"->",
"getOptions",
"(",
")",
")",
".",
"'</fg=cyan>'",
";",
"$",
"output",
"->",
"writeln",
"(",
"$",
"color",
".",
"' ['",
".",
"$",
"HTTPCode",
".",
"'] '",
".",
"$",
"url",
"->",
"getPath",
"(",
")",
".",
"' '",
".",
"$",
"options",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Renders an URL execution
@param OutputInterface $output Output
@param Url $url Url
@param string $HTTPCode Returned HTTP Code
@param boolean $success Successfully executed
@return $this Self object | [
"Renders",
"an",
"URL",
"execution"
] | train | https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Renderer/PrettyRenderer.php#L36-L55 |
Humanized/yii2-location | models/location/CitySearch.php | CitySearch.search | public function search($params)
{
$this->load($params);
$query = City::find();
$query->select(['*', 'name' => 'city_translation.name', 'language' => 'city.language_id']);
$query->leftJoin('city_translation', 'city_translation.city_id=city.id');
//$query->andWhere(['city.language_id' => 'city_translation.language_id']);
// $query->joinWith('city');
// $query->joinWith('city.localisedIdentification');
if (isset($this->uid)) {
$this->pageSize = 1;
}
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ($this->pagination ? [
'pageSize' => $this->pageSize,
] : FALSE),
'sort' => [
'attributes' => [
'name', 'postcode', 'language'
],
]
]);
if (isset($this->uid)) {
// uncomment the following line if you do not want to return any records when validation fails
$query->where(['uid' => $this->uid]);
return $dataProvider;
}
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
$query->where('0=1');
return $dataProvider;
}
return $dataProvider;
} | php | public function search($params)
{
$this->load($params);
$query = City::find();
$query->select(['*', 'name' => 'city_translation.name', 'language' => 'city.language_id']);
$query->leftJoin('city_translation', 'city_translation.city_id=city.id');
//$query->andWhere(['city.language_id' => 'city_translation.language_id']);
// $query->joinWith('city');
// $query->joinWith('city.localisedIdentification');
if (isset($this->uid)) {
$this->pageSize = 1;
}
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ($this->pagination ? [
'pageSize' => $this->pageSize,
] : FALSE),
'sort' => [
'attributes' => [
'name', 'postcode', 'language'
],
]
]);
if (isset($this->uid)) {
// uncomment the following line if you do not want to return any records when validation fails
$query->where(['uid' => $this->uid]);
return $dataProvider;
}
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
$query->where('0=1');
return $dataProvider;
}
return $dataProvider;
} | [
"public",
"function",
"search",
"(",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"load",
"(",
"$",
"params",
")",
";",
"$",
"query",
"=",
"City",
"::",
"find",
"(",
")",
";",
"$",
"query",
"->",
"select",
"(",
"[",
"'*'",
",",
"'name'",
"=>",
"'city_translation.name'",
",",
"'language'",
"=>",
"'city.language_id'",
"]",
")",
";",
"$",
"query",
"->",
"leftJoin",
"(",
"'city_translation'",
",",
"'city_translation.city_id=city.id'",
")",
";",
"//$query->andWhere(['city.language_id' => 'city_translation.language_id']);",
"// $query->joinWith('city');",
"// $query->joinWith('city.localisedIdentification');",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"uid",
")",
")",
"{",
"$",
"this",
"->",
"pageSize",
"=",
"1",
";",
"}",
"$",
"dataProvider",
"=",
"new",
"ActiveDataProvider",
"(",
"[",
"'query'",
"=>",
"$",
"query",
",",
"'pagination'",
"=>",
"(",
"$",
"this",
"->",
"pagination",
"?",
"[",
"'pageSize'",
"=>",
"$",
"this",
"->",
"pageSize",
",",
"]",
":",
"FALSE",
")",
",",
"'sort'",
"=>",
"[",
"'attributes'",
"=>",
"[",
"'name'",
",",
"'postcode'",
",",
"'language'",
"]",
",",
"]",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"uid",
")",
")",
"{",
"// uncomment the following line if you do not want to return any records when validation fails",
"$",
"query",
"->",
"where",
"(",
"[",
"'uid'",
"=>",
"$",
"this",
"->",
"uid",
"]",
")",
";",
"return",
"$",
"dataProvider",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"validate",
"(",
")",
")",
"{",
"// uncomment the following line if you do not want to return any records when validation fails",
"$",
"query",
"->",
"where",
"(",
"'0=1'",
")",
";",
"return",
"$",
"dataProvider",
";",
"}",
"return",
"$",
"dataProvider",
";",
"}"
] | Creates data provider instance with search query applied
@param array $params
@return ActiveDataProvider | [
"Creates",
"data",
"provider",
"instance",
"with",
"search",
"query",
"applied"
] | train | https://github.com/Humanized/yii2-location/blob/48ac12ceab741fc4c82ac8e979415a11bf9175f2/models/location/CitySearch.php#L46-L87 |
antaresproject/notifications | src/Processor/SidebarProcessor.php | SidebarProcessor.delete | public function delete()
{
try {
if (is_null($id = Input::get('id'))) {
throw new Exception('Invalid notification id provided');
}
$this->stack->deleteById($id);
} catch (Exception $ex) {
Log::alert($ex);
return new JsonResponse(['message' => trans('antares/notifications::messages.sidebar.unable_to_delete_notification_item')], 500);
}
} | php | public function delete()
{
try {
if (is_null($id = Input::get('id'))) {
throw new Exception('Invalid notification id provided');
}
$this->stack->deleteById($id);
} catch (Exception $ex) {
Log::alert($ex);
return new JsonResponse(['message' => trans('antares/notifications::messages.sidebar.unable_to_delete_notification_item')], 500);
}
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"is_null",
"(",
"$",
"id",
"=",
"Input",
"::",
"get",
"(",
"'id'",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Invalid notification id provided'",
")",
";",
"}",
"$",
"this",
"->",
"stack",
"->",
"deleteById",
"(",
"$",
"id",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"ex",
")",
"{",
"Log",
"::",
"alert",
"(",
"$",
"ex",
")",
";",
"return",
"new",
"JsonResponse",
"(",
"[",
"'message'",
"=>",
"trans",
"(",
"'antares/notifications::messages.sidebar.unable_to_delete_notification_item'",
")",
"]",
",",
"500",
")",
";",
"}",
"}"
] | Deletes item from sidebar
@return JsonResponse | [
"Deletes",
"item",
"from",
"sidebar"
] | train | https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Processor/SidebarProcessor.php#L65-L76 |
antaresproject/notifications | src/Processor/SidebarProcessor.php | SidebarProcessor.read | public function read()
{
try {
$this->stack->markAsRead(from_route('type', 'notifications'));
return new JsonResponse('', 200);
} catch (Exception $ex) {
Log::alert($ex);
return new JsonResponse(['message' => trans('antares/notifications::messages.sidebar.unable_to_mark_notifications_as_read')], 500);
}
} | php | public function read()
{
try {
$this->stack->markAsRead(from_route('type', 'notifications'));
return new JsonResponse('', 200);
} catch (Exception $ex) {
Log::alert($ex);
return new JsonResponse(['message' => trans('antares/notifications::messages.sidebar.unable_to_mark_notifications_as_read')], 500);
}
} | [
"public",
"function",
"read",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"stack",
"->",
"markAsRead",
"(",
"from_route",
"(",
"'type'",
",",
"'notifications'",
")",
")",
";",
"return",
"new",
"JsonResponse",
"(",
"''",
",",
"200",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"ex",
")",
"{",
"Log",
"::",
"alert",
"(",
"$",
"ex",
")",
";",
"return",
"new",
"JsonResponse",
"(",
"[",
"'message'",
"=>",
"trans",
"(",
"'antares/notifications::messages.sidebar.unable_to_mark_notifications_as_read'",
")",
"]",
",",
"500",
")",
";",
"}",
"}"
] | Marks notification item as read
@return JsonResponse | [
"Marks",
"notification",
"item",
"as",
"read"
] | train | https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Processor/SidebarProcessor.php#L83-L92 |
antaresproject/notifications | src/Processor/SidebarProcessor.php | SidebarProcessor.get | public function get()
{
$notifications = $this->stack->getNotifications()->get();
$alerts = $this->stack->getAlerts()->get();
$count = $this->stack->getCount();
$return = [
'notifications' => [
'items' => $this->decorator->decorate($notifications),
'count' => array_get($count, 'notifications', 0),
],
'alerts' => [
'items' => $this->decorator->decorate($alerts, 'alert'),
'count' => array_get($count, 'alerts', 0)
],
];
return new JsonResponse($return, 200);
} | php | public function get()
{
$notifications = $this->stack->getNotifications()->get();
$alerts = $this->stack->getAlerts()->get();
$count = $this->stack->getCount();
$return = [
'notifications' => [
'items' => $this->decorator->decorate($notifications),
'count' => array_get($count, 'notifications', 0),
],
'alerts' => [
'items' => $this->decorator->decorate($alerts, 'alert'),
'count' => array_get($count, 'alerts', 0)
],
];
return new JsonResponse($return, 200);
} | [
"public",
"function",
"get",
"(",
")",
"{",
"$",
"notifications",
"=",
"$",
"this",
"->",
"stack",
"->",
"getNotifications",
"(",
")",
"->",
"get",
"(",
")",
";",
"$",
"alerts",
"=",
"$",
"this",
"->",
"stack",
"->",
"getAlerts",
"(",
")",
"->",
"get",
"(",
")",
";",
"$",
"count",
"=",
"$",
"this",
"->",
"stack",
"->",
"getCount",
"(",
")",
";",
"$",
"return",
"=",
"[",
"'notifications'",
"=>",
"[",
"'items'",
"=>",
"$",
"this",
"->",
"decorator",
"->",
"decorate",
"(",
"$",
"notifications",
")",
",",
"'count'",
"=>",
"array_get",
"(",
"$",
"count",
",",
"'notifications'",
",",
"0",
")",
",",
"]",
",",
"'alerts'",
"=>",
"[",
"'items'",
"=>",
"$",
"this",
"->",
"decorator",
"->",
"decorate",
"(",
"$",
"alerts",
",",
"'alert'",
")",
",",
"'count'",
"=>",
"array_get",
"(",
"$",
"count",
",",
"'alerts'",
",",
"0",
")",
"]",
",",
"]",
";",
"return",
"new",
"JsonResponse",
"(",
"$",
"return",
",",
"200",
")",
";",
"}"
] | Gets notifications
@return JsonResponse | [
"Gets",
"notifications"
] | train | https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Processor/SidebarProcessor.php#L99-L115 |
aobozhang/rongcloud-facades | src/RongCloudClass.php | RongCloudClass.getToken | public function getToken($userId, $name, $portraitUri) {
try{
if(empty($userId))
throw new Exception('用户 Id 不能为空');
if(empty($name))
throw new Exception('用户名称 不能为空');
if(empty($portraitUri))
throw new Exception('用户头像 URI 不能为空');
$ret = Cache::rememberForever($userId, function() use($userId, $name, $portraitUri){
return $this->curl('/user/getToken',array('userId'=>$userId,'name'=>$name,'portraitUri'=>$portraitUri));
});
if(empty($ret))
throw new Exception('请求失败');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | php | public function getToken($userId, $name, $portraitUri) {
try{
if(empty($userId))
throw new Exception('用户 Id 不能为空');
if(empty($name))
throw new Exception('用户名称 不能为空');
if(empty($portraitUri))
throw new Exception('用户头像 URI 不能为空');
$ret = Cache::rememberForever($userId, function() use($userId, $name, $portraitUri){
return $this->curl('/user/getToken',array('userId'=>$userId,'name'=>$name,'portraitUri'=>$portraitUri));
});
if(empty($ret))
throw new Exception('请求失败');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | [
"public",
"function",
"getToken",
"(",
"$",
"userId",
",",
"$",
"name",
",",
"$",
"portraitUri",
")",
"{",
"try",
"{",
"if",
"(",
"empty",
"(",
"$",
"userId",
")",
")",
"throw",
"new",
"Exception",
"(",
"'用户 Id 不能为空');",
"",
"",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"Exception",
"(",
"'用户名称 不能为空');",
"",
"",
"if",
"(",
"empty",
"(",
"$",
"portraitUri",
")",
")",
"throw",
"new",
"Exception",
"(",
"'用户头像 URI 不能为空');",
"",
"",
"$",
"ret",
"=",
"Cache",
"::",
"rememberForever",
"(",
"$",
"userId",
",",
"function",
"(",
")",
"use",
"(",
"$",
"userId",
",",
"$",
"name",
",",
"$",
"portraitUri",
")",
"{",
"return",
"$",
"this",
"->",
"curl",
"(",
"'/user/getToken'",
",",
"array",
"(",
"'userId'",
"=>",
"$",
"userId",
",",
"'name'",
"=>",
"$",
"name",
",",
"'portraitUri'",
"=>",
"$",
"portraitUri",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"ret",
")",
")",
"throw",
"new",
"Exception",
"(",
"'请求失败');",
"",
"",
"return",
"$",
"ret",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"print_r",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | 获取 Token 方法
@param $userId 用户 Id,最大长度 32 字节。是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。
@param $name 用户名称,最大长度 128 字节。用来在 Push 推送时,或者客户端没有提供用户信息时,显示用户的名称。
@param $portraitUri 用户头像 URI,最大长度 1024 字节。
@return json|xml | [
"获取",
"Token",
"方法"
] | train | https://github.com/aobozhang/rongcloud-facades/blob/8b9a86f69f6fbf84ca204a7faeb6744edc910b8a/src/RongCloudClass.php#L50-L71 |
aobozhang/rongcloud-facades | src/RongCloudClass.php | RongCloudClass.messagePublish | public function messagePublish($fromUserId, $toUserId = array(), $objectName, $content, $pushContent='', $pushData = '') {
try{
if(empty($fromUserId))
throw new Exception('发送人用户 Id 不能为空');
if(empty($toUserId))
throw new Exception('接收用户 Id 不能为空');
if(empty($objectName))
throw new Exception('消息类型 不能为空');
if(empty($content))
throw new Exception('发送消息内容 不能为空');
$params = array(
'fromUserId'=>$fromUserId,
'objectName'=>$objectName,
'content'=>$content,
'pushContent'=>$pushContent,
'pushData'=>$pushData,
'toUserId' => $toUserId
);
$ret = $this->curl('/message/publish', $params);
if(empty($ret))
throw new Exception('请求失败');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | php | public function messagePublish($fromUserId, $toUserId = array(), $objectName, $content, $pushContent='', $pushData = '') {
try{
if(empty($fromUserId))
throw new Exception('发送人用户 Id 不能为空');
if(empty($toUserId))
throw new Exception('接收用户 Id 不能为空');
if(empty($objectName))
throw new Exception('消息类型 不能为空');
if(empty($content))
throw new Exception('发送消息内容 不能为空');
$params = array(
'fromUserId'=>$fromUserId,
'objectName'=>$objectName,
'content'=>$content,
'pushContent'=>$pushContent,
'pushData'=>$pushData,
'toUserId' => $toUserId
);
$ret = $this->curl('/message/publish', $params);
if(empty($ret))
throw new Exception('请求失败');
return $ret;
}catch (Exception $e) {
print_r($e->getMessage());
}
} | [
"public",
"function",
"messagePublish",
"(",
"$",
"fromUserId",
",",
"$",
"toUserId",
"=",
"array",
"(",
")",
",",
"$",
"objectName",
",",
"$",
"content",
",",
"$",
"pushContent",
"=",
"''",
",",
"$",
"pushData",
"=",
"''",
")",
"{",
"try",
"{",
"if",
"(",
"empty",
"(",
"$",
"fromUserId",
")",
")",
"throw",
"new",
"Exception",
"(",
"'发送人用户 Id 不能为空');",
"",
"",
"if",
"(",
"empty",
"(",
"$",
"toUserId",
")",
")",
"throw",
"new",
"Exception",
"(",
"'接收用户 Id 不能为空');",
"",
"",
"if",
"(",
"empty",
"(",
"$",
"objectName",
")",
")",
"throw",
"new",
"Exception",
"(",
"'消息类型 不能为空');",
"",
"",
"if",
"(",
"empty",
"(",
"$",
"content",
")",
")",
"throw",
"new",
"Exception",
"(",
"'发送消息内容 不能为空');",
"",
"",
"$",
"params",
"=",
"array",
"(",
"'fromUserId'",
"=>",
"$",
"fromUserId",
",",
"'objectName'",
"=>",
"$",
"objectName",
",",
"'content'",
"=>",
"$",
"content",
",",
"'pushContent'",
"=>",
"$",
"pushContent",
",",
"'pushData'",
"=>",
"$",
"pushData",
",",
"'toUserId'",
"=>",
"$",
"toUserId",
")",
";",
"$",
"ret",
"=",
"$",
"this",
"->",
"curl",
"(",
"'/message/publish'",
",",
"$",
"params",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"ret",
")",
")",
"throw",
"new",
"Exception",
"(",
"'请求失败');",
"",
"",
"return",
"$",
"ret",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"print_r",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | 发送会话消息
@param $fromUserId 发送人用户 Id。(必传)
@param $toUserId 接收用户 Id,提供多个本参数可以实现向多人发送消息。(必传)
@param $objectName 消息类型,参考融云消息类型表.消息标志;可自定义消息类型。(必传)
@param $content 发送消息内容,参考融云消息类型表.示例说明;如果 objectName 为自定义消息类型,该参数可自定义格式。(必传)
@param string $pushContent 如果为自定义消息,定义显示的 Push 内容。(可选)
@param string $pushData 针对 iOS 平台,Push 通知附加的 payload 字段,字段名为 appData。(可选)
@return json|xml | [
"发送会话消息"
] | train | https://github.com/aobozhang/rongcloud-facades/blob/8b9a86f69f6fbf84ca204a7faeb6744edc910b8a/src/RongCloudClass.php#L83-L110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.