code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
private function updateCollectionOffsets()
{
if (!empty($this->_children)) {
$this->startOffset = reset($this->_children)->startOffset;
$this->endOffset = end($this->_children)->endOffset;
}
if ($this->parent !== null) {
$this->parent->updateCollectionOffsets();
}
} | Updates token SQL code start and end offsets based on its children. | updateCollectionOffsets | php | yiisoft/yii2 | framework/db/SqlToken.php | https://github.com/yiisoft/yii2/blob/master/framework/db/SqlToken.php | BSD-3-Clause |
public function getDriverName()
{
if ($this->_driverName === null) {
if (($pos = strpos((string)$this->dsn, ':')) !== false) {
$this->_driverName = strtolower(substr($this->dsn, 0, $pos));
} else {
$this->_driverName = strtolower($this->getSlavePdo(true)->getAttribute(PDO::ATTR_DRIVER_NAME));
}
}
return $this->_driverName;
} | Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
by an end user.
@return string|null name of the DB driver | getDriverName | php | yiisoft/yii2 | framework/db/Connection.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Connection.php | BSD-3-Clause |
protected function normalizeOrderBy($columns)
{
if (empty($columns)) {
return [];
} elseif ($columns instanceof ExpressionInterface) {
return [$columns];
} elseif (is_array($columns)) {
return $columns;
}
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
$result = [];
foreach ($columns as $column) {
if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
$result[$matches[1]] = strcasecmp($matches[2], 'desc') ? SORT_ASC : SORT_DESC;
} else {
$result[$column] = SORT_ASC;
}
}
return $result;
} | Normalizes format of ORDER BY data.
@param array|string|ExpressionInterface|null $columns the columns value to normalize. See [[orderBy]] and [[addOrderBy]].
@return array | normalizeOrderBy | php | yiisoft/yii2 | framework/db/QueryTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/db/QueryTrait.php | BSD-3-Clause |
public function __construct($value, $type = null, $dimension = 1)
{
if ($value instanceof self) {
$value = $value->getValue();
}
$this->value = $value;
$this->type = $type;
$this->dimension = $dimension;
} | ArrayExpression constructor.
@param array|QueryInterface|mixed $value the array content. Either represented as an array of values or a Query that
returns these values. A single value will be considered as an array containing one element.
@param string|null $type the type of the array elements. Defaults to `null` which means the type is
not explicitly specified. In case when type is not specified explicitly and DBMS can not guess it from the context,
SQL error will be raised.
@param int $dimension the number of indices needed to select an element | __construct | php | yiisoft/yii2 | framework/db/ArrayExpression.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ArrayExpression.php | BSD-3-Clause |
public function offsetGet($offset)
{
return $this->value[$offset];
} | Offset to retrieve
@link https://www.php.net/manual/en/arrayaccess.offsetget.php
@param mixed $offset <p>
The offset to retrieve.
</p>
@return mixed Can return all value types.
@since 2.0.14 | offsetGet | php | yiisoft/yii2 | framework/db/ArrayExpression.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ArrayExpression.php | BSD-3-Clause |
public function offsetSet($offset, $value)
{
$this->value[$offset] = $value;
} | Offset to set
@link https://www.php.net/manual/en/arrayaccess.offsetset.php
@param mixed $offset <p>
The offset to assign the value to.
</p>
@param mixed $value <p>
The value to set.
</p>
@return void
@since 2.0.14 | offsetSet | php | yiisoft/yii2 | framework/db/ArrayExpression.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ArrayExpression.php | BSD-3-Clause |
public function offsetUnset($offset)
{
unset($this->value[$offset]);
} | Offset to unset
@link https://www.php.net/manual/en/arrayaccess.offsetunset.php
@param mixed $offset <p>
The offset to unset.
</p>
@return void
@since 2.0.14 | offsetUnset | php | yiisoft/yii2 | framework/db/ArrayExpression.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ArrayExpression.php | BSD-3-Clause |
public function getIterator()
{
$value = $this->getValue();
if ($value instanceof QueryInterface) {
throw new InvalidConfigException('The ArrayExpression class can not be iterated when the value is a QueryInterface object');
}
if ($value === null) {
$value = [];
}
return new \ArrayIterator($value);
} | Retrieve an external iterator
@link https://www.php.net/manual/en/iteratoraggregate.getiterator.php
@return Traversable An instance of an object implementing <b>Iterator</b> or
<b>Traversable</b>
@since 2.0.14.1
@throws InvalidConfigException when ArrayExpression contains QueryInterface object | getIterator | php | yiisoft/yii2 | framework/db/ArrayExpression.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ArrayExpression.php | BSD-3-Clause |
protected function buildDefaultValue()
{
if ($this->default === null) {
return $this->isNotNull === false ? 'NULL' : null;
}
switch (gettype($this->default)) {
case 'double':
// ensure type cast always has . as decimal separator in all locales
$defaultValue = StringHelper::floatToString($this->default);
break;
case 'boolean':
$defaultValue = $this->default ? 'TRUE' : 'FALSE';
break;
case 'integer':
case 'object':
$defaultValue = (string) $this->default;
break;
default:
$defaultValue = "'{$this->default}'";
}
return $defaultValue;
} | Return the default value for the column.
@return string|null string with default value of column. | buildDefaultValue | php | yiisoft/yii2 | framework/db/ColumnSchemaBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ColumnSchemaBuilder.php | BSD-3-Clause |
public function canSetOldAttribute($name)
{
return (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name));
} | Returns if the old named attribute can be set.
@param string $name the attribute name
@return bool whether the old attribute can be set
@see setOldAttribute() | canSetOldAttribute | php | yiisoft/yii2 | framework/db/BaseActiveRecord.php | https://github.com/yiisoft/yii2/blob/master/framework/db/BaseActiveRecord.php | BSD-3-Clause |
public function getViewNames($schema = '', $refresh = false)
{
if (!isset($this->_viewNames[$schema]) || $refresh) {
$this->_viewNames[$schema] = $this->findViewNames($schema);
}
return $this->_viewNames[$schema];
} | Returns all view names in the database.
@param string $schema the schema of the views. Defaults to empty string, meaning the current or default schema name.
If not empty, the returned view names will be prefixed with the schema name.
@param bool $refresh whether to fetch the latest available view names. If this is false,
view names fetched previously (if available) will be returned.
@return string[] all view names in the database. | getViewNames | php | yiisoft/yii2 | framework/db/ViewFinderTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ViewFinderTrait.php | BSD-3-Clause |
public function begin($isolationLevel = null)
{
if ($this->db === null) {
throw new InvalidConfigException('Transaction::db must be set.');
}
$this->db->open();
if ($this->_level === 0) {
if ($isolationLevel !== null) {
$this->db->getSchema()->setTransactionIsolationLevel($isolationLevel);
}
Yii::debug('Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : ''), __METHOD__);
$this->db->trigger(Connection::EVENT_BEGIN_TRANSACTION);
$this->db->pdo->beginTransaction();
$this->_level = 1;
return;
} | Begins a transaction.
@param string|null $isolationLevel The [isolation level][] to use for this transaction.
This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
If not specified (`null`) the isolation level will not be set explicitly and the DBMS default will be used.
> Note: This setting does not work for PostgreSQL, where setting the isolation level before the transaction
has no effect. You have to call [[setIsolationLevel()]] in this case after the transaction has started.
> Note: Some DBMS allow setting of the isolation level only for the whole connection so subsequent transactions
may get the same isolation level even if you did not specify any. When using this feature
you may need to set the isolation level for all transactions explicitly to avoid conflicting settings.
At the time of this writing affected DBMS are MSSQL and SQLite.
[isolation level]: https://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
Starting from version 2.0.16, this method throws exception when beginning nested transaction and underlying DBMS
does not support savepoints.
@throws InvalidConfigException if [[db]] is `null`
@throws NotSupportedException if the DBMS does not support nested transactions
@throws Exception if DB connection fails | begin | php | yiisoft/yii2 | framework/db/Transaction.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Transaction.php | BSD-3-Clause |
public function setIsolationLevel($level)
{
if (!$this->getIsActive()) {
throw new Exception('Failed to set isolation level: transaction was inactive.');
}
Yii::debug('Setting transaction isolation level to ' . $level, __METHOD__);
$this->db->getSchema()->setTransactionIsolationLevel($level);
} | Sets the transaction isolation level for this transaction.
This method can be used to set the isolation level while the transaction is already active.
However this is not supported by all DBMS so you might rather specify the isolation level directly
when calling [[begin()]].
@param string $level The transaction isolation level to use for this transaction.
This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
@throws Exception if the transaction is not active
@see https://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels | setIsolationLevel | php | yiisoft/yii2 | framework/db/Transaction.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Transaction.php | BSD-3-Clause |
public function createQueryBuilder()
{
return Yii::createObject(QueryBuilder::className(), [$this->db]);
} | Creates a query builder for the database.
This method may be overridden by child classes to create a DBMS-specific query builder.
@return QueryBuilder query builder instance | createQueryBuilder | php | yiisoft/yii2 | framework/db/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Schema.php | BSD-3-Clause |
public function createColumnSchemaBuilder($type, $length = null)
{
return Yii::createObject(ColumnSchemaBuilder::className(), [$type, $length]);
} | Create a column schema builder instance giving the type and value precision.
This method may be overridden by child classes to create a DBMS-specific column schema builder.
@param string $type type of the column. See [[ColumnSchemaBuilder::$type]].
@param int|string|array|null $length length or precision of the column. See [[ColumnSchemaBuilder::$length]].
@return ColumnSchemaBuilder column schema builder instance
@since 2.0.6 | createColumnSchemaBuilder | php | yiisoft/yii2 | framework/db/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/Schema.php | BSD-3-Clause |
public function findFor($name, $model)
{
if (method_exists($model, 'get' . $name)) {
$method = new \ReflectionMethod($model, 'get' . $name);
$realName = lcfirst(substr($method->getName(), 3));
if ($realName !== $name) {
throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
}
}
return $this->multiple ? $this->all() : $this->one();
} | Finds the related records for the specified primary record.
This method is invoked when a relation of an ActiveRecord is being accessed lazily.
@param string $name the relation name
@param ActiveRecordInterface|BaseActiveRecord $model the primary model
@return mixed the related record(s)
@throws InvalidArgumentException if the relation is invalid | findFor | php | yiisoft/yii2 | framework/db/ActiveRelationTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRelationTrait.php | BSD-3-Clause |
private function addInverseRelations(&$result)
{
if ($this->inverseOf === null) {
return;
}
foreach ($result as $i => $relatedModel) {
if ($relatedModel instanceof ActiveRecordInterface) {
if (!isset($inverseRelation)) {
$inverseRelation = $relatedModel->getRelation($this->inverseOf);
}
$relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel);
} else {
if (!isset($inverseRelation)) {
/* @var $modelClass ActiveRecordInterface */
$modelClass = $this->modelClass;
$inverseRelation = $modelClass::instance()->getRelation($this->inverseOf);
}
$result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel;
}
}
} | If applicable, populate the query's primary model into the related records' inverse relationship.
@param array $result the array of related records as generated by [[populate()]]
@since 2.0.9 | addInverseRelations | php | yiisoft/yii2 | framework/db/ActiveRelationTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRelationTrait.php | BSD-3-Clause |
private function indexBuckets($buckets, $indexBy)
{
$result = [];
foreach ($buckets as $key => $models) {
$result[$key] = [];
foreach ($models as $model) {
$index = is_string($indexBy) ? $model[$indexBy] : call_user_func($indexBy, $model);
$result[$key][$index] = $model;
}
}
return $result;
} | Indexes buckets by column name.
@param array $buckets
@param string|callable $indexBy the name of the column by which the query results should be indexed by.
This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
@return array | indexBuckets | php | yiisoft/yii2 | framework/db/ActiveRelationTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRelationTrait.php | BSD-3-Clause |
private function normalizeModelKey($value)
{
try {
return (string)$value;
} catch (\Exception $e) {
throw new InvalidConfigException('Value must be convertable to string.');
} catch (\Throwable $e) {
throw new InvalidConfigException('Value must be convertable to string.');
}
} | @param mixed $value raw key value. Since 2.0.40 non-string values must be convertible to string (like special
objects for cross-DBMS relations, for example: `|MongoId`).
@return string normalized key value. | normalizeModelKey | php | yiisoft/yii2 | framework/db/ActiveRelationTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRelationTrait.php | BSD-3-Clause |
public function parse($value)
{
if ($value === null) {
return null;
}
if ($value === '{}') {
return [];
}
return $this->parseArray($value);
} | Convert array from PostgreSQL to PHP
@param string $value string to be converted
@return array|null | parse | php | yiisoft/yii2 | framework/db/pgsql/ArrayParser.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/ArrayParser.php | BSD-3-Clause |
private function parseArray($value, &$i = 0)
{
$result = [];
$len = strlen($value);
for (++$i; $i < $len; ++$i) {
switch ($value[$i]) {
case '{':
$result[] = $this->parseArray($value, $i);
break;
case '}':
break 2;
case $this->delimiter:
if (empty($result)) { // `{}` case
$result[] = null;
}
if (in_array($value[$i + 1], [$this->delimiter, '}'], true)) { // `{,}` case
$result[] = null;
}
break;
default:
$result[] = $this->parseString($value, $i);
}
}
return $result;
} | Pares PgSQL array encoded in string
@param string $value
@param int $i parse starting position
@return array | parseArray | php | yiisoft/yii2 | framework/db/pgsql/ArrayParser.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/ArrayParser.php | BSD-3-Clause |
public function truncateTable($table)
{
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
} | Builds a SQL statement for truncating a DB table.
Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
@param string $table the table to be truncated. The name will be properly quoted by the method.
@return string the SQL statement for truncating a DB table. | truncateTable | php | yiisoft/yii2 | framework/db/pgsql/QueryBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/QueryBuilder.php | BSD-3-Clause |
public function alterColumn($table, $column, $type)
{
$columnName = $this->db->quoteColumnName($column);
$tableName = $this->db->quoteTableName($table);
// https://github.com/yiisoft/yii2/issues/4492
// https://www.postgresql.org/docs/9.1/sql-altertable.html
if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
}
$type = 'TYPE ' . $this->getColumnType($type);
$multiAlterStatement = [];
$constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
$type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
$multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
} else {
// safe to drop default even if there was none in the first place
$multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
}
$type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
if ($count) {
$multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
} else {
// remove additional null if any
$type = preg_replace('/\s+NULL/i', '', $type);
// safe to drop not null even if there was none in the first place
$multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
}
if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
$type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
$multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
}
$type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
if ($count) {
$multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
}
// add what's left at the beginning
array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
} | Builds a SQL statement for changing the definition of a column.
@param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
@param string $column the name of the column to be changed. The name will be properly quoted by the method.
@param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
@return string the SQL statement for changing the definition of a column. | alterColumn | php | yiisoft/yii2 | framework/db/pgsql/QueryBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/QueryBuilder.php | BSD-3-Clause |
private function normalizeTableRowData($table, $columns)
{
if ($columns instanceof Query) {
return $columns;
}
if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
foreach ($columns as $name => $value) {
if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
$columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column
}
}
}
return $columns;
} | Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
@param string $table the table that data will be saved into.
@param array|Query $columns the column data (name => value) to be saved into the table or instance
of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
@return array|Query normalized columns
@since 2.0.9 | normalizeTableRowData | php | yiisoft/yii2 | framework/db/pgsql/QueryBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/QueryBuilder.php | BSD-3-Clause |
protected function getUniqueIndexInformation($table)
{
$sql = <<<'SQL'
SELECT
i.relname as indexname,
pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
FROM (
SELECT *, generate_subscripts(indkey, 1) AS k
FROM pg_index
) idx
INNER JOIN pg_class i ON i.oid = idx.indexrelid
INNER JOIN pg_class c ON c.oid = idx.indrelid
INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
AND c.relname = :tableName AND ns.nspname = :schemaName
ORDER BY i.relname, k
SQL;
return $this->db->createCommand($sql, [
':schemaName' => $table->schemaName,
':tableName' => $table->name,
])->queryAll();
} | Gets information about given table unique indexes.
@param TableSchema $table the table metadata
@return array with index and column names | getUniqueIndexInformation | php | yiisoft/yii2 | framework/db/pgsql/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/Schema.php | BSD-3-Clause |
public function findUniqueIndexes($table)
{
$uniqueIndexes = [];
foreach ($this->getUniqueIndexInformation($table) as $row) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
$row = array_change_key_case($row, CASE_LOWER);
}
$column = $row['columnname'];
if (strncmp($column, '"', 1) === 0) {
// postgres will quote names that are not lowercase-only
// https://github.com/yiisoft/yii2/issues/10613
$column = substr($column, 1, -1);
}
$uniqueIndexes[$row['indexname']][] = $column;
}
return $uniqueIndexes;
} | Returns all unique indexes for the given table.
Each array element is of the following structure:
```php
[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]
```
@param TableSchema $table the table metadata
@return array all unique indexes for the given table. | findUniqueIndexes | php | yiisoft/yii2 | framework/db/pgsql/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/Schema.php | BSD-3-Clause |
public function build(ExpressionInterface $expression, array &$params = [])
{
$operator = $expression->getOperator();
$column = $expression->getColumn();
if (strpos($column, '(') === false) {
$column = $this->queryBuilder->db->quoteColumnName($column);
}
$phName1 = $this->createPlaceholder($expression->getIntervalStart(), $params);
$phName2 = $this->createPlaceholder($expression->getIntervalEnd(), $params);
return "$column $operator $phName1 AND $phName2";
} | Method builds the raw SQL from the $expression that will not be additionally
escaped or quoted.
@param ExpressionInterface|BetweenCondition $expression the expression to be built.
@param array $params the binding parameters.
@return string the raw SQL that will not be additionally escaped or quoted. | build | php | yiisoft/yii2 | framework/db/conditions/BetweenConditionBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/conditions/BetweenConditionBuilder.php | BSD-3-Clause |
public function __construct($value, $operator, $intervalStartColumn, $intervalEndColumn)
{
$this->value = $value;
$this->operator = $operator;
$this->intervalStartColumn = $intervalStartColumn;
$this->intervalEndColumn = $intervalEndColumn;
} | Creates a condition with the `BETWEEN` operator.
@param mixed the value to compare against
@param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
@param string|ExpressionInterface $intervalStartColumn the column name or expression that is a beginning of the interval
@param string|ExpressionInterface $intervalEndColumn the column name or expression that is an end of the interval | __construct | php | yiisoft/yii2 | framework/db/conditions/BetweenColumnsCondition.php | https://github.com/yiisoft/yii2/blob/master/framework/db/conditions/BetweenColumnsCondition.php | BSD-3-Clause |
public function defaultPhpTypecast($value)
{
if ($value !== null) {
// convert from MSSQL column_default format, e.g. ('1') -> 1, ('string') -> string
$value = substr(substr($value, 2), 0, -2);
}
return parent::phpTypecast($value);
} | Prepares default value and converts it according to [[phpType]]
@param mixed $value default value
@return mixed converted value
@since 2.0.24 | defaultPhpTypecast | php | yiisoft/yii2 | framework/db/mssql/ColumnSchema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/ColumnSchema.php | BSD-3-Clause |
public function lastInsertId($name = null)
{
return $this->query('SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS bigint)')->fetchColumn();
} | Returns value of the last inserted ID.
@param string|null $name the sequence name. Defaults to null.
@return int last inserted ID value. | lastInsertId | php | yiisoft/yii2 | framework/db/mssql/DBLibPDO.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/DBLibPDO.php | BSD-3-Clause |
public function getAttribute($attribute)
{
try {
return parent::getAttribute($attribute);
} catch (\PDOException $e) {
switch ($attribute) {
case self::ATTR_SERVER_VERSION:
return $this->query("SELECT CAST(SERVERPROPERTY('productversion') AS VARCHAR)")->fetchColumn();
default:
throw $e;
}
}
} | Retrieve a database connection attribute.
It is necessary to override PDO's method as some MSSQL PDO driver (e.g. dblib) does not
support getting attributes.
@param int $attribute One of the PDO::ATTR_* constants.
@return mixed A successful call returns the value of the requested PDO attribute.
An unsuccessful call returns null. | getAttribute | php | yiisoft/yii2 | framework/db/mssql/DBLibPDO.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/DBLibPDO.php | BSD-3-Clause |
public function setAlterColumnFormat()
{
$this->format = '{type}{length}{notnull}{append}';
} | Changes default format string to MSSQL ALTER COMMAND. | setAlterColumnFormat | php | yiisoft/yii2 | framework/db/mssql/ColumnSchemaBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/ColumnSchemaBuilder.php | BSD-3-Clause |
public function getDefaultValue()
{
if ($this->default instanceof Expression) {
return $this->default;
}
return $this->buildDefaultValue();
} | Getting the `Default` value for constraint
@return string|Expression|null default value of the column. | getDefaultValue | php | yiisoft/yii2 | framework/db/mssql/ColumnSchemaBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/ColumnSchemaBuilder.php | BSD-3-Clause |
public function getCheckValue()
{
return $this->check !== null ? (string) $this->check : null;
} | Get the `Check` value for constraint
@return string|null the `CHECK` constraint for the column. | getCheckValue | php | yiisoft/yii2 | framework/db/mssql/ColumnSchemaBuilder.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/ColumnSchemaBuilder.php | BSD-3-Clause |
protected function findTableConstraints($table, $type)
{
$keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
$tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
if ($table->catalogName !== null) {
$keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
$tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
}
$keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
$tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
$sql = <<<SQL
SELECT
[kcu].[constraint_name] AS [index_name],
[kcu].[column_name] AS [field_name]
FROM {$keyColumnUsageTableName} AS [kcu]
LEFT JOIN {$tableConstraintsTableName} AS [tc] ON
[kcu].[table_schema] = [tc].[table_schema] AND
[kcu].[table_name] = [tc].[table_name] AND
[kcu].[constraint_name] = [tc].[constraint_name]
WHERE
[tc].[constraint_type] = :type AND
[kcu].[table_name] = :tableName AND
[kcu].[table_schema] = :schemaName
SQL;
return $this->db
->createCommand($sql, [
':tableName' => $table->name,
':schemaName' => $table->schemaName,
':type' => $type,
])
->queryAll();
} | Collects the constraint details for the given table and constraint type.
@param TableSchema $table
@param string $type either PRIMARY KEY or UNIQUE
@return array each entry contains index_name and field_name
@since 2.0.4 | findTableConstraints | php | yiisoft/yii2 | framework/db/mssql/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/Schema.php | BSD-3-Clause |
protected function findPrimaryKeys($table)
{
$result = [];
foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
$result[] = $row['field_name'];
}
$table->primaryKey = $result;
} | Collects the primary key column details for the given table.
@param TableSchema $table the table metadata | findPrimaryKeys | php | yiisoft/yii2 | framework/db/mssql/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/Schema.php | BSD-3-Clause |
protected function findForeignKeys($table)
{
$object = $table->name;
if ($table->schemaName !== null) {
$object = $table->schemaName . '.' . $object;
}
if ($table->catalogName !== null) {
$object = $table->catalogName . '.' . $object;
}
// please refer to the following page for more details:
// http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
$sql = <<<'SQL'
SELECT
[fk].[name] AS [fk_name],
[cp].[name] AS [fk_column_name],
OBJECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
[cr].[name] AS [uq_column_name]
FROM
[sys].[foreign_keys] AS [fk]
INNER JOIN [sys].[foreign_key_columns] AS [fkc] ON
[fk].[object_id] = [fkc].[constraint_object_id]
INNER JOIN [sys].[columns] AS [cp] ON
[fk].[parent_object_id] = [cp].[object_id] AND
[fkc].[parent_column_id] = [cp].[column_id]
INNER JOIN [sys].[columns] AS [cr] ON
[fk].[referenced_object_id] = [cr].[object_id] AND
[fkc].[referenced_column_id] = [cr].[column_id]
WHERE
[fk].[parent_object_id] = OBJECT_ID(:object)
SQL;
$rows = $this->db->createCommand($sql, [
':object' => $object,
])->queryAll();
$table->foreignKeys = [];
foreach ($rows as $row) {
if (!isset($table->foreignKeys[$row['fk_name']])) {
$table->foreignKeys[$row['fk_name']][] = $row['uq_table_name'];
}
$table->foreignKeys[$row['fk_name']][$row['fk_column_name']] = $row['uq_column_name'];
}
} | Collects the foreign key column details for the given table.
@param TableSchema $table the table metadata | findForeignKeys | php | yiisoft/yii2 | framework/db/mssql/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/Schema.php | BSD-3-Clause |
public function findUniqueIndexes($table)
{
$result = [];
foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
$result[$row['index_name']][] = $row['field_name'];
}
return $result;
} | Returns all unique indexes for the given table.
Each array element is of the following structure:
```php
[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]
```
@param TableSchema $table the table metadata
@return array all unique indexes for the given table.
@since 2.0.4 | findUniqueIndexes | php | yiisoft/yii2 | framework/db/mssql/Schema.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/Schema.php | BSD-3-Clause |
public function lastInsertId($sequence = null)
{
return $this->query('SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS bigint)')->fetchColumn();
} | Returns value of the last inserted ID.
@param string|null $sequence the sequence name. Defaults to null.
@return int last inserted ID value. | lastInsertId | php | yiisoft/yii2 | framework/db/mssql/PDO.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/PDO.php | BSD-3-Clause |
public function beginTransaction()
{
$this->exec('BEGIN TRANSACTION');
return true;
} | Starts a transaction. It is necessary to override PDO's method as MSSQL PDO driver does not
natively support transactions.
@return bool the result of a transaction start. | beginTransaction | php | yiisoft/yii2 | framework/db/mssql/PDO.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/PDO.php | BSD-3-Clause |
public function commit()
{
$this->exec('COMMIT TRANSACTION');
return true;
} | Commits a transaction. It is necessary to override PDO's method as MSSQL PDO driver does not
natively support transactions.
@return bool the result of a transaction commit. | commit | php | yiisoft/yii2 | framework/db/mssql/PDO.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/PDO.php | BSD-3-Clause |
public function rollBack()
{
$this->exec('ROLLBACK TRANSACTION');
return true;
} | Rollbacks a transaction. It is necessary to override PDO's method as MSSQL PDO driver does not
natively support transactions.
@return bool the result of a transaction roll back. | rollBack | php | yiisoft/yii2 | framework/db/mssql/PDO.php | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/PDO.php | BSD-3-Clause |
private function defineAttributesByValidator($validator)
{
foreach ($validator->getAttributeNames() as $attribute) {
if (!$this->hasAttribute($attribute)) {
$this->defineAttribute($attribute);
}
}
} | Define the attributes that applies to the specified Validator.
@param Validator $validator the validator whose attributes are to be defined. | defineAttributesByValidator | php | yiisoft/yii2 | framework/base/DynamicModel.php | https://github.com/yiisoft/yii2/blob/master/framework/base/DynamicModel.php | BSD-3-Clause |
public function getUrl($url)
{
if (($baseUrl = $this->getBaseUrl()) !== null) {
return $baseUrl . '/' . ltrim($url, '/');
}
throw new InvalidConfigException('The "baseUrl" property must be set.');
} | Converts a relative URL into an absolute URL using [[baseUrl]].
@param string $url the relative URL to be converted.
@return string the absolute URL
@throws InvalidConfigException if [[baseUrl]] is not set | getUrl | php | yiisoft/yii2 | framework/base/Theme.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Theme.php | BSD-3-Clause |
public function getPath($path)
{
if (($basePath = $this->getBasePath()) !== null) {
return $basePath . DIRECTORY_SEPARATOR . ltrim($path, '/\\');
}
throw new InvalidConfigException('The "basePath" property must be set.');
} | Converts a relative file path into an absolute one using [[basePath]].
@param string $path the relative file path to be converted.
@return string the absolute file path
@throws InvalidConfigException if [[basePath]] is not set | getPath | php | yiisoft/yii2 | framework/base/Theme.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Theme.php | BSD-3-Clause |
public function offsetExists($offset)
{
return isset($this->data[$offset]);
} | This method is required by the interface [[\ArrayAccess]].
@param mixed $offset the offset to check on
@return bool | offsetExists | php | yiisoft/yii2 | framework/base/ArrayAccessTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ArrayAccessTrait.php | BSD-3-Clause |
public function offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
} | This method is required by the interface [[\ArrayAccess]].
@param int $offset the offset to retrieve element.
@return mixed the element at the offset, null if no element is found at the offset | offsetGet | php | yiisoft/yii2 | framework/base/ArrayAccessTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ArrayAccessTrait.php | BSD-3-Clause |
public function offsetSet($offset, $item)
{
$this->data[$offset] = $item;
} | This method is required by the interface [[\ArrayAccess]].
@param int $offset the offset to set element
@param mixed $item the element value | offsetSet | php | yiisoft/yii2 | framework/base/ArrayAccessTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ArrayAccessTrait.php | BSD-3-Clause |
public function setControllerPath($path)
{
$this->_controllerPath = Yii::getAlias($path);
} | Sets the directory that contains the controller classes.
@param string $path the root directory that contains the controller classes.
@throws InvalidArgumentException if the directory is invalid.
@since 2.0.44 | setControllerPath | php | yiisoft/yii2 | framework/base/Module.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Module.php | BSD-3-Clause |
public function offsetSet($offset, $value)
{
$this->$offset = $value;
} | Sets the element at the specified offset.
This method is required by the SPL interface [[\ArrayAccess]].
It is implicitly called when you use something like `$model[$offset] = $value;`.
@param string $offset the offset to set element
@param mixed $value the element value | offsetSet | php | yiisoft/yii2 | framework/base/Model.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Model.php | BSD-3-Clause |
public function unregister()
{
if ($this->_registered) {
$this->_memoryReserve = null;
$this->_workingDirectory = null;
restore_error_handler();
restore_exception_handler();
$this->_registered = false;
}
} | Unregisters this error handler by restoring the PHP error and exception handlers.
@since 2.0.32 this will not do anything if the error handler was not registered | unregister | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public function handleException($exception)
{
if ($exception instanceof ExitException) {
return;
}
$this->exception = $exception;
// disable error capturing to avoid recursive errors while handling exceptions
$this->unregister();
// set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
// HTTP exceptions will override this value in renderException()
if (PHP_SAPI !== 'cli') {
http_response_code(500);
}
try {
$this->logException($exception);
if ($this->discardExistingOutput) {
$this->clearOutput();
}
$this->renderException($exception);
if (!$this->silentExitOnException) {
\Yii::getLogger()->flush(true);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
}
} catch (\Exception $e) {
// an other exception could be thrown while displaying the exception
$this->handleFallbackExceptionMessage($e, $exception);
} catch (\Throwable $e) {
// additional check for \Throwable introduced in PHP 7
$this->handleFallbackExceptionMessage($e, $exception);
}
$this->exception = null;
} | Handles uncaught PHP exceptions.
This method is implemented as a PHP exception handler.
@param \Throwable $exception the exception that is not caught | handleException | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
protected function handleFallbackExceptionMessage($exception, $previousException)
{
$msg = "An Error occurred while handling another error:\n";
$msg .= (string) $exception;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $previousException;
if (YII_DEBUG) {
if (PHP_SAPI === 'cli') {
echo $msg . "\n";
} else {
echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
}
$msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
} else {
echo 'An internal server error occurred.';
}
error_log($msg);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
} | Handles exception thrown during exception processing in [[handleException()]].
@param \Throwable $exception Exception that was thrown during main exception processing.
@param \Throwable $previousException Main exception processed in [[handleException()]].
@since 2.0.11 | handleFallbackExceptionMessage | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
{
if ($this->handleError($code, $message, $file, $line)) {
return true;
}
if (E_ERROR & $code) {
$exception = new ErrorException($message, $code, $code, $file, $line);
$ref = new \ReflectionProperty('\Exception', 'trace');
$ref->setAccessible(true);
$ref->setValue($exception, $backtrace);
$this->_hhvmException = $exception;
}
return false;
} | Handles HHVM execution errors such as warnings and notices.
This method is used as a HHVM error handler. It will store exception that will
be used in fatal error handler
@param int $code the level of the error raised.
@param string $message the error message.
@param string $file the filename that the error was raised in.
@param int $line the line number the error was raised at.
@param mixed $context
@param mixed $backtrace trace of error
@return bool whether the normal error handler continues.
@throws ErrorException
@since 2.0.6 | handleHhvmError | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public function handleError($code, $message, $file, $line)
{
if (error_reporting() & $code) {
// load ErrorException manually here because autoloading them will not work
// when error occurs while autoloading a class
if (!class_exists('yii\\base\\ErrorException', false)) {
require_once __DIR__ . '/ErrorException.php';
}
$exception = new ErrorException($message, $code, $code, $file, $line);
if (PHP_VERSION_ID < 70400) {
// prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
array_shift($trace);
foreach ($trace as $frame) {
if ($frame['function'] === '__toString') {
$this->handleException($exception);
if (defined('HHVM_VERSION')) {
flush();
}
exit(1);
}
}
}
throw $exception;
}
return false;
} | Handles PHP execution errors such as warnings and notices.
This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
@param int $code the level of the error raised.
@param string $message the error message.
@param string $file the filename that the error was raised in.
@param int $line the line number the error was raised at.
@return bool whether the normal error handler continues.
@throws ErrorException | handleError | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public function clearOutput()
{
// the following manual level counting is to deal with zlib.output_compression set to On
for ($level = ob_get_level(); $level > 0; --$level) {
if (!@ob_end_clean()) {
ob_clean();
}
}
} | Removes all output echoed before calling this method. | clearOutput | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public static function convertExceptionToError($exception)
{
trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
} | Converts an exception into a PHP error.
This method can be used to convert exceptions inside of methods like `__toString()`
to PHP errors because exceptions cannot be thrown inside of them.
@param \Throwable $exception the exception to convert to a PHP error.
@return never | convertExceptionToError | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public static function convertExceptionToString($exception)
{
if ($exception instanceof UserException) {
return "{$exception->getName()}: {$exception->getMessage()}";
}
if (YII_DEBUG) {
return static::convertExceptionToVerboseString($exception);
}
return 'An internal server error occurred.';
} | Converts an exception into a simple string.
@param \Throwable $exception the exception being converted
@return string the string representation of the exception. | convertExceptionToString | php | yiisoft/yii2 | framework/base/ErrorHandler.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php | BSD-3-Clause |
public function getIsConsoleRequest()
{
return $this->_isConsoleRequest !== null ? $this->_isConsoleRequest : PHP_SAPI === 'cli';
} | Returns a value indicating whether the current request is made via command line.
@return bool the value indicating whether the current request is made via console | getIsConsoleRequest | php | yiisoft/yii2 | framework/base/Request.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Request.php | BSD-3-Clause |
public function setIsConsoleRequest($value)
{
$this->_isConsoleRequest = $value;
} | Sets the value indicating whether the current request is made via command line.
@param bool $value the value indicating whether the current request is made via command line | setIsConsoleRequest | php | yiisoft/yii2 | framework/base/Request.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Request.php | BSD-3-Clause |
public function getScriptFile()
{
if ($this->_scriptFile === null) {
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$this->setScriptFile($_SERVER['SCRIPT_FILENAME']);
} else {
throw new InvalidConfigException('Unable to determine the entry script file path.');
}
}
return $this->_scriptFile;
} | Returns entry script file path.
@return string entry script file path (processed w/ realpath())
@throws InvalidConfigException if the entry script file path cannot be determined automatically. | getScriptFile | php | yiisoft/yii2 | framework/base/Request.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Request.php | BSD-3-Clause |
public function setScriptFile($value)
{
$scriptFile = realpath(Yii::getAlias($value));
if ($scriptFile !== false && is_file($scriptFile)) {
$this->_scriptFile = $scriptFile;
} else {
throw new InvalidConfigException('Unable to determine the entry script file path.');
}
} | Sets the entry script file path.
The entry script file path can normally be determined based on the `SCRIPT_FILENAME` SERVER variable.
However, for some server configurations, this may not be correct or feasible.
This setter is provided so that the entry script file path can be manually specified.
@param string $value the entry script file path. This can be either a file path or a [path alias](guide:concept-aliases).
@throws InvalidConfigException if the provided entry script file path is invalid. | setScriptFile | php | yiisoft/yii2 | framework/base/Request.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Request.php | BSD-3-Clause |
private function isXdebugStackAvailable()
{
if (!function_exists('xdebug_get_function_stack')) {
return false;
}
// check for Xdebug being installed to ensure origin of xdebug_get_function_stack()
$version = phpversion('xdebug');
if ($version === false) {
return false;
}
// Xdebug 2 and prior
if (version_compare($version, '3.0.0', '<')) {
return true;
}
// Xdebug 3 and later, proper mode is required
return false !== strpos(ini_get('xdebug.mode'), 'develop');
} | Ensures that Xdebug stack trace is available based on Xdebug version.
Idea taken from developer bishopb at https://github.com/rollbar/rollbar-php
@return bool | isXdebugStackAvailable | php | yiisoft/yii2 | framework/base/ErrorException.php | https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorException.php | BSD-3-Clause |
public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
{
if (function_exists('hash_hkdf')) {
$outputKey = hash_hkdf((string)$algo, (string)$inputKey, $length, (string)$info, (string)$salt);
if ($outputKey === false) {
throw new InvalidArgumentException('Invalid parameters to hash_hkdf()');
}
return $outputKey;
}
$test = @hash_hmac($algo, '', '', true);
if (!$test) {
throw new InvalidArgumentException('Failed to generate HMAC with hash algorithm: ' . $algo);
}
$hashLength = StringHelper::byteLength($test);
if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
$length = (int) $length;
}
if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) {
throw new InvalidArgumentException('Invalid length');
}
$blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
if ($salt === null) {
$salt = str_repeat("\0", $hashLength);
}
$prKey = hash_hmac($algo, $inputKey, $salt, true);
$hmac = '';
$outputKey = '';
for ($i = 1; $i <= $blocks; $i++) {
$hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
$outputKey .= $hmac;
}
if ($length !== 0) {
$outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
}
return $outputKey;
} | Derives a key from the given input key using the standard HKDF algorithm.
Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869).
Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
@param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
@param string $inputKey the source key
@param string|null $salt the random salt
@param string|null $info optional info to bind the derived key material to application-
and context-specific information, e.g. a user ID or API version, see
[RFC 5869](https://tools.ietf.org/html/rfc5869)
@param int $length length of the output key in bytes. If 0, the output key is
the length of the hash algorithm output.
@throws InvalidArgumentException when HMAC generation fails.
@return string the derived key | hkdf | php | yiisoft/yii2 | framework/base/Security.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Security.php | BSD-3-Clause |
public static function instance($refresh = false)
{
$className = get_called_class();
if ($refresh || !isset(self::$_instances[$className])) {
self::$_instances[$className] = Yii::createObject($className);
}
return self::$_instances[$className];
} | Returns static class instance, which can be used to obtain meta information.
@param bool $refresh whether to re-create static instance even, if it is already cached.
@return static class instance. | instance | php | yiisoft/yii2 | framework/base/StaticInstanceTrait.php | https://github.com/yiisoft/yii2/blob/master/framework/base/StaticInstanceTrait.php | BSD-3-Clause |
public static function begin($config = [])
{
$config['class'] = get_called_class();
/* @var $widget Widget */
$widget = Yii::createObject($config);
self::$stack[] = $widget;
self::$_resolvedClasses[get_called_class()] = get_class($widget);
return $widget;
} | Begins a widget.
This method creates an instance of the calling class. It will apply the configuration
to the created instance. A matching [[end()]] call should be called later.
As some widgets may use output buffering, the [[end()]] call should be made in the same view
to avoid breaking the nesting of output buffers.
@param array $config name-value pairs that will be used to initialize the object properties
@return static the newly created widget instance
@see end() | begin | php | yiisoft/yii2 | framework/base/Widget.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Widget.php | BSD-3-Clause |
public static function end()
{
if (!empty(self::$stack)) {
$widget = array_pop(self::$stack);
$calledClass = self::$_resolvedClasses[get_called_class()] ?? get_called_class();
if (get_class($widget) === $calledClass) {
/* @var $widget Widget */
if ($widget->beforeRun()) {
$result = $widget->run();
$result = $widget->afterRun($result);
echo $result;
}
return $widget;
}
throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
}
throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
} | Ends a widget.
Note that the rendering result of the widget is directly echoed out.
@return static the widget instance that is ended.
@throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
@see begin() | end | php | yiisoft/yii2 | framework/base/Widget.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Widget.php | BSD-3-Clause |
public static function widget($config = [])
{
ob_start();
ob_implicit_flush(false);
try {
/* @var $widget Widget */
$config['class'] = get_called_class();
$widget = Yii::createObject($config);
$out = '';
if ($widget->beforeRun()) {
$result = $widget->run();
$out = $widget->afterRun($result);
}
} catch (\Exception $e) {
// close the output buffer opened above if it has not been closed already
if (ob_get_level() > 0) {
ob_end_clean();
}
throw $e;
} catch (\Throwable $e) {
// close the output buffer opened above if it has not been closed already
if (ob_get_level() > 0) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean() . $out;
} | Creates a widget instance and runs it.
The widget rendering result is returned by this method.
@param array $config name-value pairs that will be used to initialize the object properties
@return string the rendering result of the widget.
@throws \Throwable | widget | php | yiisoft/yii2 | framework/base/Widget.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Widget.php | BSD-3-Clause |
public function getViewPath()
{
$class = new ReflectionClass($this);
return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
} | Returns the directory containing the view files for this widget.
The default implementation returns the 'views' subdirectory under the directory containing the widget class file.
@return string the directory containing the view files for this widget. | getViewPath | php | yiisoft/yii2 | framework/base/Widget.php | https://github.com/yiisoft/yii2/blob/master/framework/base/Widget.php | BSD-3-Clause |
protected function getRequestedFields()
{
$fields = $this->request->get($this->fieldsParam);
$expand = $this->request->get($this->expandParam);
return [
is_string($fields) ? preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY) : [],
is_string($expand) ? preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY) : [],
];
} | @return array the names of the requested fields. The first element is an array
representing the list of default fields requested, while the second element is
an array of the extra fields requested in addition to the default fields.
@see Model::fields()
@see Model::extraFields() | getRequestedFields | php | yiisoft/yii2 | framework/rest/Serializer.php | https://github.com/yiisoft/yii2/blob/master/framework/rest/Serializer.php | BSD-3-Clause |
protected function serializePagination($pagination)
{
return [
$this->linksEnvelope => Link::serialize($pagination->getLinks(true)),
$this->metaEnvelope => [
'totalCount' => $pagination->totalCount,
'pageCount' => $pagination->getPageCount(),
'currentPage' => $pagination->getPage() + 1,
'perPage' => $pagination->getPageSize(),
],
];
} | Serializes a pagination into an array.
@param Pagination $pagination
@return array the array representation of the pagination
@see addPaginationHeaders() | serializePagination | php | yiisoft/yii2 | framework/rest/Serializer.php | https://github.com/yiisoft/yii2/blob/master/framework/rest/Serializer.php | BSD-3-Clause |
protected function addPaginationHeaders($pagination)
{
$links = [];
foreach ($pagination->getLinks(true) as $rel => $url) {
$links[] = "<$url>; rel=$rel";
}
$this->response->getHeaders()
->set($this->totalCountHeader, $pagination->totalCount)
->set($this->pageCountHeader, $pagination->getPageCount())
->set($this->currentPageHeader, $pagination->getPage() + 1)
->set($this->perPageHeader, $pagination->pageSize)
->set('Link', implode(', ', $links));
} | Adds HTTP headers about the pagination to the response.
@param Pagination $pagination | addPaginationHeaders | php | yiisoft/yii2 | framework/rest/Serializer.php | https://github.com/yiisoft/yii2/blob/master/framework/rest/Serializer.php | BSD-3-Clause |
protected function serializeModelErrors($model)
{
$this->response->setStatusCode(422, 'Data Validation Failed.');
$result = [];
foreach ($model->getFirstErrors() as $name => $message) {
$result[] = [
'field' => $name,
'message' => $message,
];
}
return $result;
} | Serializes the validation errors in a model.
@param Model $model
@return array the array representation of the errors | serializeModelErrors | php | yiisoft/yii2 | framework/rest/Serializer.php | https://github.com/yiisoft/yii2/blob/master/framework/rest/Serializer.php | BSD-3-Clause |
protected function createRule($pattern, $prefix, $action)
{
$verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
$verbs = explode(',', $matches[1]);
$pattern = isset($matches[4]) ? $matches[4] : '';
} else {
$verbs = [];
}
$config = $this->ruleConfig;
$config['verb'] = $verbs;
$config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
$config['route'] = $action;
$config['suffix'] = $this->suffix;
return Yii::createObject($config);
} | Creates a URL rule using the given pattern and action.
@param string $pattern
@param string $prefix
@param string $action
@return UrlRuleInterface | createRule | php | yiisoft/yii2 | framework/rest/UrlRule.php | https://github.com/yiisoft/yii2/blob/master/framework/rest/UrlRule.php | BSD-3-Clause |
public function isColorEnabled($stream = \STDOUT)
{
return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
} | Returns a value indicating whether ANSI color is enabled.
ANSI color is enabled only if [[color]] is set true or is not set
and the terminal supports ANSI color.
@param resource $stream the stream to check.
@return bool Whether to enable ANSI style in output. | isColorEnabled | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function select($prompt, $options = [], $default = null)
{
if ($this->interactive) {
return Console::select($prompt, $options, $default);
}
return $default;
} | Gives the user an option to choose from. Giving '?' as an input will show
a list of options to choose from and their explanations.
@param string $prompt the prompt message
@param array $options Key-value array of options to choose from
@param string|null $default value to use when the user doesn't provide an option.
If the default is `null`, the user is required to select an option.
@return string An option character the user chose
@since 2.0.49 Added the $default argument | select | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function options($actionID)
{
// $actionId might be used in subclasses to provide options specific to action id
return ['color', 'interactive', 'help', 'silentExitOnException'];
} | Returns the names of valid options for the action (id)
An option requires the existence of a public member variable whose
name is the option name.
Child classes may override this method to specify possible options.
Note that the values setting via options are not available
until [[beforeAction()]] is being called.
@param string $actionID the action id of the current request
@return string[] the names of the options valid for the action | options | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function optionAliases()
{
return [
'h' => 'help',
];
} | Returns option alias names.
Child classes may override this method to specify alias options.
@return array the options alias names valid for the action
where the keys is alias name for option and value is option name.
@since 2.0.8
@see options() | optionAliases | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getOptionValues($actionID)
{
// $actionId might be used in subclasses to provide properties specific to action id
$properties = [];
foreach ($this->options($this->action->id) as $property) {
$properties[$property] = $this->$property;
}
return $properties;
} | Returns properties corresponding to the options for the action id
Child classes may override this method to specify possible properties.
@param string $actionID the action id of the current request
@return array properties corresponding to the options for the action | getOptionValues | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getPassedOptions()
{
return $this->_passedOptions;
} | Returns the names of valid options passed during execution.
@return array the names of the options passed during execution | getPassedOptions | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getPassedOptionValues()
{
$properties = [];
foreach ($this->_passedOptions as $property) {
$properties[$property] = $this->$property;
}
return $properties;
} | Returns the properties corresponding to the passed options.
@return array the properties corresponding to the passed options | getPassedOptionValues | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getHelpSummary()
{
return $this->parseDocCommentSummary(new \ReflectionClass($this));
} | Returns one-line short summary describing this controller.
You may override this method to return customized summary.
The default implementation returns first line from the PHPDoc comment.
@return string | getHelpSummary | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getHelp()
{
return $this->parseDocCommentDetail(new \ReflectionClass($this));
} | Returns help information for this controller.
You may override this method to return customized help.
The default implementation returns help information retrieved from the PHPDoc comment.
@return string | getHelp | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getActionHelpSummary($action)
{
if ($action === null) {
return $this->ansiFormat(Yii::t('yii', 'Action not found.'), Console::FG_RED);
}
return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
} | Returns a one-line short summary describing the specified action.
@param Action $action action to get summary for
@return string a one-line short summary describing the specified action. | getActionHelpSummary | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function getActionHelp($action)
{
return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
} | Returns the detailed help information for the specified action.
@param Action $action action to get help for
@return string the detailed help information for the specified action. | getActionHelp | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
protected function parseDocCommentSummary($reflection)
{
$docLines = preg_split('~\R~u', $reflection->getDocComment());
if (isset($docLines[1])) {
return trim($docLines[1], "\t *");
}
return '';
} | Returns the first line of docblock.
@param \ReflectionClass|\ReflectionProperty|\ReflectionFunctionAbstract $reflection
@return string | parseDocCommentSummary | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
protected function parseDocCommentDetail($reflection)
{
$comment = strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
$comment = trim(substr($comment, 0, $matches[0][1]));
}
if ($comment !== '') {
return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
}
return '';
} | Returns full description from the docblock.
@param \ReflectionClass|\ReflectionProperty|\ReflectionFunctionAbstract $reflection
@return string | parseDocCommentDetail | php | yiisoft/yii2 | framework/console/Controller.php | https://github.com/yiisoft/yii2/blob/master/framework/console/Controller.php | BSD-3-Clause |
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
$this->db = Instance::ensure($this->db, Connection::className());
return true;
}
return false;
} | This method is invoked right before an action is to be executed (after all possible filters.)
It checks the existence of the [[migrationPath]].
@param \yii\base\Action $action the action to be executed.
@return bool whether the action should continue to be executed. | beforeAction | php | yiisoft/yii2 | framework/console/controllers/MigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/MigrateController.php | BSD-3-Clause |
protected function createMigration($class)
{
$this->includeMigrationFile($class);
return Yii::createObject([
'class' => $class,
'db' => $this->db,
'compact' => $this->compact,
]);
} | Creates a new migration instance.
@param string $class the migration class name
@return \yii\db\Migration the migration instance | createMigration | php | yiisoft/yii2 | framework/console/controllers/MigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/MigrateController.php | BSD-3-Clause |
protected function createMigrationHistoryTable()
{
$tableName = $this->db->schema->getRawTableName($this->migrationTable);
$this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
$this->db->createCommand()->createTable($this->migrationTable, [
'version' => 'varchar(' . static::MAX_NAME_LENGTH . ') NOT NULL PRIMARY KEY',
'apply_time' => 'integer',
])->execute();
$this->db->createCommand()->insert($this->migrationTable, [
'version' => self::BASE_MIGRATION,
'apply_time' => time(),
])->execute();
$this->stdout("Done.\n", Console::FG_GREEN);
} | Creates the migration history table. | createMigrationHistoryTable | php | yiisoft/yii2 | framework/console/controllers/MigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/MigrateController.php | BSD-3-Clause |
private function isViewRelated($errorMessage)
{
$dropViewErrors = [
'DROP VIEW to delete view', // SQLite
'SQLSTATE[42S02]', // MySQL
'is a view. Use DROP VIEW', // Microsoft SQL Server
];
foreach ($dropViewErrors as $dropViewError) {
if (strpos($errorMessage, $dropViewError) !== false) {
return true;
}
}
return false;
} | Determines whether the error message is related to deleting a view or not
@param string $errorMessage
@return bool | isViewRelated | php | yiisoft/yii2 | framework/console/controllers/MigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/MigrateController.php | BSD-3-Clause |
private function normalizeTableName($name)
{
if (substr($name, -1) === '_') {
$name = substr($name, 0, -1);
}
if (strncmp($name, '_', 1) === 0) {
return substr($name, 1);
}
return Inflector::underscore($name);
} | Normalizes table name for generator.
When name is preceded with underscore name case is kept - otherwise it's converted from camelcase to underscored.
Last underscore is always trimmed so if there should be underscore at the end of name use two of them.
@param string $name
@return string | normalizeTableName | php | yiisoft/yii2 | framework/console/controllers/MigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/MigrateController.php | BSD-3-Clause |
protected function generateTableName($tableName)
{
if (!$this->useTablePrefix) {
return $tableName;
}
return '{{%' . $tableName . '}}';
} | If `useTablePrefix` equals true, then the table name will contain the
prefix format.
@param string $tableName the table name to generate.
@return string
@since 2.0.8 | generateTableName | php | yiisoft/yii2 | framework/console/controllers/MigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/MigrateController.php | BSD-3-Clause |
public function actionCreate($name)
{
if (!preg_match('/^[\w\\\\]+$/', $name)) {
throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
}
list($namespace, $className) = $this->generateClassName($name);
// Abort if name is too long
$nameLimit = $this->getMigrationNameLimit();
if ($nameLimit !== null && strlen($className) > $nameLimit) {
throw new Exception('The migration name is too long.');
}
$migrationPath = $this->findMigrationPath($namespace);
$file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
if ($this->confirm("Create new migration '$file'?")) {
$content = $this->generateMigrationSourceCode([
'name' => $name,
'className' => $className,
'namespace' => $namespace,
]);
FileHelper::createDirectory($migrationPath);
if (file_put_contents($file, $content, LOCK_EX) === false) {
$this->stdout("Failed to create new migration.\n", Console::FG_RED);
return ExitCode::IOERR;
}
FileHelper::changeOwnership($file, $this->newFileOwnership, $this->newFileMode);
$this->stdout("New migration created successfully.\n", Console::FG_GREEN);
}
return ExitCode::OK;
} | Creates a new migration.
This command creates a new migration using the available migration template.
After using this command, developers should modify the created migration
skeleton by filling up the actual migration logic.
```
yii migrate/create create_user_table
```
In order to generate a namespaced migration, you should specify a namespace before the migration's name.
Note that backslash (`\`) is usually considered a special character in the shell, so you need to escape it
properly to avoid shell errors or incorrect behavior.
For example:
```
yii migrate/create app\\migrations\\createUserTable
```
In case [[migrationPath]] is not set and no namespace is provided, the first entry of [[migrationNamespaces]] will be used.
@param string $name the name of the new migration. This should only contain
letters, digits, underscores and/or backslashes.
Note: If the migration name is of a special form, for example create_xxx or
drop_xxx, then the generated migration file will contain extra code,
in this case for creating/dropping tables.
@throws Exception if the name argument is invalid. | actionCreate | php | yiisoft/yii2 | framework/console/controllers/BaseMigrateController.php | https://github.com/yiisoft/yii2/blob/master/framework/console/controllers/BaseMigrateController.php | BSD-3-Clause |
protected function getScreenWidth()
{
if (!$this->screenWidth) {
$size = Console::getScreenSize();
$this->screenWidth = isset($size[0])
? $size[0]
: self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET;
}
return $this->screenWidth;
} | Getting screen width.
If it is not able to determine screen width, default value `123` will be set.
@return int screen width | getScreenWidth | php | yiisoft/yii2 | framework/console/widgets/Table.php | https://github.com/yiisoft/yii2/blob/master/framework/console/widgets/Table.php | BSD-3-Clause |
public function asUrl($value, $options = [])
{
if ($value === null) {
return $this->nullDisplay;
}
$url = $value;
$scheme = ArrayHelper::remove($options, 'scheme');
if ($scheme === null) {
if (strpos($url, '://') === false) {
$url = 'http://' . $url;
}
} else {
$url = Url::ensureScheme($url, $scheme);
}
return Html::a(Html::encode($value), $url, $options);
} | Formats the value as a hyperlink.
@param mixed $value the value to be formatted.
@param array $options the tag options in terms of name-value pairs. See [[Html::a()]]. Since 2.0.43 there is
a special option available `scheme` - if set it won't be passed to [[Html::a()]] but it will control the URL
protocol part of the link by normalizing URL and ensuring that it uses specified scheme. See [[Url::ensureScheme()]].
If `scheme` is not set the original behavior is preserved which is to add "http://" prefix when "://" string is
not found in the $value.
@return string the formatted result. | asUrl | php | yiisoft/yii2 | framework/i18n/Formatter.php | https://github.com/yiisoft/yii2/blob/master/framework/i18n/Formatter.php | BSD-3-Clause |
public function asRelativeTime($value, $referenceTime = null)
{
if ($value === null) {
return $this->nullDisplay;
}
if ($value instanceof DateInterval) {
$interval = $value;
} else {
$timestamp = $this->normalizeDatetimeValue($value);
$timeZone = new DateTimeZone($this->timeZone);
if ($referenceTime === null) {
$dateNow = new DateTime('now', $timeZone);
} else {
$dateNow = $this->normalizeDatetimeValue($referenceTime);
$dateNow->setTimezone($timeZone);
}
$dateThen = $timestamp->setTimezone($timeZone);
$interval = $dateThen->diff($dateNow);
}
if ($interval->invert) {
if ($interval->y >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->language);
}
if ($interval->m >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->language);
}
if ($interval->d >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->language);
}
if ($interval->h >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->language);
}
if ($interval->i >= 1) {
return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->language);
}
if ($interval->s == 0) {
return Yii::t('yii', 'just now', [], $this->language);
}
return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->language);
}
if ($interval->y >= 1) {
return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->language);
}
if ($interval->m >= 1) {
return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->language);
}
if ($interval->d >= 1) {
return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->language);
}
if ($interval->h >= 1) {
return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->language);
}
if ($interval->i >= 1) {
return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->language);
}
if ($interval->s == 0) {
return Yii::t('yii', 'just now', [], $this->language);
}
return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->language);
} | Formats the value as the time interval between a date and now in human readable form.
This method can be used in three different ways:
1. Using a timestamp that is relative to `now`.
2. Using a timestamp that is relative to the `$referenceTime`.
3. Using a `DateInterval` object.
@param int|string|DateTime|DateTimeInterface|DateInterval|null $value the value to be formatted. The following
types of value are supported:
- an integer representing a UNIX timestamp
- a string that can be [parsed to create a DateTime object](https://www.php.net/manual/en/datetime.formats.php).
The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
- a PHP [DateTime](https://www.php.net/manual/en/class.datetime.php) object
- a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
@param int|string|DateTime|DateTimeInterface|null $referenceTime if specified the value is used as a reference time instead of `now`
when `$value` is not a `DateInterval` object.
@return string the formatted result.
@throws InvalidArgumentException if the input value can not be evaluated as a date value. | asRelativeTime | php | yiisoft/yii2 | framework/i18n/Formatter.php | https://github.com/yiisoft/yii2/blob/master/framework/i18n/Formatter.php | BSD-3-Clause |
public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
{
if ($value === null) {
return $this->nullDisplay;
}
$normalizedValue = $this->normalizeNumericValue($value);
if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
return $this->asCurrencyStringFallback((string) $value, $currency);
}
if ($this->_intlLoaded) {
$currency = $currency ?: $this->currencyCode;
// currency code must be set before fraction digits
// https://www.php.net/manual/en/numberformatter.formatcurrency.php#114376
if ($currency && !isset($textOptions[NumberFormatter::CURRENCY_CODE])) {
$textOptions[NumberFormatter::CURRENCY_CODE] = $currency;
}
$formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
if ($currency === null) {
$result = $formatter->format($normalizedValue);
} else {
$result = $formatter->formatCurrency($normalizedValue, $currency);
}
if ($result === false) {
throw new InvalidArgumentException('Formatting currency value failed: ' . $formatter->getErrorCode() . ' ' . $formatter->getErrorMessage());
}
return $result;
}
if ($currency === null) {
if ($this->currencyCode === null) {
throw new InvalidConfigException('The default currency code for the formatter is not defined and the php intl extension is not installed which could take the default currency from the locale.');
}
$currency = $this->currencyCode;
}
return $currency . ' ' . $this->asDecimal($normalizedValue, 2, $options, $textOptions);
} | Formats the value as a currency number.
This function does not require the [PHP intl extension](https://www.php.net/manual/en/book.intl.php) to be installed
to work, but it is highly recommended to install it to get good formatting results.
Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function
without PHP intl extension support. For very big numbers it's recommended to pass them as strings and not use
scientific notation otherwise the output might be wrong.
@param mixed $value the value to be formatted.
@param string|null $currency the 3-letter ISO 4217 currency code indicating the currency to use.
If null, [[currencyCode]] will be used.
@param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
@param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
@return string the formatted result.
@throws InvalidArgumentException if the input value is not numeric or the formatting failed.
@throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined. | asCurrency | php | yiisoft/yii2 | framework/i18n/Formatter.php | https://github.com/yiisoft/yii2/blob/master/framework/i18n/Formatter.php | BSD-3-Clause |
public static function of($id, $optional = false)
{
return new static($id, $optional);
} | Creates a new Instance object.
@param string $id the component ID
@param bool $optional if null should be returned instead of throwing an exception
@return Instance the new Instance object. | of | php | yiisoft/yii2 | framework/di/Instance.php | https://github.com/yiisoft/yii2/blob/master/framework/di/Instance.php | BSD-3-Clause |
public function get($container = null)
{
try {
if ($container) {
return $container->get($this->id);
}
if (Yii::$app && Yii::$app->has($this->id)) {
return Yii::$app->get($this->id);
}
return Yii::$container->get($this->id);
} catch (\Exception $e) {
if ($this->optional) {
return null;
}
throw $e;
} catch (\Throwable $e) {
if ($this->optional) {
return null;
}
throw $e;
}
} | Returns the actual object referenced by this Instance object.
@param ServiceLocator|Container|null $container the container used to locate the referenced object.
If null, the method will first try `Yii::$app` then `Yii::$container`.
@return object the actual object referenced by this Instance object. | get | php | yiisoft/yii2 | framework/di/Instance.php | https://github.com/yiisoft/yii2/blob/master/framework/di/Instance.php | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.