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 listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
crysalead/sql-dialect | src/Statement/Select.php | Select.having | public function having($conditions)
{
if ($conditions = is_array($conditions) && func_num_args() === 1 ? $conditions : func_get_args()) {
$this->_parts['having'][] = $conditions;
}
return $this;
} | php | public function having($conditions)
{
if ($conditions = is_array($conditions) && func_num_args() === 1 ? $conditions : func_get_args()) {
$this->_parts['having'][] = $conditions;
}
return $this;
} | [
"public",
"function",
"having",
"(",
"$",
"conditions",
")",
"{",
"if",
"(",
"$",
"conditions",
"=",
"is_array",
"(",
"$",
"conditions",
")",
"&&",
"func_num_args",
"(",
")",
"===",
"1",
"?",
"$",
"conditions",
":",
"func_get_args",
"(",
")",
")",
"{",... | Adds some having conditions to the query.
@param string|array $conditions The havings for this query.
@return object Returns `$this`. | [
"Adds",
"some",
"having",
"conditions",
"to",
"the",
"query",
"."
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/Select.php#L121-L127 |
crysalead/sql-dialect | src/Statement/Select.php | Select.toString | public function toString($schemas = [], $aliases = [])
{
$fields = $this->dialect()->names($this->_parts['fields']);
$sql = 'SELECT' .
$this->_buildFlags($this->_parts['flags']) .
$this->_buildChunk($fields ?: '*') .
$this->_buildClause('FROM', $this->dialect()->names($this->_parts['from'])) .
$this->_buildJoins($schemas, $aliases) .
$this->_buildClause('WHERE', $this->dialect()->conditions($this->_parts['where'], compact('schemas', 'aliases'))) .
$this->_buildClause('GROUP BY', $this->_group()) .
$this->_buildClause('HAVING', $this->dialect()->conditions($this->_parts['having'], compact('schemas', 'aliases'))) .
$this->_buildOrder($aliases) .
$this->_buildClause('LIMIT', $this->_parts['limit']);
if ($this->_parts['lock']) {
$sql .= $this->_buildFlag($this->_parts['lock'], $this->_parts['lock']) .
$this->_buildFlag('NOWAIT', $this->_parts['noWait']);
}
return $this->_alias ? "({$sql}) AS " . $this->dialect()->name($this->_alias) : $sql;
} | php | public function toString($schemas = [], $aliases = [])
{
$fields = $this->dialect()->names($this->_parts['fields']);
$sql = 'SELECT' .
$this->_buildFlags($this->_parts['flags']) .
$this->_buildChunk($fields ?: '*') .
$this->_buildClause('FROM', $this->dialect()->names($this->_parts['from'])) .
$this->_buildJoins($schemas, $aliases) .
$this->_buildClause('WHERE', $this->dialect()->conditions($this->_parts['where'], compact('schemas', 'aliases'))) .
$this->_buildClause('GROUP BY', $this->_group()) .
$this->_buildClause('HAVING', $this->dialect()->conditions($this->_parts['having'], compact('schemas', 'aliases'))) .
$this->_buildOrder($aliases) .
$this->_buildClause('LIMIT', $this->_parts['limit']);
if ($this->_parts['lock']) {
$sql .= $this->_buildFlag($this->_parts['lock'], $this->_parts['lock']) .
$this->_buildFlag('NOWAIT', $this->_parts['noWait']);
}
return $this->_alias ? "({$sql}) AS " . $this->dialect()->name($this->_alias) : $sql;
} | [
"public",
"function",
"toString",
"(",
"$",
"schemas",
"=",
"[",
"]",
",",
"$",
"aliases",
"=",
"[",
"]",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"dialect",
"(",
")",
"->",
"names",
"(",
"$",
"this",
"->",
"_parts",
"[",
"'fields'",
"]",... | Render the SQL statement
@return string The generated SQL string. | [
"Render",
"the",
"SQL",
"statement"
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/Select.php#L173-L193 |
crysalead/sql-dialect | src/Statement/Select.php | Select._group | protected function _group()
{
$result = [];
foreach ($this->_parts['group'] as $name => $value) {
$result[] = $this->dialect()->name($name);
}
return $fields = join(', ', $result);
} | php | protected function _group()
{
$result = [];
foreach ($this->_parts['group'] as $name => $value) {
$result[] = $this->dialect()->name($name);
}
return $fields = join(', ', $result);
} | [
"protected",
"function",
"_group",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"_parts",
"[",
"'group'",
"]",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"this",
"... | Build the `GROUP BY` clause.
@return string The `GROUP BY` clause. | [
"Build",
"the",
"GROUP",
"BY",
"clause",
"."
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/Select.php#L200-L207 |
crysalead/sql-dialect | src/Statement/Select.php | Select._buildJoins | protected function _buildJoins($schemas, $aliases)
{
$joins = [];
foreach ($this->_parts['joins'] as $value) {
$table = $value['join'];
$on = $value['on'];
$type = $value['type'];
$join = [strtoupper($type), 'JOIN'];
$join[] = $this->dialect()->name($table);
if ($on) {
$join[] = 'ON';
$join[] = $this->dialect()->conditions($on, compact('schemas', 'aliases'));
}
$joins[] = join(' ', $join);
}
return $joins ? ' ' . join(' ', $joins) : '';
} | php | protected function _buildJoins($schemas, $aliases)
{
$joins = [];
foreach ($this->_parts['joins'] as $value) {
$table = $value['join'];
$on = $value['on'];
$type = $value['type'];
$join = [strtoupper($type), 'JOIN'];
$join[] = $this->dialect()->name($table);
if ($on) {
$join[] = 'ON';
$join[] = $this->dialect()->conditions($on, compact('schemas', 'aliases'));
}
$joins[] = join(' ', $join);
}
return $joins ? ' ' . join(' ', $joins) : '';
} | [
"protected",
"function",
"_buildJoins",
"(",
"$",
"schemas",
",",
"$",
"aliases",
")",
"{",
"$",
"joins",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"_parts",
"[",
"'joins'",
"]",
"as",
"$",
"value",
")",
"{",
"$",
"table",
"=",
"$",
... | Build the `JOIN` clause.
@return string The `JOIN` clause. | [
"Build",
"the",
"JOIN",
"clause",
"."
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/Select.php#L214-L232 |
txj123/zilf | src/Zilf/Db/Connection.php | Connection.getQueryCacheInfo | public function getQueryCacheInfo($duration, $dependency)
{
if (!$this->enableQueryCache) {
return null;
}
$info = end($this->_queryCacheInfo);
if (is_array($info)) {
if ($duration === null) {
$duration = $info[0];
}
if ($dependency === null) {
$dependency = $info[1];
}
}
if ($duration === 0 || $duration > 0) {
if (is_string($this->queryCache) && Zilf::$app) {
$cache = Zilf::$app->get($this->queryCache, false);
} else {
$cache = $this->queryCache;
}
if ($cache instanceof CacheInterface) {
return [$cache, $duration, $dependency];
}
}
return null;
} | php | public function getQueryCacheInfo($duration, $dependency)
{
if (!$this->enableQueryCache) {
return null;
}
$info = end($this->_queryCacheInfo);
if (is_array($info)) {
if ($duration === null) {
$duration = $info[0];
}
if ($dependency === null) {
$dependency = $info[1];
}
}
if ($duration === 0 || $duration > 0) {
if (is_string($this->queryCache) && Zilf::$app) {
$cache = Zilf::$app->get($this->queryCache, false);
} else {
$cache = $this->queryCache;
}
if ($cache instanceof CacheInterface) {
return [$cache, $duration, $dependency];
}
}
return null;
} | [
"public",
"function",
"getQueryCacheInfo",
"(",
"$",
"duration",
",",
"$",
"dependency",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"enableQueryCache",
")",
"{",
"return",
"null",
";",
"}",
"$",
"info",
"=",
"end",
"(",
"$",
"this",
"->",
"_queryCach... | Returns the current query cache information.
This method is used internally by [[Command]].
@param int $duration the preferred caching duration. If null, it will be ignored.
@param \Zilf\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
@return array the current query cache information, or null if query cache is not enabled.
@internal | [
"Returns",
"the",
"current",
"query",
"cache",
"information",
".",
"This",
"method",
"is",
"used",
"internally",
"by",
"[[",
"Command",
"]]",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Connection.php#L553-L581 |
txj123/zilf | src/Zilf/Db/Connection.php | Connection.open | public function open()
{
if ($this->pdo !== null) {
return;
}
if (!empty($this->masters)) {
$db = $this->getMaster();
if ($db !== null) {
$this->pdo = $db->pdo;
return;
}
throw new InvalidConfigException('None of the master DB servers is available.');
}
if (empty($this->dsn)) {
throw new InvalidConfigException('Connection::dsn cannot be empty.');
}
$token = 'Opening DB connection: ' . $this->dsn;
$enableProfiling = $this->enableProfiling;
try {
/*Zilf::info($token, __METHOD__);
if ($enableProfiling) {
Zilf::beginProfile($token, __METHOD__);
}*/
$this->pdo = $this->createPdoInstance();
$this->initConnection();
/* if ($enableProfiling) {
Zilf::endProfile($token, __METHOD__);
}*/
} catch (\PDOException $e) {
/* if ($enableProfiling) {
Zilf::endProfile($token, __METHOD__);
}*/
throw new Exception($e->getMessage(), $e->errorInfo, (int)$e->getCode(), $e);
}
} | php | public function open()
{
if ($this->pdo !== null) {
return;
}
if (!empty($this->masters)) {
$db = $this->getMaster();
if ($db !== null) {
$this->pdo = $db->pdo;
return;
}
throw new InvalidConfigException('None of the master DB servers is available.');
}
if (empty($this->dsn)) {
throw new InvalidConfigException('Connection::dsn cannot be empty.');
}
$token = 'Opening DB connection: ' . $this->dsn;
$enableProfiling = $this->enableProfiling;
try {
/*Zilf::info($token, __METHOD__);
if ($enableProfiling) {
Zilf::beginProfile($token, __METHOD__);
}*/
$this->pdo = $this->createPdoInstance();
$this->initConnection();
/* if ($enableProfiling) {
Zilf::endProfile($token, __METHOD__);
}*/
} catch (\PDOException $e) {
/* if ($enableProfiling) {
Zilf::endProfile($token, __METHOD__);
}*/
throw new Exception($e->getMessage(), $e->errorInfo, (int)$e->getCode(), $e);
}
} | [
"public",
"function",
"open",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"pdo",
"!==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"masters",
")",
")",
"{",
"$",
"db",
"=",
"$",
"this",
"->",
"getM... | Establishes a DB connection.
It does nothing if a DB connection has already been established.
@throws Exception if connection fails | [
"Establishes",
"a",
"DB",
"connection",
".",
"It",
"does",
"nothing",
"if",
"a",
"DB",
"connection",
"has",
"already",
"been",
"established",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Connection.php#L589-L630 |
txj123/zilf | src/Zilf/Db/Connection.php | Connection.close | public function close()
{
if ($this->_master) {
if ($this->pdo === $this->_master->pdo) {
$this->pdo = null;
}
$this->_master->close();
$this->_master = false;
}
if ($this->pdo !== null) {
Log::debug('Closing DB connection: ' . $this->dsn . __METHOD__);
$this->pdo = null;
$this->_schema = null;
$this->_transaction = null;
}
if ($this->_slave) {
$this->_slave->close();
$this->_slave = false;
}
} | php | public function close()
{
if ($this->_master) {
if ($this->pdo === $this->_master->pdo) {
$this->pdo = null;
}
$this->_master->close();
$this->_master = false;
}
if ($this->pdo !== null) {
Log::debug('Closing DB connection: ' . $this->dsn . __METHOD__);
$this->pdo = null;
$this->_schema = null;
$this->_transaction = null;
}
if ($this->_slave) {
$this->_slave->close();
$this->_slave = false;
}
} | [
"public",
"function",
"close",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_master",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"pdo",
"===",
"$",
"this",
"->",
"_master",
"->",
"pdo",
")",
"{",
"$",
"this",
"->",
"pdo",
"=",
"null",
";",
"}",
... | Closes the currently active DB connection.
It does nothing if the connection is already closed. | [
"Closes",
"the",
"currently",
"active",
"DB",
"connection",
".",
"It",
"does",
"nothing",
"if",
"the",
"connection",
"is",
"already",
"closed",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Connection.php#L636-L658 |
txj123/zilf | src/Zilf/Db/Connection.php | Connection.createPdoInstance | protected function createPdoInstance()
{
$pdoClass = $this->pdoClass;
if ($pdoClass === null) {
$pdoClass = 'PDO';
if ($this->_driverName !== null) {
$driver = $this->_driverName;
} elseif (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos));
}
if (isset($driver)) {
if ($driver === 'mssql' || $driver === 'dblib') {
$pdoClass = 'Zilf\Db\mssql\PDO';
} elseif ($driver === 'sqlsrv') {
$pdoClass = 'Zilf\Db\mssql\SqlsrvPDO';
}
}
}
$dsn = $this->dsn;
if (strncmp('sqlite:@', $dsn, 8) === 0) {
$dsn = 'sqlite:' . Zilf::getAlias(substr($dsn, 7));
}
return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
} | php | protected function createPdoInstance()
{
$pdoClass = $this->pdoClass;
if ($pdoClass === null) {
$pdoClass = 'PDO';
if ($this->_driverName !== null) {
$driver = $this->_driverName;
} elseif (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos));
}
if (isset($driver)) {
if ($driver === 'mssql' || $driver === 'dblib') {
$pdoClass = 'Zilf\Db\mssql\PDO';
} elseif ($driver === 'sqlsrv') {
$pdoClass = 'Zilf\Db\mssql\SqlsrvPDO';
}
}
}
$dsn = $this->dsn;
if (strncmp('sqlite:@', $dsn, 8) === 0) {
$dsn = 'sqlite:' . Zilf::getAlias(substr($dsn, 7));
}
return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
} | [
"protected",
"function",
"createPdoInstance",
"(",
")",
"{",
"$",
"pdoClass",
"=",
"$",
"this",
"->",
"pdoClass",
";",
"if",
"(",
"$",
"pdoClass",
"===",
"null",
")",
"{",
"$",
"pdoClass",
"=",
"'PDO'",
";",
"if",
"(",
"$",
"this",
"->",
"_driverName",... | Creates the PDO instance.
This method is called by [[open]] to establish a DB connection.
The default implementation will create a PHP PDO instance.
You may override this method if the default PDO needs to be adapted for certain DBMS.
@return PDO the pdo instance | [
"Creates",
"the",
"PDO",
"instance",
".",
"This",
"method",
"is",
"called",
"by",
"[[",
"open",
"]]",
"to",
"establish",
"a",
"DB",
"connection",
".",
"The",
"default",
"implementation",
"will",
"create",
"a",
"PHP",
"PDO",
"instance",
".",
"You",
"may",
... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Connection.php#L668-L693 |
txj123/zilf | src/Zilf/Db/Connection.php | Connection.rollbackTransactionOnLevel | private function rollbackTransactionOnLevel($transaction, $level)
{
if ($transaction->isActive && $transaction->level === $level) {
// https://github.com/Zilfsoft/Zilf2/pull/13347
try {
$transaction->rollBack();
} catch (\Exception $e) {
\Zilf::error($e, __METHOD__);
// hide this exception to be able to continue throwing original exception outside
}
}
} | php | private function rollbackTransactionOnLevel($transaction, $level)
{
if ($transaction->isActive && $transaction->level === $level) {
// https://github.com/Zilfsoft/Zilf2/pull/13347
try {
$transaction->rollBack();
} catch (\Exception $e) {
\Zilf::error($e, __METHOD__);
// hide this exception to be able to continue throwing original exception outside
}
}
} | [
"private",
"function",
"rollbackTransactionOnLevel",
"(",
"$",
"transaction",
",",
"$",
"level",
")",
"{",
"if",
"(",
"$",
"transaction",
"->",
"isActive",
"&&",
"$",
"transaction",
"->",
"level",
"===",
"$",
"level",
")",
"{",
"// https://github.com/Zilfsoft/Zi... | Rolls back given [[Transaction]] object if it's still active and level match.
In some cases rollback can fail, so this method is fail safe. Exception thrown
from rollback will be caught and just logged with [[\Zilf::error()]].
@param Transaction $transaction Transaction object given from [[beginTransaction()]].
@param int $level Transaction level just after [[beginTransaction()]] call. | [
"Rolls",
"back",
"given",
"[[",
"Transaction",
"]]",
"object",
"if",
"it",
"s",
"still",
"active",
"and",
"level",
"match",
".",
"In",
"some",
"cases",
"rollback",
"can",
"fail",
"so",
"this",
"method",
"is",
"fail",
"safe",
".",
"Exception",
"thrown",
"... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Connection.php#L806-L817 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Export/Format/BaseFormat.php | BaseFormat.createResponse | public function createResponse($result)
{
return Response::make($result, 200, [
'Content-Type' => $this->getContentType(),
'Content-Disposition' => sprintf('attachment; filename="%s"', $this->getFilename()),
]);
} | php | public function createResponse($result)
{
return Response::make($result, 200, [
'Content-Type' => $this->getContentType(),
'Content-Disposition' => sprintf('attachment; filename="%s"', $this->getFilename()),
]);
} | [
"public",
"function",
"createResponse",
"(",
"$",
"result",
")",
"{",
"return",
"Response",
"::",
"make",
"(",
"$",
"result",
",",
"200",
",",
"[",
"'Content-Type'",
"=>",
"$",
"this",
"->",
"getContentType",
"(",
")",
",",
"'Content-Disposition'",
"=>",
"... | Create the download response.
@param string $result
@access public
@return mixed | [
"Create",
"the",
"download",
"response",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Export/Format/BaseFormat.php#L133-L139 |
txj123/zilf | src/Zilf/Db/ActiveRecord.php | ActiveRecord.filterCondition | protected static function filterCondition(array $condition)
{
$result = [];
// valid column names are table column names or column names prefixed with table name
$columnNames = static::getTableSchema()->getColumnNames();
$tableName = static::tableName();
$columnNames = array_merge(
$columnNames, array_map(
function ($columnName) use ($tableName) {
return "$tableName.$columnName";
}, $columnNames
)
);
foreach ($condition as $key => $value) {
if (is_string($key) && !in_array($key, $columnNames, true)) {
throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
}
$result[$key] = is_array($value) ? array_values($value) : $value;
}
return $result;
} | php | protected static function filterCondition(array $condition)
{
$result = [];
// valid column names are table column names or column names prefixed with table name
$columnNames = static::getTableSchema()->getColumnNames();
$tableName = static::tableName();
$columnNames = array_merge(
$columnNames, array_map(
function ($columnName) use ($tableName) {
return "$tableName.$columnName";
}, $columnNames
)
);
foreach ($condition as $key => $value) {
if (is_string($key) && !in_array($key, $columnNames, true)) {
throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
}
$result[$key] = is_array($value) ? array_values($value) : $value;
}
return $result;
} | [
"protected",
"static",
"function",
"filterCondition",
"(",
"array",
"$",
"condition",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"// valid column names are table column names or column names prefixed with table name",
"$",
"columnNames",
"=",
"static",
"::",
"getTableSc... | Filters array condition before it is assiged to a Query filter.
This method will ensure that an array condition only filters on existing table columns.
@param array $condition condition to filter.
@return array filtered condition.
@throws InvalidArgumentException in case array contains unsafe values.
@since 2.0.15
@internal | [
"Filters",
"array",
"condition",
"before",
"it",
"is",
"assiged",
"to",
"a",
"Query",
"filter",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/ActiveRecord.php#L209-L230 |
txj123/zilf | src/Zilf/Db/ActiveRecord.php | ActiveRecord.update | public function update($runValidation = true, $attributeNames = null)
{
if ($runValidation && !$this->validate($attributeNames)) {
//Zilf::info('Model not updated due to validation error.', __METHOD__);
return false;
}
if (!$this->isTransactional(self::OP_UPDATE)) {
return $this->updateInternal($attributeNames);
}
$transaction = static::getDb()->beginTransaction();
try {
$result = $this->updateInternal($attributeNames);
if ($result === false) {
$transaction->rollBack();
} else {
$transaction->commit();
}
return $result;
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
} | php | public function update($runValidation = true, $attributeNames = null)
{
if ($runValidation && !$this->validate($attributeNames)) {
//Zilf::info('Model not updated due to validation error.', __METHOD__);
return false;
}
if (!$this->isTransactional(self::OP_UPDATE)) {
return $this->updateInternal($attributeNames);
}
$transaction = static::getDb()->beginTransaction();
try {
$result = $this->updateInternal($attributeNames);
if ($result === false) {
$transaction->rollBack();
} else {
$transaction->commit();
}
return $result;
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
} | [
"public",
"function",
"update",
"(",
"$",
"runValidation",
"=",
"true",
",",
"$",
"attributeNames",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"runValidation",
"&&",
"!",
"$",
"this",
"->",
"validate",
"(",
"$",
"attributeNames",
")",
")",
"{",
"//Zilf::info... | Saves the changes to this active record into the associated database table.
This method performs the following steps in order:
1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
returns `false`, the rest of the steps will be skipped;
2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
failed, the rest of the steps will be skipped;
3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
the rest of the steps will be skipped;
4. save the record into database. If this fails, it will skip the rest of the steps;
5. call [[afterSave()]];
In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
[[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
will be raised by the corresponding methods.
Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
For example, to update a customer record:
```php
$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();
```
Note that it is possible the update does not affect any row in the table.
In this case, this method will return 0. For this reason, you should use the following
code to check if update() is successful or not:
```php
if ($customer->update() !== false) {
// update successful
} else {
// update failed
}
```
@param bool $runValidation whether to perform validation (calling [[validate()]])
before saving the record. Defaults to `true`. If the
validation fails, the record will not be saved to the
database and this method will return `false`.
@param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
meaning all attributes that are loaded from DB will be saved.
@return int|false the number of rows affected, or false if validation fails
or [[beforeSave()]] stops the updating process.
@throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
being updated is outdated.
@throws \Exception|\Throwable in case update failed. | [
"Saves",
"the",
"changes",
"to",
"this",
"active",
"record",
"into",
"the",
"associated",
"database",
"table",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/ActiveRecord.php#L631-L659 |
oxygen-cms/core | src/Html/Navigation/Navigation.php | Navigation.all | public function all($toolbar = self::PRIMARY) {
$this->loadLazyOrders($toolbar);
return $this->toolbars[$toolbar]->getItems();
} | php | public function all($toolbar = self::PRIMARY) {
$this->loadLazyOrders($toolbar);
return $this->toolbars[$toolbar]->getItems();
} | [
"public",
"function",
"all",
"(",
"$",
"toolbar",
"=",
"self",
"::",
"PRIMARY",
")",
"{",
"$",
"this",
"->",
"loadLazyOrders",
"(",
"$",
"toolbar",
")",
";",
"return",
"$",
"this",
"->",
"toolbars",
"[",
"$",
"toolbar",
"]",
"->",
"getItems",
"(",
")... | Returns all toolbar items.
@param integer $toolbar Which toolbar to use
@return array | [
"Returns",
"all",
"toolbar",
"items",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Navigation/Navigation.php#L77-L81 |
oxygen-cms/core | src/Html/Navigation/Navigation.php | Navigation.order | public function order($toolbar, $keys) {
if(is_callable($keys)) {
$this->addLazyOrder($toolbar, $keys);
} else {
$this->toolbars[$toolbar]->setOrder($keys);
}
} | php | public function order($toolbar, $keys) {
if(is_callable($keys)) {
$this->addLazyOrder($toolbar, $keys);
} else {
$this->toolbars[$toolbar]->setOrder($keys);
}
} | [
"public",
"function",
"order",
"(",
"$",
"toolbar",
",",
"$",
"keys",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"keys",
")",
")",
"{",
"$",
"this",
"->",
"addLazyOrder",
"(",
"$",
"toolbar",
",",
"$",
"keys",
")",
";",
"}",
"else",
"{",
"$",
... | Orders the toolbar.
@param integer $toolbar Which toolbar to use
@param array|callable $keys
@return void | [
"Orders",
"the",
"toolbar",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Navigation/Navigation.php#L100-L106 |
oxygen-cms/core | src/Html/Navigation/Navigation.php | Navigation.loadLazyOrders | protected function loadLazyOrders($toolbar) {
foreach($this->lazyOrders[$toolbar] as $callback) {
$this->order($toolbar, $callback());
}
} | php | protected function loadLazyOrders($toolbar) {
foreach($this->lazyOrders[$toolbar] as $callback) {
$this->order($toolbar, $callback());
}
} | [
"protected",
"function",
"loadLazyOrders",
"(",
"$",
"toolbar",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"lazyOrders",
"[",
"$",
"toolbar",
"]",
"as",
"$",
"callback",
")",
"{",
"$",
"this",
"->",
"order",
"(",
"$",
"toolbar",
",",
"$",
"callback",... | Loads orders of the navigation items.
@param string $toolbar
@return void | [
"Loads",
"orders",
"of",
"the",
"navigation",
"items",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Navigation/Navigation.php#L124-L128 |
txj123/zilf | src/Zilf/Console/Commands/ServeCommand.php | ServeCommand.handle | public function handle()
{
chdir(public_path());
$this->line("<info>Zilf development server started:</info> <http://{$this->host()}:{$this->port()}>");
passthru($this->serverCommand(), $status);
return $status;
} | php | public function handle()
{
chdir(public_path());
$this->line("<info>Zilf development server started:</info> <http://{$this->host()}:{$this->port()}>");
passthru($this->serverCommand(), $status);
return $status;
} | [
"public",
"function",
"handle",
"(",
")",
"{",
"chdir",
"(",
"public_path",
"(",
")",
")",
";",
"$",
"this",
"->",
"line",
"(",
"\"<info>Zilf development server started:</info> <http://{$this->host()}:{$this->port()}>\"",
")",
";",
"passthru",
"(",
"$",
"this",
"->"... | Execute the console command.
@return int
@throws \Exception | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Console/Commands/ServeCommand.php#L33-L42 |
willemo/flightstats | src/FlexClient.php | FlexClient.getClient | public function getClient()
{
if ($this->client === null) {
$this->client = new Client([
'base_uri' => $this->config['base_uri'],
]);
}
return $this->client;
} | php | public function getClient()
{
if ($this->client === null) {
$this->client = new Client([
'base_uri' => $this->config['base_uri'],
]);
}
return $this->client;
} | [
"public",
"function",
"getClient",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"client",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"client",
"=",
"new",
"Client",
"(",
"[",
"'base_uri'",
"=>",
"$",
"this",
"->",
"config",
"[",
"'base_uri'",
"]",
... | Get the configured HTTP client.
@return Client The configured HTTP client | [
"Get",
"the",
"configured",
"HTTP",
"client",
"."
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/FlexClient.php#L70-L79 |
willemo/flightstats | src/FlexClient.php | FlexClient.sendRequest | public function sendRequest(
$api,
$version,
$endpoint,
array $queryParams = []
) {
$endpoint = $this->buildEndpoint($api, $version, $endpoint);
$query = $this->buildQuery($queryParams);
try {
$response = $this->getClient()->request('GET', $endpoint, [
'query' => $query
]);
return $this->parseResponse($response);
} catch (ClientException $e) {
$this->parseClientException($e);
}
return [];
} | php | public function sendRequest(
$api,
$version,
$endpoint,
array $queryParams = []
) {
$endpoint = $this->buildEndpoint($api, $version, $endpoint);
$query = $this->buildQuery($queryParams);
try {
$response = $this->getClient()->request('GET', $endpoint, [
'query' => $query
]);
return $this->parseResponse($response);
} catch (ClientException $e) {
$this->parseClientException($e);
}
return [];
} | [
"public",
"function",
"sendRequest",
"(",
"$",
"api",
",",
"$",
"version",
",",
"$",
"endpoint",
",",
"array",
"$",
"queryParams",
"=",
"[",
"]",
")",
"{",
"$",
"endpoint",
"=",
"$",
"this",
"->",
"buildEndpoint",
"(",
"$",
"api",
",",
"$",
"version"... | Send a request to the API.
@param string $api The API name
@param string $version The API version
@param string $endpoint The endpoint of the URI
@param array $queryParams The query parameters
@return array The response from the API | [
"Send",
"a",
"request",
"to",
"the",
"API",
"."
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/FlexClient.php#L101-L122 |
willemo/flightstats | src/FlexClient.php | FlexClient.buildEndpoint | protected function buildEndpoint($api, $version, $endpoint)
{
return implode('/', [
$api,
$this->config['protocol'],
$version,
$this->config['format'],
$endpoint,
]);
} | php | protected function buildEndpoint($api, $version, $endpoint)
{
return implode('/', [
$api,
$this->config['protocol'],
$version,
$this->config['format'],
$endpoint,
]);
} | [
"protected",
"function",
"buildEndpoint",
"(",
"$",
"api",
",",
"$",
"version",
",",
"$",
"endpoint",
")",
"{",
"return",
"implode",
"(",
"'/'",
",",
"[",
"$",
"api",
",",
"$",
"this",
"->",
"config",
"[",
"'protocol'",
"]",
",",
"$",
"version",
",",... | Build the endpoint of the URI.
@param string $api The API name
@param string $version The API version
@param string $endpoint The endpoint to use
@return string The full endpoint string for this API endpoint | [
"Build",
"the",
"endpoint",
"of",
"the",
"URI",
"."
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/FlexClient.php#L152-L161 |
willemo/flightstats | src/FlexClient.php | FlexClient.buildQuery | protected function buildQuery(array $queryParams = [])
{
$auth = [
'appId' => $this->config['appId'],
'appKey' => $this->config['appKey'],
];
$queryParams = array_merge($auth, $queryParams);
if (isset($queryParams['extendedOptions'])) {
$extendedOptions = $queryParams['extendedOptions'];
} else {
$extendedOptions = [];
}
if (!is_array($extendedOptions)) {
$extendedOptions = [$extendedOptions];
}
if ($this->config['use_http_errors'] &&
!in_array('useHTTPErrors', $extendedOptions)
) {
$extendedOptions[] = 'useHTTPErrors';
}
$queryParams['extendedOptions'] = implode('+', $extendedOptions);
return $queryParams;
} | php | protected function buildQuery(array $queryParams = [])
{
$auth = [
'appId' => $this->config['appId'],
'appKey' => $this->config['appKey'],
];
$queryParams = array_merge($auth, $queryParams);
if (isset($queryParams['extendedOptions'])) {
$extendedOptions = $queryParams['extendedOptions'];
} else {
$extendedOptions = [];
}
if (!is_array($extendedOptions)) {
$extendedOptions = [$extendedOptions];
}
if ($this->config['use_http_errors'] &&
!in_array('useHTTPErrors', $extendedOptions)
) {
$extendedOptions[] = 'useHTTPErrors';
}
$queryParams['extendedOptions'] = implode('+', $extendedOptions);
return $queryParams;
} | [
"protected",
"function",
"buildQuery",
"(",
"array",
"$",
"queryParams",
"=",
"[",
"]",
")",
"{",
"$",
"auth",
"=",
"[",
"'appId'",
"=>",
"$",
"this",
"->",
"config",
"[",
"'appId'",
"]",
",",
"'appKey'",
"=>",
"$",
"this",
"->",
"config",
"[",
"'app... | Build the query array for the endpoint, including authentication
information.
@param array $queryParams The query parameters to use
@return array The query parameters | [
"Build",
"the",
"query",
"array",
"for",
"the",
"endpoint",
"including",
"authentication",
"information",
"."
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/FlexClient.php#L170-L198 |
willemo/flightstats | src/FlexClient.php | FlexClient.parseClientException | protected function parseClientException(ClientException $exception)
{
$response = $exception->getResponse();
$lines = explode("\n", $response->getBody());
$message = 'Something went wrong';
foreach ($lines as $line) {
if (strpos($line, 'message') !== false) {
$message = substr($line, 9);
break;
}
}
throw new FlexClientException($message, 0);
} | php | protected function parseClientException(ClientException $exception)
{
$response = $exception->getResponse();
$lines = explode("\n", $response->getBody());
$message = 'Something went wrong';
foreach ($lines as $line) {
if (strpos($line, 'message') !== false) {
$message = substr($line, 9);
break;
}
}
throw new FlexClientException($message, 0);
} | [
"protected",
"function",
"parseClientException",
"(",
"ClientException",
"$",
"exception",
")",
"{",
"$",
"response",
"=",
"$",
"exception",
"->",
"getResponse",
"(",
")",
";",
"$",
"lines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"response",
"->",
"getBod... | Parse the error response from the API
@param ClientException $exception The exception that contains the
response
@throws FlexClientException The parsed error response from the API
@return void | [
"Parse",
"the",
"error",
"response",
"from",
"the",
"API"
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/FlexClient.php#L219-L236 |
xutl/qcloud-cmq | src/Http/BaseResponse.php | BaseResponse.unwrapResponse | public function unwrapResponse(ResponseInterface $response)
{
if ($response->getStatusCode() != 200) {
throw new CMQServerNetworkException($response->getStatusCode(), $response->getHeaders(), $response->getBody()->getContents());
}
$content = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);
if ($content['code'] == 0) {
$this->succeed = true;
foreach ($content as $name => $value) {
if (property_exists($this, $name)) {
$this->{$name} = $value;
} else {
$this->_content[$name] = $value;
}
}
} else {
$this->unwrapErrorResponse($content);
}
} | php | public function unwrapResponse(ResponseInterface $response)
{
if ($response->getStatusCode() != 200) {
throw new CMQServerNetworkException($response->getStatusCode(), $response->getHeaders(), $response->getBody()->getContents());
}
$content = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);
if ($content['code'] == 0) {
$this->succeed = true;
foreach ($content as $name => $value) {
if (property_exists($this, $name)) {
$this->{$name} = $value;
} else {
$this->_content[$name] = $value;
}
}
} else {
$this->unwrapErrorResponse($content);
}
} | [
"public",
"function",
"unwrapResponse",
"(",
"ResponseInterface",
"$",
"response",
")",
"{",
"if",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"!=",
"200",
")",
"{",
"throw",
"new",
"CMQServerNetworkException",
"(",
"$",
"response",
"->",
"getStatus... | 解析响应
@param \Psr\Http\Message\ResponseInterface $response | [
"解析响应"
] | train | https://github.com/xutl/qcloud-cmq/blob/f48b905c2d4001817126f0c25a0433acda79ea6a/src/Http/BaseResponse.php#L59-L77 |
xutl/qcloud-cmq | src/Http/BaseResponse.php | BaseResponse.unwrapErrorResponse | public function unwrapErrorResponse($content)
{
$this->succeed = false;
throw new CMQServerException($content['message'], $content['requestId'] ?? '', $content['code'], $content);
} | php | public function unwrapErrorResponse($content)
{
$this->succeed = false;
throw new CMQServerException($content['message'], $content['requestId'] ?? '', $content['code'], $content);
} | [
"public",
"function",
"unwrapErrorResponse",
"(",
"$",
"content",
")",
"{",
"$",
"this",
"->",
"succeed",
"=",
"false",
";",
"throw",
"new",
"CMQServerException",
"(",
"$",
"content",
"[",
"'message'",
"]",
",",
"$",
"content",
"[",
"'requestId'",
"]",
"??... | 解析错误的响应
@param array $content | [
"解析错误的响应"
] | train | https://github.com/xutl/qcloud-cmq/blob/f48b905c2d4001817126f0c25a0433acda79ea6a/src/Http/BaseResponse.php#L83-L87 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Field/NumberField.php | NumberField.render | public function render()
{
$separators = $this->getSeparators();
$this->setValue(number_format($this->getValue(), $this->getDecimals(), $separators[0], $separators[1]));
return View::make('krafthaus/bauhaus::models.fields._number')
->with('field', $this);
} | php | public function render()
{
$separators = $this->getSeparators();
$this->setValue(number_format($this->getValue(), $this->getDecimals(), $separators[0], $separators[1]));
return View::make('krafthaus/bauhaus::models.fields._number')
->with('field', $this);
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"separators",
"=",
"$",
"this",
"->",
"getSeparators",
"(",
")",
";",
"$",
"this",
"->",
"setValue",
"(",
"number_format",
"(",
"$",
"this",
"->",
"getValue",
"(",
")",
",",
"$",
"this",
"->",
"getD... | Render the field.
@access public
@return mixed|string | [
"Render",
"the",
"field",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Field/NumberField.php#L95-L102 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Alnum.php | Zend_Validate_Alnum.isValid | public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
if ('' === $valueString) {
$this->_error(self::STRING_EMPTY);
return false;
}
if (null === self::$_filter) {
/**
* @see Zend_Filter_Alnum
*/
include_once 'Zend/Filter/Alnum.php';
self::$_filter = new Zend_Filter_Alnum();
}
self::$_filter->allowWhiteSpace = $this->allowWhiteSpace;
if ($valueString !== self::$_filter->filter($valueString)) {
$this->_error(self::NOT_ALNUM);
return false;
}
return true;
} | php | public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
if ('' === $valueString) {
$this->_error(self::STRING_EMPTY);
return false;
}
if (null === self::$_filter) {
/**
* @see Zend_Filter_Alnum
*/
include_once 'Zend/Filter/Alnum.php';
self::$_filter = new Zend_Filter_Alnum();
}
self::$_filter->allowWhiteSpace = $this->allowWhiteSpace;
if ($valueString !== self::$_filter->filter($valueString)) {
$this->_error(self::NOT_ALNUM);
return false;
}
return true;
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
")",
"{",
"$",
"valueString",
"=",
"(",
"string",
")",
"$",
"value",
";",
"$",
"this",
"->",
"_setValue",
"(",
"$",
"valueString",
")",
";",
"if",
"(",
"''",
"===",
"$",
"valueString",
")",
"{",
"... | Defined by Zend_Validate_Interface
Returns true if and only if $value contains only alphabetic and digit characters
@param string $value
@return boolean | [
"Defined",
"by",
"Zend_Validate_Interface"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Alnum.php#L91-L118 |
txj123/zilf | src/Zilf/Di/Container.php | Container.get | public function get(string $id, array $params = [])
{
if (empty($id)) {
throw new \Exception('参数 id 不能为空');
}
$this->_id = $id;
//别名
if ($this->hasAlias($this->_id)) {
$this->_definitions[$this->_id] = $this->_alias[$this->_id];
}
if ($this->has($this->_id)) {
$definition = $this->_definitions[$this->_id];
} else {
throw new \Exception('获取的' . $this->_id . '不存在');
}
$object = null;
if (!empty($params)) {
$definition['params'] = (array)$params;
}
$class = $definition['class'];
$params = empty($definition['params']) ? [] : $definition['params'];
$type = $definition['type'];
if ($type == self::TYPE_DEFINITION_CALLBACK) {
$object = call_user_func($class, $params);
} elseif ($type == self::TYPE_DEFINITION_OBJ) {
$object = $class;
} elseif ($type == self::TYPE_DEFINITION_STRING) {
if (!class_exists($class)) {
throw new \Exception('类:' . $class . '不存在!');
}
$object = $this->build($class, $params);
} else {
throw new \Exception('Unexpected object definition type: ' . gettype($class));
}
$this->_objects[$this->_id] = $object;
//清除变量 释放内存
unset($definition);
unset($class);
unset($params);
unset($type);
unset($id);
return $object;
} | php | public function get(string $id, array $params = [])
{
if (empty($id)) {
throw new \Exception('参数 id 不能为空');
}
$this->_id = $id;
//别名
if ($this->hasAlias($this->_id)) {
$this->_definitions[$this->_id] = $this->_alias[$this->_id];
}
if ($this->has($this->_id)) {
$definition = $this->_definitions[$this->_id];
} else {
throw new \Exception('获取的' . $this->_id . '不存在');
}
$object = null;
if (!empty($params)) {
$definition['params'] = (array)$params;
}
$class = $definition['class'];
$params = empty($definition['params']) ? [] : $definition['params'];
$type = $definition['type'];
if ($type == self::TYPE_DEFINITION_CALLBACK) {
$object = call_user_func($class, $params);
} elseif ($type == self::TYPE_DEFINITION_OBJ) {
$object = $class;
} elseif ($type == self::TYPE_DEFINITION_STRING) {
if (!class_exists($class)) {
throw new \Exception('类:' . $class . '不存在!');
}
$object = $this->build($class, $params);
} else {
throw new \Exception('Unexpected object definition type: ' . gettype($class));
}
$this->_objects[$this->_id] = $object;
//清除变量 释放内存
unset($definition);
unset($class);
unset($params);
unset($type);
unset($id);
return $object;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"id",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'参数 id 不能为空');",
"",
"",
"}",
"$",
"this",
... | 获取类的对象
@param $id
@param array $params
@return $this
@throws \Exception | [
"获取类的对象"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L57-L110 |
txj123/zilf | src/Zilf/Di/Container.php | Container.getShare | public function getShare(string $id, array $params = [])
{
if (isset($this->_objects[$id]) && !empty($this->_objects[$id])) {
return $this->_objects[$id];
} elseif (!isset($this->_definitions[$id])) {
throw new \Exception('You have requested a non-existent id: ' . $id);
} else {
if ($this->has($id)) {
$definition = $this->_definitions[$id];
} else {
throw new \Exception('获取的' . $id . '不存在');
}
$object = null;
if (!empty($params)) {
$definition['params'] = (array)$params;
}
if(is_string($definition)) {
$class = $definition;
$type = self::TYPE_DEFINITION_STRING;
}else{
$class = $definition['class'];
$params = empty($definition['params']) ? [] : $definition['params'];
$type = $definition['type'];
}
if ($type == self::TYPE_DEFINITION_CALLBACK) {
$object = call_user_func($class, $params);
} elseif ($type == self::TYPE_DEFINITION_OBJ) {
$object = $class;
} elseif ($type == self::TYPE_DEFINITION_STRING) {
if (!class_exists($class)) {
throw new \Exception('类:' . $class . '不存在!');
}
$object = $this->build($class, $params);
} else {
throw new \Exception('Unexpected object definition type: ' . gettype($class));
}
$this->_objects[$id] = $object;
return $object;
// return $this->get($id, $params);
}
} | php | public function getShare(string $id, array $params = [])
{
if (isset($this->_objects[$id]) && !empty($this->_objects[$id])) {
return $this->_objects[$id];
} elseif (!isset($this->_definitions[$id])) {
throw new \Exception('You have requested a non-existent id: ' . $id);
} else {
if ($this->has($id)) {
$definition = $this->_definitions[$id];
} else {
throw new \Exception('获取的' . $id . '不存在');
}
$object = null;
if (!empty($params)) {
$definition['params'] = (array)$params;
}
if(is_string($definition)) {
$class = $definition;
$type = self::TYPE_DEFINITION_STRING;
}else{
$class = $definition['class'];
$params = empty($definition['params']) ? [] : $definition['params'];
$type = $definition['type'];
}
if ($type == self::TYPE_DEFINITION_CALLBACK) {
$object = call_user_func($class, $params);
} elseif ($type == self::TYPE_DEFINITION_OBJ) {
$object = $class;
} elseif ($type == self::TYPE_DEFINITION_STRING) {
if (!class_exists($class)) {
throw new \Exception('类:' . $class . '不存在!');
}
$object = $this->build($class, $params);
} else {
throw new \Exception('Unexpected object definition type: ' . gettype($class));
}
$this->_objects[$id] = $object;
return $object;
// return $this->get($id, $params);
}
} | [
"public",
"function",
"getShare",
"(",
"string",
"$",
"id",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_objects",
"[",
"$",
"id",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"_ob... | 获取共享的对象,类仅仅实例化一次
@param $id
@param array $params
@return mixed|null
@throws \Exception | [
"获取共享的对象,类仅仅实例化一次"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L120-L166 |
txj123/zilf | src/Zilf/Di/Container.php | Container.register | public function register(string $id, $definition, $params = [])
{
$this->_id = $id;
//清除已经存在的对象信息
unset($this->_objects[$id]);
if (is_callable($definition)) { //
$class = array(
'class' => $definition,
'params' => [],
'type' => self::TYPE_DEFINITION_CALLBACK,
);
} elseif (is_object($definition)) { //是对象
$class = array(
'class' => $definition,
'params' => [],
'type' => self::TYPE_DEFINITION_OBJ,
);
} elseif (is_array($definition)) {
if (count($definition) != 2) {
throw new \Exception('注册的参数错误,只能输入controller和action方法');
}
$class = array(
'class' => $definition[0] ?? '',
'params' => $params,
'method' => $definition[1] ?? '',
'type' => self::TYPE_DEFINITION_STRING,
);
$this->setAlias($this->_id, $definition);
} else {
$class = array(
'class' => $definition,
'params' => $params,
'type' => self::TYPE_DEFINITION_STRING,
);
}
//定义类
$this->_alias[$id] = $class;
$this->_definitions[$this->_id] = $class;
unset($id);
unset($definition);
unset($class);
return $this;
} | php | public function register(string $id, $definition, $params = [])
{
$this->_id = $id;
//清除已经存在的对象信息
unset($this->_objects[$id]);
if (is_callable($definition)) { //
$class = array(
'class' => $definition,
'params' => [],
'type' => self::TYPE_DEFINITION_CALLBACK,
);
} elseif (is_object($definition)) { //是对象
$class = array(
'class' => $definition,
'params' => [],
'type' => self::TYPE_DEFINITION_OBJ,
);
} elseif (is_array($definition)) {
if (count($definition) != 2) {
throw new \Exception('注册的参数错误,只能输入controller和action方法');
}
$class = array(
'class' => $definition[0] ?? '',
'params' => $params,
'method' => $definition[1] ?? '',
'type' => self::TYPE_DEFINITION_STRING,
);
$this->setAlias($this->_id, $definition);
} else {
$class = array(
'class' => $definition,
'params' => $params,
'type' => self::TYPE_DEFINITION_STRING,
);
}
//定义类
$this->_alias[$id] = $class;
$this->_definitions[$this->_id] = $class;
unset($id);
unset($definition);
unset($class);
return $this;
} | [
"public",
"function",
"register",
"(",
"string",
"$",
"id",
",",
"$",
"definition",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"_id",
"=",
"$",
"id",
";",
"//清除已经存在的对象信息",
"unset",
"(",
"$",
"this",
"->",
"_objects",
"[",
"$",
... | 注册定义的类
指定该类对应的__construnct()参数,已经函数方法的参数
使用说明:
//curl不存在
register('curl','Zilf\Curl\Curl',parmas);//params 参数为构造函数的参数
register('curl',['Zilf\Curl\Curl','方法']',[ '__construct'=[] , 'other1'='11','other2'='22' ]);//params 参数为构造函数的参数
register('curl','Zilf\Curl\Curl@方法',[ '__construct'=[] , 'other1'='11','other2'='22' ]);//params 参数为构造函数的参数
//curl已经存在
register('curl',params) //params 参数为构造函数的参数
//回调函数
register('curl',new \Zilf\Curl\Curl());
//回调函数
register('curl',function(){
return new \Zilf\Curl\Curl();
});
@param string $id 为别名,或者类的对象字符串
@param string $definition 支持类的对象,类的对象字符串,回调函数
@param array $params 传递的参数,数组或者字符串,允许为空
@return $this
@throws \Exception | [
"注册定义的类",
"指定该类对应的__construnct",
"()",
"参数,已经函数方法的参数"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L196-L250 |
txj123/zilf | src/Zilf/Di/Container.php | Container.set | public function set(string $id, $definition, $params = [])
{
return $this->register($id, $definition, $params);
} | php | public function set(string $id, $definition, $params = [])
{
return $this->register($id, $definition, $params);
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"id",
",",
"$",
"definition",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"register",
"(",
"$",
"id",
",",
"$",
"definition",
",",
"$",
"params",
")",
";",
"}"
] | 函数register的别名
@param $id
@param $definition
@param array $params
@return $this | [
"函数register的别名"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L260-L263 |
txj123/zilf | src/Zilf/Di/Container.php | Container.setAlias | public function setAlias($aliasName, $definition = '')
{
if (is_array($aliasName) && !empty($aliasName)) {
foreach ($aliasName as $id => $item) {
$this->_alias[$id] = array(
'class' => $item,
'params' => '',
'type' => self::TYPE_DEFINITION_STRING,
);
$this->_definitions[$id] = $item;
}
} else {
$aliasName = strtolower($aliasName);
$this->_alias[$aliasName] = array(
'class' => $definition,
'params' => '',
'type' => self::TYPE_DEFINITION_STRING,
);
$this->_definitions[$aliasName] = $definition;
}
return $this;
} | php | public function setAlias($aliasName, $definition = '')
{
if (is_array($aliasName) && !empty($aliasName)) {
foreach ($aliasName as $id => $item) {
$this->_alias[$id] = array(
'class' => $item,
'params' => '',
'type' => self::TYPE_DEFINITION_STRING,
);
$this->_definitions[$id] = $item;
}
} else {
$aliasName = strtolower($aliasName);
$this->_alias[$aliasName] = array(
'class' => $definition,
'params' => '',
'type' => self::TYPE_DEFINITION_STRING,
);
$this->_definitions[$aliasName] = $definition;
}
return $this;
} | [
"public",
"function",
"setAlias",
"(",
"$",
"aliasName",
",",
"$",
"definition",
"=",
"''",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"aliasName",
")",
"&&",
"!",
"empty",
"(",
"$",
"aliasName",
")",
")",
"{",
"foreach",
"(",
"$",
"aliasName",
"as",... | 设置类的别名
@param string|array $aliasName
@param string $definition //回调函数
字符串
对象
@return $this | [
"设置类的别名"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L298-L326 |
txj123/zilf | src/Zilf/Di/Container.php | Container.getAlias | public function getAlias(string $aliasName)
{
$aliasName = strtolower($aliasName);
return isset($this->_alias[$aliasName]) ? $this->_alias[$aliasName] : '';
} | php | public function getAlias(string $aliasName)
{
$aliasName = strtolower($aliasName);
return isset($this->_alias[$aliasName]) ? $this->_alias[$aliasName] : '';
} | [
"public",
"function",
"getAlias",
"(",
"string",
"$",
"aliasName",
")",
"{",
"$",
"aliasName",
"=",
"strtolower",
"(",
"$",
"aliasName",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"_alias",
"[",
"$",
"aliasName",
"]",
")",
"?",
"$",
"this",
... | 获取别名的value值
@param $aliasName
@return mixed|string | [
"获取别名的value值"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L335-L339 |
txj123/zilf | src/Zilf/Di/Container.php | Container.renameAlias | public function renameAlias(string $aliasName, string $newAliasName)
{
$aliasName = strtolower($aliasName);
$newAliasName = strtolower($newAliasName);
if ($this->hasAlias($aliasName)) {
$this->_alias[$newAliasName] = $this->_alias[$aliasName];
unset($this->_alias[$aliasName]);
} else {
throw new \Exception('该别名' . $aliasName . '没有不存在');
}
return $this;
} | php | public function renameAlias(string $aliasName, string $newAliasName)
{
$aliasName = strtolower($aliasName);
$newAliasName = strtolower($newAliasName);
if ($this->hasAlias($aliasName)) {
$this->_alias[$newAliasName] = $this->_alias[$aliasName];
unset($this->_alias[$aliasName]);
} else {
throw new \Exception('该别名' . $aliasName . '没有不存在');
}
return $this;
} | [
"public",
"function",
"renameAlias",
"(",
"string",
"$",
"aliasName",
",",
"string",
"$",
"newAliasName",
")",
"{",
"$",
"aliasName",
"=",
"strtolower",
"(",
"$",
"aliasName",
")",
";",
"$",
"newAliasName",
"=",
"strtolower",
"(",
"$",
"newAliasName",
")",
... | 重新命名别名的名称
@param string $aliasName 原来的别名
@param string $newAliasName 新的别名
@return $this
@throws \Exception | [
"重新命名别名的名称"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L371-L383 |
txj123/zilf | src/Zilf/Di/Container.php | Container.build | public function build($definition, array $params = [])
{
/**
* @var $reflection (new \Reflection)
*/
list ($reflection, $dependencies, $props) = $this->getDependencies($definition);
$this->_reflections[$this->_id] = $reflection;
//根绝$dependencies的参数位置,赋值参数
//注意 参数的匹配以key相同为优先,其他怎按照索引排序
if (!empty($params)) {
$index = 0;
foreach ($dependencies as $key => $value) {
if (isset($params[$key])) {
$dependencies[$key] = $params[$key];
} elseif (!empty($dependencies[$key])) {
} elseif (isset($params[$index])) {
$dependencies[$key] = $params[$index];
$index++;
}
}
}
//判断是否可以初始化
if (!$reflection->isInstantiable()) {
throw new \Exception('Can not instantiate ' . $reflection->name);
}
$object = null === empty($dependencies) ? $reflection->newInstance() : $reflection->newInstanceArgs($dependencies);
//初始化对象的属性
if (!empty($props)) {
foreach ($props as $prop) {
$key = $prop->getName();
if (isset($params[$key]) && !empty($params[$key])) {
$object->$key = $params[$key];
}
}
}
return $object;
} | php | public function build($definition, array $params = [])
{
/**
* @var $reflection (new \Reflection)
*/
list ($reflection, $dependencies, $props) = $this->getDependencies($definition);
$this->_reflections[$this->_id] = $reflection;
//根绝$dependencies的参数位置,赋值参数
//注意 参数的匹配以key相同为优先,其他怎按照索引排序
if (!empty($params)) {
$index = 0;
foreach ($dependencies as $key => $value) {
if (isset($params[$key])) {
$dependencies[$key] = $params[$key];
} elseif (!empty($dependencies[$key])) {
} elseif (isset($params[$index])) {
$dependencies[$key] = $params[$index];
$index++;
}
}
}
//判断是否可以初始化
if (!$reflection->isInstantiable()) {
throw new \Exception('Can not instantiate ' . $reflection->name);
}
$object = null === empty($dependencies) ? $reflection->newInstance() : $reflection->newInstanceArgs($dependencies);
//初始化对象的属性
if (!empty($props)) {
foreach ($props as $prop) {
$key = $prop->getName();
if (isset($params[$key]) && !empty($params[$key])) {
$object->$key = $params[$key];
}
}
}
return $object;
} | [
"public",
"function",
"build",
"(",
"$",
"definition",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"/**\n * @var $reflection (new \\Reflection)\n */",
"list",
"(",
"$",
"reflection",
",",
"$",
"dependencies",
",",
"$",
"props",
")",
"="... | 根绝类的字符串,返回类的对象
@param string $definition 字符串
@param array $params 传递的参数
@return mixed
@throws \Exception | [
"根绝类的字符串,返回类的对象"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L408-L450 |
txj123/zilf | src/Zilf/Di/Container.php | Container.getDependencies | private function getDependencies($class)
{
if (isset($this->_reflections[$class])) {
return [$this->_reflections[$class], $this->_dependencies[$class], $this->_defaultProperties[$class]];
}
$dependencies = [];
$reflection = new \ReflectionClass($class);
//获取类的公共public属性
$props = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
//获取构造器的参数
$constructor = $reflection->getConstructor();
if ($constructor !== null) {
foreach ($constructor->getParameters() as $param) {
$name = $param->getName();
if ($param->isDefaultValueAvailable()) {
$dependencies[$name] = $param->getDefaultValue();
} else {
$dependencies[$name] = '';
}
}
}
$this->_reflections[$class] = $reflection;
$this->_dependencies[$class] = $dependencies;
$this->_defaultProperties[$class] = $props;
unset($reflection);
unset($defaultProperties);
unset($dependencies);
unset($constructor);
return [$this->_reflections[$class], $this->_dependencies[$class], $this->_defaultProperties[$class]];
} | php | private function getDependencies($class)
{
if (isset($this->_reflections[$class])) {
return [$this->_reflections[$class], $this->_dependencies[$class], $this->_defaultProperties[$class]];
}
$dependencies = [];
$reflection = new \ReflectionClass($class);
//获取类的公共public属性
$props = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
//获取构造器的参数
$constructor = $reflection->getConstructor();
if ($constructor !== null) {
foreach ($constructor->getParameters() as $param) {
$name = $param->getName();
if ($param->isDefaultValueAvailable()) {
$dependencies[$name] = $param->getDefaultValue();
} else {
$dependencies[$name] = '';
}
}
}
$this->_reflections[$class] = $reflection;
$this->_dependencies[$class] = $dependencies;
$this->_defaultProperties[$class] = $props;
unset($reflection);
unset($defaultProperties);
unset($dependencies);
unset($constructor);
return [$this->_reflections[$class], $this->_dependencies[$class], $this->_defaultProperties[$class]];
} | [
"private",
"function",
"getDependencies",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_reflections",
"[",
"$",
"class",
"]",
")",
")",
"{",
"return",
"[",
"$",
"this",
"->",
"_reflections",
"[",
"$",
"class",
"]",
",",
... | 获取类的构造函数的参数,以及reflections对象
@param $class
@return array
@throws \ReflectionException | [
"获取类的构造函数的参数,以及reflections对象"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L460-L495 |
txj123/zilf | src/Zilf/Di/Container.php | Container.offsetSet | public function offsetSet($id, $value)
{
if (is_array($value)) {
$param1 = isset($value[0]) ? $value[0] : '';
$param2 = isset($value[1]) ? $value[1] : '';
$this->set($id, $param1, $param2);
} else {
$this->set($id, $value);
}
} | php | public function offsetSet($id, $value)
{
if (is_array($value)) {
$param1 = isset($value[0]) ? $value[0] : '';
$param2 = isset($value[1]) ? $value[1] : '';
$this->set($id, $param1, $param2);
} else {
$this->set($id, $value);
}
} | [
"public",
"function",
"offsetSet",
"(",
"$",
"id",
",",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"param1",
"=",
"isset",
"(",
"$",
"value",
"[",
"0",
"]",
")",
"?",
"$",
"value",
"[",
"0",
"]",
":"... | Offset to set
@param string $id
@param mixed $value | [
"Offset",
"to",
"set"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Di/Container.php#L535-L544 |
txj123/zilf | src/Zilf/Queue/Failed/DatabaseFailedJobProvider.php | DatabaseFailedJobProvider.log | public function log($connection, $queue, $payload, $exception)
{
$failed_at = Carbon::now();
$exception = (string)$exception;
return $this->resolver->createCommand()->insert(
$this->table, compact(
'connection', 'queue', 'payload', 'exception', 'failed_at'
)
)->execute();
} | php | public function log($connection, $queue, $payload, $exception)
{
$failed_at = Carbon::now();
$exception = (string)$exception;
return $this->resolver->createCommand()->insert(
$this->table, compact(
'connection', 'queue', 'payload', 'exception', 'failed_at'
)
)->execute();
} | [
"public",
"function",
"log",
"(",
"$",
"connection",
",",
"$",
"queue",
",",
"$",
"payload",
",",
"$",
"exception",
")",
"{",
"$",
"failed_at",
"=",
"Carbon",
"::",
"now",
"(",
")",
";",
"$",
"exception",
"=",
"(",
"string",
")",
"$",
"exception",
... | Log a failed job into storage.
@param string $connection
@param string $queue
@param string $payload
@param \Exception $exception
@return int|null | [
"Log",
"a",
"failed",
"job",
"into",
"storage",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Failed/DatabaseFailedJobProvider.php#L56-L67 |
txj123/zilf | src/Zilf/Queue/Failed/DatabaseFailedJobProvider.php | DatabaseFailedJobProvider.forget | public function forget($id)
{
return $this->resolver->createCommand()->delete($this->table, ['id' => $id])->execute();
} | php | public function forget($id)
{
return $this->resolver->createCommand()->delete($this->table, ['id' => $id])->execute();
} | [
"public",
"function",
"forget",
"(",
"$",
"id",
")",
"{",
"return",
"$",
"this",
"->",
"resolver",
"->",
"createCommand",
"(",
")",
"->",
"delete",
"(",
"$",
"this",
"->",
"table",
",",
"[",
"'id'",
"=>",
"$",
"id",
"]",
")",
"->",
"execute",
"(",
... | Delete a single failed job from storage.
@param mixed $id
@return bool | [
"Delete",
"a",
"single",
"failed",
"job",
"from",
"storage",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Failed/DatabaseFailedJobProvider.php#L96-L99 |
railken/search-query | src/Languages/BoomTree/Resolvers/InResolver.php | InResolver.resolveNextNode | public function resolveNextNode(NodeContract $node, NodeContract $new_node)
{
if ($new_node->next() && ($new_node->next() instanceof Nodes\GroupNode)) {
$values = $new_node->next()->valueToString();
$new_node->next()->removeAllChildren();
foreach (explode(',', $values) as $value) {
$vn = new Nodes\ValueNode();
$vn->setValue($value);
$new_node->next()->addChild($vn);
}
$new_node->moveNodeAsChild($new_node->next());
} else {
throw new Exceptions\QuerySyntaxException($node->getRoot()->getValue());
}
} | php | public function resolveNextNode(NodeContract $node, NodeContract $new_node)
{
if ($new_node->next() && ($new_node->next() instanceof Nodes\GroupNode)) {
$values = $new_node->next()->valueToString();
$new_node->next()->removeAllChildren();
foreach (explode(',', $values) as $value) {
$vn = new Nodes\ValueNode();
$vn->setValue($value);
$new_node->next()->addChild($vn);
}
$new_node->moveNodeAsChild($new_node->next());
} else {
throw new Exceptions\QuerySyntaxException($node->getRoot()->getValue());
}
} | [
"public",
"function",
"resolveNextNode",
"(",
"NodeContract",
"$",
"node",
",",
"NodeContract",
"$",
"new_node",
")",
"{",
"if",
"(",
"$",
"new_node",
"->",
"next",
"(",
")",
"&&",
"(",
"$",
"new_node",
"->",
"next",
"(",
")",
"instanceof",
"Nodes",
"\\"... | Resolve previous node match.
@param NodeContract $node
@param NodeContract $new_node | [
"Resolve",
"previous",
"node",
"match",
"."
] | train | https://github.com/railken/search-query/blob/06e1bfb3eb59347afec9ca764d6f8c3b691d6889/src/Languages/BoomTree/Resolvers/InResolver.php#L34-L52 |
crysalead/sql-dialect | src/Statement.php | Statement.dialect | public function dialect($dialect = null)
{
if ($dialect !== null) {
$this->_dialect = $dialect;
return $this;
}
if (!$this->_dialect) {
throw new SqlException('Missing SQL dialect adapter.');
}
return $this->_dialect;
} | php | public function dialect($dialect = null)
{
if ($dialect !== null) {
$this->_dialect = $dialect;
return $this;
}
if (!$this->_dialect) {
throw new SqlException('Missing SQL dialect adapter.');
}
return $this->_dialect;
} | [
"public",
"function",
"dialect",
"(",
"$",
"dialect",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"dialect",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"_dialect",
"=",
"$",
"dialect",
";",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"!",
"$",
"this"... | Gets/sets the dialect instance
@param object $dialect The dialect instance to set or none the get the setted one.
@return object The dialect instance or `$this` on set. | [
"Gets",
"/",
"sets",
"the",
"dialect",
"instance"
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement.php#L42-L52 |
crysalead/sql-dialect | src/Statement.php | Statement.data | public function data($name, $value = null)
{
if (func_num_args() === 2) {
return $this->_parts[$name] = $value;
}
return isset($this->_parts[$name]) ? $this->_parts[$name] : null;
} | php | public function data($name, $value = null)
{
if (func_num_args() === 2) {
return $this->_parts[$name] = $value;
}
return isset($this->_parts[$name]) ? $this->_parts[$name] : null;
} | [
"public",
"function",
"data",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"func_num_args",
"(",
")",
"===",
"2",
")",
"{",
"return",
"$",
"this",
"->",
"_parts",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"re... | Gets/sets data to the statement.
@param string $name The name of the value to set/get.
@param mixed $value The value to set.
@return mixed The setted value. | [
"Gets",
"/",
"sets",
"data",
"to",
"the",
"statement",
"."
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement.php#L61-L67 |
oxygen-cms/core | src/Form/Type/RelationshipType.php | RelationshipType.transformInput | public function transformInput(FieldMetadata $metadata, $value) {
$repo = $metadata->options['repository'];
$repo = is_callable($repo) ? $repo() : $repo;
return $repo->getReference((int)$value);
} | php | public function transformInput(FieldMetadata $metadata, $value) {
$repo = $metadata->options['repository'];
$repo = is_callable($repo) ? $repo() : $repo;
return $repo->getReference((int)$value);
} | [
"public",
"function",
"transformInput",
"(",
"FieldMetadata",
"$",
"metadata",
",",
"$",
"value",
")",
"{",
"$",
"repo",
"=",
"$",
"metadata",
"->",
"options",
"[",
"'repository'",
"]",
";",
"$",
"repo",
"=",
"is_callable",
"(",
"$",
"repo",
")",
"?",
... | Takes the given input value and transforms it into a compatible value for storage.
@param FieldMetadata $metadata
@param string $value
@return mixed | [
"Takes",
"the",
"given",
"input",
"value",
"and",
"transforms",
"it",
"into",
"a",
"compatible",
"value",
"for",
"storage",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Form/Type/RelationshipType.php#L16-L22 |
txj123/zilf | src/Zilf/Queue/Connectors/BeanstalkdConnector.php | BeanstalkdConnector.pheanstalk | protected function pheanstalk(array $config)
{
return new Pheanstalk(
$config['host'],
$config['port'] ?? PheanstalkInterface::DEFAULT_PORT,
$config['timeout'] ?? Connection::DEFAULT_CONNECT_TIMEOUT,
$config['persistent'] ?? false
);
} | php | protected function pheanstalk(array $config)
{
return new Pheanstalk(
$config['host'],
$config['port'] ?? PheanstalkInterface::DEFAULT_PORT,
$config['timeout'] ?? Connection::DEFAULT_CONNECT_TIMEOUT,
$config['persistent'] ?? false
);
} | [
"protected",
"function",
"pheanstalk",
"(",
"array",
"$",
"config",
")",
"{",
"return",
"new",
"Pheanstalk",
"(",
"$",
"config",
"[",
"'host'",
"]",
",",
"$",
"config",
"[",
"'port'",
"]",
"??",
"PheanstalkInterface",
"::",
"DEFAULT_PORT",
",",
"$",
"confi... | Create a Pheanstalk instance.
@param array $config
@return \Pheanstalk\Pheanstalk | [
"Create",
"a",
"Pheanstalk",
"instance",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Connectors/BeanstalkdConnector.php#L31-L39 |
txj123/zilf | src/Zilf/System/Bootstrap/LoadEnvironmentVariables.php | LoadEnvironmentVariables.bootstrap | public function bootstrap()
{
$app = Zilf::$app;
$this->checkForSpecificEnvironmentFile($app);
try {
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
} catch (InvalidPathException $e) {
//
} catch (InvalidFileException $e) {
die('The environment file is invalid: ' . $e->getMessage());
}
} | php | public function bootstrap()
{
$app = Zilf::$app;
$this->checkForSpecificEnvironmentFile($app);
try {
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
} catch (InvalidPathException $e) {
//
} catch (InvalidFileException $e) {
die('The environment file is invalid: ' . $e->getMessage());
}
} | [
"public",
"function",
"bootstrap",
"(",
")",
"{",
"$",
"app",
"=",
"Zilf",
"::",
"$",
"app",
";",
"$",
"this",
"->",
"checkForSpecificEnvironmentFile",
"(",
"$",
"app",
")",
";",
"try",
"{",
"(",
"new",
"Dotenv",
"(",
"$",
"app",
"->",
"environmentPath... | Bootstrap the given application.
@return void | [
"Bootstrap",
"the",
"given",
"application",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Bootstrap/LoadEnvironmentVariables.php#L18-L30 |
txj123/zilf | src/Zilf/Queue/BeanstalkdQueue.php | BeanstalkdQueue.pop | public function pop($queue = null)
{
$queue = $this->getQueue($queue);
$job = $this->pheanstalk->watchOnly($queue)->reserve(0);
if ($job instanceof PheanstalkJob) {
return new BeanstalkdJob(
$this->container, $this->pheanstalk, $job, $this->connectionName, $queue
);
}
} | php | public function pop($queue = null)
{
$queue = $this->getQueue($queue);
$job = $this->pheanstalk->watchOnly($queue)->reserve(0);
if ($job instanceof PheanstalkJob) {
return new BeanstalkdJob(
$this->container, $this->pheanstalk, $job, $this->connectionName, $queue
);
}
} | [
"public",
"function",
"pop",
"(",
"$",
"queue",
"=",
"null",
")",
"{",
"$",
"queue",
"=",
"$",
"this",
"->",
"getQueue",
"(",
"$",
"queue",
")",
";",
"$",
"job",
"=",
"$",
"this",
"->",
"pheanstalk",
"->",
"watchOnly",
"(",
"$",
"queue",
")",
"->... | Pop the next job off of the queue.
@param string $queue
@return \Illuminate\Contracts\Queue\Job|null | [
"Pop",
"the",
"next",
"job",
"off",
"of",
"the",
"queue",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/BeanstalkdQueue.php#L116-L127 |
awurth/SlimHelpers | Command/RoutesCommand.php | RoutesCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$markdown = $input->getOption('markdown');
if ($markdown) {
$this->markdown($input, $output);
} else {
$this->text($input, $output);
}
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$markdown = $input->getOption('markdown');
if ($markdown) {
$this->markdown($input, $output);
} else {
$this->text($input, $output);
}
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"markdown",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'markdown'",
")",
";",
"if",
"(",
"$",
"markdown",
")",
"{",
"$",
"this... | {@inheritdoc} | [
"{"
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Command/RoutesCommand.php#L55-L66 |
awurth/SlimHelpers | Command/RoutesCommand.php | RoutesCommand.text | public function text(InputInterface $input, OutputInterface $output)
{
foreach ($this->router->getRoutes() as $route) {
if (!empty($route->getName())) {
$output->writeln('<fg=cyan;options=bold>'.$route->getName().'</>');
$output->writeln(' '.implode(', ', $route->getMethods()));
$output->writeln(' '.$route->getPattern());
if (is_string($route->getCallable())) {
$output->writeln(' '.$route->getCallable());
}
$output->writeln('');
}
}
} | php | public function text(InputInterface $input, OutputInterface $output)
{
foreach ($this->router->getRoutes() as $route) {
if (!empty($route->getName())) {
$output->writeln('<fg=cyan;options=bold>'.$route->getName().'</>');
$output->writeln(' '.implode(', ', $route->getMethods()));
$output->writeln(' '.$route->getPattern());
if (is_string($route->getCallable())) {
$output->writeln(' '.$route->getCallable());
}
$output->writeln('');
}
}
} | [
"public",
"function",
"text",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"router",
"->",
"getRoutes",
"(",
")",
"as",
"$",
"route",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
... | Displays routes in plain text.
@param InputInterface $input
@param OutputInterface $output | [
"Displays",
"routes",
"in",
"plain",
"text",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Command/RoutesCommand.php#L74-L88 |
awurth/SlimHelpers | Command/RoutesCommand.php | RoutesCommand.markdown | public function markdown(InputInterface $input, OutputInterface $output)
{
$output->writeln('# Routes');
$output->writeln('');
$url = rtrim($this->options['url'], '/');
foreach ($this->router->getRoutes() as $route) {
$output->writeln(sprintf('### `%s` [%s](%s)',
implode(', ', $route->getMethods()),
$route->getPattern(),
$url.$route->getPattern()
));
if (is_string($route->getCallable())) {
$output->writeln('##### '.$route->getCallable());
}
if (!empty($route->getName())) {
$output->writeln('###### '.$route->getName());
}
$output->writeln('');
}
} | php | public function markdown(InputInterface $input, OutputInterface $output)
{
$output->writeln('# Routes');
$output->writeln('');
$url = rtrim($this->options['url'], '/');
foreach ($this->router->getRoutes() as $route) {
$output->writeln(sprintf('### `%s` [%s](%s)',
implode(', ', $route->getMethods()),
$route->getPattern(),
$url.$route->getPattern()
));
if (is_string($route->getCallable())) {
$output->writeln('##### '.$route->getCallable());
}
if (!empty($route->getName())) {
$output->writeln('###### '.$route->getName());
}
$output->writeln('');
}
} | [
"public",
"function",
"markdown",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'# Routes'",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"$",
"url",
"=",
"... | Displays routes in markdown format.
@param InputInterface $input
@param OutputInterface $output | [
"Displays",
"routes",
"in",
"markdown",
"format",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Command/RoutesCommand.php#L96-L118 |
dave-redfern/laravel-doctrine-tenancy | src/Console/TenantRouteListCommand.php | TenantRouteListCommand.fire | public function fire()
{
$this->resolveTenantRoutes($this->argument('domain'));
if (count($this->routes) == 0) {
return $this->error("The specified tenant does not have any routes.");
}
$this->displayRoutes($this->getRoutes());
} | php | public function fire()
{
$this->resolveTenantRoutes($this->argument('domain'));
if (count($this->routes) == 0) {
return $this->error("The specified tenant does not have any routes.");
}
$this->displayRoutes($this->getRoutes());
} | [
"public",
"function",
"fire",
"(",
")",
"{",
"$",
"this",
"->",
"resolveTenantRoutes",
"(",
"$",
"this",
"->",
"argument",
"(",
"'domain'",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"routes",
")",
"==",
"0",
")",
"{",
"return",
"$"... | Execute the console command.
@return void | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Console/TenantRouteListCommand.php#L76-L85 |
dave-redfern/laravel-doctrine-tenancy | src/Console/TenantRouteListCommand.php | TenantRouteListCommand.getMiddleware | protected function getMiddleware($route)
{
return collect($route->gatherMiddleware())->map(function ($middleware) {
return $middleware instanceof \Closure ? 'Closure' : $middleware;
})->implode(',');
} | php | protected function getMiddleware($route)
{
return collect($route->gatherMiddleware())->map(function ($middleware) {
return $middleware instanceof \Closure ? 'Closure' : $middleware;
})->implode(',');
} | [
"protected",
"function",
"getMiddleware",
"(",
"$",
"route",
")",
"{",
"return",
"collect",
"(",
"$",
"route",
"->",
"gatherMiddleware",
"(",
")",
")",
"->",
"map",
"(",
"function",
"(",
"$",
"middleware",
")",
"{",
"return",
"$",
"middleware",
"instanceof... | Get before filters.
@param \Illuminate\Routing\Route $route
@return string | [
"Get",
"before",
"filters",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Console/TenantRouteListCommand.php#L162-L167 |
dave-redfern/laravel-doctrine-tenancy | src/Console/TenantRouteListCommand.php | TenantRouteListCommand.filterRoute | protected function filterRoute(array $route)
{
if (
($this->option('name') && !Str::contains($route['name'], $this->option('name'))) ||
$this->option('path') && !Str::contains($route['uri'], $this->option('path')) ||
$this->option('method') && !Str::contains($route['method'], $this->option('method'))
) {
return;
}
return $route;
} | php | protected function filterRoute(array $route)
{
if (
($this->option('name') && !Str::contains($route['name'], $this->option('name'))) ||
$this->option('path') && !Str::contains($route['uri'], $this->option('path')) ||
$this->option('method') && !Str::contains($route['method'], $this->option('method'))
) {
return;
}
return $route;
} | [
"protected",
"function",
"filterRoute",
"(",
"array",
"$",
"route",
")",
"{",
"if",
"(",
"(",
"$",
"this",
"->",
"option",
"(",
"'name'",
")",
"&&",
"!",
"Str",
"::",
"contains",
"(",
"$",
"route",
"[",
"'name'",
"]",
",",
"$",
"this",
"->",
"optio... | Filter the route by URI and / or name.
@param array $route
@return array|null | [
"Filter",
"the",
"route",
"by",
"URI",
"and",
"/",
"or",
"name",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Console/TenantRouteListCommand.php#L176-L187 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php | NativeSessionStorage.save | public function save()
{
// Register custom error handler to catch a possible failure warning during session write
set_error_handler(
function ($errno, $errstr, $errfile, $errline, $errcontext) {
throw new ContextErrorException($errstr, $errno, E_WARNING, $errfile, $errline, $errcontext);
}, E_WARNING
);
try {
session_write_close();
restore_error_handler();
} catch (ContextErrorException $e) {
// The default PHP error message is not very helpful, as it does not give any information on the current save handler.
// Therefore, we catch this error and trigger a warning with a better error message
$handler = $this->getSaveHandler();
if ($handler instanceof SessionHandlerProxy) {
$handler = $handler->getHandler();
}
restore_error_handler();
trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', get_class($handler)), E_USER_WARNING);
}
$this->closed = true;
$this->started = false;
} | php | public function save()
{
// Register custom error handler to catch a possible failure warning during session write
set_error_handler(
function ($errno, $errstr, $errfile, $errline, $errcontext) {
throw new ContextErrorException($errstr, $errno, E_WARNING, $errfile, $errline, $errcontext);
}, E_WARNING
);
try {
session_write_close();
restore_error_handler();
} catch (ContextErrorException $e) {
// The default PHP error message is not very helpful, as it does not give any information on the current save handler.
// Therefore, we catch this error and trigger a warning with a better error message
$handler = $this->getSaveHandler();
if ($handler instanceof SessionHandlerProxy) {
$handler = $handler->getHandler();
}
restore_error_handler();
trigger_error(sprintf('session_write_close(): Failed to write session data with %s handler', get_class($handler)), E_USER_WARNING);
}
$this->closed = true;
$this->started = false;
} | [
"public",
"function",
"save",
"(",
")",
"{",
"// Register custom error handler to catch a possible failure warning during session write",
"set_error_handler",
"(",
"function",
"(",
"$",
"errno",
",",
"$",
"errstr",
",",
"$",
"errfile",
",",
"$",
"errline",
",",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php#L211-L237 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php | NativeSessionStorage.getBag | public function getBag($name)
{
if (!isset($this->bags[$name])) {
throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
}
if ($this->saveHandler->isActive() && !$this->started) {
$this->loadSession();
} elseif (!$this->started) {
$this->start();
}
return $this->bags[$name];
} | php | public function getBag($name)
{
if (!isset($this->bags[$name])) {
throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
}
if ($this->saveHandler->isActive() && !$this->started) {
$this->loadSession();
} elseif (!$this->started) {
$this->start();
}
return $this->bags[$name];
} | [
"public",
"function",
"getBag",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"bags",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The SessionBagInterface %s... | {@inheritdoc} | [
"{"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php#L271-L284 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php | NativeSessionStorage.setOptions | public function setOptions(array $options)
{
$validOptions = array_flip(
array(
'cache_limiter', 'cookie_domain', 'cookie_httponly',
'cookie_lifetime', 'cookie_path', 'cookie_secure',
'entropy_file', 'entropy_length', 'gc_divisor',
'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character',
'hash_function', 'name', 'referer_check',
'serialize_handler', 'use_strict_mode', 'use_cookies',
'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags',
)
);
foreach ($options as $key => $value) {
if (isset($validOptions[$key])) {
ini_set('session.'.$key, $value);
}
}
} | php | public function setOptions(array $options)
{
$validOptions = array_flip(
array(
'cache_limiter', 'cookie_domain', 'cookie_httponly',
'cookie_lifetime', 'cookie_path', 'cookie_secure',
'entropy_file', 'entropy_length', 'gc_divisor',
'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character',
'hash_function', 'name', 'referer_check',
'serialize_handler', 'use_strict_mode', 'use_cookies',
'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags',
)
);
foreach ($options as $key => $value) {
if (isset($validOptions[$key])) {
ini_set('session.'.$key, $value);
}
}
} | [
"public",
"function",
"setOptions",
"(",
"array",
"$",
"options",
")",
"{",
"$",
"validOptions",
"=",
"array_flip",
"(",
"array",
"(",
"'cache_limiter'",
",",
"'cookie_domain'",
",",
"'cookie_httponly'",
",",
"'cookie_lifetime'",
",",
"'cookie_path'",
",",
"'cooki... | Sets session.* ini variables.
For convenience we omit 'session.' from the beginning of the keys.
Explicitly ignores other ini keys.
@param array $options Session ini directives array(key => value)
@see http://php.net/session.configuration | [
"Sets",
"session",
".",
"*",
"ini",
"variables",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php#L328-L349 |
txj123/zilf | src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php | NativeSessionStorage.setSaveHandler | public function setSaveHandler($saveHandler = null)
{
if (!$saveHandler instanceof AbstractProxy
&& !$saveHandler instanceof NativeSessionHandler
&& !$saveHandler instanceof \SessionHandlerInterface
&& null !== $saveHandler
) {
throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.');
}
// Wrap $saveHandler in proxy and prevent double wrapping of proxy
if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
$saveHandler = new SessionHandlerProxy($saveHandler);
} elseif (!$saveHandler instanceof AbstractProxy) {
$saveHandler = new SessionHandlerProxy(new \SessionHandler());
}
$this->saveHandler = $saveHandler;
if ($this->saveHandler instanceof \SessionHandlerInterface) {
session_set_save_handler($this->saveHandler, false);
}
} | php | public function setSaveHandler($saveHandler = null)
{
if (!$saveHandler instanceof AbstractProxy
&& !$saveHandler instanceof NativeSessionHandler
&& !$saveHandler instanceof \SessionHandlerInterface
&& null !== $saveHandler
) {
throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.');
}
// Wrap $saveHandler in proxy and prevent double wrapping of proxy
if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
$saveHandler = new SessionHandlerProxy($saveHandler);
} elseif (!$saveHandler instanceof AbstractProxy) {
$saveHandler = new SessionHandlerProxy(new \SessionHandler());
}
$this->saveHandler = $saveHandler;
if ($this->saveHandler instanceof \SessionHandlerInterface) {
session_set_save_handler($this->saveHandler, false);
}
} | [
"public",
"function",
"setSaveHandler",
"(",
"$",
"saveHandler",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"saveHandler",
"instanceof",
"AbstractProxy",
"&&",
"!",
"$",
"saveHandler",
"instanceof",
"NativeSessionHandler",
"&&",
"!",
"$",
"saveHandler",
"instan... | Registers session save handler as a PHP session handler.
To use internal PHP session save handlers, override this method using ini_set with
session.save_handler and session.save_path e.g.
ini_set('session.save_handler', 'files');
ini_set('session.save_path', '/tmp');
or pass in a NativeSessionHandler instance which configures session.save_handler in the
constructor, for a template see NativeFileSessionHandler or use handlers in
composer package drak/native-session
@see http://php.net/session-set-save-handler
@see http://php.net/sessionhandlerinterface
@see http://php.net/sessionhandler
@see http://github.com/drak/NativeSession
@param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $saveHandler
@throws \InvalidArgumentException | [
"Registers",
"session",
"save",
"handler",
"as",
"a",
"PHP",
"session",
"handler",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/HttpFoundation/Session/Storage/NativeSessionStorage.php#L373-L394 |
krafthaus/bauhaus | src/commands/ViewsGenerateCommand.php | ViewsGenerateCommand.fire | public function fire()
{
$view = $this->option('view');
$model = $this->option('model');
$path = app_path(sprintf('views/bauhaus/%s', $model));
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$stub = file_get_contents(__DIR__ . sprintf('/stubs/views/%s.txt', $view));
$stub = str_replace('$NAME$', $model, $stub);
file_put_contents(sprintf('%s/%s.blade.php', $path, $view), $stub);
$this->info(sprintf('Views generated in %s`', $path));
} | php | public function fire()
{
$view = $this->option('view');
$model = $this->option('model');
$path = app_path(sprintf('views/bauhaus/%s', $model));
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$stub = file_get_contents(__DIR__ . sprintf('/stubs/views/%s.txt', $view));
$stub = str_replace('$NAME$', $model, $stub);
file_put_contents(sprintf('%s/%s.blade.php', $path, $view), $stub);
$this->info(sprintf('Views generated in %s`', $path));
} | [
"public",
"function",
"fire",
"(",
")",
"{",
"$",
"view",
"=",
"$",
"this",
"->",
"option",
"(",
"'view'",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"option",
"(",
"'model'",
")",
";",
"$",
"path",
"=",
"app_path",
"(",
"sprintf",
"(",
"'vi... | Execute the console command.
@access public
@return mixed | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/commands/ViewsGenerateCommand.php#L43-L58 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Float.php | Zend_Validate_Float.isValid | public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
$locale = localeconv();
$valueFiltered = str_replace($locale['thousands_sep'], '', $valueString);
$valueFiltered = str_replace($locale['decimal_point'], '.', $valueFiltered);
if (strval(floatval($valueFiltered)) != $valueFiltered) {
$this->_error();
return false;
}
return true;
} | php | public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
$locale = localeconv();
$valueFiltered = str_replace($locale['thousands_sep'], '', $valueString);
$valueFiltered = str_replace($locale['decimal_point'], '.', $valueFiltered);
if (strval(floatval($valueFiltered)) != $valueFiltered) {
$this->_error();
return false;
}
return true;
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
")",
"{",
"$",
"valueString",
"=",
"(",
"string",
")",
"$",
"value",
";",
"$",
"this",
"->",
"_setValue",
"(",
"$",
"valueString",
")",
";",
"$",
"locale",
"=",
"localeconv",
"(",
")",
";",
"$",
"... | Defined by Zend_Validate_Interface
Returns true if and only if $value is a floating-point value
@param string $value
@return boolean | [
"Defined",
"by",
"Zend_Validate_Interface"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/Float.php#L56-L73 |
phpmath/bignumber | src/Utils.php | Utils.convertToBase10 | public static function convertToBase10($number, $fromBase)
{
$number = (string)ceil(static::getPlainNumber($number));
if ($fromBase == 10) {
return $number;
} elseif ($fromBase < 2 || $fromBase > 32) {
throw new InvalidArgumentException(sprintf(
'Base %d is unsupported, should be between 2 and 32.',
$fromBase
));
}
$result = '0';
$chars = self::BASE32_ALPHABET;
for ($i = 0, $len = strlen($number); $i < $len; $i++) {
$index = strpos($chars, $number[$i]);
if ($index >= $fromBase) {
throw new RuntimeException(sprintf(
'The digit %s in the number %s is an invalid digit for base-%s.',
$chars[$index],
$number,
$fromBase
));
}
$result = bcmul($result, $fromBase);
$result = bcadd($result, strpos($chars, $number[$i]));
}
return $result;
} | php | public static function convertToBase10($number, $fromBase)
{
$number = (string)ceil(static::getPlainNumber($number));
if ($fromBase == 10) {
return $number;
} elseif ($fromBase < 2 || $fromBase > 32) {
throw new InvalidArgumentException(sprintf(
'Base %d is unsupported, should be between 2 and 32.',
$fromBase
));
}
$result = '0';
$chars = self::BASE32_ALPHABET;
for ($i = 0, $len = strlen($number); $i < $len; $i++) {
$index = strpos($chars, $number[$i]);
if ($index >= $fromBase) {
throw new RuntimeException(sprintf(
'The digit %s in the number %s is an invalid digit for base-%s.',
$chars[$index],
$number,
$fromBase
));
}
$result = bcmul($result, $fromBase);
$result = bcadd($result, strpos($chars, $number[$i]));
}
return $result;
} | [
"public",
"static",
"function",
"convertToBase10",
"(",
"$",
"number",
",",
"$",
"fromBase",
")",
"{",
"$",
"number",
"=",
"(",
"string",
")",
"ceil",
"(",
"static",
"::",
"getPlainNumber",
"(",
"$",
"number",
")",
")",
";",
"if",
"(",
"$",
"fromBase",... | Converts the provided number from an arbitrary base to to a base 10 number.
@param string|int|BigNumber $number The number to convert.
@param int $fromBase The base to convert the number from.
@return string
@throws InvalidArgumentException Thrown when the base is out of reach. | [
"Converts",
"the",
"provided",
"number",
"from",
"an",
"arbitrary",
"base",
"to",
"to",
"a",
"base",
"10",
"number",
"."
] | train | https://github.com/phpmath/bignumber/blob/9d8343a535a66e1e61362abf71ca26133222fe9a/src/Utils.php#L45-L78 |
phpmath/bignumber | src/Utils.php | Utils.convertBase | public static function convertBase($number, $fromBase, $toBase)
{
$number = static::getPlainNumber($number);
if ($fromBase == $toBase) {
return $number;
}
if ($fromBase < 2 || $fromBase > 32) {
throw new InvalidArgumentException(sprintf(
'Base %d is unsupported, should be between 2 and 32.',
$fromBase
));
}
if ($toBase < 2 || $toBase > 32) {
throw new InvalidArgumentException(sprintf(
'Base %d is unsupported, should be between 2 and 32.',
$toBase
));
}
// Save the sign and trim it off so we can easier calculate the number:
$sign = (strpos($number, '-') === 0) ? '-' : '';
$number = ltrim($number, '-+');
// First we convert the number to a decimal value:
$decimal = static::convertToBase10($number, $fromBase);
if ($toBase == 10) {
return $decimal;
}
// Next we convert to the correct base:
$result = '';
$chars = self::BASE32_ALPHABET;
do {
$remainder = bcmod($decimal, $toBase);
$decimal = bcdiv($decimal, $toBase);
$result = $chars[$remainder] . $result;
} while (bccomp($decimal, '0'));
return $sign . ltrim($result, '0');
} | php | public static function convertBase($number, $fromBase, $toBase)
{
$number = static::getPlainNumber($number);
if ($fromBase == $toBase) {
return $number;
}
if ($fromBase < 2 || $fromBase > 32) {
throw new InvalidArgumentException(sprintf(
'Base %d is unsupported, should be between 2 and 32.',
$fromBase
));
}
if ($toBase < 2 || $toBase > 32) {
throw new InvalidArgumentException(sprintf(
'Base %d is unsupported, should be between 2 and 32.',
$toBase
));
}
// Save the sign and trim it off so we can easier calculate the number:
$sign = (strpos($number, '-') === 0) ? '-' : '';
$number = ltrim($number, '-+');
// First we convert the number to a decimal value:
$decimal = static::convertToBase10($number, $fromBase);
if ($toBase == 10) {
return $decimal;
}
// Next we convert to the correct base:
$result = '';
$chars = self::BASE32_ALPHABET;
do {
$remainder = bcmod($decimal, $toBase);
$decimal = bcdiv($decimal, $toBase);
$result = $chars[$remainder] . $result;
} while (bccomp($decimal, '0'));
return $sign . ltrim($result, '0');
} | [
"public",
"static",
"function",
"convertBase",
"(",
"$",
"number",
",",
"$",
"fromBase",
",",
"$",
"toBase",
")",
"{",
"$",
"number",
"=",
"static",
"::",
"getPlainNumber",
"(",
"$",
"number",
")",
";",
"if",
"(",
"$",
"fromBase",
"==",
"$",
"toBase",
... | Converts the provided number from an arbitrary base to another arbitrary base (from 2 to 36).
@param string|int|BigNumber $number The number to convert.
@param int $fromBase The base to convert the number from.
@param int $toBase The base to convert the number to.
@return string
@throws InvalidArgumentException Thrown when the base is out of reach. | [
"Converts",
"the",
"provided",
"number",
"from",
"an",
"arbitrary",
"base",
"to",
"another",
"arbitrary",
"base",
"(",
"from",
"2",
"to",
"36",
")",
"."
] | train | https://github.com/phpmath/bignumber/blob/9d8343a535a66e1e61362abf71ca26133222fe9a/src/Utils.php#L89-L132 |
phpmath/bignumber | src/Utils.php | Utils.convertExponentialToString | public static function convertExponentialToString($value)
{
if (!is_float($value)) {
return $value;
}
$result = explode('E', strtoupper($value));
if (count($result) === 1) {
return $result[0];
}
$dotSplitted = explode('.', $result[0]);
return '0.' . str_repeat('0', abs($result[1]) - 1) . $dotSplitted[0];
} | php | public static function convertExponentialToString($value)
{
if (!is_float($value)) {
return $value;
}
$result = explode('E', strtoupper($value));
if (count($result) === 1) {
return $result[0];
}
$dotSplitted = explode('.', $result[0]);
return '0.' . str_repeat('0', abs($result[1]) - 1) . $dotSplitted[0];
} | [
"public",
"static",
"function",
"convertExponentialToString",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_float",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"$",
"result",
"=",
"explode",
"(",
"'E'",
",",
"strtoupper",
"("... | Converts the given exponential value to a string.
@param float|string $value The exponential value to convert.
@return string | [
"Converts",
"the",
"given",
"exponential",
"value",
"to",
"a",
"string",
"."
] | train | https://github.com/phpmath/bignumber/blob/9d8343a535a66e1e61362abf71ca26133222fe9a/src/Utils.php#L140-L155 |
phpmath/bignumber | src/Utils.php | Utils.multiply | public static function multiply(BigNumber $lft, BigNumber $rgt, $scale = 10, $mutable = true)
{
$bigNumber = new BigNumber($lft, $scale, $mutable);
return $bigNumber->multiply($rgt);
} | php | public static function multiply(BigNumber $lft, BigNumber $rgt, $scale = 10, $mutable = true)
{
$bigNumber = new BigNumber($lft, $scale, $mutable);
return $bigNumber->multiply($rgt);
} | [
"public",
"static",
"function",
"multiply",
"(",
"BigNumber",
"$",
"lft",
",",
"BigNumber",
"$",
"rgt",
",",
"$",
"scale",
"=",
"10",
",",
"$",
"mutable",
"=",
"true",
")",
"{",
"$",
"bigNumber",
"=",
"new",
"BigNumber",
"(",
"$",
"lft",
",",
"$",
... | Multiplies the two given numbers.
@param BigNumber $lft The left number.
@param BigNumber $rgt The right number.
@param int $scale The scale of the calculated number.
@param bool $mutable Whether or not the result is mutable.
@return BigNumber | [
"Multiplies",
"the",
"two",
"given",
"numbers",
"."
] | train | https://github.com/phpmath/bignumber/blob/9d8343a535a66e1e61362abf71ca26133222fe9a/src/Utils.php#L166-L171 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php | Zend_Validate_File_ImageSize.setImageMin | public function setImageMin($minwidth, $minheight)
{
if (($this->_maxwidth !== null) and ($minwidth > $this->_maxwidth)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The minimum image width must be less than or equal to the "
. " maximum image width, but {$minwidth} > {$this->_maxwidth}"
);
}
if (($this->_maxheight !== null) and ($minheight > $this->_maxheight)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The minimum image height must be less than or equal to the "
. " maximum image height, but {$minheight} > {$this->_maxheight}"
);
}
$this->_minwidth = max(0, (integer) $minwidth);
$this->_minheight = max(0, (integer) $minheight);
return $this;
} | php | public function setImageMin($minwidth, $minheight)
{
if (($this->_maxwidth !== null) and ($minwidth > $this->_maxwidth)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The minimum image width must be less than or equal to the "
. " maximum image width, but {$minwidth} > {$this->_maxwidth}"
);
}
if (($this->_maxheight !== null) and ($minheight > $this->_maxheight)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The minimum image height must be less than or equal to the "
. " maximum image height, but {$minheight} > {$this->_maxheight}"
);
}
$this->_minwidth = max(0, (integer) $minwidth);
$this->_minheight = max(0, (integer) $minheight);
return $this;
} | [
"public",
"function",
"setImageMin",
"(",
"$",
"minwidth",
",",
"$",
"minheight",
")",
"{",
"if",
"(",
"(",
"$",
"this",
"->",
"_maxwidth",
"!==",
"null",
")",
"and",
"(",
"$",
"minwidth",
">",
"$",
"this",
"->",
"_maxwidth",
")",
")",
"{",
"include_... | Sets the minimum image size
@param integer $minwidth The minimum image width
@param integer $minheight The minimum image height
@throws Zend_Validate_Exception When minwidth is greater than maxwidth
@throws Zend_Validate_Exception When minheight is greater than maxheight
@return Zend_Validate_File_ImageSize Provides a fluent interface | [
"Sets",
"the",
"minimum",
"image",
"size"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php#L187-L208 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php | Zend_Validate_File_ImageSize.setImageMax | public function setImageMax($maxwidth, $maxheight)
{
if ($maxwidth === null) {
$tempwidth = null;
} else if (($this->_minwidth !== null) and ($maxwidth < $this->_minwidth)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The maximum image width must be greater than or equal to the "
. "minimum image width, but {$maxwidth} < {$this->_minwidth}"
);
} else {
$tempwidth = (integer) $maxwidth;
}
if ($maxheight === null) {
$tempheight = null;
} else if (($this->_minheight !== null) and ($maxheight < $this->_minheight)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The maximum image height must be greater than or equal to the "
. "minimum image height, but {$maxheight} < {$this->_minwidth}"
);
} else {
$tempheight = (integer) $maxheight;
}
$this->_maxwidth = $tempwidth;
$this->_maxheight = $tempheight;
return $this;
} | php | public function setImageMax($maxwidth, $maxheight)
{
if ($maxwidth === null) {
$tempwidth = null;
} else if (($this->_minwidth !== null) and ($maxwidth < $this->_minwidth)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The maximum image width must be greater than or equal to the "
. "minimum image width, but {$maxwidth} < {$this->_minwidth}"
);
} else {
$tempwidth = (integer) $maxwidth;
}
if ($maxheight === null) {
$tempheight = null;
} else if (($this->_minheight !== null) and ($maxheight < $this->_minheight)) {
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception(
"The maximum image height must be greater than or equal to the "
. "minimum image height, but {$maxheight} < {$this->_minwidth}"
);
} else {
$tempheight = (integer) $maxheight;
}
$this->_maxwidth = $tempwidth;
$this->_maxheight = $tempheight;
return $this;
} | [
"public",
"function",
"setImageMax",
"(",
"$",
"maxwidth",
",",
"$",
"maxheight",
")",
"{",
"if",
"(",
"$",
"maxwidth",
"===",
"null",
")",
"{",
"$",
"tempwidth",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"(",
"$",
"this",
"->",
"_minwidth",
"!==",
... | Sets the maximum image size
@param integer $maxwidth The maximum image width
@param integer $maxheight The maximum image height
@throws Zend_Validate_Exception When maxwidth is smaller than minwidth
@throws Zend_Validate_Exception When maxheight is smaller than minheight
@return Zend_Validate_StringLength Provides a fluent interface | [
"Sets",
"the",
"maximum",
"image",
"size"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php#L219-L248 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php | Zend_Validate_File_ImageSize.setImageWidth | public function setImageWidth($minwidth, $maxwidth)
{
$this->setImageMin($minwidth, $this->_minheight);
$this->setImageMax($maxwidth, $this->_maxheight);
return $this;
} | php | public function setImageWidth($minwidth, $maxwidth)
{
$this->setImageMin($minwidth, $this->_minheight);
$this->setImageMax($maxwidth, $this->_maxheight);
return $this;
} | [
"public",
"function",
"setImageWidth",
"(",
"$",
"minwidth",
",",
"$",
"maxwidth",
")",
"{",
"$",
"this",
"->",
"setImageMin",
"(",
"$",
"minwidth",
",",
"$",
"this",
"->",
"_minheight",
")",
";",
"$",
"this",
"->",
"setImageMax",
"(",
"$",
"maxwidth",
... | Sets the mimimum and maximum image width
@param integer $minwidth The minimum image width
@param integer $maxwidth The maximum image width
@return Zend_Validate_File_ImageSize Provides a fluent interface | [
"Sets",
"the",
"mimimum",
"and",
"maximum",
"image",
"width"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php#L257-L262 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php | Zend_Validate_File_ImageSize.setImageHeight | public function setImageHeight($minheight, $maxheight)
{
$this->setImageMin($this->_minwidth, $minheight);
$this->setImageMax($this->_maxwidth, $maxheight);
return $this;
} | php | public function setImageHeight($minheight, $maxheight)
{
$this->setImageMin($this->_minwidth, $minheight);
$this->setImageMax($this->_maxwidth, $maxheight);
return $this;
} | [
"public",
"function",
"setImageHeight",
"(",
"$",
"minheight",
",",
"$",
"maxheight",
")",
"{",
"$",
"this",
"->",
"setImageMin",
"(",
"$",
"this",
"->",
"_minwidth",
",",
"$",
"minheight",
")",
";",
"$",
"this",
"->",
"setImageMax",
"(",
"$",
"this",
... | Sets the mimimum and maximum image height
@param integer $minheight The minimum image height
@param integer $maxheight The maximum image height
@return Zend_Validate_File_ImageSize Provides a fluent interface | [
"Sets",
"the",
"mimimum",
"and",
"maximum",
"image",
"height"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php#L271-L276 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php | Zend_Validate_File_ImageSize.isValid | public function isValid($value, $file = null)
{
// Is file readable ?
if (@is_readable($value) === false) {
$this->_throw($file, self::NOT_READABLE);
return false;
}
$size = @getimagesize($value);
$this->_setValue($file);
if (empty($size) or ($size[0] === 0) or ($size[1] === 0)) {
$this->_throw($file, self::NOT_DETECTED);
return false;
}
if ($size[0] < $this->_minwidth) {
$this->_throw($file, self::WIDTH_TOO_SMALL);
}
if ($size[1] < $this->_minheight) {
$this->_throw($file, self::HEIGHT_TOO_SMALL);
}
if (($this->_maxwidth !== null) and ($this->_maxwidth < $size[0])) {
$this->_throw($file, self::WIDTH_TOO_BIG);
}
if (($this->_maxheight !== null) and ($this->_maxheight < $size[1])) {
$this->_throw($file, self::HEIGHT_TOO_BIG);
}
if (count($this->_messages) > 0) {
return false;
} else {
return true;
}
} | php | public function isValid($value, $file = null)
{
// Is file readable ?
if (@is_readable($value) === false) {
$this->_throw($file, self::NOT_READABLE);
return false;
}
$size = @getimagesize($value);
$this->_setValue($file);
if (empty($size) or ($size[0] === 0) or ($size[1] === 0)) {
$this->_throw($file, self::NOT_DETECTED);
return false;
}
if ($size[0] < $this->_minwidth) {
$this->_throw($file, self::WIDTH_TOO_SMALL);
}
if ($size[1] < $this->_minheight) {
$this->_throw($file, self::HEIGHT_TOO_SMALL);
}
if (($this->_maxwidth !== null) and ($this->_maxwidth < $size[0])) {
$this->_throw($file, self::WIDTH_TOO_BIG);
}
if (($this->_maxheight !== null) and ($this->_maxheight < $size[1])) {
$this->_throw($file, self::HEIGHT_TOO_BIG);
}
if (count($this->_messages) > 0) {
return false;
} else {
return true;
}
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
",",
"$",
"file",
"=",
"null",
")",
"{",
"// Is file readable ?",
"if",
"(",
"@",
"is_readable",
"(",
"$",
"value",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"_throw",
"(",
"$",
"file",
",",... | Defined by Zend_Validate_Interface
Returns true if and only if the imagesize of $value is at least min and
not bigger than max
@param string $value Real file to check for image size
@param array $file File data from Zend_File_Transfer
@return boolean | [
"Defined",
"by",
"Zend_Validate_Interface"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/File/ImageSize.php#L288-L325 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.getPattern | public function getPattern($name = '')
{
if ('' === $name) {
return $this->pattern;
}
return isset($this->pattern[$name]) ? $this->pattern[$name] : null;
} | php | public function getPattern($name = '')
{
if ('' === $name) {
return $this->pattern;
}
return isset($this->pattern[$name]) ? $this->pattern[$name] : null;
} | [
"public",
"function",
"getPattern",
"(",
"$",
"name",
"=",
"''",
")",
"{",
"if",
"(",
"''",
"===",
"$",
"name",
")",
"{",
"return",
"$",
"this",
"->",
"pattern",
";",
"}",
"return",
"isset",
"(",
"$",
"this",
"->",
"pattern",
"[",
"$",
"name",
"]... | 获取变量规则定义
@access public
@param string $name 变量名
@return mixed | [
"获取变量规则定义"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L195-L202 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.getOption | public function getOption($name = '')
{
if ('' === $name) {
return $this->option;
}
return isset($this->option[$name]) ? $this->option[$name] : null;
} | php | public function getOption($name = '')
{
if ('' === $name) {
return $this->option;
}
return isset($this->option[$name]) ? $this->option[$name] : null;
} | [
"public",
"function",
"getOption",
"(",
"$",
"name",
"=",
"''",
")",
"{",
"if",
"(",
"''",
"===",
"$",
"name",
")",
"{",
"return",
"$",
"this",
"->",
"option",
";",
"}",
"return",
"isset",
"(",
"$",
"this",
"->",
"option",
"[",
"$",
"name",
"]",
... | 获取路由参数定义
@access public
@param string $name 参数名
@return mixed | [
"获取路由参数定义"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L221-L228 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.option | public function option($name, $value = '')
{
if (is_array($name)) {
$this->option = array_merge($this->option, $name);
} else {
$this->option[$name] = $value;
}
return $this;
} | php | public function option($name, $value = '')
{
if (is_array($name)) {
$this->option = array_merge($this->option, $name);
} else {
$this->option[$name] = $value;
}
return $this;
} | [
"public",
"function",
"option",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"''",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"option",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"option",
",",
"$",
"name",... | 注册路由参数
@access public
@param string|array $name 参数名
@param mixed $value 值
@return $this | [
"注册路由参数"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L237-L246 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.pattern | public function pattern($name, $rule = '')
{
if (is_array($name)) {
$this->pattern = array_merge($this->pattern, $name);
} else {
$this->pattern[$name] = $rule;
}
return $this;
} | php | public function pattern($name, $rule = '')
{
if (is_array($name)) {
$this->pattern = array_merge($this->pattern, $name);
} else {
$this->pattern[$name] = $rule;
}
return $this;
} | [
"public",
"function",
"pattern",
"(",
"$",
"name",
",",
"$",
"rule",
"=",
"''",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"pattern",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"pattern",
",",
"$",
"name... | 注册变量规则
@access public
@param string|array $name 变量名
@param string $rule 变量规则
@return $this | [
"注册变量规则"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L255-L264 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.filter | public function filter($name, $value = null)
{
if (is_array($name)) {
$this->option['filter'] = $name;
} else {
$this->option['filter'][$name] = $value;
}
return $this;
} | php | public function filter($name, $value = null)
{
if (is_array($name)) {
$this->option['filter'] = $name;
} else {
$this->option['filter'][$name] = $value;
}
return $this;
} | [
"public",
"function",
"filter",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"option",
"[",
"'filter'",
"]",
"=",
"$",
"name",
";",
"}",
"else",
"{",
"$",... | 设置参数过滤检查
@access public
@param string|array $name
@param mixed $value
@return $this | [
"设置参数过滤检查"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L365-L374 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.model | public function model($var, $model = null, $exception = true)
{
if ($var instanceof \Closure) {
$this->option['model'][] = $var;
} elseif (is_array($var)) {
$this->option['model'] = $var;
} elseif (is_null($model)) {
$this->option['model']['id'] = [$var, true];
} else {
$this->option['model'][$var] = [$model, $exception];
}
return $this;
} | php | public function model($var, $model = null, $exception = true)
{
if ($var instanceof \Closure) {
$this->option['model'][] = $var;
} elseif (is_array($var)) {
$this->option['model'] = $var;
} elseif (is_null($model)) {
$this->option['model']['id'] = [$var, true];
} else {
$this->option['model'][$var] = [$model, $exception];
}
return $this;
} | [
"public",
"function",
"model",
"(",
"$",
"var",
",",
"$",
"model",
"=",
"null",
",",
"$",
"exception",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"var",
"instanceof",
"\\",
"Closure",
")",
"{",
"$",
"this",
"->",
"option",
"[",
"'model'",
"]",
"[",
"... | 绑定模型
@access public
@param array|string $var 路由变量名 多个使用 & 分割
@param string|\Closure $model 绑定模型类
@param bool $exception 是否抛出异常
@return $this | [
"绑定模型"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L384-L397 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.append | public function append(array $append = [])
{
if (isset($this->option['append'])) {
$this->option['append'] = array_merge($this->option['append'], $append);
} else {
$this->option['append'] = $append;
}
return $this;
} | php | public function append(array $append = [])
{
if (isset($this->option['append'])) {
$this->option['append'] = array_merge($this->option['append'], $append);
} else {
$this->option['append'] = $append;
}
return $this;
} | [
"public",
"function",
"append",
"(",
"array",
"$",
"append",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"option",
"[",
"'append'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"option",
"[",
"'append'",
"]",
"=",
"array_merge",
... | 附加路由隐式参数
@access public
@param array $append
@return $this | [
"附加路由隐式参数"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L405-L414 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.validate | public function validate($validate, $scene = null, $message = [], $batch = false)
{
$this->option['validate'] = [$validate, $scene, $message, $batch];
return $this;
} | php | public function validate($validate, $scene = null, $message = [], $batch = false)
{
$this->option['validate'] = [$validate, $scene, $message, $batch];
return $this;
} | [
"public",
"function",
"validate",
"(",
"$",
"validate",
",",
"$",
"scene",
"=",
"null",
",",
"$",
"message",
"=",
"[",
"]",
",",
"$",
"batch",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"option",
"[",
"'validate'",
"]",
"=",
"[",
"$",
"validate",
... | 绑定验证
@access public
@param mixed $validate 验证器类
@param string $scene 验证场景
@param array $message 验证提示
@param bool $batch 批量验证
@return $this | [
"绑定验证"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L425-L430 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.header | public function header($header, $value = null)
{
if (is_array($header)) {
$this->option['header'] = $header;
} else {
$this->option['header'][$header] = $value;
}
return $this;
} | php | public function header($header, $value = null)
{
if (is_array($header)) {
$this->option['header'] = $header;
} else {
$this->option['header'][$header] = $value;
}
return $this;
} | [
"public",
"function",
"header",
"(",
"$",
"header",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"header",
")",
")",
"{",
"$",
"this",
"->",
"option",
"[",
"'header'",
"]",
"=",
"$",
"header",
";",
"}",
"else",
"{",
... | 设置Response Header信息
@access public
@param string|array $name 参数名
@param string $value 参数值
@return $this | [
"设置Response",
"Header信息"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L451-L460 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.middleware | public function middleware($middleware, $param = null)
{
if (is_null($param) && is_array($middleware)) {
$this->option['middleware'] = $middleware;
} else {
foreach ((array)$middleware as $item) {
$this->option['middleware'][] = [$item, $param];
}
}
return $this;
} | php | public function middleware($middleware, $param = null)
{
if (is_null($param) && is_array($middleware)) {
$this->option['middleware'] = $middleware;
} else {
foreach ((array)$middleware as $item) {
$this->option['middleware'][] = [$item, $param];
}
}
return $this;
} | [
"public",
"function",
"middleware",
"(",
"$",
"middleware",
",",
"$",
"param",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"param",
")",
"&&",
"is_array",
"(",
"$",
"middleware",
")",
")",
"{",
"$",
"this",
"->",
"option",
"[",
"'middlewar... | 指定路由中间件
@access public
@param string|array|\Closure $middleware
@param mixed $param
@return $this | [
"指定路由中间件"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L469-L480 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.allowCrossDomain | public function allowCrossDomain($allow = true, $header = [])
{
if (!empty($header)) {
$this->header($header);
}
if ($allow && $this->parent) {
$this->parent->addRuleItem($this, 'options');
}
return $this->option('cross_domain', $allow);
} | php | public function allowCrossDomain($allow = true, $header = [])
{
if (!empty($header)) {
$this->header($header);
}
if ($allow && $this->parent) {
$this->parent->addRuleItem($this, 'options');
}
return $this->option('cross_domain', $allow);
} | [
"public",
"function",
"allowCrossDomain",
"(",
"$",
"allow",
"=",
"true",
",",
"$",
"header",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"header",
")",
")",
"{",
"$",
"this",
"->",
"header",
"(",
"$",
"header",
")",
";",
"}",
"... | 设置是否允许跨域
@access public
@param bool $allow
@param array $header
@return $this | [
"设置是否允许跨域"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L622-L633 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.checkCrossDomain | protected function checkCrossDomain()
{
if (!empty($this->option['cross_domain'])) {
$header = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
];
if (!empty($this->option['header'])) {
$header = array_merge($header, $this->option['header']);
}
$this->option['header'] = $header;
if (Request::getMethod() == 'OPTIONS') {
return new ResponseDispatch($request, $this, Response::create()->code(204)->header($header));
}
}
} | php | protected function checkCrossDomain()
{
if (!empty($this->option['cross_domain'])) {
$header = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
];
if (!empty($this->option['header'])) {
$header = array_merge($header, $this->option['header']);
}
$this->option['header'] = $header;
if (Request::getMethod() == 'OPTIONS') {
return new ResponseDispatch($request, $this, Response::create()->code(204)->header($header));
}
}
} | [
"protected",
"function",
"checkCrossDomain",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"option",
"[",
"'cross_domain'",
"]",
")",
")",
"{",
"$",
"header",
"=",
"[",
"'Access-Control-Allow-Origin'",
"=>",
"'*'",
",",
"'Access-Control-All... | 检查OPTIONS请求
@access public
@return Dispatch|void | [
"检查OPTIONS请求"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L640-L660 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.crossDomainRule | public function crossDomainRule()
{
if ($this instanceof RuleGroup) {
$method = '*';
} else {
$method = $this->method;
}
$this->router->setCrossDomainRule($this, $method);
return $this;
} | php | public function crossDomainRule()
{
if ($this instanceof RuleGroup) {
$method = '*';
} else {
$method = $this->method;
}
$this->router->setCrossDomainRule($this, $method);
return $this;
} | [
"public",
"function",
"crossDomainRule",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"instanceof",
"RuleGroup",
")",
"{",
"$",
"method",
"=",
"'*'",
";",
"}",
"else",
"{",
"$",
"method",
"=",
"$",
"this",
"->",
"method",
";",
"}",
"$",
"this",
"->",
"ro... | 设置路由规则全局有效
@access public
@return $this | [
"设置路由规则全局有效"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L667-L678 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.mergeGroupOptions | public function mergeGroupOptions()
{
if (!$this->lockOption) {
$parentOption = $this->parent->getOption();
// 合并分组参数
foreach ($this->mergeOptions as $item) {
if (isset($parentOption[$item]) && isset($this->option[$item])) {
$this->option[$item] = array_merge($parentOption[$item], $this->option[$item]);
}
}
$this->option = array_merge($parentOption, $this->option);
$this->lockOption = true;
}
return $this->option;
} | php | public function mergeGroupOptions()
{
if (!$this->lockOption) {
$parentOption = $this->parent->getOption();
// 合并分组参数
foreach ($this->mergeOptions as $item) {
if (isset($parentOption[$item]) && isset($this->option[$item])) {
$this->option[$item] = array_merge($parentOption[$item], $this->option[$item]);
}
}
$this->option = array_merge($parentOption, $this->option);
$this->lockOption = true;
}
return $this->option;
} | [
"public",
"function",
"mergeGroupOptions",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"lockOption",
")",
"{",
"$",
"parentOption",
"=",
"$",
"this",
"->",
"parent",
"->",
"getOption",
"(",
")",
";",
"// 合并分组参数",
"foreach",
"(",
"$",
"this",
"->"... | 合并分组参数
@access public
@return array | [
"合并分组参数"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L685-L701 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.parseRule | public function parseRule($rule, $route, $url, $option = [], $matches = [])
{
if (is_string($route) && isset($option['prefix'])) {
// 路由地址前缀
$route = $option['prefix'] . $route;
}
// 替换路由地址中的变量
if (is_string($route) && !empty($matches)) {
foreach ($matches as $key => $val) {
if (false !== strpos($route, '<' . $key . '>')) {
$route = str_replace('<' . $key . '>', $val, $route);
} elseif (false !== strpos($route, ':' . $key)) {
$route = str_replace(':' . $key, $val, $route);
}
}
}
// 解析额外参数
$count = substr_count($rule, '/');
$url = array_slice(explode('|', $url), $count + 1);
$this->parseUrlParams(implode('|', $url), $matches);
$this->vars = $matches;
$this->option = $option;
$this->doAfter = true;
// 发起路由调度
return ['route' => $route, 'option' => $option,'param' => $this->getVars()];
} | php | public function parseRule($rule, $route, $url, $option = [], $matches = [])
{
if (is_string($route) && isset($option['prefix'])) {
// 路由地址前缀
$route = $option['prefix'] . $route;
}
// 替换路由地址中的变量
if (is_string($route) && !empty($matches)) {
foreach ($matches as $key => $val) {
if (false !== strpos($route, '<' . $key . '>')) {
$route = str_replace('<' . $key . '>', $val, $route);
} elseif (false !== strpos($route, ':' . $key)) {
$route = str_replace(':' . $key, $val, $route);
}
}
}
// 解析额外参数
$count = substr_count($rule, '/');
$url = array_slice(explode('|', $url), $count + 1);
$this->parseUrlParams(implode('|', $url), $matches);
$this->vars = $matches;
$this->option = $option;
$this->doAfter = true;
// 发起路由调度
return ['route' => $route, 'option' => $option,'param' => $this->getVars()];
} | [
"public",
"function",
"parseRule",
"(",
"$",
"rule",
",",
"$",
"route",
",",
"$",
"url",
",",
"$",
"option",
"=",
"[",
"]",
",",
"$",
"matches",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"route",
")",
"&&",
"isset",
"(",
"$",
... | 解析匹配到的规则路由
@access public
@param string $rule 路由规则
@param string $route 路由地址
@param string $url URL地址
@param array $option 路由参数
@param array $matches 匹配的变量
@return Dispatch | [
"解析匹配到的规则路由"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L713-L742 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.checkBefore | protected function checkBefore($before)
{
$hook = Container::get('hook');
foreach ((array)$before as $behavior) {
$result = $hook->exec($behavior);
if (false === $result) {
return false;
}
}
} | php | protected function checkBefore($before)
{
$hook = Container::get('hook');
foreach ((array)$before as $behavior) {
$result = $hook->exec($behavior);
if (false === $result) {
return false;
}
}
} | [
"protected",
"function",
"checkBefore",
"(",
"$",
"before",
")",
"{",
"$",
"hook",
"=",
"Container",
"::",
"get",
"(",
"'hook'",
")",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"before",
"as",
"$",
"behavior",
")",
"{",
"$",
"result",
"=",
"$",
"... | 检查路由前置行为
@access protected
@param mixed $before 前置行为
@return mixed | [
"检查路由前置行为"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L750-L761 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.dispatchMethod | protected function dispatchMethod($request, $route)
{
list($path, $var) = $this->parseUrlPath($route);
$route = str_replace('/', '@', implode('/', $path));
$method = strpos($route, '@') ? explode('@', $route) : $route;
return new CallbackDispatch($request, $this, $method, $var);
} | php | protected function dispatchMethod($request, $route)
{
list($path, $var) = $this->parseUrlPath($route);
$route = str_replace('/', '@', implode('/', $path));
$method = strpos($route, '@') ? explode('@', $route) : $route;
return new CallbackDispatch($request, $this, $method, $var);
} | [
"protected",
"function",
"dispatchMethod",
"(",
"$",
"request",
",",
"$",
"route",
")",
"{",
"list",
"(",
"$",
"path",
",",
"$",
"var",
")",
"=",
"$",
"this",
"->",
"parseUrlPath",
"(",
"$",
"route",
")",
";",
"$",
"route",
"=",
"str_replace",
"(",
... | 解析URL地址为 模块/控制器/操作
@access protected
@param Request $request Request对象
@param string $route 路由地址
@return CallbackDispatch | [
"解析URL地址为",
"模块",
"/",
"控制器",
"/",
"操作"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L805-L813 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.dispatchController | protected function dispatchController($request, $route)
{
list($route, $var) = $this->parseUrlPath($route);
$result = new ControllerDispatch($request, $this, implode('/', $route), $var);
$request->setAction(array_pop($route));
$request->setController($route ? array_pop($route) : $this->getConfig('default_controller'));
$request->setModule($route ? array_pop($route) : $this->getConfig('default_module'));
return $result;
} | php | protected function dispatchController($request, $route)
{
list($route, $var) = $this->parseUrlPath($route);
$result = new ControllerDispatch($request, $this, implode('/', $route), $var);
$request->setAction(array_pop($route));
$request->setController($route ? array_pop($route) : $this->getConfig('default_controller'));
$request->setModule($route ? array_pop($route) : $this->getConfig('default_module'));
return $result;
} | [
"protected",
"function",
"dispatchController",
"(",
"$",
"request",
",",
"$",
"route",
")",
"{",
"list",
"(",
"$",
"route",
",",
"$",
"var",
")",
"=",
"$",
"this",
"->",
"parseUrlPath",
"(",
"$",
"route",
")",
";",
"$",
"result",
"=",
"new",
"Control... | 解析URL地址为 模块/控制器/操作
@access protected
@param Request $request Request对象
@param string $route 路由地址
@return ControllerDispatch | [
"解析URL地址为",
"模块",
"/",
"控制器",
"/",
"操作"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L822-L833 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.dispatchModule | protected function dispatchModule($route)
{
list($path, $var) = $this->parseUrlPath($route);
$action = array_pop($path);
$controller = !empty($path) ? array_pop($path) : null;
$module = !empty($path) ? array_pop($path) : null;
$method = Request::getMethod();
if ($this->getConfig('use_action_prefix') && $this->router->getMethodPrefix($method)) {
$prefix = $this->router->getMethodPrefix($method);
// 操作方法前缀支持
$action = 0 !== strpos($action, $prefix) ? $prefix . $action : $action;
}
// 设置当前请求的路由变量
Request::setRouteVars($var);
// 路由到模块/控制器/操作
return new ModuleDispatch($this, [$module, $controller, $action], ['convert' => false]);
} | php | protected function dispatchModule($route)
{
list($path, $var) = $this->parseUrlPath($route);
$action = array_pop($path);
$controller = !empty($path) ? array_pop($path) : null;
$module = !empty($path) ? array_pop($path) : null;
$method = Request::getMethod();
if ($this->getConfig('use_action_prefix') && $this->router->getMethodPrefix($method)) {
$prefix = $this->router->getMethodPrefix($method);
// 操作方法前缀支持
$action = 0 !== strpos($action, $prefix) ? $prefix . $action : $action;
}
// 设置当前请求的路由变量
Request::setRouteVars($var);
// 路由到模块/控制器/操作
return new ModuleDispatch($this, [$module, $controller, $action], ['convert' => false]);
} | [
"protected",
"function",
"dispatchModule",
"(",
"$",
"route",
")",
"{",
"list",
"(",
"$",
"path",
",",
"$",
"var",
")",
"=",
"$",
"this",
"->",
"parseUrlPath",
"(",
"$",
"route",
")",
";",
"$",
"action",
"=",
"array_pop",
"(",
"$",
"path",
")",
";"... | 解析URL地址为 模块/控制器/操作
@access protected
@param string $route 路由地址
@return ModuleDispatch | [
"解析URL地址为",
"模块",
"/",
"控制器",
"/",
"操作"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L841-L861 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.checkOption | protected function checkOption($option)
{
// 请求类型检测
if (!empty($option['method'])) {
if (is_string($option['method']) && false === stripos($option['method'], Request::getMethod())) {
return false;
}
}
// AJAX PJAX 请求检查
foreach (['ajax', 'pjax', 'mobile'] as $item) {
if (isset($option[$item])) {
$call = 'is' . $item;
if ($option[$item] && !$request->$call() || !$option[$item] && $request->$call()) {
return false;
}
}
}
// 伪静态后缀检测
if (Request::getRequestUri() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . Request::ext() . '|'))
|| (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . Request::ext() . '|')))) {
return false;
}
// 域名检查
if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
return false;
}
// HTTPS检查
if ((isset($option['https']) && $option['https'] && !$request->isSsl())
|| (isset($option['https']) && !$option['https'] && $request->isSsl())) {
return false;
}
// 请求参数检查
if (isset($option['filter'])) {
foreach ($option['filter'] as $name => $value) {
if ($request->param($name, '', null) != $value) {
return false;
}
}
}
return true;
} | php | protected function checkOption($option)
{
// 请求类型检测
if (!empty($option['method'])) {
if (is_string($option['method']) && false === stripos($option['method'], Request::getMethod())) {
return false;
}
}
// AJAX PJAX 请求检查
foreach (['ajax', 'pjax', 'mobile'] as $item) {
if (isset($option[$item])) {
$call = 'is' . $item;
if ($option[$item] && !$request->$call() || !$option[$item] && $request->$call()) {
return false;
}
}
}
// 伪静态后缀检测
if (Request::getRequestUri() != '/' && ((isset($option['ext']) && false === stripos('|' . $option['ext'] . '|', '|' . Request::ext() . '|'))
|| (isset($option['deny_ext']) && false !== stripos('|' . $option['deny_ext'] . '|', '|' . Request::ext() . '|')))) {
return false;
}
// 域名检查
if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
return false;
}
// HTTPS检查
if ((isset($option['https']) && $option['https'] && !$request->isSsl())
|| (isset($option['https']) && !$option['https'] && $request->isSsl())) {
return false;
}
// 请求参数检查
if (isset($option['filter'])) {
foreach ($option['filter'] as $name => $value) {
if ($request->param($name, '', null) != $value) {
return false;
}
}
}
return true;
} | [
"protected",
"function",
"checkOption",
"(",
"$",
"option",
")",
"{",
"// 请求类型检测",
"if",
"(",
"!",
"empty",
"(",
"$",
"option",
"[",
"'method'",
"]",
")",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"option",
"[",
"'method'",
"]",
")",
"&&",
"false",... | 路由检查
@access protected
@param array $option 路由参数
@param Request $request Request对象
@return bool | [
"路由检查"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L870-L915 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.parseUrlParams | protected function parseUrlParams($url, &$var = [])
{
if ($url) {
if ($this->getConfig('url_param_type')) {
$var += explode('|', $url);
} else {
preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
$var[$match[1]] = strip_tags($match[2]);
}, $url);
}
}
} | php | protected function parseUrlParams($url, &$var = [])
{
if ($url) {
if ($this->getConfig('url_param_type')) {
$var += explode('|', $url);
} else {
preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
$var[$match[1]] = strip_tags($match[2]);
}, $url);
}
}
} | [
"protected",
"function",
"parseUrlParams",
"(",
"$",
"url",
",",
"&",
"$",
"var",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'url_param_type'",
")",
")",
"{",
"$",
"var",
"+=",
"expl... | 解析URL地址中的参数Request对象
@access protected
@param string $rule 路由规则
@param array $var 变量
@return void | [
"解析URL地址中的参数Request对象"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L924-L935 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.parseUrlPath | public function parseUrlPath($url)
{
// 分隔符替换 确保路由定义使用统一的分隔符
$url = str_replace('|', '/', $url);
$url = trim($url, '/');
$var = [];
if (false !== strpos($url, '?')) {
// [模块/控制器/操作?]参数1=值1&参数2=值2...
$info = parse_url($url);
$path = explode('/', $info['path']);
parse_str($info['query'], $var);
} elseif (strpos($url, '/')) {
// [模块/控制器/操作]
$path = explode('/', $url);
} elseif (false !== strpos($url, '=')) {
// 参数1=值1&参数2=值2...
$path = [];
parse_str($url, $var);
} elseif($url) {
$path = [$url];
}else{
$path = [];
}
return [$path, $var];
} | php | public function parseUrlPath($url)
{
// 分隔符替换 确保路由定义使用统一的分隔符
$url = str_replace('|', '/', $url);
$url = trim($url, '/');
$var = [];
if (false !== strpos($url, '?')) {
// [模块/控制器/操作?]参数1=值1&参数2=值2...
$info = parse_url($url);
$path = explode('/', $info['path']);
parse_str($info['query'], $var);
} elseif (strpos($url, '/')) {
// [模块/控制器/操作]
$path = explode('/', $url);
} elseif (false !== strpos($url, '=')) {
// 参数1=值1&参数2=值2...
$path = [];
parse_str($url, $var);
} elseif($url) {
$path = [$url];
}else{
$path = [];
}
return [$path, $var];
} | [
"public",
"function",
"parseUrlPath",
"(",
"$",
"url",
")",
"{",
"// 分隔符替换 确保路由定义使用统一的分隔符",
"$",
"url",
"=",
"str_replace",
"(",
"'|'",
",",
"'/'",
",",
"$",
"url",
")",
";",
"$",
"url",
"=",
"trim",
"(",
"$",
"url",
",",
"'/'",
")",
";",
"$",
"var... | 解析URL的pathinfo参数和变量
@access public
@param string $url URL地址
@return array | [
"解析URL的pathinfo参数和变量"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L943-L969 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.buildRuleRegex | protected function buildRuleRegex($rule, $match, $pattern = [], $option = [], $completeMatch = false, $suffix = '')
{
foreach ($match as $name) {
$replace[] = $this->buildNameRegex($name, $pattern, $suffix);
}
// 是否区分 / 地址访问
if ('/' != $rule) {
if (!empty($option['remove_slash'])) {
$rule = rtrim($rule, '/');
} elseif (substr($rule, -1) == '/') {
$rule = rtrim($rule, '/');
$hasSlash = true;
}
}
$regex = str_replace($match, $replace, $rule);
$regex = str_replace([')?/', ')/', ')?-', ')-', '\\\\/'], [')\/', ')\/', ')\-', ')\-', '\/'], $regex);
if (isset($hasSlash)) {
$regex .= '\/';
}
return $regex . ($completeMatch ? '$' : '');
} | php | protected function buildRuleRegex($rule, $match, $pattern = [], $option = [], $completeMatch = false, $suffix = '')
{
foreach ($match as $name) {
$replace[] = $this->buildNameRegex($name, $pattern, $suffix);
}
// 是否区分 / 地址访问
if ('/' != $rule) {
if (!empty($option['remove_slash'])) {
$rule = rtrim($rule, '/');
} elseif (substr($rule, -1) == '/') {
$rule = rtrim($rule, '/');
$hasSlash = true;
}
}
$regex = str_replace($match, $replace, $rule);
$regex = str_replace([')?/', ')/', ')?-', ')-', '\\\\/'], [')\/', ')\/', ')\-', ')\-', '\/'], $regex);
if (isset($hasSlash)) {
$regex .= '\/';
}
return $regex . ($completeMatch ? '$' : '');
} | [
"protected",
"function",
"buildRuleRegex",
"(",
"$",
"rule",
",",
"$",
"match",
",",
"$",
"pattern",
"=",
"[",
"]",
",",
"$",
"option",
"=",
"[",
"]",
",",
"$",
"completeMatch",
"=",
"false",
",",
"$",
"suffix",
"=",
"''",
")",
"{",
"foreach",
"(",... | 生成路由的正则规则
@access protected
@param string $rule 路由规则
@param array $match 匹配的变量
@param array $pattern 路由变量规则
@param array $option 路由参数
@param bool $completeMatch 路由是否完全匹配
@param string $suffix 路由正则变量后缀
@return string | [
"生成路由的正则规则"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L982-L1006 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.buildNameRegex | protected function buildNameRegex($name, $pattern, $suffix)
{
$optional = '';
$slash = substr($name, 0, 1);
if (in_array($slash, ['/', '-'])) {
$prefix = '\\' . $slash;
$name = substr($name, 1);
$slash = substr($name, 0, 1);
} else {
$prefix = '';
}
if ('<' != $slash) {
return $prefix . preg_quote($name, '/');
}
if (strpos($name, '?')) {
$name = substr($name, 1, -2);
$optional = '?';
} elseif (strpos($name, '>')) {
$name = substr($name, 1, -1);
}
if (isset($pattern[$name])) {
$nameRule = $pattern[$name];
if (0 === strpos($nameRule, '/') && '/' == substr($nameRule, -1)) {
$nameRule = substr($nameRule, 1, -1);
}
} else {
$nameRule = $this->getConfig('app.default_route_pattern');
}
return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
} | php | protected function buildNameRegex($name, $pattern, $suffix)
{
$optional = '';
$slash = substr($name, 0, 1);
if (in_array($slash, ['/', '-'])) {
$prefix = '\\' . $slash;
$name = substr($name, 1);
$slash = substr($name, 0, 1);
} else {
$prefix = '';
}
if ('<' != $slash) {
return $prefix . preg_quote($name, '/');
}
if (strpos($name, '?')) {
$name = substr($name, 1, -2);
$optional = '?';
} elseif (strpos($name, '>')) {
$name = substr($name, 1, -1);
}
if (isset($pattern[$name])) {
$nameRule = $pattern[$name];
if (0 === strpos($nameRule, '/') && '/' == substr($nameRule, -1)) {
$nameRule = substr($nameRule, 1, -1);
}
} else {
$nameRule = $this->getConfig('app.default_route_pattern');
}
return '(' . $prefix . '(?<' . $name . $suffix . '>' . $nameRule . '))' . $optional;
} | [
"protected",
"function",
"buildNameRegex",
"(",
"$",
"name",
",",
"$",
"pattern",
",",
"$",
"suffix",
")",
"{",
"$",
"optional",
"=",
"''",
";",
"$",
"slash",
"=",
"substr",
"(",
"$",
"name",
",",
"0",
",",
"1",
")",
";",
"if",
"(",
"in_array",
"... | 生成路由变量的正则规则
@access protected
@param string $name 路由变量
@param string $pattern 变量规则
@param string $suffix 路由正则变量后缀
@return string | [
"生成路由变量的正则规则"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L1016-L1050 |
txj123/zilf | src/Zilf/Routing/Rule.php | Rule.parseVar | protected function parseVar($rule)
{
// 提取路由规则中的变量
$var = [];
if (preg_match_all('/<\w+\??>/', $rule, $matches)) {
foreach ($matches[0] as $name) {
$optional = false;
if (strpos($name, '?')) {
$name = substr($name, 1, -2);
$optional = true;
} else {
$name = substr($name, 1, -1);
}
$var[$name] = $optional ? 2 : 1;
}
}
return $var;
} | php | protected function parseVar($rule)
{
// 提取路由规则中的变量
$var = [];
if (preg_match_all('/<\w+\??>/', $rule, $matches)) {
foreach ($matches[0] as $name) {
$optional = false;
if (strpos($name, '?')) {
$name = substr($name, 1, -2);
$optional = true;
} else {
$name = substr($name, 1, -1);
}
$var[$name] = $optional ? 2 : 1;
}
}
return $var;
} | [
"protected",
"function",
"parseVar",
"(",
"$",
"rule",
")",
"{",
"// 提取路由规则中的变量",
"$",
"var",
"=",
"[",
"]",
";",
"if",
"(",
"preg_match_all",
"(",
"'/<\\w+\\??>/'",
",",
"$",
"rule",
",",
"$",
"matches",
")",
")",
"{",
"foreach",
"(",
"$",
"matches",
... | 分析路由规则中的变量
@access protected
@param string $rule 路由规则
@return array | [
"分析路由规则中的变量"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Routing/Rule.php#L1058-L1079 |
txj123/zilf | src/Zilf/Db/base/Module.php | Module.getInstance | public static function getInstance()
{
$class = get_called_class();
return isset(Zilf::$app->loadedModules[$class]) ? Zilf::$app->loadedModules[$class] : null;
} | php | public static function getInstance()
{
$class = get_called_class();
return isset(Zilf::$app->loadedModules[$class]) ? Zilf::$app->loadedModules[$class] : null;
} | [
"public",
"static",
"function",
"getInstance",
"(",
")",
"{",
"$",
"class",
"=",
"get_called_class",
"(",
")",
";",
"return",
"isset",
"(",
"Zilf",
"::",
"$",
"app",
"->",
"loadedModules",
"[",
"$",
"class",
"]",
")",
"?",
"Zilf",
"::",
"$",
"app",
"... | Returns the currently requested instance of this module class.
If the module class is not currently requested, `null` will be returned.
This method is provided so that you access the module instance from anywhere within the module.
@return static|null the currently requested instance of this module class, or `null` if the module class is not requested. | [
"Returns",
"the",
"currently",
"requested",
"instance",
"of",
"this",
"module",
"class",
".",
"If",
"the",
"module",
"class",
"is",
"not",
"currently",
"requested",
"null",
"will",
"be",
"returned",
".",
"This",
"method",
"is",
"provided",
"so",
"that",
"you... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Module.php#L170-L174 |
txj123/zilf | src/Zilf/Db/base/Module.php | Module.setInstance | public static function setInstance($instance)
{
if ($instance === null) {
unset(Zilf::$app->loadedModules[get_called_class()]);
} else {
Zilf::$app->loadedModules[get_class($instance)] = $instance;
}
} | php | public static function setInstance($instance)
{
if ($instance === null) {
unset(Zilf::$app->loadedModules[get_called_class()]);
} else {
Zilf::$app->loadedModules[get_class($instance)] = $instance;
}
} | [
"public",
"static",
"function",
"setInstance",
"(",
"$",
"instance",
")",
"{",
"if",
"(",
"$",
"instance",
"===",
"null",
")",
"{",
"unset",
"(",
"Zilf",
"::",
"$",
"app",
"->",
"loadedModules",
"[",
"get_called_class",
"(",
")",
"]",
")",
";",
"}",
... | Sets the currently requested instance of this module class.
@param Module|null $instance the currently requested instance of this module class.
If it is `null`, the instance of the calling class will be removed, if any. | [
"Sets",
"the",
"currently",
"requested",
"instance",
"of",
"this",
"module",
"class",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Module.php#L182-L189 |
txj123/zilf | src/Zilf/Db/base/Module.php | Module.setAliases | public function setAliases($aliases)
{
foreach ($aliases as $name => $alias) {
Zilf::setAlias($name, $alias);
}
} | php | public function setAliases($aliases)
{
foreach ($aliases as $name => $alias) {
Zilf::setAlias($name, $alias);
}
} | [
"public",
"function",
"setAliases",
"(",
"$",
"aliases",
")",
"{",
"foreach",
"(",
"$",
"aliases",
"as",
"$",
"name",
"=>",
"$",
"alias",
")",
"{",
"Zilf",
"::",
"setAlias",
"(",
"$",
"name",
",",
"$",
"alias",
")",
";",
"}",
"}"
] | Defines path aliases.
This method calls [[Zilf::setAlias()]] to register the path aliases.
This method is provided so that you can define path aliases when configuring a module.
@property array list of path aliases to be defined. The array keys are alias names
(must start with `@`) and the array values are the corresponding paths or aliases.
See [[setAliases()]] for an example.
@param array $aliases list of path aliases to be defined. The array keys are alias names
(must start with `@`) and the array values are the corresponding paths or aliases.
For example,
```php
[
'@models' => '@app/models', // an existing alias
'@backend' => __DIR__ . '/../backend', // a directory
]
``` | [
"Defines",
"path",
"aliases",
".",
"This",
"method",
"calls",
"[[",
"Zilf",
"::",
"setAlias",
"()",
"]]",
"to",
"register",
"the",
"path",
"aliases",
".",
"This",
"method",
"is",
"provided",
"so",
"that",
"you",
"can",
"define",
"path",
"aliases",
"when",
... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/base/Module.php#L393-L398 |
omnilight/yii2-phonenumbers | PhoneNumberBehavior.php | PhoneNumberBehavior.onBeforeValidate | public function onBeforeValidate($event)
{
/** @var PhoneNumberValidator $validator */
$validator = \Yii::createObject([
'class' => PhoneNumberValidator::className(),
'defaultRegion' => $this->defaultRegion,
]);
foreach ($this->attributes as $localAttribute => $dbAttribute) {
if ($this->isLocalValueAssigned($localAttribute))
$validator->validateAttribute($this->owner, $localAttribute);
}
} | php | public function onBeforeValidate($event)
{
/** @var PhoneNumberValidator $validator */
$validator = \Yii::createObject([
'class' => PhoneNumberValidator::className(),
'defaultRegion' => $this->defaultRegion,
]);
foreach ($this->attributes as $localAttribute => $dbAttribute) {
if ($this->isLocalValueAssigned($localAttribute))
$validator->validateAttribute($this->owner, $localAttribute);
}
} | [
"public",
"function",
"onBeforeValidate",
"(",
"$",
"event",
")",
"{",
"/** @var PhoneNumberValidator $validator */",
"$",
"validator",
"=",
"\\",
"Yii",
"::",
"createObject",
"(",
"[",
"'class'",
"=>",
"PhoneNumberValidator",
"::",
"className",
"(",
")",
",",
"'d... | Performs validation for all the attributes
@param Event $event | [
"Performs",
"validation",
"for",
"all",
"the",
"attributes"
] | train | https://github.com/omnilight/yii2-phonenumbers/blob/01444ef39803b05321f75379198d88af9307f72f/PhoneNumberBehavior.php#L61-L72 |
kiwiz/esquery | src/Result.php | Result.execute | public function execute() {
if(is_null($this->client)) {
$this->client = $this->getConnection();
}
if(is_null($this->query)) {
throw new Exception('No query');
}
list($query_data, $meta) = $this->constructQuery($this->source, $this->query, $this->aggs, $this->post_query, $this->settings);
$results_set = $this->query($query_data, $meta);
$results = $this->processResults($results_set, $meta);
$results = $this->postProcessResults($this->post_query, $results, $meta);
return $results;
} | php | public function execute() {
if(is_null($this->client)) {
$this->client = $this->getConnection();
}
if(is_null($this->query)) {
throw new Exception('No query');
}
list($query_data, $meta) = $this->constructQuery($this->source, $this->query, $this->aggs, $this->post_query, $this->settings);
$results_set = $this->query($query_data, $meta);
$results = $this->processResults($results_set, $meta);
$results = $this->postProcessResults($this->post_query, $results, $meta);
return $results;
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"client",
")",
")",
"{",
"$",
"this",
"->",
"client",
"=",
"$",
"this",
"->",
"getConnection",
"(",
")",
";",
"}",
"if",
"(",
"is_null",
"(",
"$",
"this... | Process the query and return the results. | [
"Process",
"the",
"query",
"and",
"return",
"the",
"results",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L86-L101 |
kiwiz/esquery | src/Result.php | Result.query | public function query($query_data, $meta) {
$result_set = [];
if($meta['scroll']) {
$query_data['scroll'] = '15s';
$response = $this->client->search($query_data);
$state = [];
do {
if(!array_key_exists('_scroll_id', $response)) {
throw new Exception('No scroll id');
}
$response = $this->client->scroll([
'scroll_id' => $response['_scroll_id'],
'scroll' => '15s'
]);
$result_set[] = $response;
} while(count($response['hits']['hits']) > 0);
$this->client->clearScroll(['scroll_id' => $response['_scroll_id']]);
} else {
$result_set[] = $this->client->search($query_data);
}
return $result_set;
} | php | public function query($query_data, $meta) {
$result_set = [];
if($meta['scroll']) {
$query_data['scroll'] = '15s';
$response = $this->client->search($query_data);
$state = [];
do {
if(!array_key_exists('_scroll_id', $response)) {
throw new Exception('No scroll id');
}
$response = $this->client->scroll([
'scroll_id' => $response['_scroll_id'],
'scroll' => '15s'
]);
$result_set[] = $response;
} while(count($response['hits']['hits']) > 0);
$this->client->clearScroll(['scroll_id' => $response['_scroll_id']]);
} else {
$result_set[] = $this->client->search($query_data);
}
return $result_set;
} | [
"public",
"function",
"query",
"(",
"$",
"query_data",
",",
"$",
"meta",
")",
"{",
"$",
"result_set",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"meta",
"[",
"'scroll'",
"]",
")",
"{",
"$",
"query_data",
"[",
"'scroll'",
"]",
"=",
"'15s'",
";",
"$",
"re... | Send the query off to Elasticsearch and get the raw results back. | [
"Send",
"the",
"query",
"off",
"to",
"Elasticsearch",
"and",
"get",
"the",
"raw",
"results",
"back",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L106-L132 |
kiwiz/esquery | src/Result.php | Result.jsonSerialize | public function jsonSerialize() {
list($query_data, $meta) = $this->constructQuery($this->source, $this->query, $this->aggs, $this->post_query, $this->settings);
return $query_data;
} | php | public function jsonSerialize() {
list($query_data, $meta) = $this->constructQuery($this->source, $this->query, $this->aggs, $this->post_query, $this->settings);
return $query_data;
} | [
"public",
"function",
"jsonSerialize",
"(",
")",
"{",
"list",
"(",
"$",
"query_data",
",",
"$",
"meta",
")",
"=",
"$",
"this",
"->",
"constructQuery",
"(",
"$",
"this",
"->",
"source",
",",
"$",
"this",
"->",
"query",
",",
"$",
"this",
"->",
"aggs",
... | Output the query as a json string. | [
"Output",
"the",
"query",
"as",
"a",
"json",
"string",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L137-L141 |
kiwiz/esquery | src/Result.php | Result.constructQuery | public function constructQuery($source, $query, $aggs, $post_query, $settings) {
$query_data = [
'ignore_unavailable' => true,
];
$query_body = [
'size' => 100,
];
$meta = [
'aggs' => [],
'flatten' => true,
'map' => [],
'scroll' => false,
'post_query' => false,
'count' => false,
];
$from = Util::get($settings, 'from', time());
$to = Util::get($settings, 'to', time());
$date_field = Util::get($settings, 'date_field');
// Construct filter query clauses.
$filter_data = $this->constructFilter($source, $query, $date_field, $from, $to);
if(!is_null($filter_data)) {
$query_body['query'] = [
'bool' => [
'filter' => $filter_data
]
];
}
// Set index.
if(Util::exists($settings, 'index')) {
$query_data['index'] = $settings['index'];
if(Util::get($settings, 'date_based', false)) {
$query_data['index'] = implode(',', Util::generateDateIndices($query_data['index'], Util::get($settings, 'date_interval'), $from, $to));
}
}
// Construct agg queries clauses.
$agg_data = $this->constructAggs($aggs);
// Construct setting data.
if(!is_null($agg_data)) {
$query_body['aggs'] = $agg_data;
// When executing an agg, we don't care about the actual hits.
$query_body['size'] = 0;
$meta['aggs'] = $aggs;
}
if(array_key_exists('count', $settings)) {
$meta['count'] = (bool) $settings['count'];
// Same thing if we want a count and have no aggs or post query.
if(is_null($post_query)) {
$query_body['size'] = 0;
}
}
if(array_key_exists('flatten', $settings)) {
$meta['flatten'] = (bool) $settings['flatten'];
}
if(array_key_exists('map', $settings)) {
$meta['map'] = (array) $settings['map'];
}
if(!is_null($post_query)) {
$meta['post_query'] = true;
}
// Determine whether to use a scroll query, which is more efficient.
/*
if(...) {
$meta['scroll'] = true;
}
*/
// Construct setting clauses.
$query_body = array_merge($query_body, $this->constructSettings($settings));
$query_data['body'] = $query_body;
return [$query_data, $meta];
} | php | public function constructQuery($source, $query, $aggs, $post_query, $settings) {
$query_data = [
'ignore_unavailable' => true,
];
$query_body = [
'size' => 100,
];
$meta = [
'aggs' => [],
'flatten' => true,
'map' => [],
'scroll' => false,
'post_query' => false,
'count' => false,
];
$from = Util::get($settings, 'from', time());
$to = Util::get($settings, 'to', time());
$date_field = Util::get($settings, 'date_field');
// Construct filter query clauses.
$filter_data = $this->constructFilter($source, $query, $date_field, $from, $to);
if(!is_null($filter_data)) {
$query_body['query'] = [
'bool' => [
'filter' => $filter_data
]
];
}
// Set index.
if(Util::exists($settings, 'index')) {
$query_data['index'] = $settings['index'];
if(Util::get($settings, 'date_based', false)) {
$query_data['index'] = implode(',', Util::generateDateIndices($query_data['index'], Util::get($settings, 'date_interval'), $from, $to));
}
}
// Construct agg queries clauses.
$agg_data = $this->constructAggs($aggs);
// Construct setting data.
if(!is_null($agg_data)) {
$query_body['aggs'] = $agg_data;
// When executing an agg, we don't care about the actual hits.
$query_body['size'] = 0;
$meta['aggs'] = $aggs;
}
if(array_key_exists('count', $settings)) {
$meta['count'] = (bool) $settings['count'];
// Same thing if we want a count and have no aggs or post query.
if(is_null($post_query)) {
$query_body['size'] = 0;
}
}
if(array_key_exists('flatten', $settings)) {
$meta['flatten'] = (bool) $settings['flatten'];
}
if(array_key_exists('map', $settings)) {
$meta['map'] = (array) $settings['map'];
}
if(!is_null($post_query)) {
$meta['post_query'] = true;
}
// Determine whether to use a scroll query, which is more efficient.
/*
if(...) {
$meta['scroll'] = true;
}
*/
// Construct setting clauses.
$query_body = array_merge($query_body, $this->constructSettings($settings));
$query_data['body'] = $query_body;
return [$query_data, $meta];
} | [
"public",
"function",
"constructQuery",
"(",
"$",
"source",
",",
"$",
"query",
",",
"$",
"aggs",
",",
"$",
"post_query",
",",
"$",
"settings",
")",
"{",
"$",
"query_data",
"=",
"[",
"'ignore_unavailable'",
"=>",
"true",
",",
"]",
";",
"$",
"query_body",
... | Construct the query portion of the request body. | [
"Construct",
"the",
"query",
"portion",
"of",
"the",
"request",
"body",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L146-L225 |
kiwiz/esquery | src/Result.php | Result.constructFilter | private function constructFilter($source, $query, $date_field, $from, $to) {
if(is_null($query)) {
return null;
}
if($query[0] !== Token::C_SEARCH && is_null($source)) {
throw new Exception('No source data for query');
}
// There are 2 types of queries. Process each one separately.
$filters = [];
switch($query[0]) {
case Token::C_SEARCH:
$filters = $query[1];
break;
case Token::C_JOIN:
$filters = $query[3];
$terms = [];
foreach($source as $row) {
$terms[] = [[$row[$query[1]]], true];
}
$filter = [Token::X_LIST, $query[2], $terms, false];
// AND the filter with the rest of the filters (if they exist).
if(count($filters)) {
$filters = [Token::F_AND, [$filters, $filter]];
} else {
$filters = $filter;
}
break;
default:
throw new Exception('Unexpected query type');
}
// Add time range filter.
if(!is_null($date_field)) {
$filter = [Token::F_RANGE, $date_field, true, false, $from, $to];
if(count($filters)) {
$filters = [Token::F_AND, [$filters, $filter]];
} else {
$filters = $filter;
}
}
return $this->constructFilterRecurse($filters);
} | php | private function constructFilter($source, $query, $date_field, $from, $to) {
if(is_null($query)) {
return null;
}
if($query[0] !== Token::C_SEARCH && is_null($source)) {
throw new Exception('No source data for query');
}
// There are 2 types of queries. Process each one separately.
$filters = [];
switch($query[0]) {
case Token::C_SEARCH:
$filters = $query[1];
break;
case Token::C_JOIN:
$filters = $query[3];
$terms = [];
foreach($source as $row) {
$terms[] = [[$row[$query[1]]], true];
}
$filter = [Token::X_LIST, $query[2], $terms, false];
// AND the filter with the rest of the filters (if they exist).
if(count($filters)) {
$filters = [Token::F_AND, [$filters, $filter]];
} else {
$filters = $filter;
}
break;
default:
throw new Exception('Unexpected query type');
}
// Add time range filter.
if(!is_null($date_field)) {
$filter = [Token::F_RANGE, $date_field, true, false, $from, $to];
if(count($filters)) {
$filters = [Token::F_AND, [$filters, $filter]];
} else {
$filters = $filter;
}
}
return $this->constructFilterRecurse($filters);
} | [
"private",
"function",
"constructFilter",
"(",
"$",
"source",
",",
"$",
"query",
",",
"$",
"date_field",
",",
"$",
"from",
",",
"$",
"to",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"query",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$... | Construct the filters within the query. | [
"Construct",
"the",
"filters",
"within",
"the",
"query",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L230-L274 |
kiwiz/esquery | src/Result.php | Result.constructSettings | private function constructSettings($settings) {
$ret = [];
if(array_key_exists('fields', $settings)) {
$ret['_source'] = ['include' => $settings['fields']];
}
if(array_key_exists('sort', $settings)) {
$ret['sort'] = array_map(function($x) { return [$x[0] => ['order' => $x[1] ? 'asc':'desc']]; }, $settings['sort']);
}
$valid_keys = ['size'];
foreach($valid_keys as $key) {
if(array_key_exists($key, $settings)) {
$ret[$key] = $settings[$key];
}
}
return $ret;
} | php | private function constructSettings($settings) {
$ret = [];
if(array_key_exists('fields', $settings)) {
$ret['_source'] = ['include' => $settings['fields']];
}
if(array_key_exists('sort', $settings)) {
$ret['sort'] = array_map(function($x) { return [$x[0] => ['order' => $x[1] ? 'asc':'desc']]; }, $settings['sort']);
}
$valid_keys = ['size'];
foreach($valid_keys as $key) {
if(array_key_exists($key, $settings)) {
$ret[$key] = $settings[$key];
}
}
return $ret;
} | [
"private",
"function",
"constructSettings",
"(",
"$",
"settings",
")",
"{",
"$",
"ret",
"=",
"[",
"]",
";",
"if",
"(",
"array_key_exists",
"(",
"'fields'",
",",
"$",
"settings",
")",
")",
"{",
"$",
"ret",
"[",
"'_source'",
"]",
"=",
"[",
"'include'",
... | Construct settings for the request body. | [
"Construct",
"settings",
"for",
"the",
"request",
"body",
"."
] | train | https://github.com/kiwiz/esquery/blob/ad05f8d18cb9f1227a82f8d0b9d270882865b31d/src/Result.php#L487-L506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.