_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q241900
Connection.noCache
validation
public function noCache(callable $callable) { $this->_queryCacheInfo[] = false; try { $result = call_user_func($callable, $this); array_pop($this->_queryCacheInfo); return $result; } catch (\Exception $e) { array_pop($this->_queryCacheInfo); throw $e; } catch (\Throwable $e) { array_pop($this->_queryCacheInfo); throw $e; } }
php
{ "resource": "" }
q241901
Connection.createCommand
validation
public function createCommand($sql = null, $params = []) { $driver = $this->getDriverName(); $config = ['class' => 'yii\db\Command']; if ($this->commandClass !== $config['class']) { $config['class'] = $this->commandClass; } elseif (isset($this->commandMap[$driver])) { $config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver]; } $config['db'] = $this; $config['sql'] = $sql; /** @var Command $command */ $command = Yii::createObject($config); return $command->bindValues($params); }
php
{ "resource": "" }
q241902
Connection.beginTransaction
validation
public function beginTransaction($isolationLevel = null) { $this->open(); if (($transaction = $this->getTransaction()) === null) { $transaction = $this->_transaction = new Transaction(['db' => $this]); } $transaction->begin($isolationLevel); return $transaction; }
php
{ "resource": "" }
q241903
Connection.transaction
validation
public function transaction(callable $callback, $isolationLevel = null) { $transaction = $this->beginTransaction($isolationLevel); $level = $transaction->level; try { $result = call_user_func($callback, $this); if ($transaction->isActive && $transaction->level === $level) { $transaction->commit(); } } catch (\Exception $e) { $this->rollbackTransactionOnLevel($transaction, $level); throw $e; } catch (\Throwable $e) { $this->rollbackTransactionOnLevel($transaction, $level); throw $e; } return $result; }
php
{ "resource": "" }
q241904
Connection.getMaster
validation
public function getMaster() { if ($this->_master === false) { $this->_master = $this->shuffleMasters ? $this->openFromPool($this->masters, $this->masterConfig) : $this->openFromPoolSequentially($this->masters, $this->masterConfig); } return $this->_master; }
php
{ "resource": "" }
q241905
Connection.useMaster
validation
public function useMaster(callable $callback) { if ($this->enableSlaves) { $this->enableSlaves = false; try { $result = call_user_func($callback, $this); } catch (\Exception $e) { $this->enableSlaves = true; throw $e; } catch (\Throwable $e) { $this->enableSlaves = true; throw $e; } // TODO: use "finally" keyword when miminum required PHP version is >= 5.5 $this->enableSlaves = true; } else { $result = call_user_func($callback, $this); } return $result; }
php
{ "resource": "" }
q241906
Connection.openFromPoolSequentially
validation
protected function openFromPoolSequentially(array $pool, array $sharedConfig) { if (empty($pool)) { return null; } if (!isset($sharedConfig['class'])) { $sharedConfig['class'] = get_class($this); } $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache; foreach ($pool as $config) { $config = array_merge($sharedConfig, $config); if (empty($config['dsn'])) { throw new InvalidConfigException('The "dsn" option must be specified.'); } $key = [__METHOD__, $config['dsn']]; if ($cache instanceof CacheInterface && $cache->get($key)) { // should not try this dead server now continue; } /* @var $db Connection */ $db = Yii::createObject($config); try { $db->open(); return $db; } catch (\Exception $e) { Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__); if ($cache instanceof CacheInterface) { // mark this server as dead and only retry it after the specified interval $cache->set($key, 1, $this->serverRetryInterval); } } } return null; }
php
{ "resource": "" }
q241907
ListView.renderItems
validation
public function renderItems() { $models = $this->dataProvider->getModels(); $keys = $this->dataProvider->getKeys(); $rows = []; foreach (array_values($models) as $index => $model) { $key = $keys[$index]; if (($before = $this->renderBeforeItem($model, $key, $index)) !== null) { $rows[] = $before; } $rows[] = $this->renderItem($model, $key, $index); if (($after = $this->renderAfterItem($model, $key, $index)) !== null) { $rows[] = $after; } } return implode($this->separator, $rows); }
php
{ "resource": "" }
q241908
BaseStringHelper.startsWith
validation
public static function startsWith($string, $with, $caseSensitive = true) { if (!$bytes = static::byteLength($with)) { return true; } if ($caseSensitive) { return strncmp($string, $with, $bytes) === 0; } $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8'; return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), $encoding) === mb_strtolower($with, $encoding); }
php
{ "resource": "" }
q241909
BaseStringHelper.normalizeNumber
validation
public static function normalizeNumber($value) { $value = (string)$value; $localeInfo = localeconv(); $decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null; if ($decimalSeparator !== null && $decimalSeparator !== '.') { $value = str_replace($decimalSeparator, '.', $value); } return $value; }
php
{ "resource": "" }
q241910
DbDependency.generateDependencyData
validation
protected function generateDependencyData($cache) { /* @var $db Connection */ $db = Instance::ensure($this->db, Connection::className()); if ($this->sql === null) { throw new InvalidConfigException('DbDependency::sql must be set.'); } if ($db->enableQueryCache) { // temporarily disable and re-enable query caching $db->enableQueryCache = false; $result = $db->createCommand($this->sql, $this->params)->queryOne(); $db->enableQueryCache = true; } else { $result = $db->createCommand($this->sql, $this->params)->queryOne(); } return $result; }
php
{ "resource": "" }
q241911
DbCache.gc
validation
public function gc($force = false) { if ($force || mt_rand(0, 1000000) < $this->gcProbability) { $this->db->createCommand() ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time()) ->execute(); } }
php
{ "resource": "" }
q241912
UpdateAction.run
validation
public function run($id) { /* @var $model ActiveRecord */ $model = $this->findModel($id); if ($this->checkAccess) { call_user_func($this->checkAccess, $this->id, $model); } $model->scenario = $this->scenario; $model->load(Yii::$app->getRequest()->getBodyParams(), ''); if ($model->save() === false && !$model->hasErrors()) { throw new ServerErrorHttpException('Failed to update the object for unknown reason.'); } return $model; }
php
{ "resource": "" }
q241913
OptimisticLockBehavior.upgrade
validation
public function upgrade() { /* @var $owner BaseActiveRecord */ $owner = $this->owner; if ($owner->getIsNewRecord()) { throw new InvalidCallException('Upgrading the model version is not possible on a new record.'); } $lock = $this->getLockAttribute(); $version = $owner->$lock ?: 0; $owner->updateAttributes([$lock => $version + 1]); }
php
{ "resource": "" }
q241914
QueryBuilder.alterColumn
validation
public function alterColumn($table, $column, $type) { $columnName = $this->db->quoteColumnName($column); $tableName = $this->db->quoteTableName($table); // https://github.com/yiisoft/yii2/issues/4492 // http://www.postgresql.org/docs/9.1/static/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); }
php
{ "resource": "" }
q241915
QueryBuilder.normalizeTableRowData
validation
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; }
php
{ "resource": "" }
q241916
Pagination.getPage
validation
public function getPage($recalculate = false) { if ($this->_page === null || $recalculate) { $page = (int) $this->getQueryParam($this->pageParam, 1) - 1; $this->setPage($page, true); } return $this->_page; }
php
{ "resource": "" }
q241917
Pagination.setPage
validation
public function setPage($value, $validatePage = false) { if ($value === null) { $this->_page = null; } else { $value = (int) $value; if ($validatePage && $this->validatePage) { $pageCount = $this->getPageCount(); if ($value >= $pageCount) { $value = $pageCount - 1; } } if ($value < 0) { $value = 0; } $this->_page = $value; } }
php
{ "resource": "" }
q241918
Pagination.getLinks
validation
public function getLinks($absolute = false) { $currentPage = $this->getPage(); $pageCount = $this->getPageCount(); $links = [ Link::REL_SELF => $this->createUrl($currentPage, null, $absolute), ]; if ($currentPage > 0) { $links[self::LINK_FIRST] = $this->createUrl(0, null, $absolute); $links[self::LINK_PREV] = $this->createUrl($currentPage - 1, null, $absolute); } if ($currentPage < $pageCount - 1) { $links[self::LINK_NEXT] = $this->createUrl($currentPage + 1, null, $absolute); $links[self::LINK_LAST] = $this->createUrl($pageCount - 1, null, $absolute); } return $links; }
php
{ "resource": "" }
q241919
DataFilter.detectSearchAttributeType
validation
protected function detectSearchAttributeType(Validator $validator) { if ($validator instanceof BooleanValidator) { return self::TYPE_BOOLEAN; } if ($validator instanceof NumberValidator) { return $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT; } if ($validator instanceof StringValidator) { return self::TYPE_STRING; } if ($validator instanceof EachValidator) { return self::TYPE_ARRAY; } if ($validator instanceof DateValidator) { if ($validator->type == DateValidator::TYPE_DATETIME) { return self::TYPE_DATETIME; } if ($validator->type == DateValidator::TYPE_TIME) { return self::TYPE_TIME; } return self::TYPE_DATE; } }
php
{ "resource": "" }
q241920
DataFilter.validateCondition
validation
protected function validateCondition($condition) { if (!is_array($condition)) { $this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidFilter')); return; } if (empty($condition)) { return; } foreach ($condition as $key => $value) { $method = 'validateAttributeCondition'; if (isset($this->filterControls[$key])) { $controlKey = $this->filterControls[$key]; if (isset($this->conditionValidators[$controlKey])) { $method = $this->conditionValidators[$controlKey]; } } $this->$method($key, $value); } }
php
{ "resource": "" }
q241921
DataFilter.validateConjunctionCondition
validation
protected function validateConjunctionCondition($operator, $condition) { if (!is_array($condition) || !ArrayHelper::isIndexed($condition)) { $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator])); return; } foreach ($condition as $part) { $this->validateCondition($part); } }
php
{ "resource": "" }
q241922
DataFilter.validateAttributeCondition
validation
protected function validateAttributeCondition($attribute, $condition) { $attributeTypes = $this->getSearchAttributeTypes(); if (!isset($attributeTypes[$attribute])) { $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute])); return; } if (is_array($condition)) { $operatorCount = 0; foreach ($condition as $rawOperator => $value) { if (isset($this->filterControls[$rawOperator])) { $operator = $this->filterControls[$rawOperator]; if (isset($this->operatorTypes[$operator])) { $operatorCount++; $this->validateOperatorCondition($rawOperator, $value, $attribute); } } } if ($operatorCount > 0) { if ($operatorCount < count($condition)) { $this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidAttributeValueFormat', ['attribute' => $attribute])); } } else { // attribute may allow array value: $this->validateAttributeValue($attribute, $condition); } } else { $this->validateAttributeValue($attribute, $condition); } }
php
{ "resource": "" }
q241923
DataFilter.validateOperatorCondition
validation
protected function validateOperatorCondition($operator, $condition, $attribute = null) { if ($attribute === null) { // absence of an attribute indicates that operator has been placed in a wrong position $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireAttribute', ['operator' => $operator])); return; } $internalOperator = $this->filterControls[$operator]; // check operator type : $operatorTypes = $this->operatorTypes[$internalOperator]; if ($operatorTypes !== '*') { $attributeTypes = $this->getSearchAttributeTypes(); $attributeType = $attributeTypes[$attribute]; if (!in_array($attributeType, $operatorTypes, true)) { $this->addError($this->filterAttributeName, $this->parseErrorMessage('unsupportedOperatorType', ['attribute' => $attribute, 'operator' => $operator])); return; } } if (in_array($internalOperator, $this->multiValueOperators, true)) { // multi-value operator: if (!is_array($condition)) { $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator])); } else { foreach ($condition as $v) { $this->validateAttributeValue($attribute, $v); } } } else { // single-value operator : $this->validateAttributeValue($attribute, $condition); } }
php
{ "resource": "" }
q241924
DataFilter.normalizeComplexFilter
validation
private function normalizeComplexFilter(array $filter) { $result = []; foreach ($filter as $key => $value) { if (isset($this->filterControls[$key])) { $key = $this->filterControls[$key]; } elseif (isset($this->attributeMap[$key])) { $key = $this->attributeMap[$key]; } if (is_array($value)) { $result[$key] = $this->normalizeComplexFilter($value); } else { $result[$key] = $value; } } return $result; }
php
{ "resource": "" }
q241925
YiiConfig.mergeRules
validation
public function mergeRules(array $rules) { $this->setRules(ArrayHelper::merge($this->getRules(), $rules)); return $this; }
php
{ "resource": "" }
q241926
Locale.getCurrencySymbol
validation
public function getCurrencySymbol($currencyCode = null) { $locale = $this->locale; if ($currencyCode !== null) { $locale .= '@currency=' . $currencyCode; } $formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY); return $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL); }
php
{ "resource": "" }
q241927
ArrayDataProvider.sortModels
validation
protected function sortModels($models, $sort) { $orders = $sort->getOrders(); if (!empty($orders)) { ArrayHelper::multisort($models, array_keys($orders), array_values($orders)); } return $models; }
php
{ "resource": "" }
q241928
DbManager.getChildrenRecursive
validation
protected function getChildrenRecursive($name, $childrenList, &$result) { if (isset($childrenList[$name])) { foreach ($childrenList[$name] as $child) { $result[$child] = true; $this->getChildrenRecursive($child, $childrenList, $result); } } }
php
{ "resource": "" }
q241929
DbManager.removeAllItems
validation
protected function removeAllItems($type) { if (!$this->supportsCascadeUpdate()) { $names = (new Query()) ->select(['name']) ->from($this->itemTable) ->where(['type' => $type]) ->column($this->db); if (empty($names)) { return; } $key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent'; $this->db->createCommand() ->delete($this->itemChildTable, [$key => $names]) ->execute(); $this->db->createCommand() ->delete($this->assignmentTable, ['item_name' => $names]) ->execute(); } $this->db->createCommand() ->delete($this->itemTable, ['type' => $type]) ->execute(); $this->invalidateCache(); }
php
{ "resource": "" }
q241930
UrlManager.addRules
validation
public function addRules($rules, $append = true) { if (!$this->enablePrettyUrl) { return; } $rules = $this->buildRules($rules); if ($append) { $this->rules = array_merge($this->rules, $rules); } else { $this->rules = array_merge($rules, $this->rules); } }
php
{ "resource": "" }
q241931
UrlManager.getUrlFromCache
validation
protected function getUrlFromCache($cacheKey, $route, $params) { if (!empty($this->_ruleCache[$cacheKey])) { foreach ($this->_ruleCache[$cacheKey] as $rule) { /* @var $rule UrlRule */ if (($url = $rule->createUrl($this, $route, $params)) !== false) { return $url; } } } else { $this->_ruleCache[$cacheKey] = []; } return false; }
php
{ "resource": "" }
q241932
ActionFilter.isActive
validation
protected function isActive($action) { $id = $this->getActionId($action); if (empty($this->only)) { $onlyMatch = true; } else { $onlyMatch = false; foreach ($this->only as $pattern) { if (StringHelper::matchWildcard($pattern, $id)) { $onlyMatch = true; break; } } } $exceptMatch = false; foreach ($this->except as $pattern) { if (StringHelper::matchWildcard($pattern, $id)) { $exceptMatch = true; break; } } return !$exceptMatch && $onlyMatch; }
php
{ "resource": "" }
q241933
BaseMailer.createView
validation
protected function createView(array $config) { if (!array_key_exists('class', $config)) { $config['class'] = View::className(); } return Yii::createObject($config); }
php
{ "resource": "" }
q241934
BaseMailer.compose
validation
public function compose($view = null, array $params = []) { $message = $this->createMessage(); if ($view === null) { return $message; } if (!array_key_exists('message', $params)) { $params['message'] = $message; } $this->_message = $message; if (is_array($view)) { if (isset($view['html'])) { $html = $this->render($view['html'], $params, $this->htmlLayout); } if (isset($view['text'])) { $text = $this->render($view['text'], $params, $this->textLayout); } } else { $html = $this->render($view, $params, $this->htmlLayout); } $this->_message = null; if (isset($html)) { $message->setHtmlBody($html); } if (isset($text)) { $message->setTextBody($text); } elseif (isset($html)) { if (preg_match('~<body[^>]*>(.*?)</body>~is', $html, $match)) { $html = $match[1]; } // remove style and script $html = preg_replace('~<((style|script))[^>]*>(.*?)</\1>~is', '', $html); // strip all HTML tags and decoded HTML entities $text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, Yii::$app ? Yii::$app->charset : 'UTF-8'); // improve whitespace $text = preg_replace("~^[ \t]+~m", '', trim($text)); $text = preg_replace('~\R\R+~mu', "\n\n", $text); $message->setTextBody($text); } return $message; }
php
{ "resource": "" }
q241935
BaseMailer.sendMultiple
validation
public function sendMultiple(array $messages) { $successCount = 0; foreach ($messages as $message) { if ($this->send($message)) { $successCount++; } } return $successCount; }
php
{ "resource": "" }
q241936
BaseMailer.beforeSend
validation
public function beforeSend($message) { $event = new MailEvent(['message' => $message]); $this->trigger(self::EVENT_BEFORE_SEND, $event); return $event->isValid; }
php
{ "resource": "" }
q241937
BaseMailer.afterSend
validation
public function afterSend($message, $isSuccessful) { $event = new MailEvent(['message' => $message, 'isSuccessful' => $isSuccessful]); $this->trigger(self::EVENT_AFTER_SEND, $event); }
php
{ "resource": "" }
q241938
DevController.actionAll
validation
public function actionAll() { if (!$this->confirm('Install all applications and all extensions now?')) { return 1; } foreach ($this->extensions as $ext => $repo) { $ret = $this->actionExt($ext); if ($ret !== 0) { return $ret; } } foreach ($this->apps as $app => $repo) { $ret = $this->actionApp($app); if ($ret !== 0) { return $ret; } } return 0; }
php
{ "resource": "" }
q241939
DevController.actionRun
validation
public function actionRun($command) { $command = implode(' ', \func_get_args()); // root of the dev repo $base = \dirname(\dirname(__DIR__)); $dirs = $this->listSubDirs("$base/extensions"); $dirs = array_merge($dirs, $this->listSubDirs("$base/apps")); asort($dirs); $oldcwd = getcwd(); foreach ($dirs as $dir) { $displayDir = substr($dir, \strlen($base)); $this->stdout("Running '$command' in $displayDir...\n", Console::BOLD); chdir($dir); passthru($command); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); } chdir($oldcwd); }
php
{ "resource": "" }
q241940
DevController.actionApp
validation
public function actionApp($app, $repo = null) { // root of the dev repo $base = \dirname(\dirname(__DIR__)); $appDir = "$base/apps/$app"; if (!file_exists($appDir)) { if (empty($repo)) { if (isset($this->apps[$app])) { $repo = $this->apps[$app]; if ($this->useHttp) { $repo = str_replace('[email protected]:', 'https://github.com/', $repo); } } else { $this->stderr("Repo argument is required for app '$app'.\n", Console::FG_RED); return 1; } } $this->stdout("cloning application repo '$app' from '$repo'...\n", Console::BOLD); passthru('git clone ' . escapeshellarg($repo) . ' ' . $appDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); } // cleanup $this->stdout("cleaning up application '$app' vendor directory...\n", Console::BOLD); $this->cleanupVendorDir($appDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // composer update $this->stdout("updating composer for app '$app'...\n", Console::BOLD); chdir($appDir); $command = 'composer update --prefer-dist'; if ($this->composerNoProgress) { $command .= ' --no-progress'; } passthru($command); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // link directories $this->stdout("linking framework and extensions to '$app' app vendor dir...\n", Console::BOLD); $this->linkFrameworkAndExtensions($appDir, $base); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); return 0; }
php
{ "resource": "" }
q241941
DevController.actionExt
validation
public function actionExt($extension, $repo = null) { // root of the dev repo $base = \dirname(\dirname(__DIR__)); $extensionDir = "$base/extensions/$extension"; if (!file_exists($extensionDir)) { if (empty($repo)) { if (isset($this->extensions[$extension])) { $repo = $this->extensions[$extension]; if ($this->useHttp) { $repo = str_replace('[email protected]:', 'https://github.com/', $repo); } } else { $this->stderr("Repo argument is required for extension '$extension'.\n", Console::FG_RED); return 1; } } $this->stdout("cloning extension repo '$extension' from '$repo'...\n", Console::BOLD); passthru('git clone ' . escapeshellarg($repo) . ' ' . $extensionDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); } // cleanup $this->stdout("cleaning up extension '$extension' vendor directory...\n", Console::BOLD); $this->cleanupVendorDir($extensionDir); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // composer update $this->stdout("updating composer for extension '$extension'...\n", Console::BOLD); chdir($extensionDir); $command = 'composer update --prefer-dist'; if ($this->composerNoProgress) { $command .= ' --no-progress'; } passthru($command); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); // link directories $this->stdout("linking framework and extensions to '$extension' vendor dir...\n", Console::BOLD); $this->linkFrameworkAndExtensions($extensionDir, $base); $this->stdout("done.\n", Console::BOLD, Console::FG_GREEN); return 0; }
php
{ "resource": "" }
q241942
DevController.cleanupVendorDir
validation
protected function cleanupVendorDir($dir) { if (is_link($link = "$dir/vendor/yiisoft/yii2")) { $this->stdout("Removing symlink $link.\n"); FileHelper::unlink($link); } $extensions = $this->findDirs("$dir/vendor/yiisoft"); foreach ($extensions as $ext) { if (is_link($link = "$dir/vendor/yiisoft/yii2-$ext")) { $this->stdout("Removing symlink $link.\n"); FileHelper::unlink($link); } } }
php
{ "resource": "" }
q241943
DevController.findDirs
validation
protected function findDirs($dir) { $list = []; $handle = @opendir($dir); if ($handle === false) { return []; } while (($file = readdir($handle)) !== false) { if ($file === '.' || $file === '..') { continue; } $path = $dir . DIRECTORY_SEPARATOR . $file; if (is_dir($path) && preg_match('/^yii2-(.*)$/', $file, $matches)) { $list[] = $matches[1]; } } closedir($handle); foreach ($list as $i => $e) { if ($e === 'composer') { // skip composer to not break composer update unset($list[$i]); } } return $list; }
php
{ "resource": "" }
q241944
JsonParser.parse
validation
public function parse($rawBody, $contentType) { try { $parameters = Json::decode($rawBody, $this->asArray); return $parameters === null ? [] : $parameters; } catch (InvalidArgumentException $e) { if ($this->throwException) { throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage()); } return []; } }
php
{ "resource": "" }
q241945
BaseManager.setDefaultRoles
validation
public function setDefaultRoles($roles) { if (is_array($roles)) { $this->defaultRoles = $roles; } elseif ($roles instanceof \Closure) { $roles = call_user_func($roles); if (!is_array($roles)) { throw new InvalidValueException('Default roles closure must return an array'); } $this->defaultRoles = $roles; } else { throw new InvalidArgumentException('Default roles must be either an array or a callable'); } }
php
{ "resource": "" }
q241946
BaseManager.getDefaultRoleInstances
validation
public function getDefaultRoleInstances() { $result = []; foreach ($this->defaultRoles as $roleName) { $result[$roleName] = $this->createRole($roleName); } return $result; }
php
{ "resource": "" }
q241947
SchemaBuilderTrait.primaryKey
validation
public function primaryKey($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_PK, $length); }
php
{ "resource": "" }
q241948
SchemaBuilderTrait.bigPrimaryKey
validation
public function bigPrimaryKey($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGPK, $length); }
php
{ "resource": "" }
q241949
SchemaBuilderTrait.char
validation
public function char($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_CHAR, $length); }
php
{ "resource": "" }
q241950
SchemaBuilderTrait.string
validation
public function string($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, $length); }
php
{ "resource": "" }
q241951
SchemaBuilderTrait.tinyInteger
validation
public function tinyInteger($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TINYINT, $length); }
php
{ "resource": "" }
q241952
SchemaBuilderTrait.smallInteger
validation
public function smallInteger($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_SMALLINT, $length); }
php
{ "resource": "" }
q241953
SchemaBuilderTrait.integer
validation
public function integer($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_INTEGER, $length); }
php
{ "resource": "" }
q241954
SchemaBuilderTrait.bigInteger
validation
public function bigInteger($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BIGINT, $length); }
php
{ "resource": "" }
q241955
SchemaBuilderTrait.float
validation
public function float($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_FLOAT, $precision); }
php
{ "resource": "" }
q241956
SchemaBuilderTrait.double
validation
public function double($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DOUBLE, $precision); }
php
{ "resource": "" }
q241957
SchemaBuilderTrait.decimal
validation
public function decimal($precision = null, $scale = null) { $length = []; if ($precision !== null) { $length[] = $precision; } if ($scale !== null) { $length[] = $scale; } return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DECIMAL, $length); }
php
{ "resource": "" }
q241958
SchemaBuilderTrait.dateTime
validation
public function dateTime($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_DATETIME, $precision); }
php
{ "resource": "" }
q241959
SchemaBuilderTrait.timestamp
validation
public function timestamp($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIMESTAMP, $precision); }
php
{ "resource": "" }
q241960
SchemaBuilderTrait.time
validation
public function time($precision = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_TIME, $precision); }
php
{ "resource": "" }
q241961
SchemaBuilderTrait.binary
validation
public function binary($length = null) { return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_BINARY, $length); }
php
{ "resource": "" }
q241962
SchemaBuilderTrait.money
validation
public function money($precision = null, $scale = null) { $length = []; if ($precision !== null) { $length[] = $precision; } if ($scale !== null) { $length[] = $scale; } return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_MONEY, $length); }
php
{ "resource": "" }
q241963
SchemaBuilderTrait.json
validation
public function json() { /* * TODO Remove in Yii 2.1 * * Disabled due to bug in MySQL extension * @link https://bugs.php.net/bug.php?id=70384 */ if (version_compare(PHP_VERSION, '5.6', '<') && $this->getDb()->getDriverName() === 'mysql') { throw new \yii\base\Exception('JSON column type is not supported in PHP < 5.6'); } return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_JSON); }
php
{ "resource": "" }
q241964
QueryBuilder.checkIntegrity
validation
public function checkIntegrity($check = true, $schema = '', $table = '') { $enable = $check ? 'CHECK' : 'NOCHECK'; $schema = $schema ?: $this->db->getSchema()->defaultSchema; $tableNames = $this->db->getTableSchema($table) ? [$table] : $this->db->getSchema()->getTableNames($schema); $viewNames = $this->db->getSchema()->getViewNames($schema); $tableNames = array_diff($tableNames, $viewNames); $command = ''; foreach ($tableNames as $tableName) { $tableName = $this->db->quoteTableName("{$schema}.{$tableName}"); $command .= "ALTER TABLE $tableName $enable CONSTRAINT ALL; "; } return $command; }
php
{ "resource": "" }
q241965
Controller.getUniqueId
validation
public function getUniqueId() { return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id; }
php
{ "resource": "" }
q241966
Controller.render
validation
public function render($view, $params = []) { $content = $this->getView()->render($view, $params, $this); return $this->renderContent($content); }
php
{ "resource": "" }
q241967
PDO.getAttribute
validation
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; } } }
php
{ "resource": "" }
q241968
Event.on
validation
public static function on($class, $name, $handler, $data = null, $append = true) { $class = ltrim($class, '\\'); if (strpos($class, '*') !== false || strpos($name, '*') !== false) { if ($append || empty(self::$_eventWildcards[$name][$class])) { self::$_eventWildcards[$name][$class][] = [$handler, $data]; } else { array_unshift(self::$_eventWildcards[$name][$class], [$handler, $data]); } return; } if ($append || empty(self::$_events[$name][$class])) { self::$_events[$name][$class][] = [$handler, $data]; } else { array_unshift(self::$_events[$name][$class], [$handler, $data]); } }
php
{ "resource": "" }
q241969
Event.off
validation
public static function off($class, $name, $handler = null) { $class = ltrim($class, '\\'); if (empty(self::$_events[$name][$class]) && empty(self::$_eventWildcards[$name][$class])) { return false; } if ($handler === null) { unset(self::$_events[$name][$class]); unset(self::$_eventWildcards[$name][$class]); return true; } // plain event names if (isset(self::$_events[$name][$class])) { $removed = false; foreach (self::$_events[$name][$class] as $i => $event) { if ($event[0] === $handler) { unset(self::$_events[$name][$class][$i]); $removed = true; } } if ($removed) { self::$_events[$name][$class] = array_values(self::$_events[$name][$class]); return $removed; } } // wildcard event names $removed = false; if (isset(self::$_eventWildcards[$name][$class])) { foreach (self::$_eventWildcards[$name][$class] as $i => $event) { if ($event[0] === $handler) { unset(self::$_eventWildcards[$name][$class][$i]); $removed = true; } } if ($removed) { self::$_eventWildcards[$name][$class] = array_values(self::$_eventWildcards[$name][$class]); // remove empty wildcards to save future redundant regex checks : if (empty(self::$_eventWildcards[$name][$class])) { unset(self::$_eventWildcards[$name][$class]); if (empty(self::$_eventWildcards[$name])) { unset(self::$_eventWildcards[$name]); } } } } return $removed; }
php
{ "resource": "" }
q241970
MigrateController.addDefaultPrimaryKey
validation
protected function addDefaultPrimaryKey(&$fields) { foreach ($fields as $field) { if (false !== strripos($field['decorators'], 'primarykey()')) { return; } } array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']); }
php
{ "resource": "" }
q241971
CreateAction.run
validation
public function run() { if ($this->checkAccess) { call_user_func($this->checkAccess, $this->id); } /* @var $model \yii\db\ActiveRecord */ $model = new $this->modelClass([ 'scenario' => $this->scenario, ]); $model->load(Yii::$app->getRequest()->getBodyParams(), ''); if ($model->save()) { $response = Yii::$app->getResponse(); $response->setStatusCode(201); $id = implode(',', array_values($model->getPrimaryKey(true))); $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true)); } elseif (!$model->hasErrors()) { throw new ServerErrorHttpException('Failed to create the object for unknown reason.'); } return $model; }
php
{ "resource": "" }
q241972
Schema.getUniqueIndexInformation
validation
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(); }
php
{ "resource": "" }
q241973
AttributesBehavior.evaluateAttributes
validation
public function evaluateAttributes($event) { if ($this->skipUpdateOnClean && $event->name === ActiveRecord::EVENT_BEFORE_UPDATE && empty($this->owner->dirtyAttributes) ) { return; } $attributes = array_keys(array_filter($this->attributes, function ($carry) use ($event) { return array_key_exists($event->name, $carry); })); if (!empty($this->order[$event->name])) { $attributes = array_merge( array_intersect((array) $this->order[$event->name], $attributes), array_diff($attributes, (array) $this->order[$event->name])); } foreach ($attributes as $attribute) { if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) { continue; } $this->owner->$attribute = $this->getValue($attribute, $event); } }
php
{ "resource": "" }
q241974
ArrayableTrait.toArray
validation
public function toArray(array $fields = [], array $expand = [], $recursive = true) { $data = []; foreach ($this->resolveFields($fields, $expand) as $field => $definition) { $attribute = is_string($definition) ? $this->$definition : $definition($this, $field); if ($recursive) { $nestedFields = $this->extractFieldsFor($fields, $field); $nestedExpand = $this->extractFieldsFor($expand, $field); if ($attribute instanceof Arrayable) { $attribute = $attribute->toArray($nestedFields, $nestedExpand); } elseif (is_array($attribute)) { $attribute = array_map( function ($item) use ($nestedFields, $nestedExpand) { if ($item instanceof Arrayable) { return $item->toArray($nestedFields, $nestedExpand); } return $item; }, $attribute ); } } $data[$field] = $attribute; } if ($this instanceof Linkable) { $data['_links'] = Link::serialize($this->getLinks()); } return $recursive ? ArrayHelper::toArray($data) : $data; }
php
{ "resource": "" }
q241975
PhpManager.init
validation
public function init() { parent::init(); $this->itemFile = Yii::getAlias($this->itemFile); $this->assignmentFile = Yii::getAlias($this->assignmentFile); $this->ruleFile = Yii::getAlias($this->ruleFile); $this->load(); }
php
{ "resource": "" }
q241976
PhpManager.getDirectPermissionsByUser
validation
protected function getDirectPermissionsByUser($userId) { $permissions = []; foreach ($this->getAssignments($userId) as $name => $assignment) { $permission = $this->items[$assignment->roleName]; if ($permission->type === Item::TYPE_PERMISSION) { $permissions[$name] = $permission; } } return $permissions; }
php
{ "resource": "" }
q241977
PhpManager.getInheritedPermissionsByUser
validation
protected function getInheritedPermissionsByUser($userId) { $assignments = $this->getAssignments($userId); $result = []; foreach (array_keys($assignments) as $roleName) { $this->getChildrenRecursive($roleName, $result); } if (empty($result)) { return []; } $permissions = []; foreach (array_keys($result) as $itemName) { if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) { $permissions[$itemName] = $this->items[$itemName]; } } return $permissions; }
php
{ "resource": "" }
q241978
PhpManager.saveToFile
validation
protected function saveToFile($data, $file) { file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX); $this->invalidateScriptCache($file); }
php
{ "resource": "" }
q241979
PhpManager.saveItems
validation
protected function saveItems() { $items = []; foreach ($this->items as $name => $item) { /* @var $item Item */ $items[$name] = array_filter( [ 'type' => $item->type, 'description' => $item->description, 'ruleName' => $item->ruleName, 'data' => $item->data, ] ); if (isset($this->children[$name])) { foreach ($this->children[$name] as $child) { /* @var $child Item */ $items[$name]['children'][] = $child->name; } } } $this->saveToFile($items, $this->itemFile); }
php
{ "resource": "" }
q241980
PhpManager.saveAssignments
validation
protected function saveAssignments() { $assignmentData = []; foreach ($this->assignments as $userId => $assignments) { foreach ($assignments as $name => $assignment) { /* @var $assignment Assignment */ $assignmentData[$userId][] = $assignment->roleName; } } $this->saveToFile($assignmentData, $this->assignmentFile); }
php
{ "resource": "" }
q241981
PhpManager.saveRules
validation
protected function saveRules() { $rules = []; foreach ($this->rules as $name => $rule) { $rules[$name] = serialize($rule); } $this->saveToFile($rules, $this->ruleFile); }
php
{ "resource": "" }
q241982
CacheableWidgetBehavior.beforeRun
validation
public function beforeRun($event) { $cacheKey = $this->getCacheKey(); $fragmentCacheConfiguration = $this->getFragmentCacheConfiguration(); if (!$this->owner->view->beginCache($cacheKey, $fragmentCacheConfiguration)) { $event->isValid = false; } }
php
{ "resource": "" }
q241983
CacheableWidgetBehavior.afterRun
validation
public function afterRun($event) { echo $event->result; $event->result = null; $this->owner->view->endCache(); }
php
{ "resource": "" }
q241984
CacheableWidgetBehavior.initializeEventHandlers
validation
private function initializeEventHandlers() { $this->owner->on(Widget::EVENT_BEFORE_RUN, [$this, 'beforeRun']); $this->owner->on(Widget::EVENT_AFTER_RUN, [$this, 'afterRun']); }
php
{ "resource": "" }
q241985
CacheableWidgetBehavior.getFragmentCacheConfiguration
validation
private function getFragmentCacheConfiguration() { $cache = $this->getCacheInstance(); $fragmentCacheConfiguration = [ 'cache' => $cache, 'duration' => $this->cacheDuration, 'dependency' => $this->cacheDependency, 'enabled' => $this->cacheEnabled, ]; return $fragmentCacheConfiguration; }
php
{ "resource": "" }
q241986
ColumnSchemaBuilder.unsigned
validation
public function unsigned() { switch ($this->type) { case Schema::TYPE_PK: $this->type = Schema::TYPE_UPK; break; case Schema::TYPE_BIGPK: $this->type = Schema::TYPE_UBIGPK; break; } $this->isUnsigned = true; return $this; }
php
{ "resource": "" }
q241987
ColumnSchemaBuilder.buildDefaultString
validation
protected function buildDefaultString() { if ($this->default === null) { return $this->isNotNull === false ? ' DEFAULT NULL' : ''; } $string = ' DEFAULT '; switch (gettype($this->default)) { case 'integer': $string .= (string) $this->default; break; case 'double': // ensure type cast always has . as decimal separator in all locales $string .= StringHelper::floatToString($this->default); break; case 'boolean': $string .= $this->default ? 'TRUE' : 'FALSE'; break; case 'object': $string .= (string) $this->default; break; default: $string .= "'{$this->default}'"; } return $string; }
php
{ "resource": "" }
q241988
ColumnSchemaBuilder.getTypeCategory
validation
protected function getTypeCategory() { return isset($this->categoryMap[$this->type]) ? $this->categoryMap[$this->type] : null; }
php
{ "resource": "" }
q241989
ColumnSchemaBuilder.buildCompleteString
validation
protected function buildCompleteString($format) { $placeholderValues = [ '{type}' => $this->type, '{length}' => $this->buildLengthString(), '{unsigned}' => $this->buildUnsignedString(), '{notnull}' => $this->buildNotNullString(), '{unique}' => $this->buildUniqueString(), '{default}' => $this->buildDefaultString(), '{check}' => $this->buildCheckString(), '{comment}' => $this->buildCommentString(), '{pos}' => $this->isFirst ? $this->buildFirstString() : $this->buildAfterString(), '{append}' => $this->buildAppendString(), ]; return strtr($format, $placeholderValues); }
php
{ "resource": "" }
q241990
GettextPoFile.load
validation
public function load($filePath, $context) { $pattern = '/(msgctxt\s+"(.*?(?<!\\\\))")?\s+' // context . 'msgid\s+((?:".*(?<!\\\\)"\s*)+)\s+' // message ID, i.e. original string . 'msgstr\s+((?:".*(?<!\\\\)"\s*)+)/'; // translated string $content = file_get_contents($filePath); $matches = []; $matchCount = preg_match_all($pattern, $content, $matches); $messages = []; for ($i = 0; $i < $matchCount; ++$i) { if ($matches[2][$i] === $context) { $id = $this->decode($matches[3][$i]); $message = $this->decode($matches[4][$i]); $messages[$id] = $message; } } return $messages; }
php
{ "resource": "" }
q241991
GettextPoFile.save
validation
public function save($filePath, $messages) { $language = str_replace('-', '_', basename(dirname($filePath))); $headers = [ 'msgid ""', 'msgstr ""', '"Project-Id-Version: \n"', '"POT-Creation-Date: \n"', '"PO-Revision-Date: \n"', '"Last-Translator: \n"', '"Language-Team: \n"', '"Language: ' . $language . '\n"', '"MIME-Version: 1.0\n"', '"Content-Type: text/plain; charset=' . Yii::$app->charset . '\n"', '"Content-Transfer-Encoding: 8bit\n"', ]; $content = implode("\n", $headers) . "\n\n"; foreach ($messages as $id => $message) { $separatorPosition = strpos($id, chr(4)); if ($separatorPosition !== false) { $content .= 'msgctxt "' . substr($id, 0, $separatorPosition) . "\"\n"; $id = substr($id, $separatorPosition + 1); } $content .= 'msgid "' . $this->encode($id) . "\"\n"; $content .= 'msgstr "' . $this->encode($message) . "\"\n\n"; } file_put_contents($filePath, $content); }
php
{ "resource": "" }
q241992
SluggableBehavior.validateSlug
validation
protected function validateSlug($slug) { /* @var $validator UniqueValidator */ /* @var $model BaseActiveRecord */ $validator = Yii::createObject(array_merge( [ 'class' => UniqueValidator::className(), ], $this->uniqueValidator )); $model = clone $this->owner; $model->clearErrors(); $model->{$this->slugAttribute} = $slug; $validator->validateAttribute($model, $this->slugAttribute); return !$model->hasErrors(); }
php
{ "resource": "" }
q241993
RateLimiter.addRateLimitHeaders
validation
public function addRateLimitHeaders($response, $limit, $remaining, $reset) { if ($this->enableRateLimitHeaders) { $response->getHeaders() ->set('X-Rate-Limit-Limit', $limit) ->set('X-Rate-Limit-Remaining', $remaining) ->set('X-Rate-Limit-Reset', $reset); } }
php
{ "resource": "" }
q241994
CaptchaAction.init
validation
public function init() { $this->fontFile = Yii::getAlias($this->fontFile); if (!is_file($this->fontFile)) { throw new InvalidConfigException("The font file does not exist: {$this->fontFile}"); } }
php
{ "resource": "" }
q241995
CaptchaAction.run
validation
public function run() { if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) { // AJAX request for regenerating code $code = $this->getVerifyCode(true); Yii::$app->response->format = Response::FORMAT_JSON; return [ 'hash1' => $this->generateValidationHash($code), 'hash2' => $this->generateValidationHash(strtolower($code)), // we add a random 'v' parameter so that FireFox can refresh the image // when src attribute of image tag is changed 'url' => Url::to([$this->id, 'v' => uniqid('', true)]), ]; } $this->setHttpHeaders(); Yii::$app->response->format = Response::FORMAT_RAW; return $this->renderImage($this->getVerifyCode()); }
php
{ "resource": "" }
q241996
CaptchaAction.validate
validation
public function validate($input, $caseSensitive) { $code = $this->getVerifyCode(); $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0; $session = Yii::$app->getSession(); $session->open(); $name = $this->getSessionKey() . 'count'; $session[$name] += 1; if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) { $this->getVerifyCode(true); } return $valid; }
php
{ "resource": "" }
q241997
CaptchaAction.renderImage
validation
protected function renderImage($code) { if (isset($this->imageLibrary)) { $imageLibrary = $this->imageLibrary; } else { $imageLibrary = Captcha::checkRequirements(); } if ($imageLibrary === 'gd') { return $this->renderImageByGD($code); } elseif ($imageLibrary === 'imagick') { return $this->renderImageByImagick($code); } throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported"); }
php
{ "resource": "" }
q241998
CaptchaAction.renderImageByGD
validation
protected function renderImageByGD($code) { $image = imagecreatetruecolor($this->width, $this->height); $backColor = imagecolorallocate( $image, (int) ($this->backColor % 0x1000000 / 0x10000), (int) ($this->backColor % 0x10000 / 0x100), $this->backColor % 0x100 ); imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor); imagecolordeallocate($image, $backColor); if ($this->transparent) { imagecolortransparent($image, $backColor); } $foreColor = imagecolorallocate( $image, (int) ($this->foreColor % 0x1000000 / 0x10000), (int) ($this->foreColor % 0x10000 / 0x100), $this->foreColor % 0x100 ); $length = strlen($code); $box = imagettfbbox(30, 0, $this->fontFile, $code); $w = $box[4] - $box[0] + $this->offset * ($length - 1); $h = $box[1] - $box[5]; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 10; $y = round($this->height * 27 / 40); for ($i = 0; $i < $length; ++$i) { $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8); $angle = mt_rand(-10, 10); $letter = $code[$i]; $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter); $x = $box[2] + $this->offset; } imagecolordeallocate($image, $foreColor); ob_start(); imagepng($image); imagedestroy($image); return ob_get_clean(); }
php
{ "resource": "" }
q241999
CaptchaAction.renderImageByImagick
validation
protected function renderImageByImagick($code) { $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT)); $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT)); $image = new \Imagick(); $image->newImage($this->width, $this->height, $backColor); $draw = new \ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize(30); $fontMetrics = $image->queryFontMetrics($draw, $code); $length = strlen($code); $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1); $h = (int) $fontMetrics['textHeight'] - 8; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 10; $y = round($this->height * 27 / 40); for ($i = 0; $i < $length; ++$i) { $draw = new \ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8)); $draw->setFillColor($foreColor); $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]); $fontMetrics = $image->queryFontMetrics($draw, $code[$i]); $x += (int) $fontMetrics['textWidth'] + $this->offset; } $image->setImageFormat('png'); return $image->getImageBlob(); }
php
{ "resource": "" }