_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q257200 | PDODriver._execute | test | protected function _execute()
{
try {
$this->_wrapPrepareSql();
$this->_pdoSt = $this->_pdo->prepare($this->_prepare_sql);
$this->_bindParams();
$this->_pdoSt->execute();
$this->_reset(); // memory-resident mode, singleton pattern, need reset build attr
// if debug mode, print sql and bind params to stdout
if ($this->_debug) {
$this->_pdoSt->debugDumpParams();
$this->_debug = FALSE; // close debug
}
} catch (PDOException $e) {
// when time out, reconnect
if ($this->_isTimeout($e)) {
$this->_closeConnection();
$this->_connect();
// retry
try {
$this->_wrapPrepareSql();
$this->_pdoSt = $this->_pdo->prepare($this->_prepare_sql);
$this->_bindParams();
$this->_pdoSt->execute();
$this->_reset();
// if debug mode, print sql and bind params to stdout
if ($this->_debug) {
$this->_pdoSt->debugDumpParams();
$this->_debug = FALSE; // close debug
}
} catch (PDOException $e) {
throw $e;
}
} else {
throw $e;
}
}
} | php | {
"resource": ""
} |
q257201 | PDODriver._bindParams | test | protected function _bindParams()
{
if (is_array($this->_bind_params)) {
foreach ($this->_bind_params as $plh => $param) {
$data_type = PDO::PARAM_STR;
if (is_numeric($param)) {
$data_type = PDO::PARAM_INT;
}
if (is_null($param)) {
$data_type = PDO::PARAM_NULL;
}
if (is_bool($param)) {
$data_type = PDO::PARAM_BOOL;
}
$this->_pdoSt->bindValue($plh, $param, $data_type);
}
}
} | php | {
"resource": ""
} |
q257202 | PDODriver._wrapTable | test | protected function _wrapTable($table)
{
$prefix = array_key_exists('prefix', $this->_config) ?
$this->_config['prefix'] : '';
return $prefix.$table;
} | php | {
"resource": ""
} |
q257203 | PDODriver._wrapRow | test | protected static function _wrapRow($str)
{
// match pattern
$alias_pattern = '/([a-zA-Z0-9_\.]+)\s+(AS|as|As)\s+([a-zA-Z0-9_]+)/';
$alias_replace = self::_quote('$1').' $2 '.self::_quote('$3');
$prefix_pattern = '/([a-zA-Z0-9_]+\s*)(\.)(\s*[a-zA-Z0-9_]+)/';
$prefix_replace = self::_quote('$1').'$2'.self::_quote('$3');
$func_pattern = '/[a-zA-Z0-9_]+\([a-zA-Z0-9_\,\s\`\'\"\*]*\)/';
// alias mode
if (preg_match($alias_pattern, $str, $alias_match)) {
// if field is aa.bb as cc mode
if (preg_match($prefix_pattern, $alias_match[1])) {
$pre_rst = preg_replace($prefix_pattern, $prefix_replace, $alias_match[1]);
$alias_replace = $pre_rst.' $2 '.self::_quote('$3');
}
return preg_replace($alias_pattern, $alias_replace, $str);
}
// prefix mode
if (preg_match($prefix_pattern, $str)) {
return preg_replace($prefix_pattern, $prefix_replace, $str);
}
// func mode (do nothing)
if (preg_match($func_pattern, $str)) {
return $str;
}
// field mode
return self::_quote($str);
} | php | {
"resource": ""
} |
q257204 | PDODriver._condition_constructor | test | protected function _condition_constructor($args_num, $params, &$construct_str)
{
// params dose not conform to specification
if ( ! $args_num || $args_num > 3) {
throw new \InvalidArgumentException("Error number of parameters");
}
// argurment mode
switch ($args_num) {
// assoc array mode
case 1:
if ( ! is_array($params[0])) {
throw new \InvalidArgumentException($params[0].' should be Array');
}
$construct_str .= '(';
foreach ($params[0] as $field => $value) {
$plh = self::_getPlh();
$construct_str .= ' '.self::_wrapRow($field).' = '.$plh.' AND';
$this->_bind_params[$plh] = $value;
}
// remove last operator
$construct_str = substr($construct_str, 0, strrpos($construct_str, 'AND'));
$construct_str .= ')';
break;
// ('a', 10) : a = 10 mode or ('a', null) : a is null mode
case 2:
if (is_null($params[1])) {
$construct_str .= ' '.self::_wrapRow($params[0]).' IS NULL ';
} else {
$plh = self::_getPlh();
$construct_str .= ' '.self::_wrapRow($params[0]).' = '.$plh.' ';
$this->_bind_params[$plh] = $params[1];
}
break;
// ('a', '>', 10) : a > 10 mode \ ('name', 'like', '%adam%') : name like '%adam%' mode
case 3:
if ( ! in_array(strtolower($params[1]), $this->_operators)) {
throw new \InvalidArgumentException('Confusing Symbol '.$params[1]);
}
$plh = self::_getPlh();
$construct_str .= ' '.self::_wrapRow($params[0]).' '.$params[1].' '.$plh.' ';
$this->_bind_params[$plh] = $params[2];
break;
}
} | php | {
"resource": ""
} |
q257205 | PDODriver._storeBuildAttr | test | protected function _storeBuildAttr()
{
// attribute need to store
$store = [];
// store attr
foreach ($this->_buildAttrs as $buildAttr) {
$store[$buildAttr] = $this->$buildAttr;
}
return $store;
} | php | {
"resource": ""
} |
q257206 | PDODriver._reStoreBuildAttr | test | protected function _reStoreBuildAttr(array $data)
{
foreach ($this->_buildAttrs as $buildAttr) {
$this->$buildAttr = $data[$buildAttr];
}
} | php | {
"resource": ""
} |
q257207 | PDODriver._subBuilder | test | protected function _subBuilder(Closure $callback)
{
// store build attr
$store = $this->_storeBuildAttr();
/**************** begin sub query build ****************/
// empty attribute
$this->_resetBuildAttr();
// call sub query callback
call_user_func($callback, $this);
// get sub query build attr
$sub_attr = [];
$this->_buildQuery();
foreach ($this->_buildAttrs as $buildAttr) {
$sub_attr[$buildAttr] = $this->$buildAttr;
}
/**************** end sub query build ****************/
// restore attribute
$this->_reStoreBuildAttr($store);
return $sub_attr;
} | php | {
"resource": ""
} |
q257208 | PDODriver.select | test | public function select()
{
$cols = func_get_args();
if ( ! func_num_args() || in_array('*', $cols)) {
$this->_cols_str = ' * ';
} else {
// _cols_str default ' * ' , it easy to get a result when select func dosen't called
// but when you call select func , you should set it to ''
$this->_cols_str = '';
foreach ($cols as $col) {
$this->_cols_str .= ' '.self::_wrapRow($col).',';
}
$this->_cols_str = rtrim($this->_cols_str, ',');
}
return $this;
} | php | {
"resource": ""
} |
q257209 | PDODriver.where | test | public function where()
{
$operator = 'AND';
// is the first time call where method ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE ';
} else {
$this->_where_str .= ' '.$operator.' ';
}
// build attribute, bind params
$this->_condition_constructor(func_num_args(), func_get_args(), $this->_where_str);
return $this;
} | php | {
"resource": ""
} |
q257210 | PDODriver.orWhere | test | public function orWhere()
{
$operator = 'OR';
// is the first time call where method ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE ';
} else {
$this->_where_str .= ' '.$operator.' ';
}
// build attribute, bind params
$this->_condition_constructor(func_num_args(), func_get_args(), $this->_where_str);
return $this;
} | php | {
"resource": ""
} |
q257211 | PDODriver.whereIn | test | public function whereIn($field, array $data, $condition = 'IN', $operator = 'AND')
{
if ( ! in_array($condition, ['IN', 'NOT IN']) || ! in_array($operator, ['AND', 'OR'])) {
throw new \InvalidArgumentException("Error whereIn mode");
}
// create placeholder
foreach ($data as $key => $value) {
$plh = self::_getPlh();
$data[$key] = $plh;
$this->_bind_params[$plh] = $value;
}
// is the first time call where method ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE '.self::_wrapRow($field).' '.$condition.' ('.implode(',', $data).')';
} else {
$this->_where_str .= ' '.$operator.' '.self::_wrapRow($field).' '.$condition.' ('.implode(',', $data).')';
}
return $this;
} | php | {
"resource": ""
} |
q257212 | PDODriver.whereBetween | test | public function whereBetween($field, $start, $end, $operator = 'AND')
{
if ( ! in_array($operator, ['AND', 'OR'])) {
throw new \InvalidArgumentException("Logical operator");
}
// create placeholder
$start_plh = self::_getPlh();
$end_plh = self::_getPlh();
$this->_bind_params[$start_plh] = $start;
$this->_bind_params[$end_plh] = $end;
// is the first time call where method ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE '.self::_wrapRow($field).' BETWEEN '.$start_plh.' AND '.$end_plh;
} else {
$this->_where_str .= ' '.$operator.' '.self::_wrapRow($field).' BETWEEN '.$start_plh.' AND '.$end_plh;
}
return $this;
} | php | {
"resource": ""
} |
q257213 | PDODriver.whereNull | test | public function whereNull($field, $condition = 'NULL', $operator = 'AND')
{
if ( ! in_array($condition, ['NULL', 'NOT NULL']) || ! in_array($operator, ['AND', 'OR'])) {
throw new \InvalidArgumentException("Logical operator");
}
// is the first time call where method ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE ';
} else {
$this->_where_str .= ' '.$operator.' ';
}
$this->_where_str .= self::_wrapRow($field).' IS '.$condition.' ';
return $this;
} | php | {
"resource": ""
} |
q257214 | PDODriver.whereBrackets | test | public function whereBrackets(Closure $callback, $operator = 'AND')
{
if ( ! in_array($operator, ['AND', 'OR'])) {
throw new \InvalidArgumentException("Logical operator");
}
// first time call where ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE ( ';
} else {
$this->_where_str .= ' '.$operator.' ( ';
}
$sub_attr = $this->_subBuilder($callback);
$this->_where_str .= preg_replace('/WHERE/', '', $sub_attr['_where_str'], 1).' ) ';
return $this;
} | php | {
"resource": ""
} |
q257215 | PDODriver.whereExists | test | public function whereExists(Closure $callback, $condition = 'EXISTS', $operator = 'AND')
{
if ( ! in_array($condition, ['EXISTS', 'NOT EXISTS']) || ! in_array($operator, ['AND', 'OR'])) {
throw new \InvalidArgumentException("Error whereExists mode");
}
// first time call where ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE '.$condition.' ( ';
} else {
$this->_where_str .= ' '.$operator.' '.$condition.' ( ';
}
$sub_attr = $this->_subBuilder($callback);
$this->_where_str .= $sub_attr['_prepare_sql'].' ) ';
return $this;
} | php | {
"resource": ""
} |
q257216 | PDODriver.whereInSub | test | public function whereInSub($field, Closure $callback, $condition = 'IN', $operator = 'AND')
{
if ( ! in_array($condition, ['IN', 'NOT IN']) || ! in_array($operator, ['AND', 'OR'])) {
throw new \InvalidArgumentException("Error whereIn mode");
}
// first time call where ?
if ($this->_where_str == '') {
$this->_where_str = ' WHERE '.self::_wrapRow($field).' '.$condition.' ( ';
} else {
$this->_where_str .= ' '.$operator.' '.self::_wrapRow($field).' '.$condition.' ( ';
}
$sub_attr = $this->_subBuilder($callback);
$this->_where_str .= $sub_attr['_prepare_sql'].' ) ';
return $this;
} | php | {
"resource": ""
} |
q257217 | PDODriver.groupBy | test | public function groupBy($field)
{
// is the first time call groupBy method ?
if ($this->_groupby_str == '') {
$this->_groupby_str = ' GROUP BY '.self::_wrapRow($field);
} else {
$this->_groupby_str .= ' , '.self::_wrapRow($field);
}
return $this;
} | php | {
"resource": ""
} |
q257218 | PDODriver.having | test | public function having()
{
$operator = 'AND';
// is the first time call where method ?
if ($this->_having_str == '') {
$this->_having_str = ' HAVING ';
} else {
$this->_having_str .= ' '.$operator.' ';
}
// build attribute, bind params
$this->_condition_constructor(func_num_args(), func_get_args(), $this->_having_str);
return $this;
} | php | {
"resource": ""
} |
q257219 | PDODriver.orHaving | test | public function orHaving()
{
$operator = 'OR';
// is the first time call where method ?
if ($this->_having_str == '') {
$this->_having_str = ' HAVING ';
} else {
$this->_having_str .= ' '.$operator.' ';
}
// build attribute, bind params
$this->_condition_constructor(func_num_args(), func_get_args(), $this->_having_str);
return $this;
} | php | {
"resource": ""
} |
q257220 | PDODriver.orderBy | test | public function orderBy($field, $mode = 'ASC')
{
$mode = strtoupper($mode);
if ( ! in_array($mode, ['ASC', 'DESC'])) {
throw new \InvalidArgumentException("Error order by mode");
}
// is the first time call orderBy method ?
if ($this->_orderby_str == '') {
$this->_orderby_str = ' ORDER BY '.self::_wrapRow($field).' '.$mode;
} else {
$this->_orderby_str .= ' , '.self::_wrapRow($field).' '.$mode;
}
return $this;
} | php | {
"resource": ""
} |
q257221 | PDODriver.join | test | public function join($table, $one, $two, $type = 'INNER')
{
if ( ! in_array($type, ['INNER', 'LEFT', 'RIGHT'])) {
throw new \InvalidArgumentException("Error join mode");
}
// set table prefix
$table = $this->_wrapTable($table);
// create join string
$this->_join_str .= ' '.$type.' JOIN '.self::_wrapRow($table).
' ON '.self::_wrapRow($one).' = '.self::_wrapRow($two);
return $this;
} | php | {
"resource": ""
} |
q257222 | PDODriver.fromSub | test | public function fromSub(Closure $callback)
{
$sub_attr = $this->_subBuilder($callback);
$this->_table .= ' ( '.$sub_attr['_prepare_sql'].' ) AS tb_'.uniqid().' ';
return $this;
} | php | {
"resource": ""
} |
q257223 | PDODriver.paginate | test | public function paginate($step, $page = NULL)
{
// store build attr\bind param
$store = $this->_storeBuildAttr();
$bind_params = $this->_storeBindParam();
// get count
$count = $this->count();
// restore build attr\bind param
$this->_reStoreBuildAttr($store);
$this->_reStoreBindParam($bind_params);
// create paginate data
$page = $page ? $page : 1;
$this->limit($step * ($page - 1), $step);
$rst['total'] = $count;
$rst['per_page'] = $step;
$rst['current_page'] = $page;
$rst['next_page'] = ($page + 1) > ($count / $step) ? NULL : ($page + 1);
$rst['prev_page'] = ($page - 1) < 1 ? NULL : ($page - 1);
$rst['first_page'] = 1;
$rst['last_page'] = $count / $step;
$rst['data'] = $this->get();
return $rst;
} | php | {
"resource": ""
} |
q257224 | PDODriver.get | test | public function get()
{
$this->_buildQuery();
$this->_execute();
return $this->_pdoSt->fetchAll(PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q257225 | PDODriver.row | test | public function row()
{
$this->_buildQuery();
$this->_execute();
return $this->_pdoSt->fetch(PDO::FETCH_ASSOC);
} | php | {
"resource": ""
} |
q257226 | PDODriver.getList | test | public function getList($field)
{
$this->_cols_str = ' '.self::_quote($field).' ';
$this->_buildQuery();
$this->_execute();
return $this->_pdoSt->fetchAll(PDO::FETCH_COLUMN, 0);
} | php | {
"resource": ""
} |
q257227 | PDODriver.query | test | public function query($sql)
{
try {
return $this->_pdo->query($sql);
} catch (PDOException $e) {
// when time out, reconnect
if ($this->_isTimeout($e)) {
$this->_closeConnection();
$this->_connect();
try {
return $this->_pdo->query($sql);
} catch (PDOException $e) {
throw $e;
}
} else {
throw $e;
}
}
} | php | {
"resource": ""
} |
q257228 | PDODriver.prepare | test | public function prepare($sql, array $driver_options = [])
{
try {
return $this->_pdo->prepare($sql, $driver_options);
} catch (PDOException $e) {
// when time out, reconnect
if ($this->_isTimeout($e)) {
$this->_closeConnection();
$this->_connect();
try {
return $this->_pdo->prepare($sql, $driver_options);
} catch (PDOException $e) {
throw $e;
}
} else {
throw $e;
}
}
} | php | {
"resource": ""
} |
q257229 | PDODriver.beginTrans | test | public function beginTrans()
{
try {
return $this->_pdo->beginTransaction();
} catch (PDOException $e) {
// when time out, reconnect
if ($this->_isTimeout($e)) {
$this->_closeConnection();
$this->_connect();
try {
return $this->_pdo->beginTransaction();
} catch (PDOException $e) {
throw $e;
}
} else {
throw $e;
}
}
} | php | {
"resource": ""
} |
q257230 | ExceptionHandler.handle | test | public function handle(\Exception $e)
{
$httpCode = 500;
// create http response header
if (property_exists($e, 'httpCode') &&
array_key_exists($e->httpCode, Response::$statusCodes)
) { // is a http exception
$httpCode = $e->httpCode;
$header = Response::$statusCodes[$httpCode];
} else { // other exception
$header = Response::$statusCodes[$httpCode];
Error::printError($e); // if Server error, echo to stdout
}
Response::header($header);
return Error::errorHtml($e, $header, Config::get('app.debug'));
} | php | {
"resource": ""
} |
q257231 | Client.generateId | test | public function generateId($size = 0, $mode = self::MODE_NORMAL)
{
$size = $size>0? $size: $this->size;
switch ($mode) {
case self::MODE_DYNAMIC:
return $this->core->random($this->generator, $size);
default:
return $this->normalRandom($size);
}
} | php | {
"resource": ""
} |
q257232 | Client.formatedId | test | public function formatedId($alphabet, $size, GeneratorInterface $generator = null)
{
$generator = $generator?:$this->generator;
$alphabet = $alphabet?:CoreInterface::SAFE_SYMBOLS;
return $this->core->random($generator, $size, $alphabet);
} | php | {
"resource": ""
} |
q257233 | Client.normalRandom | test | private function normalRandom($size)
{
$id = '';
while (1 <= $size--) {
$rand = mt_rand()/(mt_getrandmax() + 1);
$id .= $this->alphbet[$rand*64 | 0];
}
return $id;
} | php | {
"resource": ""
} |
q257234 | Connection.normalizeDSN | test | public static function normalizeDSN($dsn, $user = null, $pass = null)
{
// Try to dissect DSN into parts
$parts = is_array($dsn) ? $dsn : parse_url($dsn);
// If parts are usable, convert DSN format
if ($parts !== false && isset($parts['host'], $parts['path'])) {
// DSN is using URL-like format, so we need to convert it
$dsn =
$parts['scheme'].
':host='.$parts['host'].
(isset($parts['port']) ? ';port='.$parts['port'] : '').
';dbname='.substr($parts['path'], 1);
$user = $user !== null ? $user : (isset($parts['user']) ? $parts['user'] : null);
$pass = $pass !== null ? $pass : (isset($parts['pass']) ? $parts['pass'] : null);
}
// If it's still array, then simply use it
if (is_array($dsn)) {
return $dsn;
}
// If it's string, then find driver
if (is_string($dsn)) {
if (strpos($dsn, ':') === false) {
throw new Exception([
"Your DSN format is invalid. Must be in 'driver:host;options' format",
'dsn' => $dsn,
]);
}
list($driver, $rest) = explode(':', $dsn, 2);
$driver = strtolower($driver);
} else {
// currently impossible to be like this, but we don't want ugly exceptions here
$driver = $rest = null;
}
return ['dsn' => $dsn, 'user' => $user, 'pass' => $pass, 'driver' => $driver, 'rest' => $rest];
} | php | {
"resource": ""
} |
q257235 | Connection.dsql | test | public function dsql($properties = [])
{
$c = $this->query_class;
$q = new $c($properties);
$q->connection = $this;
return $q;
} | php | {
"resource": ""
} |
q257236 | Connection.execute | test | public function execute(Expression $expr)
{
// If custom connection is set, execute again using that
if ($this->connection && $this->connection !== $this) {
return $expr->execute($this->connection);
}
throw new Exception('Queries cannot be executed through this connection');
} | php | {
"resource": ""
} |
q257237 | Connection.beginTransaction | test | public function beginTransaction()
{
// transaction starts only if it was not started before
$r = $this->inTransaction()
? false
: $this->connection->beginTransaction();
$this->transaction_depth++;
return $r;
} | php | {
"resource": ""
} |
q257238 | Connection.commit | test | public function commit()
{
// check if transaction is actually started
if (!$this->inTransaction()) {
throw new Exception('Using commit() when no transaction has started');
}
$this->transaction_depth--;
if ($this->transaction_depth == 0) {
return $this->connection->commit();
}
return false;
} | php | {
"resource": ""
} |
q257239 | Connection.rollBack | test | public function rollBack()
{
// check if transaction is actually started
if (!$this->inTransaction()) {
throw new Exception('Using rollBack() when no transaction has started');
}
$this->transaction_depth--;
if ($this->transaction_depth == 0) {
return $this->connection->rollBack();
}
return false;
} | php | {
"resource": ""
} |
q257240 | Connection_Oracle.lastInsertID | test | public function lastInsertID($m = null)
{
if ($m instanceof \atk4\data\Model) {
// if we use sequence, then we can easily get current value
if (isset($m->sequence)) {
return $this->dsql()->mode('seq_currval')->sequence($m->sequence)->getOne();
}
// otherwise we have to select max(id_field) - this can be bad for performance !!!
// Imants: Disabled for now because otherwise this will work even if database use triggers or
// any other mechanism to automatically increment ID and we can't tell this line to not execute.
//return $this->expr('SELECT max([field]) FROM [table]', ['field'=>$m->id_field, 'table'=>$m->table])->getOne();
}
// fallback
return parent::lastInsertID($m);
} | php | {
"resource": ""
} |
q257241 | Expression.reset | test | public function reset($tag = null)
{
// unset all arguments
if ($tag === null) {
$this->args = ['custom' => []];
return $this;
}
if (!is_string($tag)) {
throw new Exception([
'Tag should be string',
'tag' => $tag,
]);
}
// unset custom/argument or argument if such exists
if ($this->offsetExists($tag)) {
$this->offsetUnset($tag);
} elseif (isset($this->args[$tag])) {
unset($this->args[$tag]);
}
return $this;
} | php | {
"resource": ""
} |
q257242 | Expression._consume | test | protected function _consume($sql_code, $escape_mode = 'param')
{
if (!is_object($sql_code)) {
switch ($escape_mode) {
case 'param':
return $this->_param($sql_code);
case 'escape':
return $this->_escape($sql_code);
case 'soft-escape':
return $this->_escapeSoft($sql_code);
case 'none':
return $sql_code;
}
throw new Exception([
'$escape_mode value is incorrect',
'escape_mode' => $escape_mode,
]);
}
// User may add Expressionable trait to any class, then pass it's objects
if ($sql_code instanceof Expressionable) {
$sql_code = $sql_code->getDSQLExpression($this);
}
if (!$sql_code instanceof self) {
throw new Exception([
'Only Expressions or Expressionable objects may be used in Expression',
'object' => $sql_code,
]);
}
// at this point $sql_code is instance of Expression
$sql_code->params = &$this->params;
$sql_code->_paramBase = &$this->_paramBase;
$ret = $sql_code->render();
// Queries should be wrapped in parentheses in most cases
if ($sql_code instanceof Query) {
$ret = '('.$ret.')';
}
// unset is needed here because ->params=&$othervar->params=foo will also change $othervar.
// if we unset() first, we’re safe.
unset($sql_code->params);
$sql_code->params = [];
return $ret;
} | php | {
"resource": ""
} |
q257243 | Expression._escapeSoft | test | protected function _escapeSoft($value)
{
// supports array
if (is_array($value)) {
return array_map(__METHOD__, $value);
}
// in some cases we should not escape
if ($this->isUnescapablePattern($value)) {
return $value;
}
if (is_string($value) && strpos($value, '.') !== false) {
return implode('.', array_map(__METHOD__, explode('.', $value)));
}
return $this->escape_char.trim($value).$this->escape_char;
} | php | {
"resource": ""
} |
q257244 | Expression.render | test | public function render()
{
$nameless_count = 0;
if (!isset($this->_paramBase)) {
$this->_paramBase = $this->paramBase;
}
if ($this->template === null) {
throw new Exception('Template is not defined for Expression');
}
$res = preg_replace_callback(
'/\[[a-z0-9_]*\]|{[a-z0-9_]*}/i',
function ($matches) use (&$nameless_count) {
$identifier = substr($matches[0], 1, -1);
$escaping = ($matches[0][0] == '[') ? 'param' : 'escape';
// Allow template to contain []
if ($identifier === '') {
$identifier = $nameless_count++;
// use rendering only with named tags
}
$fx = '_render_'.$identifier;
// [foo] will attempt to call $this->_render_foo()
if (array_key_exists($identifier, $this->args['custom'])) {
$value = $this->_consume($this->args['custom'][$identifier], $escaping);
} elseif (method_exists($this, $fx)) {
$value = $this->$fx();
} else {
throw new Exception([
'Expression could not render tag',
'tag' => $identifier,
]);
}
return is_array($value) ? '('.implode(',', $value).')' : $value;
},
$this->template
);
unset($this->_paramBase);
return trim($res);
} | php | {
"resource": ""
} |
q257245 | Expression.getDebugQuery | test | public function getDebugQuery($html = null)
{
$d = $this->render();
$pp = [];
foreach (array_reverse($this->params) as $key => $val) {
if (is_numeric($val)) {
$d = preg_replace(
'/'.$key.'([^_]|$)/',
$val.'\1',
$d
);
} elseif (is_string($val)) {
$d = preg_replace('/'.$key.'([^_]|$)/', "'".addslashes($val)."'\\1", $d);
} elseif ($val === null) {
$d = preg_replace(
'/'.$key.'([^_]|$)/',
'NULL\1',
$d
);
} else {
$d = preg_replace('/'.$key.'([^_]|$)/', $val.'\\1', $d);
}
$pp[] = $key;
}
if (class_exists('SqlFormatter')) {
if ($html) {
$result = \SqlFormatter::format($d);
} else {
$result = \SqlFormatter::format($d, false);
}
} else {
$result = $d; // output as-is
}
if (!$html) {
return str_replace('#lte#', '<=', strip_tags(str_replace('<=', '#lte#', $result), '<>'));
}
return $result;
} | php | {
"resource": ""
} |
q257246 | Expression.get | test | public function get()
{
$stmt = $this->execute();
if ($stmt instanceof \Generator) {
return iterator_to_array($stmt);
}
return $stmt->fetchAll();
} | php | {
"resource": ""
} |
q257247 | Expression.getOne | test | public function getOne()
{
$data = $this->getRow();
if (!$data) {
throw new Exception([
'Unable to fetch single cell of data for getOne from this query',
'result' => $data,
'query' => $this->getDebugQuery(),
]);
}
$one = array_shift($data);
return $one;
} | php | {
"resource": ""
} |
q257248 | Expression.getRow | test | public function getRow()
{
$stmt = $this->execute();
if ($stmt instanceof \Generator) {
return $stmt->current();
}
return $stmt->fetch();
} | php | {
"resource": ""
} |
q257249 | Query.table | test | public function table($table, $alias = null)
{
// comma-separated table names
if (is_string($table) && strpos($table, ',') !== false) {
$table = explode(',', $table);
}
// array of tables - recursively process each
if (is_array($table)) {
if ($alias !== null) {
throw new Exception([
'You cannot use single alias with multiple tables',
'alias' => $alias,
]);
}
foreach ($table as $alias => $t) {
if (is_numeric($alias)) {
$alias = null;
}
$this->table($t, $alias);
}
return $this;
}
// if table is set as sub-Query, then alias is mandatory
if ($table instanceof self && $alias === null) {
throw new Exception('If table is set as Query, then table alias is mandatory');
}
if (is_string($table) && $alias === null) {
$alias = $table;
}
// main_table will be set only if table() is called once.
// it's used as "default table" when joining with other tables, see join().
// on multiple calls, main_table will be false and we won't
// be able to join easily anymore.
$this->main_table = ($this->main_table === null && $alias !== null ? $alias : false);
// save table in args
$this->_set_args('table', $alias, $table);
return $this;
} | php | {
"resource": ""
} |
q257250 | Query.where | test | public function where($field, $cond = null, $value = null, $kind = 'where', $num_args = null)
{
// Number of passed arguments will be used to determine if arguments were specified or not
if ($num_args === null) {
$num_args = func_num_args();
}
// Array as first argument means we have to replace it with orExpr()
if (is_array($field)) {
// or conditions
$or = $this->orExpr();
foreach ($field as $row) {
if (is_array($row)) {
call_user_func_array([$or, 'where'], $row);
} else {
$or->where($row);
}
}
$field = $or;
}
if ($num_args === 1 && is_string($field)) {
$this->args[$kind][] = [$this->expr($field)];
return $this;
}
// first argument is string containing more than just a field name and no more than 2
// arguments means that we either have a string expression or embedded condition.
if ($num_args === 2 && is_string($field) && !preg_match('/^[.a-zA-Z0-9_]*$/', $field)) {
// field contains non-alphanumeric values. Look for condition
preg_match(
'/^([^ <>!=]*)([><!=]*|( *(not|is|in|like))*) *$/',
$field,
$matches
);
// matches[2] will contain the condition, but $cond will contain the value
$value = $cond;
$cond = $matches[2];
// if we couldn't clearly identify the condition, we might be dealing with
// a more complex expression. If expression is followed by another argument
// we need to add equation sign where('now()',123).
if (!$cond) {
$matches[1] = $this->expr($field);
$cond = '=';
} else {
$num_args++;
}
$field = $matches[1];
}
switch ($num_args) {
case 1:
$this->args[$kind][] = [$field];
break;
case 2:
if (is_object($cond) && !$cond instanceof Expressionable && !$cond instanceof Expression) {
throw new Exception([
'Value cannot be converted to SQL-compatible expression',
'field'=> $field,
'value'=> $cond,
]);
}
$this->args[$kind][] = [$field, $cond];
break;
case 3:
if (is_object($value) && !$value instanceof Expressionable && !$value instanceof Expression) {
throw new Exception([
'Value cannot be converted to SQL-compatible expression',
'field'=> $field,
'cond' => $cond,
'value'=> $value,
]);
}
$this->args[$kind][] = [$field, $cond, $value];
break;
}
return $this;
} | php | {
"resource": ""
} |
q257251 | Query.__render_condition | test | protected function __render_condition($row)
{
if (count($row) === 3) {
list($field, $cond, $value) = $row;
} elseif (count($row) === 2) {
list($field, $cond) = $row;
} elseif (count($row) === 1) {
list($field) = $row;
}
$field = $this->_consume($field, 'soft-escape');
if (count($row) == 1) {
// Only a single parameter was passed, so we simply include all
return $field;
}
// below are only cases when 2 or 3 arguments are passed
// if no condition defined - set default condition
if (count($row) == 2) {
$value = $cond;
if (is_array($value)) {
$cond = 'in';
} elseif ($value instanceof self && $value->mode === 'select') {
$cond = 'in';
} else {
$cond = '=';
}
} else {
$cond = trim(strtolower($cond));
}
// below we can be sure that all 3 arguments has been passed
// special conditions (IS | IS NOT) if value is null
if ($value === null) {
if ($cond === '=') {
$cond = 'is';
} elseif (in_array($cond, ['!=', '<>', 'not'])) {
$cond = 'is not';
}
}
// value should be array for such conditions
if (in_array($cond, ['in', 'not in', 'not']) && is_string($value)) {
$value = array_map('trim', explode(',', $value));
}
// special conditions (IN | NOT IN) if value is array
if (is_array($value)) {
$value = '('.implode(',', $this->_param($value)).')';
$cond = in_array($cond, ['!=', '<>', 'not', 'not in']) ? 'not in' : 'in';
return $field.' '.$cond.' '.$value;
}
// if value is object, then it should be Expression or Query itself
// otherwise just escape value
$value = $this->_consume($value, 'param');
return $field.' '.$cond.' '.$value;
} | php | {
"resource": ""
} |
q257252 | Query.group | test | public function group($group)
{
// Case with comma-separated fields
if (is_string($group) && !$this->isUnescapablePattern($group) && strpos($group, ',') !== false) {
$group = explode(',', $group);
}
if (is_array($group)) {
foreach ($group as $g) {
$this->args['group'][] = $g;
}
return $this;
}
$this->args['group'][] = $group;
return $this;
} | php | {
"resource": ""
} |
q257253 | Query.set | test | public function set($field, $value = null)
{
if ($value === false) {
throw new Exception([
'Value "false" is not supported by SQL',
'field' => $field,
'value' => $value,
]);
}
if (is_array($value)) {
throw new Exception([
'Array values are not supported by SQL',
'field' => $field,
'value' => $value,
]);
}
if (is_array($field)) {
foreach ($field as $key => $value) {
$this->set($key, $value);
}
return $this;
}
if (is_string($field) || $field instanceof Expression || $field instanceof Expressionable) {
$this->args['set'][] = [$field, $value];
} else {
throw new Exception([
'Field name should be string or Expressionable',
'field' => $field,
]);
}
return $this;
} | php | {
"resource": ""
} |
q257254 | Query.option | test | public function option($option, $mode = 'select')
{
// Case with comma-separated options
if (is_string($option) && strpos($option, ',') !== false) {
$option = explode(',', $option);
}
if (is_array($option)) {
foreach ($option as $opt) {
$this->args['option'][$mode][] = $opt;
}
return $this;
}
$this->args['option'][$mode][] = $option;
return $this;
} | php | {
"resource": ""
} |
q257255 | Query.order | test | public function order($order, $desc = null)
{
// Case with comma-separated fields or first argument being an array
if (is_string($order) && strpos($order, ',') !== false) {
$order = explode(',', $order);
}
if (is_array($order)) {
if ($desc !== null) {
throw new Exception(
'If first argument is array, second argument must not be used'
);
}
foreach (array_reverse($order) as $o) {
$this->order($o);
}
return $this;
}
// First argument may contain space, to divide field and ordering keyword.
// Explode string only if ordering keyword is 'desc' or 'asc'.
if ($desc === null && is_string($order) && strpos($order, ' ') !== false) {
$_chunks = explode(' ', $order);
$_desc = strtolower(array_pop($_chunks));
if (in_array($_desc, ['desc', 'asc'])) {
$order = implode(' ', $_chunks);
$desc = $_desc;
}
}
if (is_bool($desc)) {
$desc = $desc ? 'desc' : '';
} elseif (strtolower($desc) === 'asc') {
$desc = '';
} else {
// allows custom order like "order by name desc nulls last" for Oracle
}
$this->args['order'][] = [$order, $desc];
return $this;
} | php | {
"resource": ""
} |
q257256 | Query.mode | test | public function mode($mode)
{
$prop = 'template_'.$mode;
if (isset($this->{$prop})) {
$this->mode = $mode;
$this->template = $this->{$prop};
} else {
throw new Exception([
'Query does not have this mode',
'mode' => $mode,
]);
}
return $this;
} | php | {
"resource": ""
} |
q257257 | Query_Oracle.limit | test | public function limit($cnt, $shift = null)
{
// This is for pre- 12c version
$this->template_select = $this->template_select_limit;
return parent::limit($cnt, $shift);
} | php | {
"resource": ""
} |
q257258 | ValueParser.parseString | test | private function parseString($value)
{
$single = false;
$regex = self::REGEX_QUOTE_DOUBLE_STRING;
$symbol = '"';
if ($this->parser->string_helper->startsWith('\'', $value)) {
$single = true;
$regex = self::REGEX_QUOTE_SINGLE_STRING;
$symbol = "'";
}
$matches = $this->fetchStringMatches($value, $regex, $symbol);
$value = trim($matches[0], $symbol);
$value = strtr($value, self::$character_map);
return ($single) ? $value : $this->variable_parser->parse($value, true);
} | php | {
"resource": ""
} |
q257259 | ValueParser.fetchStringMatches | test | private function fetchStringMatches($value, $regex, $symbol)
{
if (!preg_match('/'.$regex.'/', $value, $matches)) {
throw new ParseException(
sprintf('Missing end %s quote', $symbol),
$value,
$this->parser->line_num
);
}
return $matches;
} | php | {
"resource": ""
} |
q257260 | ParseException.createMessage | test | private function createMessage($message, $line, $line_num)
{
if (!is_null($line)) {
$message .= sprintf(" near %s", $line);
}
if (!is_null($line_num)) {
$message .= sprintf(" at line %d", $line_num);
}
return $message;
} | php | {
"resource": ""
} |
q257261 | StringHelper.startsWith | test | public function startsWith($string, $line)
{
return $string === "" || strrpos($line, $string, -strlen($line)) !== false;
} | php | {
"resource": ""
} |
q257262 | VariableParser.fetchVariableMatches | test | private function fetchVariableMatches($value)
{
preg_match_all('/' . self::REGEX_ENV_VARIABLE . '/', $value, $matches);
if (!is_array($matches) || !isset($matches[0]) || empty($matches[0])) {
return false;
}
return $matches;
} | php | {
"resource": ""
} |
q257263 | VariableParser.hasParameterExpansion | test | private function hasParameterExpansion($variable)
{
if ((strpos($variable, self::SYMBOL_DEFAULT_VALUE) !== false) ||
(strpos($variable, self::SYMBOL_ASSIGN_DEFAULT_VALUE) !== false)
) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q257264 | VariableParser.fetchParameterExpansion | test | private function fetchParameterExpansion($variable_name)
{
$parameter_type = $this->fetchParameterExpansionType($variable_name);
list($parameter_symbol, $empty_flag) = $this->fetchParameterExpansionSymbol($variable_name, $parameter_type);
list($variable, $default) = $this->splitVariableDefault($variable_name, $parameter_symbol);
$value = $this->getVariable($variable);
return $this->parseVariableParameter(
$variable,
$default,
$this->hasVariable($variable),
$empty_flag && empty($value),
$parameter_type
);
} | php | {
"resource": ""
} |
q257265 | VariableParser.fetchParameterExpansionSymbol | test | private function fetchParameterExpansionSymbol($variable_name, $type)
{
$class = new \ReflectionClass($this);
$symbol = $class->getConstant('SYMBOL_'.strtoupper($type));
$pos = strpos($variable_name, $symbol);
$check_empty = substr($variable_name, ($pos - 1), 1) === ":";
if ($check_empty) {
$symbol = sprintf(":%s", $symbol);
}
return array($symbol, $check_empty);
} | php | {
"resource": ""
} |
q257266 | VariableParser.splitVariableDefault | test | private function splitVariableDefault($variable_name, $parameter_symbol)
{
$variable_default = explode($parameter_symbol, $variable_name, 2);
if (count($variable_default) !== 2 || empty($variable_default[1])) {
throw new ParseException(
'You must have valid parameter expansion syntax, eg. ${parameter:=word}',
$variable_name,
$this->parser->line_num
);
}
return array(trim($variable_default[0]), trim($variable_default[1]));
} | php | {
"resource": ""
} |
q257267 | VariableParser.parseVariableParameter | test | private function parseVariableParameter($variable, $default, $exists, $empty, $type)
{
if ($exists && !$empty) {
return $this->getVariable($variable);
}
return $this->assignVariableParameterDefault($variable, $default, $empty, $type);
} | php | {
"resource": ""
} |
q257268 | VariableParser.assignVariableParameterDefault | test | private function assignVariableParameterDefault($variable, $default, $empty, $type)
{
$default = $this->parser->value_parser->parse($default);
if ($type === "assign_default_value" && $empty) {
$this->parser->lines[$variable] = $default;
}
return $default;
} | php | {
"resource": ""
} |
q257269 | VariableParser.hasVariable | test | private function hasVariable($variable)
{
if (array_key_exists($variable, $this->parser->lines)) {
return true;
}
if (array_key_exists($variable, $this->context)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q257270 | VariableParser.getVariable | test | private function getVariable($variable)
{
if (array_key_exists($variable, $this->parser->lines)) {
return $this->parser->lines[$variable];
}
if (array_key_exists($variable, $this->context)) {
return $this->context[$variable];
}
return null;
} | php | {
"resource": ""
} |
q257271 | KeyParser.parse | test | public function parse($key)
{
$key = trim($key);
if ($this->parser->string_helper->startsWith('#', $key)) {
return false;
}
if (!ctype_alnum(str_replace('_', '', $key)) || $this->parser->string_helper->startsWithNumber($key)) {
throw new ParseException(
sprintf('Key can only contain alphanumeric and underscores and can not start with a number: %s', $key),
$key,
$this->parser->line_num
);
}
return $key;
} | php | {
"resource": ""
} |
q257272 | Parser.doParse | test | protected function doParse($content)
{
$raw_lines = array_filter($this->makeLines($content), 'strlen');
if (empty($raw_lines)) {
return;
}
return $this->parseContent($raw_lines);
} | php | {
"resource": ""
} |
q257273 | Parser.parseContent | test | private function parseContent(array $raw_lines)
{
$this->lines = array();
$this->line_num = 0;
foreach ($raw_lines as $raw_line) {
$this->line_num++;
if ($this->string_helper->startsWith('#', $raw_line) || !$raw_line) {
continue;
}
$this->parseLine($raw_line);
}
return $this->lines;
} | php | {
"resource": ""
} |
q257274 | Parser.parseLine | test | private function parseLine($raw_line)
{
$raw_line = $this->parseExport($raw_line);
list($key, $value) = $this->parseKeyValue($raw_line);
$key = $this->key_parser->parse($key);
if (!is_string($key)) {
return;
}
$this->lines[$key] = $this->value_parser->parse($value);
} | php | {
"resource": ""
} |
q257275 | Parser.parseExport | test | private function parseExport($raw_line)
{
$line = trim($raw_line);
if ($this->string_helper->startsWith("export", $line)) {
$export_line = explode("export", $raw_line, 2);
if (count($export_line) !== 2 || empty($export_line[1])) {
throw new ParseException(
'You must have a export key = value',
$raw_line,
$this->line_num
);
}
$line = trim($export_line[1]);
}
return $line;
} | php | {
"resource": ""
} |
q257276 | Parser.parseKeyValue | test | private function parseKeyValue($raw_line)
{
$key_value = explode("=", $raw_line, 2);
if (count($key_value) !== 2) {
throw new ParseException(
'You must have a key = value',
$raw_line,
$this->line_num
);
}
return $key_value;
} | php | {
"resource": ""
} |
q257277 | Parser.getContent | test | public function getContent($keyName = null)
{
if (!is_null($keyName)) {
return (array_key_exists($keyName, $this->lines)) ? $this->lines[$keyName] : null;
}
return $this->lines;
} | php | {
"resource": ""
} |
q257278 | Client.startTask | test | public function startTask(TaskInterface $task)
{
$response = $this->http->post($this->getTaskWorkerUrl(), [
self::ATTR_PROG => self::PROG,
self::ATTR_NAME => get_class($task),
self::ATTR_DATA => $this->serializer->encode($this->properties->getPropertiesFromObject($task)),
self::ATTR_MAX_PROCESSING_TIME => method_exists($task, 'getMaxProcessingTime') ? $task->getMaxProcessingTime() : null,
]);
if ($response->hasErrors()) {
if (strpos($response->body->error, 'Your worker does not listen') !== false) {
throw new AgentNotListeningException($this->appId, $this->appEnv);
}
if (strpos($response->body->error, 'Unknown version') !== false) {
throw new AgentUpdateRequiredException('>=0.6.0');
}
throw new AgentException($response->body->error);
}
} | php | {
"resource": ""
} |
q257279 | Client.startWorkflow | test | public function startWorkflow(WorkflowInterface $flow)
{
$canonical = null;
// if $flow is a versionned workflow
if ($flow instanceof VersionedWorkflow) {
// store canonical name
$canonical = get_class($flow);
// replace by true current implementation
$flow = $flow->getCurrentImplementation();
}
// custom id management
$customId = null;
if (method_exists($flow, 'getId')) {
$customId = $flow->getId();
if (!is_string($customId) && !is_int($customId)) {
throw new InvalidArgumentException('Provided Id must be a string or an integer');
}
// at the end, it's a string
$customId = (string) $customId;
// should be not more than 256 bytes;
if (strlen($customId) > self::MAX_ID_SIZE) {
throw new InvalidArgumentException('Provided Id must not exceed '.self::MAX_ID_SIZE.' bytes');
}
}
// start workflow
$this->http->post($this->getInstanceWorkerUrl(), [
self::ATTR_PROG => self::PROG,
self::ATTR_CANONICAL => $canonical,
self::ATTR_NAME => get_class($flow),
self::ATTR_DATA => $this->serializer->encode($this->properties->getPropertiesFromObject($flow)),
self::ATTR_ID => $customId,
]);
} | php | {
"resource": ""
} |
q257280 | Client.findWorkflow | test | public function findWorkflow($workflowName, $customId)
{
$params = [
static::ATTR_ID => $customId,
static::ATTR_NAME => $workflowName,
static::ATTR_PROG => static::PROG,
];
$response = $this->http->get($this->getInstanceWebsiteUrl($params));
if ($response->code === 404) {
return null;
}
if ($response->hasErrors()) {
throw ApiException::unexpectedStatusCode($response->code);
}
return $this->properties->getObjectFromNameAndProperties($response->body->data->name, $this->serializer->decode($response->body->data->properties));
} | php | {
"resource": ""
} |
q257281 | WithTimestamp._getTimestampOrDuration | test | public function _getTimestampOrDuration()
{
if (null === $this->_buffer) {
return [null, null];
}
list($now, $then) = $this->_initNowThen();
$this->_mode = null;
// apply buffered methods
foreach ($this->_buffer as $call) {
$then = $this->_apply($call[0], $call[1], $now, $then);
}
// has user used a method by timestamp?
$isTimestamp = null !== $this->_mode;
//return
if ($isTimestamp) {
return [$then->timestamp, null];
}
return [null, $now->diffInSeconds($then)];
} | php | {
"resource": ""
} |
q257282 | Properties.getClassProperties | test | private function getClassProperties($argument, $filter = null)
{
if (null === $filter) {
$filter = \ReflectionProperty::IS_STATIC | \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PRIVATE;
}
$reflectionClass = new \ReflectionClass($argument);
if ($parentClass = $reflectionClass->getParentClass()) {
return array_merge($this->getClassProperties($parentClass->getName(), $filter), $reflectionClass->getProperties($filter));
}
return $reflectionClass->getProperties($filter);
} | php | {
"resource": ""
} |
q257283 | SonataSeoExtension.configureSitemap | test | protected function configureSitemap(array $config, ContainerBuilder $container)
{
$source = $container->getDefinition('sonata.seo.sitemap.manager');
if (method_exists($source, 'setShared')) { // Symfony 2.8+
$source->setShared(false);
} else {
// For Symfony <2.8 compatibility
$source->setScope(ContainerInterface::SCOPE_PROTOTYPE);
}
foreach ($config['doctrine_orm'] as $pos => $sitemap) {
// define the connectionIterator
$connectionIteratorId = 'sonata.seo.source.doctrine_connection_iterator_'.$pos;
$connectionIterator = new Definition('%sonata.seo.exporter.database_source_iterator.class%', [
new Reference($sitemap['connection']),
$sitemap['query'],
]);
$connectionIterator->setPublic(false);
$container->setDefinition($connectionIteratorId, $connectionIterator);
// define the sitemap proxy iterator
$sitemapIteratorId = 'sonata.seo.source.doctrine_sitemap_iterator_'.$pos;
$sitemapIterator = new Definition('%sonata.seo.exporter.sitemap_source_iterator.class%', [
new Reference($connectionIteratorId),
new Reference('router'),
$sitemap['route'],
$sitemap['parameters'],
]);
$sitemapIterator->setPublic(false);
$container->setDefinition($sitemapIteratorId, $sitemapIterator);
$source->addMethodCall('addSource', [$sitemap['group'], new Reference($sitemapIteratorId), $sitemap['types']]);
}
foreach ($config['services'] as $service) {
$source->addMethodCall('addSource', [$service['group'], new Reference($service['id']), $service['types']]);
}
} | php | {
"resource": ""
} |
q257284 | SonataSeoExtension.fixConfiguration | test | protected function fixConfiguration(array $config)
{
foreach ($config['sitemap']['doctrine_orm'] as $pos => $sitemap) {
$sitemap['group'] = $sitemap['group'] ?? false;
$sitemap['types'] = $sitemap['types'] ?? [];
$sitemap['connection'] = $sitemap['connection'] ?? 'doctrine.dbal.default_connection';
$sitemap['route'] = $sitemap['route'] ?? false;
$sitemap['parameters'] = $sitemap['parameters'] ?? false;
$sitemap['query'] = $sitemap['query'] ?? false;
if (false === $sitemap['route']) {
throw new \RuntimeException('Route cannot be empty, please review the sonata_seo.sitemap configuration');
}
if (false === $sitemap['query']) {
throw new \RuntimeException('Query cannot be empty, please review the sonata_seo.sitemap configuration');
}
if (false === $sitemap['parameters']) {
throw new \RuntimeException('Route\'s parameters cannot be empty, please review the sonata_seo.sitemap configuration');
}
$config['sitemap']['doctrine_orm'][$pos] = $sitemap;
}
foreach ($config['sitemap']['services'] as $pos => $sitemap) {
if (!\is_array($sitemap)) {
$sitemap = [
'group' => false,
'types' => [],
'id' => $sitemap,
];
} else {
$sitemap['group'] = $sitemap['group'] ?? false;
$sitemap['types'] = $sitemap['types'] ?? [];
if (!isset($sitemap['id'])) {
throw new \RuntimeException('Service id must to be defined, please review the sonata_seo.sitemap configuration');
}
}
$config['sitemap']['services'][$pos] = $sitemap;
}
return $config;
} | php | {
"resource": ""
} |
q257285 | SourceManager.addSource | test | public function addSource($group, SourceIteratorInterface $source, array $types = [])
{
if (!isset($this->sources[$group])) {
$this->sources[$group] = new \stdClass();
$this->sources[$group]->sources = new ChainSourceIterator();
$this->sources[$group]->types = [];
}
$this->sources[$group]->sources->addSource($source);
if ($types) {
$this->sources[$group]->types += array_diff($types, $this->sources[$group]->types);
}
} | php | {
"resource": ""
} |
q257286 | BreadcrumbListener.onBlock | test | public function onBlock(BlockEvent $event)
{
$context = $event->getSetting('context', null);
if (null === $context) {
return;
}
foreach ($this->blockServices as $type => $blockService) {
if ($blockService->handleContext($context)) {
$block = new Block();
$block->setId(uniqid());
$block->setSettings($event->getSettings());
$block->setType($type);
$event->addBlock($block);
return;
}
}
} | php | {
"resource": ""
} |
q257287 | BaseBreadcrumbMenuBlockService.getRootMenu | test | protected function getRootMenu(BlockContextInterface $blockContext)
{
$settings = $blockContext->getSettings();
/*
* @todo : Use the router to get the homepage URI
*/
$menu = $this->factory->createItem('breadcrumb');
$menu->setChildrenAttribute('class', 'breadcrumb');
if (method_exists($menu, 'setCurrentUri')) {
$menu->setCurrentUri($settings['current_uri']);
}
if (method_exists($menu, 'setCurrent')) {
$menu->setCurrent($settings['current_uri']);
}
if ($settings['include_homepage_link']) {
$menu->addChild('sonata_seo_homepage_breadcrumb', ['uri' => '/']);
}
return $menu;
} | php | {
"resource": ""
} |
q257288 | Iconpicker.getFonts | test | private function getFonts()
{
if (empty($this->fonts)) {
$files = FileHelper::findFiles(Craft::getAlias(self::FONT_DIR), ['only' => self::FONT_EXT]);
$filenames = [];
$fonts = [];
foreach ($files as $file) {
$pathInfo = pathinfo($file);
$safename = in_array($pathInfo['filename'], $filenames) ? $pathInfo['basename'] : $pathInfo['filename'];
$safename = $this->safeName($safename);
$fonts[$safename] = ArrayHelper::merge(
[
'path' => $file,
'safename' => $safename
],
$pathInfo
);
$filenames[] = $pathInfo['filename'];
}
$this->fonts = $fonts;
}
return $this->fonts;
} | php | {
"resource": ""
} |
q257289 | Iconpicker.getIcons | test | private function getIcons()
{
if (!empty($this->iconFont)) {
$fonts = $this->getFonts();
if (!empty($fonts) && isset($fonts[$this->iconFont])) {
$font = Font::load($fonts[$this->iconFont]['path']);
$font->parse();
if ($font !== null) {
return $font->getUnicodeCharMap();
}
}
}
return null;
} | php | {
"resource": ""
} |
q257290 | Iconpicker.getFontCss | test | public function getFontCss()
{
$sharedAsset = new sharedAsset();
$scss = "";
foreach ($this->getFonts() as $safeName => $pathInfo) {
$fontFile = $pathInfo['path'];
$font = Font::load($fontFile);
$font->parse();
if (!empty($font)) {
$iconFontName = $safeName;
if (!empty($iconFontName)) {
$scss .= "
@font-face {
font-family: 'dq-iconpicker-".$iconFontName."';
src: url('../fonts/".$pathInfo['basename']."');
font-weight: 100;
font-style: normal;
}\n\n";
$scss .= '
[class*="dq-icon-'.$iconFontName.'"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: dq-iconpicker-'.$iconFontName.' !important;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
display: inline-block;
vertical-align: baseline;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}'."\n\n";
}
}
}
file_put_contents(Craft::getAlias($sharedAsset->sourcePath . '/css/fonts.css'), $scss);
// Register the assetbundle that loads the generated css
Craft::$app->view->registerAssetBundle(sharedAsset::className());
} | php | {
"resource": ""
} |
q257291 | PasswordLock.hashAndEncrypt | test | public static function hashAndEncrypt(string $password, Key $aesKey): string
{
/** @var string $hash */
$hash = \password_hash(
Base64::encode(
\hash('sha384', $password, true)
),
PASSWORD_DEFAULT
);
if (!\is_string($hash)) {
throw new \Exception("Unknown hashing error.");
}
return Crypto::encrypt($hash, $aesKey);
} | php | {
"resource": ""
} |
q257292 | PasswordLock.upgradeFromVersion1 | test | public static function upgradeFromVersion1(
string $password,
string $ciphertext,
string $oldKey,
Key $newKey
): string {
if (!self::decryptAndVerifyLegacy($password, $ciphertext, $oldKey)) {
throw new \Exception(
'The correct password is necessary for legacy migration.'
);
}
$plaintext = Crypto::legacyDecrypt($ciphertext, $oldKey);
return self::hashAndEncrypt($plaintext, $newKey);
} | php | {
"resource": ""
} |
q257293 | ExplainCommand.execute | test | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->init($input, $output);
$config = $this->initConfiguration($input->getOption('config_file'));
$rules = $config->getRules();
foreach ($rules as $name => $rule) {
$info = Init::getInitInformationByClass(get_class($rule));
$output->writeln(' ' . $name . ':');
$output->writeln(' class: ' . get_class($rule));
$output->writeln(' description: ' . str_replace("\n", "\n ", $info['documentation']));
if (count($info['parameters']) > 0) {
$output->writeln(' parameter:');
foreach ($info['parameters'] as $parameter) {
$output->writeln(' ' . $parameter['name'] . ': ' . $parameter['description'] . ' (default: ' . $parameter['default'] . ')');
}
}
$output->writeln('');
}
} | php | {
"resource": ""
} |
q257294 | SmokeCommand.writeSmokeCredentials | test | protected function writeSmokeCredentials($url = null)
{
if (defined('SMOKE_CREDENTIALS')) {
$this->output->writeln("\n " . SMOKE_CREDENTIALS . "\n");
} else {
$this->output->writeln("\n Smoke " . SMOKE_VERSION . " by Nils Langner\n");
}
if ($url) {
$this->output->writeln(' <info>Scanning ' . $url . "</info>\n");
}
} | php | {
"resource": ""
} |
q257295 | SmokeCommand.getConfigArray | test | protected function getConfigArray($configFile, $mandatory = false)
{
$configArray = array();
if ($configFile) {
if (strpos($configFile, 'http://') === 0 || strpos($configFile, 'https://') === 0) {
$curlClient = new Client();
$fileContent = (string)$curlClient->get($configFile)->getBody();
} else {
if (file_exists($configFile)) {
$fileContent = file_get_contents($configFile);
} else {
throw new \RuntimeException("Config file was not found ('" . $configFile . "').");
}
}
$configArray = EnvAwareYaml::parse($fileContent);
} else {
if ($mandatory) {
throw new \RuntimeException('Config file was not defined.');
}
}
return $configArray;
} | php | {
"resource": ""
} |
q257296 | ForeignDomainFilter.isFiltered | test | public function isFiltered(UriInterface $currentUri, UriInterface $startUri)
{
/* @var $currentUri Uri */
/* @var $startUri Uri */
$startDomainElements = explode('.', $startUri->getHost());
$currentDomainElements = explode('.', $currentUri->getHost());
$startDomainLength = count($startDomainElements);
$currentDomainLength = count($currentDomainElements);
if ($currentDomainLength < $startDomainLength) {
return true;
}
return $currentUri->getHost($startDomainLength) !== $startUri->getHost($startDomainLength);
} | php | {
"resource": ""
} |
q257297 | Application.registerCommands | test | private function registerCommands()
{
$this->add(new ScanCommand());
$this->add(new ExplainCommand());
$this->add(new WarmUpCommand());
$this->add(new CustomCommand());
} | php | {
"resource": ""
} |
q257298 | TemplateFinder.findAllTemplates | test | public function findAllTemplates()
{
if (null !== $this->templates) {
return $this->templates;
}
//All themes
$this->themes = $this->themeManager->getThemes();
$templates = array();
foreach ($this->kernel->getBundles() as $bundle) {
$templates = array_merge($templates, $this->findTemplatesInBundle($bundle));
}
$templates = array_merge($templates, $this->findTemplatesInFolder($this->rootDir.'/views'));
return $this->templates = $templates;
} | php | {
"resource": ""
} |
q257299 | TemplateFinder.findTemplatesInBundle | test | private function findTemplatesInBundle(BundleInterface $bundle)
{
$name = $bundle->getName();
$templates = array_merge(
$this->findTemplatesInFolder($bundle->getPath().'/Resources/views'),
$this->findTemplatesInFolder($this->rootDir.'/'.$name.'/views')
);
//追踪主题下的模板
foreach ($this->themes as $theme) {
$templates = array_merge($templates,
$this->findTemplatesInFolder($this->themeDir.'/'.$name.'/views')
);
}
$templates = array_unique($templates);
foreach ($templates as $i => $template) {
$templates[$i] = $template->set('bundle', $name);
}
return $templates;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.