_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q241700
QueryBuilder.getColumnType
validation
public function getColumnType($type) { if ($type instanceof ColumnSchemaBuilder) { $type = $type->__toString(); } if (isset($this->typeMap[$type])) { return $this->typeMap[$type]; } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) { if (isset($this->typeMap[$matches[1]])) { return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3]; } } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) { if (isset($this->typeMap[$matches[1]])) { return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type); } } return $type; }
php
{ "resource": "" }
q241701
QueryBuilder.quoteTableNames
validation
private function quoteTableNames($tables, &$params) { foreach ($tables as $i => $table) { if ($table instanceof Query) { list($sql, $params) = $this->build($table, $params); $tables[$i] = "($sql) " . $this->db->quoteTableName($i); } elseif (is_string($i)) { if (strpos($table, '(') === false) { $table = $this->db->quoteTableName($table); } $tables[$i] = "$table " . $this->db->quoteTableName($i); } elseif (strpos($table, '(') === false) { if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias $tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]); } else { $tables[$i] = $this->db->quoteTableName($table); } } } return $tables; }
php
{ "resource": "" }
q241702
QueryBuilder.buildColumns
validation
public function buildColumns($columns) { if (!is_array($columns)) { if (strpos($columns, '(') !== false) { return $columns; } $rawColumns = $columns; $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY); if ($columns === false) { throw new InvalidArgumentException("$rawColumns is not valid columns."); } } foreach ($columns as $i => $column) { if ($column instanceof ExpressionInterface) { $columns[$i] = $this->buildExpression($column); } elseif (strpos($column, '(') === false) { $columns[$i] = $this->db->quoteColumnName($column); } } return implode(', ', $columns); }
php
{ "resource": "" }
q241703
QueryBuilder.buildCondition
validation
public function buildCondition($condition, &$params) { if (is_array($condition)) { if (empty($condition)) { return ''; } $condition = $this->createConditionFromArray($condition); } if ($condition instanceof ExpressionInterface) { return $this->buildExpression($condition, $params); } return (string) $condition; }
php
{ "resource": "" }
q241704
QueryBuilder.buildAndCondition
validation
public function buildAndCondition($operator, $operands, &$params) { array_unshift($operands, $operator); return $this->buildCondition($operands, $params); }
php
{ "resource": "" }
q241705
QueryBuilder.buildNotCondition
validation
public function buildNotCondition($operator, $operands, &$params) { array_unshift($operands, $operator); return $this->buildCondition($operands, $params); }
php
{ "resource": "" }
q241706
QueryBuilder.buildBetweenCondition
validation
public function buildBetweenCondition($operator, $operands, &$params) { array_unshift($operands, $operator); return $this->buildCondition($operands, $params); }
php
{ "resource": "" }
q241707
QueryBuilder.buildInCondition
validation
public function buildInCondition($operator, $operands, &$params) { array_unshift($operands, $operator); return $this->buildCondition($operands, $params); }
php
{ "resource": "" }
q241708
QueryBuilder.buildExistsCondition
validation
public function buildExistsCondition($operator, $operands, &$params) { array_unshift($operands, $operator); return $this->buildCondition($operands, $params); }
php
{ "resource": "" }
q241709
QueryBuilder.buildSimpleCondition
validation
public function buildSimpleCondition($operator, $operands, &$params) { array_unshift($operands, $operator); return $this->buildCondition($operands, $params); }
php
{ "resource": "" }
q241710
ViewAction.run
validation
public function run($id) { $model = $this->findModel($id); if ($this->checkAccess) { call_user_func($this->checkAccess, $this->id, $model); } return $model; }
php
{ "resource": "" }
q241711
Migration.up
validation
public function up() { $transaction = $this->db->beginTransaction(); try { if ($this->safeUp() === false) { $transaction->rollBack(); return false; } $transaction->commit(); } catch (\Exception $e) { $this->printException($e); $transaction->rollBack(); return false; } catch (\Throwable $e) { $this->printException($e); $transaction->rollBack(); return false; } return null; }
php
{ "resource": "" }
q241712
Migration.down
validation
public function down() { $transaction = $this->db->beginTransaction(); try { if ($this->safeDown() === false) { $transaction->rollBack(); return false; } $transaction->commit(); } catch (\Exception $e) { $this->printException($e); $transaction->rollBack(); return false; } catch (\Throwable $e) { $this->printException($e); $transaction->rollBack(); return false; } return null; }
php
{ "resource": "" }
q241713
Migration.insert
validation
public function insert($table, $columns) { $time = $this->beginCommand("insert into $table"); $this->db->createCommand()->insert($table, $columns)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241714
Migration.batchInsert
validation
public function batchInsert($table, $columns, $rows) { $time = $this->beginCommand("insert into $table"); $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241715
Migration.update
validation
public function update($table, $columns, $condition = '', $params = []) { $time = $this->beginCommand("update $table"); $this->db->createCommand()->update($table, $columns, $condition, $params)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241716
Migration.delete
validation
public function delete($table, $condition = '', $params = []) { $time = $this->beginCommand("delete from $table"); $this->db->createCommand()->delete($table, $condition, $params)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241717
Migration.createTable
validation
public function createTable($table, $columns, $options = null) { $time = $this->beginCommand("create table $table"); $this->db->createCommand()->createTable($table, $columns, $options)->execute(); foreach ($columns as $column => $type) { if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) { $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute(); } } $this->endCommand($time); }
php
{ "resource": "" }
q241718
Migration.renameTable
validation
public function renameTable($table, $newName) { $time = $this->beginCommand("rename table $table to $newName"); $this->db->createCommand()->renameTable($table, $newName)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241719
Migration.dropColumn
validation
public function dropColumn($table, $column) { $time = $this->beginCommand("drop column $column from table $table"); $this->db->createCommand()->dropColumn($table, $column)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241720
Migration.renameColumn
validation
public function renameColumn($table, $name, $newName) { $time = $this->beginCommand("rename column $name in table $table to $newName"); $this->db->createCommand()->renameColumn($table, $name, $newName)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241721
Migration.alterColumn
validation
public function alterColumn($table, $column, $type) { $time = $this->beginCommand("alter column $column in table $table to $type"); $this->db->createCommand()->alterColumn($table, $column, $type)->execute(); if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) { $this->db->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute(); } $this->endCommand($time); }
php
{ "resource": "" }
q241722
Migration.addPrimaryKey
validation
public function addPrimaryKey($name, $table, $columns) { $time = $this->beginCommand("add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ')'); $this->db->createCommand()->addPrimaryKey($name, $table, $columns)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241723
Migration.addForeignKey
validation
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null) { $time = $this->beginCommand("add foreign key $name: $table (" . implode(',', (array) $columns) . ") references $refTable (" . implode(',', (array) $refColumns) . ')'); $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241724
Migration.createIndex
validation
public function createIndex($name, $table, $columns, $unique = false) { $time = $this->beginCommand('create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array) $columns) . ')'); $this->db->createCommand()->createIndex($name, $table, $columns, $unique)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241725
Migration.dropIndex
validation
public function dropIndex($name, $table) { $time = $this->beginCommand("drop index $name on $table"); $this->db->createCommand()->dropIndex($name, $table)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241726
Migration.addCommentOnColumn
validation
public function addCommentOnColumn($table, $column, $comment) { $time = $this->beginCommand("add comment on column $column"); $this->db->createCommand()->addCommentOnColumn($table, $column, $comment)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241727
Migration.addCommentOnTable
validation
public function addCommentOnTable($table, $comment) { $time = $this->beginCommand("add comment on table $table"); $this->db->createCommand()->addCommentOnTable($table, $comment)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241728
Migration.dropCommentFromTable
validation
public function dropCommentFromTable($table) { $time = $this->beginCommand("drop comment from table $table"); $this->db->createCommand()->dropCommentFromTable($table)->execute(); $this->endCommand($time); }
php
{ "resource": "" }
q241729
UploadedFile.getInstances
validation
public static function getInstances($model, $attribute) { $name = Html::getInputName($model, $attribute); return static::getInstancesByName($name); }
php
{ "resource": "" }
q241730
Schema.findTableConstraints
validation
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(); }
php
{ "resource": "" }
q241731
Schema.findPrimaryKeys
validation
protected function findPrimaryKeys($table) { $result = []; foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) { $result[] = $row['field_name']; } $table->primaryKey = $result; }
php
{ "resource": "" }
q241732
ActiveRelationTrait.via
validation
public function via($relationName, callable $callable = null) { $relation = $this->primaryModel->getRelation($relationName); $callableUsed = $callable !== null; $this->via = [$relationName, $relation, $callableUsed]; if ($callable !== null) { call_user_func($callable, $relation); } return $this; }
php
{ "resource": "" }
q241733
ActiveRelationTrait.findFor
validation
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(); }
php
{ "resource": "" }
q241734
ActiveRelationTrait.indexBuckets
validation
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; }
php
{ "resource": "" }
q241735
Logger.flush
validation
public function flush($final = false) { $messages = $this->messages; // https://github.com/yiisoft/yii2/issues/5619 // new messages could be logged while the existing ones are being handled by targets $this->messages = []; if ($this->dispatcher instanceof Dispatcher) { $this->dispatcher->dispatch($messages, $final); } }
php
{ "resource": "" }
q241736
Logger.getProfiling
validation
public function getProfiling($categories = [], $excludeCategories = []) { $timings = $this->calculateTimings($this->messages); if (empty($categories) && empty($excludeCategories)) { return $timings; } foreach ($timings as $i => $timing) { $matched = empty($categories); foreach ($categories as $category) { $prefix = rtrim($category, '*'); if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) { $matched = true; break; } } if ($matched) { foreach ($excludeCategories as $category) { $prefix = rtrim($category, '*'); foreach ($timings as $i => $timing) { if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) { $matched = false; break; } } } } if (!$matched) { unset($timings[$i]); } } return array_values($timings); }
php
{ "resource": "" }
q241737
Logger.getDbProfiling
validation
public function getDbProfiling() { $timings = $this->getProfiling(['yii\db\Command::query', 'yii\db\Command::execute']); $count = count($timings); $time = 0; foreach ($timings as $timing) { $time += $timing['duration']; } return [$count, $time]; }
php
{ "resource": "" }
q241738
Logger.calculateTimings
validation
public function calculateTimings($messages) { $timings = []; $stack = []; foreach ($messages as $i => $log) { list($token, $level, $category, $timestamp, $traces) = $log; $memory = isset($log[5]) ? $log[5] : 0; $log[6] = $i; $hash = md5(json_encode($token)); if ($level == self::LEVEL_PROFILE_BEGIN) { $stack[$hash] = $log; } elseif ($level == self::LEVEL_PROFILE_END) { if (isset($stack[$hash])) { $timings[$stack[$hash][6]] = [ 'info' => $stack[$hash][0], 'category' => $stack[$hash][2], 'timestamp' => $stack[$hash][3], 'trace' => $stack[$hash][4], 'level' => count($stack) - 1, 'duration' => $timestamp - $stack[$hash][3], 'memory' => $memory, 'memoryDiff' => $memory - (isset($stack[$hash][5]) ? $stack[$hash][5] : 0), ]; unset($stack[$hash]); } } } ksort($timings); return array_values($timings); }
php
{ "resource": "" }
q241739
Theme.applyTo
validation
public function applyTo($path) { $pathMap = $this->pathMap; if (empty($pathMap)) { if (($basePath = $this->getBasePath()) === null) { throw new InvalidConfigException('The "basePath" property must be set.'); } $pathMap = [Yii::$app->getBasePath() => [$basePath]]; } $path = FileHelper::normalizePath($path); foreach ($pathMap as $from => $tos) { $from = FileHelper::normalizePath(Yii::getAlias($from)) . DIRECTORY_SEPARATOR; if (strpos($path, $from) === 0) { $n = strlen($from); foreach ((array) $tos as $to) { $to = FileHelper::normalizePath(Yii::getAlias($to)) . DIRECTORY_SEPARATOR; $file = $to . substr($path, $n); if (is_file($file)) { return $file; } } } } return $path; }
php
{ "resource": "" }
q241740
GettextMoFile.writeInteger
validation
protected function writeInteger($fileHandle, $integer) { return $this->writeBytes($fileHandle, pack($this->useBigEndian ? 'N' : 'V', (int) $integer)); }
php
{ "resource": "" }
q241741
GettextMoFile.readString
validation
protected function readString($fileHandle, $length, $offset = null) { if ($offset !== null) { fseek($fileHandle, $offset); } return $this->readBytes($fileHandle, $length); }
php
{ "resource": "" }
q241742
CheckboxColumn.getHeaderCheckBoxName
validation
protected function getHeaderCheckBoxName() { $name = $this->name; if (substr_compare($name, '[]', -2, 2) === 0) { $name = substr($name, 0, -2); } if (substr_compare($name, ']', -1, 1) === 0) { $name = substr($name, 0, -1) . '_all]'; } else { $name .= '_all'; } return $name; }
php
{ "resource": "" }
q241743
CheckboxColumn.registerClientScript
validation
public function registerClientScript() { $id = $this->grid->options['id']; $options = Json::encode([ 'name' => $this->name, 'class' => $this->cssClass, 'multiple' => $this->multiple, 'checkAll' => $this->grid->showHeader ? $this->getHeaderCheckBoxName() : null, ]); $this->grid->getView()->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);"); }
php
{ "resource": "" }
q241744
QueryBuilder.batchInsert
validation
public function batchInsert($table, $columns, $rows, &$params = []) { if (empty($rows)) { return ''; } // SQLite supports batch insert natively since 3.7.11 // http://www.sqlite.org/releaselog/3_7_11.html $this->db->open(); // ensure pdo is not null if (version_compare($this->db->getServerVersion(), '3.7.11', '>=')) { return parent::batchInsert($table, $columns, $rows, $params); } $schema = $this->db->getSchema(); if (($tableSchema = $schema->getTableSchema($table)) !== null) { $columnSchemas = $tableSchema->columns; } else { $columnSchemas = []; } $values = []; foreach ($rows as $row) { $vs = []; foreach ($row as $i => $value) { if (isset($columnSchemas[$columns[$i]])) { $value = $columnSchemas[$columns[$i]]->dbTypecast($value); } if (is_string($value)) { $value = $schema->quoteValue($value); } elseif (is_float($value)) { // ensure type cast always has . as decimal separator in all locales $value = StringHelper::floatToString($value); } elseif ($value === false) { $value = 0; } elseif ($value === null) { $value = 'NULL'; } elseif ($value instanceof ExpressionInterface) { $value = $this->buildExpression($value, $params); } $vs[] = $value; } $values[] = implode(', ', $vs); } if (empty($values)) { return ''; } foreach ($columns as $i => $name) { $columns[$i] = $schema->quoteColumnName($name); } return 'INSERT INTO ' . $schema->quoteTableName($table) . ' (' . implode(', ', $columns) . ') SELECT ' . implode(' UNION SELECT ', $values); }
php
{ "resource": "" }
q241745
ErrorAction.renderHtmlResponse
validation
protected function renderHtmlResponse() { return $this->controller->render($this->view ?: $this->id, $this->getViewRenderParams()); }
php
{ "resource": "" }
q241746
I18N.init
validation
public function init() { parent::init(); if (!isset($this->translations['yii']) && !isset($this->translations['yii*'])) { $this->translations['yii'] = [ 'class' => 'yii\i18n\PhpMessageSource', 'sourceLanguage' => 'en-US', 'basePath' => '@yii/messages', ]; } if (!isset($this->translations['app']) && !isset($this->translations['app*'])) { $this->translations['app'] = [ 'class' => 'yii\i18n\PhpMessageSource', 'sourceLanguage' => Yii::$app->sourceLanguage, 'basePath' => '@app/messages', ]; } }
php
{ "resource": "" }
q241747
I18N.getMessageFormatter
validation
public function getMessageFormatter() { if ($this->_messageFormatter === null) { $this->_messageFormatter = new MessageFormatter(); } elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) { $this->_messageFormatter = Yii::createObject($this->_messageFormatter); } return $this->_messageFormatter; }
php
{ "resource": "" }
q241748
I18N.getMessageSource
validation
public function getMessageSource($category) { if (isset($this->translations[$category])) { $source = $this->translations[$category]; if ($source instanceof MessageSource) { return $source; } return $this->translations[$category] = Yii::createObject($source); } // try wildcard matching foreach ($this->translations as $pattern => $source) { if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) { if ($source instanceof MessageSource) { return $source; } return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source); } } // match '*' in the last if (isset($this->translations['*'])) { $source = $this->translations['*']; if ($source instanceof MessageSource) { return $source; } return $this->translations[$category] = $this->translations['*'] = Yii::createObject($source); } throw new InvalidConfigException("Unable to locate message source for category '$category'."); }
php
{ "resource": "" }
q241749
MultiFieldSession.composeFields
validation
protected function composeFields($id = null, $data = null) { $fields = $this->writeCallback ? call_user_func($this->writeCallback, $this) : []; if ($id !== null) { $fields['id'] = $id; } if ($data !== null) { $fields['data'] = $data; } return $fields; }
php
{ "resource": "" }
q241750
HelpController.actionIndex
validation
public function actionIndex($command = null) { if ($command !== null) { $result = Yii::$app->createController($command); if ($result === false) { $name = $this->ansiFormat($command, Console::FG_YELLOW); throw new Exception("No help for unknown command \"$name\"."); } list($controller, $actionID) = $result; $actions = $this->getActions($controller); if ($actionID !== '' || count($actions) === 1 && $actions[0] === $controller->defaultAction) { $this->getSubCommandHelp($controller, $actionID); } else { $this->getCommandHelp($controller); } } else { $this->getDefaultHelp(); } }
php
{ "resource": "" }
q241751
HelpController.actionList
validation
public function actionList() { foreach ($this->getCommandDescriptions() as $command => $description) { $result = Yii::$app->createController($command); if ($result === false || !($result[0] instanceof Controller)) { continue; } /** @var $controller Controller */ list($controller, $actionID) = $result; $actions = $this->getActions($controller); if (!empty($actions)) { $prefix = $controller->getUniqueId(); $this->stdout("$prefix\n"); foreach ($actions as $action) { $this->stdout("$prefix/$action\n"); } } } }
php
{ "resource": "" }
q241752
HelpController.formatOptionHelp
validation
protected function formatOptionHelp($name, $required, $type, $defaultValue, $comment) { $comment = trim($comment); $type = trim($type); if (strncmp($type, 'bool', 4) === 0) { $type = 'boolean, 0 or 1'; } if ($defaultValue !== null && !is_array($defaultValue)) { if ($type === null) { $type = gettype($defaultValue); } if (is_bool($defaultValue)) { // show as integer to avoid confusion $defaultValue = (int)$defaultValue; } if (is_string($defaultValue)) { $defaultValue = "'" . $defaultValue . "'"; } else { $defaultValue = var_export($defaultValue, true); } $doc = "$type (defaults to $defaultValue)"; } else { $doc = $type; } if ($doc === '') { $doc = $comment; } elseif ($comment !== '') { $doc .= "\n" . preg_replace('/^/m', ' ', $comment); } $name = $required ? "$name (required)" : $name; return $doc === '' ? $name : "$name: $doc"; }
php
{ "resource": "" }
q241753
ApcCache.addValues
validation
protected function addValues($data, $duration) { $result = $this->useApcu ? apcu_add($data, null, $duration) : apc_add($data, null, $duration); return is_array($result) ? array_keys($result) : []; }
php
{ "resource": "" }
q241754
BaseMigrateController.actionUp
validation
public function actionUp($limit = 0) { $migrations = $this->getNewMigrations(); if (empty($migrations)) { $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN); return ExitCode::OK; } $total = count($migrations); $limit = (int) $limit; if ($limit > 0) { $migrations = array_slice($migrations, 0, $limit); } $n = count($migrations); if ($n === $total) { $this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW); } else { $this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW); } foreach ($migrations as $migration) { $nameLimit = $this->getMigrationNameLimit(); if ($nameLimit !== null && strlen($migration) > $nameLimit) { $this->stdout("\nThe migration name '$migration' is too long. Its not possible to apply this migration.\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $this->stdout("\t$migration\n"); } $this->stdout("\n"); $applied = 0; if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) { foreach ($migrations as $migration) { if (!$this->migrateUp($migration)) { $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $applied++; } $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN); $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN); } }
php
{ "resource": "" }
q241755
BaseMigrateController.actionDown
validation
public function actionDown($limit = 1) { if ($limit === 'all') { $limit = null; } else { $limit = (int) $limit; if ($limit < 1) { throw new Exception('The step argument must be greater than 0.'); } } $migrations = $this->getMigrationHistory($limit); if (empty($migrations)) { $this->stdout("No migration has been done before.\n", Console::FG_YELLOW); return ExitCode::OK; } $migrations = array_keys($migrations); $n = count($migrations); $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW); foreach ($migrations as $migration) { $this->stdout("\t$migration\n"); } $this->stdout("\n"); $reverted = 0; if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) { foreach ($migrations as $migration) { if (!$this->migrateDown($migration)) { $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $reverted++; } $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN); $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN); } }
php
{ "resource": "" }
q241756
BaseMigrateController.actionTo
validation
public function actionTo($version) { if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) { $this->migrateToVersion($namespaceVersion); } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) { $this->migrateToVersion($migrationName); } elseif ((string) (int) $version == $version) { $this->migrateToTime($version); } elseif (($time = strtotime($version)) !== false) { $this->migrateToTime($time); } else { throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401),\n the full name of a migration (e.g. m101129_185401_create_user_table),\n the full namespaced name of a migration (e.g. app\\migrations\\M101129185401CreateUserTable),\n a UNIX timestamp (e.g. 1392853000), or a datetime string parseable\nby the strtotime() function (e.g. 2014-02-15 13:00:50)."); } }
php
{ "resource": "" }
q241757
BaseMigrateController.actionMark
validation
public function actionMark($version) { $originalVersion = $version; if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) { $version = $namespaceVersion; } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) { $version = $migrationName; } elseif ($version !== static::BASE_MIGRATION) { throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table)\nor the full name of a namespaced migration (e.g. app\\migrations\\M101129185401CreateUserTable)."); } // try mark up $migrations = $this->getNewMigrations(); foreach ($migrations as $i => $migration) { if (strpos($migration, $version) === 0) { if ($this->confirm("Set migration history at $originalVersion?")) { for ($j = 0; $j <= $i; ++$j) { $this->addMigrationHistory($migrations[$j]); } $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN); } return ExitCode::OK; } } // try mark down $migrations = array_keys($this->getMigrationHistory(null)); $migrations[] = static::BASE_MIGRATION; foreach ($migrations as $i => $migration) { if (strpos($migration, $version) === 0) { if ($i === 0) { $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW); } else { if ($this->confirm("Set migration history at $originalVersion?")) { for ($j = 0; $j < $i; ++$j) { $this->removeMigrationHistory($migrations[$j]); } $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN); } } return ExitCode::OK; } } throw new Exception("Unable to find the version '$originalVersion'."); }
php
{ "resource": "" }
q241758
BaseMigrateController.actionFresh
validation
public function actionFresh() { if (YII_ENV_PROD) { $this->stdout("YII_ENV is set to 'prod'.\nRefreshing migrations is not possible on production systems.\n"); return ExitCode::OK; } if ($this->confirm( "Are you sure you want to reset the database and start the migration from the beginning?\nAll data will be lost irreversibly!")) { $this->truncateDatabase(); $this->actionUp(); } else { $this->stdout('Action was cancelled by user. Nothing has been performed.'); } }
php
{ "resource": "" }
q241759
BaseMigrateController.generateClassName
validation
private function generateClassName($name) { $namespace = null; $name = trim($name, '\\'); if (strpos($name, '\\') !== false) { $namespace = substr($name, 0, strrpos($name, '\\')); $name = substr($name, strrpos($name, '\\') + 1); } else { if ($this->migrationPath === null) { $migrationNamespaces = $this->migrationNamespaces; $namespace = array_shift($migrationNamespaces); } } if ($namespace === null) { $class = 'm' . gmdate('ymd_His') . '_' . $name; } else { $class = 'M' . gmdate('ymdHis') . ucfirst($name); } return [$namespace, $class]; }
php
{ "resource": "" }
q241760
BaseMigrateController.findMigrationPath
validation
private function findMigrationPath($namespace) { if (empty($namespace)) { return is_array($this->migrationPath) ? reset($this->migrationPath) : $this->migrationPath; } if (!in_array($namespace, $this->migrationNamespaces, true)) { throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`"); } return $this->getNamespacePath($namespace); }
php
{ "resource": "" }
q241761
BaseMigrateController.migrateUp
validation
protected function migrateUp($class) { if ($class === self::BASE_MIGRATION) { return true; } $this->stdout("*** applying $class\n", Console::FG_YELLOW); $start = microtime(true); $migration = $this->createMigration($class); if ($migration->up() !== false) { $this->addMigrationHistory($class); $time = microtime(true) - $start; $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN); return true; } $time = microtime(true) - $start; $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED); return false; }
php
{ "resource": "" }
q241762
BaseMigrateController.migrateDown
validation
protected function migrateDown($class) { if ($class === self::BASE_MIGRATION) { return true; } $this->stdout("*** reverting $class\n", Console::FG_YELLOW); $start = microtime(true); $migration = $this->createMigration($class); if ($migration->down() !== false) { $this->removeMigrationHistory($class); $time = microtime(true) - $start; $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN); return true; } $time = microtime(true) - $start; $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED); return false; }
php
{ "resource": "" }
q241763
BaseMigrateController.createMigration
validation
protected function createMigration($class) { $this->includeMigrationFile($class); /** @var MigrationInterface $migration */ $migration = Yii::createObject($class); if ($migration instanceof BaseObject && $migration->canSetProperty('compact')) { $migration->compact = $this->compact; } return $migration; }
php
{ "resource": "" }
q241764
BaseMigrateController.includeMigrationFile
validation
protected function includeMigrationFile($class) { $class = trim($class, '\\'); if (strpos($class, '\\') === false) { if (is_array($this->migrationPath)) { foreach ($this->migrationPath as $path) { $file = $path . DIRECTORY_SEPARATOR . $class . '.php'; if (is_file($file)) { require_once $file; break; } } } else { $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php'; require_once $file; } } }
php
{ "resource": "" }
q241765
BaseMigrateController.migrateToTime
validation
protected function migrateToTime($time) { $count = 0; $migrations = array_values($this->getMigrationHistory(null)); while ($count < count($migrations) && $migrations[$count] > $time) { ++$count; } if ($count === 0) { $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN); } else { $this->actionDown($count); } }
php
{ "resource": "" }
q241766
BaseMigrateController.migrateToVersion
validation
protected function migrateToVersion($version) { $originalVersion = $version; // try migrate up $migrations = $this->getNewMigrations(); foreach ($migrations as $i => $migration) { if (strpos($migration, $version) === 0) { $this->actionUp($i + 1); return ExitCode::OK; } } // try migrate down $migrations = array_keys($this->getMigrationHistory(null)); foreach ($migrations as $i => $migration) { if (strpos($migration, $version) === 0) { if ($i === 0) { $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW); } else { $this->actionDown($i); } return ExitCode::OK; } } throw new Exception("Unable to find the version '$originalVersion'."); }
php
{ "resource": "" }
q241767
AssetBundle.init
validation
public function init() { if ($this->sourcePath !== null) { $this->sourcePath = rtrim(Yii::getAlias($this->sourcePath), '/\\'); } if ($this->basePath !== null) { $this->basePath = rtrim(Yii::getAlias($this->basePath), '/\\'); } if ($this->baseUrl !== null) { $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/'); } }
php
{ "resource": "" }
q241768
AssetBundle.registerAssetFiles
validation
public function registerAssetFiles($view) { $manager = $view->getAssetManager(); foreach ($this->js as $js) { if (is_array($js)) { $file = array_shift($js); $options = ArrayHelper::merge($this->jsOptions, $js); $view->registerJsFile($manager->getAssetUrl($this, $file), $options); } else { if ($js !== null) { $view->registerJsFile($manager->getAssetUrl($this, $js), $this->jsOptions); } } } foreach ($this->css as $css) { if (is_array($css)) { $file = array_shift($css); $options = ArrayHelper::merge($this->cssOptions, $css); $view->registerCssFile($manager->getAssetUrl($this, $file), $options); } else { if ($css !== null) { $view->registerCssFile($manager->getAssetUrl($this, $css), $this->cssOptions); } } } }
php
{ "resource": "" }
q241769
ReleaseController.actionInfo
validation
public function actionInfo() { $items = [ 'framework', 'app-basic', 'app-advanced', ]; $extensionPath = "{$this->basePath}/extensions"; foreach (scandir($extensionPath) as $extension) { if (ctype_alpha($extension) && is_dir($extensionPath . '/' . $extension)) { $items[] = $extension; } } if ($this->update) { foreach ($items as $item) { $this->stdout("fetching tags for $item..."); if ($item === 'framework') { $this->gitFetchTags((string)$this->basePath); } elseif (strncmp('app-', $item, 4) === 0) { $this->gitFetchTags("{$this->basePath}/apps/" . substr($item, 4)); } else { $this->gitFetchTags("{$this->basePath}/extensions/$item"); } $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD); } } else { $this->stdout("\nInformation may be outdated, re-run with `--update` to fetch latest tags.\n\n"); } $versions = $this->getCurrentVersions($items); $nextVersions = $this->getNextVersions($versions, self::PATCH); // print version table $w = $this->minWidth(array_keys($versions)); $this->stdout(str_repeat(' ', $w + 2) . "Current Version Next Version\n", Console::BOLD); foreach ($versions as $ext => $version) { $this->stdout($ext . str_repeat(' ', $w + 3 - mb_strlen($ext)) . $version . ''); $this->stdout(str_repeat(' ', 17 - mb_strlen($version)) . $nextVersions[$ext] . "\n"); } }
php
{ "resource": "" }
q241770
ReleaseController.actionPackage
validation
public function actionPackage(array $what) { $this->validateWhat($what, ['app']); $versions = $this->getCurrentVersions($what); $this->stdout("You are about to generate packages for the following things:\n\n"); foreach ($what as $ext) { if (strncmp('app-', $ext, 4) === 0) { $this->stdout(' - '); $this->stdout(substr($ext, 4), Console::FG_RED); $this->stdout(' application version '); } elseif ($ext === 'framework') { $this->stdout(' - Yii Framework version '); } else { $this->stdout(' - '); $this->stdout($ext, Console::FG_RED); $this->stdout(' extension version '); } $this->stdout($versions[$ext], Console::BOLD); $this->stdout("\n"); } $this->stdout("\n"); $packagePath = "{$this->basePath}/packages"; $this->stdout("Packages will be stored in $packagePath\n\n"); if (!$this->confirm('Continue?', false)) { $this->stdout("Canceled.\n"); return 1; } foreach ($what as $ext) { if ($ext === 'framework') { throw new Exception('Can not package framework.'); } elseif (strncmp('app-', $ext, 4) === 0) { $this->packageApplication(substr($ext, 4), $versions[$ext], $packagePath); } else { throw new Exception('Can not package extension.'); } } $this->stdout("\ndone. verify the versions composer installed above and push it to github!\n\n"); return 0; }
php
{ "resource": "" }
q241771
ReleaseController.actionSortChangelog
validation
public function actionSortChangelog(array $what) { if (\count($what) > 1) { $this->stdout("Currently only one simultaneous release is supported.\n"); return 1; } $this->validateWhat($what, ['framework', 'ext'], false); $version = $this->version ?: array_values($this->getNextVersions($this->getCurrentVersions($what), self::PATCH))[0]; $this->stdout('sorting CHANGELOG of '); $this->stdout(reset($what), Console::BOLD); $this->stdout(' for version '); $this->stdout($version, Console::BOLD); $this->stdout('...'); $this->resortChangelogs($what, $version); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); }
php
{ "resource": "" }
q241772
ReleaseController.splitChangelog
validation
protected function splitChangelog($file, $version) { $lines = explode("\n", file_get_contents($file)); // split the file into relevant parts $start = []; $changelog = []; $end = []; $state = 'start'; foreach ($lines as $l => $line) { // starting from the changelogs headline if (isset($lines[$l - 2]) && strpos($lines[$l - 2], $version) !== false && isset($lines[$l - 1]) && strncmp($lines[$l - 1], '---', 3) === 0) { $state = 'changelog'; } if ($state === 'changelog' && isset($lines[$l + 1]) && strncmp($lines[$l + 1], '---', 3) === 0) { $state = 'end'; } // add continued lines to the last item to keep them together if (!empty(${$state}) && trim($line) !== '' && strncmp($line, '- ', 2) !== 0) { end(${$state}); ${$state}[key(${$state})] .= "\n" . $line; } else { ${$state}[] = $line; } } return [$start, $changelog, $end]; }
php
{ "resource": "" }
q241773
ReleaseController.resortChangelog
validation
protected function resortChangelog($changelog) { // cleanup whitespace foreach ($changelog as $i => $line) { $changelog[$i] = rtrim($line); } $changelog = array_filter($changelog); $i = 0; ArrayHelper::multisort($changelog, function ($line) use (&$i) { if (preg_match('/^- (Chg|Enh|Bug|New)( #\d+(, #\d+)*)?: .+/', $line, $m)) { $o = ['Bug' => 'C', 'Enh' => 'D', 'Chg' => 'E', 'New' => 'F']; return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++); } return 'B' . $i++; }, SORT_ASC, SORT_NATURAL); // re-add leading and trailing lines array_unshift($changelog, ''); $changelog[] = ''; $changelog[] = ''; return $changelog; }
php
{ "resource": "" }
q241774
PhpDocController.actionFix
validation
public function actionFix($root = null) { $files = $this->findFiles($root, false); $nFilesTotal = 0; $nFilesUpdated = 0; foreach ($files as $file) { $contents = file_get_contents($file); $hash = $this->hash($contents); // fix line endings $lines = preg_split('/(\r\n|\n|\r)/', $contents); if (!$this->skipFrameworkRequirements) { $this->fixFileDoc($lines); } $this->fixDocBlockIndentation($lines); $lines = array_values($this->fixLineSpacing($lines)); $newContent = implode("\n", $lines); if ($hash !== $this->hash($newContent)) { file_put_contents($file, $newContent); $nFilesUpdated++; } $nFilesTotal++; } $this->stdout("\nParsed $nFilesTotal files.\n"); $this->stdout("Updated $nFilesUpdated files.\n"); }
php
{ "resource": "" }
q241775
PhpDocController.fixFileDoc
validation
protected function fixFileDoc(&$lines) { // find namespace $namespace = false; $namespaceLine = ''; $contentAfterNamespace = false; foreach ($lines as $i => $line) { $line = trim($line); if (!empty($line)) { if (strncmp($line, 'namespace', 9) === 0) { $namespace = $i; $namespaceLine = $line; } elseif ($namespace !== false) { $contentAfterNamespace = $i; break; } } } if ($namespace !== false && $contentAfterNamespace !== false) { while ($contentAfterNamespace > 0) { array_shift($lines); $contentAfterNamespace--; } $lines = array_merge([ '<?php', '/**', ' * @link http://www.yiiframework.com/', ' * @copyright Copyright (c) 2008 Yii Software LLC', ' * @license http://www.yiiframework.com/license/', ' */', '', $namespaceLine, '', ], $lines); } }
php
{ "resource": "" }
q241776
PhpDocController.fixDocBlockIndentation
validation
protected function fixDocBlockIndentation(&$lines) { $docBlock = false; $codeBlock = false; $listIndent = ''; $tag = false; $indent = ''; foreach ($lines as $i => $line) { if (preg_match('~^(\s*)/\*\*$~', $line, $matches)) { $docBlock = true; $indent = $matches[1]; } elseif (preg_match('~^(\s*)\*+/~', $line)) { if ($docBlock) { // could be the end of normal comment $lines[$i] = $indent . ' */'; } $docBlock = false; $codeBlock = false; $listIndent = ''; $tag = false; } elseif ($docBlock) { $line = ltrim($line); if (isset($line[0]) && $line[0] === '*') { $line = substr($line, 1); } if (isset($line[0]) && $line[0] === ' ') { $line = substr($line, 1); } $docLine = str_replace("\t", ' ', rtrim($line)); if (empty($docLine)) { $listIndent = ''; } elseif ($docLine[0] === '@') { $listIndent = ''; $codeBlock = false; $tag = true; $docLine = preg_replace('/\s+/', ' ', $docLine); $docLine = $this->fixParamTypes($docLine); } elseif (preg_match('/^(~~~|```)/', $docLine)) { $codeBlock = !$codeBlock; $listIndent = ''; } elseif (preg_match('/^(\s*)([0-9]+\.|-|\*|\+) /', $docLine, $matches)) { $listIndent = str_repeat(' ', \strlen($matches[0])); $tag = false; $lines[$i] = $indent . ' * ' . $docLine; continue; } if ($codeBlock) { $lines[$i] = rtrim($indent . ' * ' . $docLine); } else { $lines[$i] = rtrim($indent . ' * ' . (empty($listIndent) && !$tag ? $docLine : ($listIndent . ltrim($docLine)))); } } } }
php
{ "resource": "" }
q241777
PhpDocController.cleanDocComment
validation
protected function cleanDocComment($doc) { $lines = explode("\n", $doc); $n = \count($lines); for ($i = 0; $i < $n; $i++) { $lines[$i] = rtrim($lines[$i]); if (trim($lines[$i]) == '*' && trim($lines[$i + 1]) == '*') { unset($lines[$i]); } } return implode("\n", $lines); }
php
{ "resource": "" }
q241778
PhpDocController.updateDocComment
validation
protected function updateDocComment($doc, $properties) { $lines = explode("\n", $doc); $propertyPart = false; $propertyPosition = false; foreach ($lines as $i => $line) { $line = trim($line); if (strncmp($line, '* @property ', 12) === 0) { $propertyPart = true; } elseif ($propertyPart && $line == '*') { $propertyPosition = $i; $propertyPart = false; } if (strncmp($line, '* @author ', 10) === 0 && $propertyPosition === false) { $propertyPosition = $i - 1; $propertyPart = false; } if ($propertyPart) { unset($lines[$i]); } } // if no properties or other tags where present add properties at the end if ($propertyPosition === false) { $propertyPosition = \count($lines) - 2; } $finalDoc = ''; foreach ($lines as $i => $line) { $finalDoc .= $line . "\n"; if ($i == $propertyPosition) { $finalDoc .= $properties; } } return $finalDoc; }
php
{ "resource": "" }
q241779
Serializer.serializeDataProvider
validation
protected function serializeDataProvider($dataProvider) { if ($this->preserveKeys) { $models = $dataProvider->getModels(); } else { $models = array_values($dataProvider->getModels()); } $models = $this->serializeModels($models); if (($pagination = $dataProvider->getPagination()) !== false) { $this->addPaginationHeaders($pagination); } if ($this->request->getIsHead()) { return null; } elseif ($this->collectionEnvelope === null) { return $models; } $result = [ $this->collectionEnvelope => $models, ]; if ($pagination !== false) { return array_merge($result, $this->serializePagination($pagination)); } return $result; }
php
{ "resource": "" }
q241780
Serializer.serializePagination
validation
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(), ], ]; }
php
{ "resource": "" }
q241781
Serializer.addPaginationHeaders
validation
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)); }
php
{ "resource": "" }
q241782
Serializer.serializeModelErrors
validation
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; }
php
{ "resource": "" }
q241783
Serializer.serializeModels
validation
protected function serializeModels(array $models) { list($fields, $expand) = $this->getRequestedFields(); foreach ($models as $i => $model) { if ($model instanceof Arrayable) { $models[$i] = $model->toArray($fields, $expand); } elseif (is_array($model)) { $models[$i] = ArrayHelper::toArray($model); } } return $models; }
php
{ "resource": "" }
q241784
FileTarget.init
validation
public function init() { parent::init(); if ($this->logFile === null) { $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log'; } else { $this->logFile = Yii::getAlias($this->logFile); } if ($this->maxLogFiles < 1) { $this->maxLogFiles = 1; } if ($this->maxFileSize < 1) { $this->maxFileSize = 1; } }
php
{ "resource": "" }
q241785
FileTarget.export
validation
public function export() { $logPath = dirname($this->logFile); FileHelper::createDirectory($logPath, $this->dirMode, true); $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n"; if (($fp = @fopen($this->logFile, 'a')) === false) { throw new InvalidConfigException("Unable to append to log file: {$this->logFile}"); } @flock($fp, LOCK_EX); if ($this->enableRotation) { // clear stat cache to ensure getting the real current file size and not a cached one // this may result in rotating twice when cached file size is used on subsequent calls clearstatcache(); } if ($this->enableRotation && @filesize($this->logFile) > $this->maxFileSize * 1024) { @flock($fp, LOCK_UN); @fclose($fp); $this->rotateFiles(); $writeResult = @file_put_contents($this->logFile, $text, FILE_APPEND | LOCK_EX); if ($writeResult === false) { $error = error_get_last(); throw new LogRuntimeException("Unable to export log through file!: {$error['message']}"); } $textSize = strlen($text); if ($writeResult < $textSize) { throw new LogRuntimeException("Unable to export whole log through file! Wrote $writeResult out of $textSize bytes."); } } else { $writeResult = @fwrite($fp, $text); if ($writeResult === false) { $error = error_get_last(); throw new LogRuntimeException("Unable to export log through file!: {$error['message']}"); } $textSize = strlen($text); if ($writeResult < $textSize) { throw new LogRuntimeException("Unable to export whole log through file! Wrote $writeResult out of $textSize bytes."); } @flock($fp, LOCK_UN); @fclose($fp); } if ($this->fileMode !== null) { @chmod($this->logFile, $this->fileMode); } }
php
{ "resource": "" }
q241786
FileTarget.rotateFiles
validation
protected function rotateFiles() { $file = $this->logFile; for ($i = $this->maxLogFiles; $i >= 0; --$i) { // $i == 0 is the original log file $rotateFile = $file . ($i === 0 ? '' : '.' . $i); if (is_file($rotateFile)) { // suppress errors because it's possible multiple processes enter into this section if ($i === $this->maxLogFiles) { @unlink($rotateFile); continue; } $newFile = $this->logFile . '.' . ($i + 1); $this->rotateByCopy ? $this->rotateByCopy($rotateFile, $newFile) : $this->rotateByRename($rotateFile, $newFile); if ($i === 0) { $this->clearLogFile($rotateFile); } } } }
php
{ "resource": "" }
q241787
Schema.getCreateTableSql
validation
protected function getCreateTableSql($table) { $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne(); if (isset($row['Create Table'])) { $sql = $row['Create Table']; } else { $row = array_values($row); $sql = $row[1]; } return $sql; }
php
{ "resource": "" }
q241788
MemCache.addServers
validation
protected function addServers($cache, $servers) { if (empty($servers)) { $servers = [new MemCacheServer([ 'host' => '127.0.0.1', 'port' => 11211, ])]; } else { foreach ($servers as $server) { if ($server->host === null) { throw new InvalidConfigException("The 'host' property must be specified for every memcache server."); } } } if ($this->useMemcached) { $this->addMemcachedServers($cache, $servers); } else { $this->addMemcacheServers($cache, $servers); } }
php
{ "resource": "" }
q241789
MemCache.addMemcachedServers
validation
protected function addMemcachedServers($cache, $servers) { $existingServers = []; if ($this->persistentId !== null) { foreach ($cache->getServerList() as $s) { $existingServers[$s['host'] . ':' . $s['port']] = true; } } foreach ($servers as $server) { if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) { $cache->addServer($server->host, $server->port, $server->weight); } } }
php
{ "resource": "" }
q241790
BaseVarDumper.dumpAsString
validation
public static function dumpAsString($var, $depth = 10, $highlight = false) { self::$_output = ''; self::$_objects = []; self::$_depth = $depth; self::dumpInternal($var, 0); if ($highlight) { $result = highlight_string("<?php\n" . self::$_output, true); self::$_output = preg_replace('/&lt;\\?php<br \\/>/', '', $result, 1); } return self::$_output; }
php
{ "resource": "" }
q241791
CacheController.actionIndex
validation
public function actionIndex() { $caches = $this->findCaches(); if (!empty($caches)) { $this->notifyCachesCanBeFlushed($caches); } else { $this->notifyNoCachesFound(); } }
php
{ "resource": "" }
q241792
CacheController.actionFlush
validation
public function actionFlush() { $cachesInput = func_get_args(); if (empty($cachesInput)) { throw new Exception('You should specify cache components names'); } $caches = $this->findCaches($cachesInput); $cachesInfo = []; $foundCaches = array_keys($caches); $notFoundCaches = array_diff($cachesInput, array_keys($caches)); if ($notFoundCaches) { $this->notifyNotFoundCaches($notFoundCaches); } if (!$foundCaches) { $this->notifyNoCachesFound(); return ExitCode::OK; } if (!$this->confirmFlush($foundCaches)) { return ExitCode::OK; } foreach ($caches as $name => $class) { $cachesInfo[] = [ 'name' => $name, 'class' => $class, 'is_flushed' => $this->canBeFlushed($class) ? Yii::$app->get($name)->flush() : false, ]; } $this->notifyFlushed($cachesInfo); }
php
{ "resource": "" }
q241793
CacheController.actionFlushAll
validation
public function actionFlushAll() { $caches = $this->findCaches(); $cachesInfo = []; if (empty($caches)) { $this->notifyNoCachesFound(); return ExitCode::OK; } foreach ($caches as $name => $class) { $cachesInfo[] = [ 'name' => $name, 'class' => $class, 'is_flushed' => $this->canBeFlushed($class) ? Yii::$app->get($name)->flush() : false, ]; } $this->notifyFlushed($cachesInfo); }
php
{ "resource": "" }
q241794
CacheController.actionFlushSchema
validation
public function actionFlushSchema($db = 'db') { $connection = Yii::$app->get($db, false); if ($connection === null) { $this->stdout("Unknown component \"$db\".\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } if (!$connection instanceof \yii\db\Connection) { $this->stdout("\"$db\" component doesn't inherit \\yii\\db\\Connection.\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } elseif (!$this->confirm("Flush cache schema for \"$db\" connection?")) { return ExitCode::OK; } try { $schema = $connection->getSchema(); $schema->refresh(); $this->stdout("Schema cache for component \"$db\", was flushed.\n\n", Console::FG_GREEN); } catch (\Exception $e) { $this->stdout($e->getMessage() . "\n\n", Console::FG_RED); } }
php
{ "resource": "" }
q241795
CacheController.notifyCachesCanBeFlushed
validation
private function notifyCachesCanBeFlushed($caches) { $this->stdout("The following caches were found in the system:\n\n", Console::FG_YELLOW); foreach ($caches as $name => $class) { if ($this->canBeFlushed($class)) { $this->stdout("\t* $name ($class)\n", Console::FG_GREEN); } else { $this->stdout("\t* $name ($class) - can not be flushed via console\n", Console::FG_YELLOW); } } $this->stdout("\n"); }
php
{ "resource": "" }
q241796
CacheController.notifyNotFoundCaches
validation
private function notifyNotFoundCaches($cachesNames) { $this->stdout("The following cache components were NOT found:\n\n", Console::FG_RED); foreach ($cachesNames as $name) { $this->stdout("\t* $name \n", Console::FG_GREEN); } $this->stdout("\n"); }
php
{ "resource": "" }
q241797
ServiceLocator.setComponents
validation
public function setComponents($components) { foreach ($components as $id => $component) { $this->set($id, $component); } }
php
{ "resource": "" }
q241798
ActiveDataFilter.buildConjunctionCondition
validation
protected function buildConjunctionCondition($operator, $condition) { if (isset($this->queryOperatorMap[$operator])) { $operator = $this->queryOperatorMap[$operator]; } $result = [$operator]; foreach ($condition as $part) { $result[] = $this->buildCondition($part); } return $result; }
php
{ "resource": "" }
q241799
ActiveDataFilter.buildBlockCondition
validation
protected function buildBlockCondition($operator, $condition) { if (isset($this->queryOperatorMap[$operator])) { $operator = $this->queryOperatorMap[$operator]; } return [ $operator, $this->buildCondition($condition), ]; }
php
{ "resource": "" }