_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q241400
Query.having
validation
public function having($condition, $params = []) { $this->having = $condition; $this->addParams($params); return $this; }
php
{ "resource": "" }
q241401
Query.andHaving
validation
public function andHaving($condition, $params = []) { if ($this->having === null) { $this->having = $condition; } else { $this->having = ['and', $this->having, $condition]; } $this->addParams($params); return $this; }
php
{ "resource": "" }
q241402
Query.orHaving
validation
public function orHaving($condition, $params = []) { if ($this->having === null) { $this->having = $condition; } else { $this->having = ['or', $this->having, $condition]; } $this->addParams($params); return $this; }
php
{ "resource": "" }
q241403
Query.addParams
validation
public function addParams($params) { if (!empty($params)) { if (empty($this->params)) { $this->params = $params; } else { foreach ($params as $name => $value) { if (is_int($name)) { $this->params[] = $value; } else { $this->params[$name] = $value; } } } } return $this; }
php
{ "resource": "" }
q241404
Query.cache
validation
public function cache($duration = true, $dependency = null) { $this->queryCacheDuration = $duration; $this->queryCacheDependency = $dependency; return $this; }
php
{ "resource": "" }
q241405
Query.create
validation
public static function create($from) { return new self([ 'where' => $from->where, 'limit' => $from->limit, 'offset' => $from->offset, 'orderBy' => $from->orderBy, 'indexBy' => $from->indexBy, 'select' => $from->select, 'selectOption' => $from->selectOption, 'distinct' => $from->distinct, 'from' => $from->from, 'groupBy' => $from->groupBy, 'join' => $from->join, 'having' => $from->having, 'union' => $from->union, 'params' => $from->params, ]); }
php
{ "resource": "" }
q241406
Link.serialize
validation
public static function serialize(array $links) { foreach ($links as $rel => $link) { if (is_array($link)) { foreach ($link as $i => $l) { $link[$i] = $l instanceof self ? array_filter((array) $l) : ['href' => $l]; } $links[$rel] = $link; } elseif (!$link instanceof self) { $links[$rel] = ['href' => $link]; } } return $links; }
php
{ "resource": "" }
q241407
GettextMessageSource.loadMessagesFromFile
validation
protected function loadMessagesFromFile($messageFile, $category) { if (is_file($messageFile)) { if ($this->useMoFile) { $gettextFile = new GettextMoFile(['useBigEndian' => $this->useBigEndian]); } else { $gettextFile = new GettextPoFile(); } $messages = $gettextFile->load($messageFile, $category); if (!is_array($messages)) { $messages = []; } return $messages; } return null; }
php
{ "resource": "" }
q241408
BaseFileHelper.loadMimeTypes
validation
protected static function loadMimeTypes($magicFile) { if ($magicFile === null) { $magicFile = static::$mimeMagicFile; } $magicFile = Yii::getAlias($magicFile); if (!isset(self::$_mimeTypes[$magicFile])) { self::$_mimeTypes[$magicFile] = require $magicFile; } return self::$_mimeTypes[$magicFile]; }
php
{ "resource": "" }
q241409
BaseFileHelper.loadMimeAliases
validation
protected static function loadMimeAliases($aliasesFile) { if ($aliasesFile === null) { $aliasesFile = static::$mimeAliasesFile; } $aliasesFile = Yii::getAlias($aliasesFile); if (!isset(self::$_mimeAliases[$aliasesFile])) { self::$_mimeAliases[$aliasesFile] = require $aliasesFile; } return self::$_mimeAliases[$aliasesFile]; }
php
{ "resource": "" }
q241410
BaseFileHelper.unlink
validation
public static function unlink($path) { $isWindows = DIRECTORY_SEPARATOR === '\\'; if (!$isWindows) { return unlink($path); } if (is_link($path) && is_dir($path)) { return rmdir($path); } try { return unlink($path); } catch (ErrorException $e) { // last resort measure for Windows if (function_exists('exec') && file_exists($path)) { exec('DEL /F/Q ' . escapeshellarg($path)); return !file_exists($path); } return false; } }
php
{ "resource": "" }
q241411
BaseFileHelper.filterPath
validation
public static function filterPath($path, $options) { if (isset($options['filter'])) { $result = call_user_func($options['filter'], $path); if (is_bool($result)) { return $result; } } if (empty($options['except']) && empty($options['only'])) { return true; } $path = str_replace('\\', '/', $path); if (!empty($options['except'])) { if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) { return $except['flags'] & self::PATTERN_NEGATIVE; } } if (!empty($options['only']) && !is_dir($path)) { if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) { // don't check PATTERN_NEGATIVE since those entries are not prefixed with ! return true; } return false; } return true; }
php
{ "resource": "" }
q241412
BaseFileHelper.createDirectory
validation
public static function createDirectory($path, $mode = 0775, $recursive = true) { if (is_dir($path)) { return true; } $parentDir = dirname($path); // recurse if parent dir does not exist and we are not at the root of the file system. if ($recursive && !is_dir($parentDir) && $parentDir !== $path) { static::createDirectory($parentDir, $mode, true); } try { if (!mkdir($path, $mode)) { return false; } } catch (\Exception $e) { if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288 throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e); } } try { return chmod($path, $mode); } catch (\Exception $e) { throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e); } }
php
{ "resource": "" }
q241413
BaseFileHelper.matchPathname
validation
private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags) { // match with FNM_PATHNAME; the pattern has base implicitly in front of it. if (isset($pattern[0]) && $pattern[0] === '/') { $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern)); if ($firstWildcard !== false && $firstWildcard !== 0) { $firstWildcard--; } } $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1); $name = StringHelper::byteSubstr($path, -$namelen, $namelen); if ($firstWildcard !== 0) { if ($firstWildcard === false) { $firstWildcard = StringHelper::byteLength($pattern); } // if the non-wildcard part is longer than the remaining pathname, surely it cannot match. if ($firstWildcard > $namelen) { return false; } if (strncmp($pattern, $name, $firstWildcard)) { return false; } $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern)); $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen); // If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all. if (empty($pattern) && empty($name)) { return true; } } $matchOptions = [ 'filePath' => true ]; if ($flags & self::PATTERN_CASE_INSENSITIVE) { $matchOptions['caseSensitive'] = false; } return StringHelper::matchWildcard($pattern, $name, $matchOptions); }
php
{ "resource": "" }
q241414
BaseFileHelper.firstWildcardInPattern
validation
private static function firstWildcardInPattern($pattern) { $wildcards = ['*', '?', '[', '\\']; $wildcardSearch = function ($r, $c) use ($pattern) { $p = strpos($pattern, $c); return $r === false ? $p : ($p === false ? $r : min($r, $p)); }; return array_reduce($wildcards, $wildcardSearch, false); }
php
{ "resource": "" }
q241415
AuthMethod.isOptional
validation
protected function isOptional($action) { $id = $this->getActionId($action); foreach ($this->optional as $pattern) { if (StringHelper::matchWildcard($pattern, $id)) { return true; } } return false; }
php
{ "resource": "" }
q241416
BaseArrayHelper.remove
validation
public static function remove(&$array, $key, $default = null) { if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) { $value = $array[$key]; unset($array[$key]); return $value; } return $default; }
php
{ "resource": "" }
q241417
BaseArrayHelper.removeValue
validation
public static function removeValue(&$array, $value) { $result = []; if (is_array($array)) { foreach ($array as $key => $val) { if ($val === $value) { $result[$key] = $val; unset($array[$key]); } } } return $result; }
php
{ "resource": "" }
q241418
BaseArrayHelper.htmlDecode
validation
public static function htmlDecode($data, $valuesOnly = true) { $d = []; foreach ($data as $key => $value) { if (!$valuesOnly && is_string($key)) { $key = htmlspecialchars_decode($key, ENT_QUOTES); } if (is_string($value)) { $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES); } elseif (is_array($value)) { $d[$key] = static::htmlDecode($value); } else { $d[$key] = $value; } } return $d; }
php
{ "resource": "" }
q241419
BaseArrayHelper.filter
validation
public static function filter($array, $filters) { $result = []; $forbiddenVars = []; foreach ($filters as $var) { $keys = explode('.', $var); $globalKey = $keys[0]; $localKey = isset($keys[1]) ? $keys[1] : null; if ($globalKey[0] === '!') { $forbiddenVars[] = [ substr($globalKey, 1), $localKey, ]; continue; } if (!array_key_exists($globalKey, $array)) { continue; } if ($localKey === null) { $result[$globalKey] = $array[$globalKey]; continue; } if (!isset($array[$globalKey][$localKey])) { continue; } if (!array_key_exists($globalKey, $result)) { $result[$globalKey] = []; } $result[$globalKey][$localKey] = $array[$globalKey][$localKey]; } foreach ($forbiddenVars as $var) { list($globalKey, $localKey) = $var; if (array_key_exists($globalKey, $result)) { unset($result[$globalKey][$localKey]); } } return $result; }
php
{ "resource": "" }
q241420
AssetManager.loadBundle
validation
protected function loadBundle($name, $config = [], $publish = true) { if (!isset($config['class'])) { $config['class'] = $name; } /* @var $bundle AssetBundle */ $bundle = Yii::createObject($config); if ($publish) { $bundle->publish($this); } return $bundle; }
php
{ "resource": "" }
q241421
AssetManager.loadDummyBundle
validation
protected function loadDummyBundle($name) { if (!isset($this->_dummyBundles[$name])) { $this->_dummyBundles[$name] = $this->loadBundle($name, [ 'sourcePath' => null, 'js' => [], 'css' => [], 'depends' => [], ]); } return $this->_dummyBundles[$name]; }
php
{ "resource": "" }
q241422
AssetManager.getConverter
validation
public function getConverter() { if ($this->_converter === null) { $this->_converter = Yii::createObject(AssetConverter::className()); } elseif (is_array($this->_converter) || is_string($this->_converter)) { if (is_array($this->_converter) && !isset($this->_converter['class'])) { $this->_converter['class'] = AssetConverter::className(); } $this->_converter = Yii::createObject($this->_converter); } return $this->_converter; }
php
{ "resource": "" }
q241423
AssetManager.publishFile
validation
protected function publishFile($src) { $dir = $this->hash($src); $fileName = basename($src); $dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir; $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName; if (!is_dir($dstDir)) { FileHelper::createDirectory($dstDir, $this->dirMode, true); } if ($this->linkAssets) { if (!is_file($dstFile)) { try { // fix #6226 symlinking multi threaded symlink($src, $dstFile); } catch (\Exception $e) { if (!is_file($dstFile)) { throw $e; } } } } elseif (@filemtime($dstFile) < @filemtime($src)) { copy($src, $dstFile); if ($this->fileMode !== null) { @chmod($dstFile, $this->fileMode); } } if ($this->appendTimestamp && ($timestamp = @filemtime($dstFile)) > 0) { $fileName = $fileName . "?v=$timestamp"; } return [$dstFile, $this->baseUrl . "/$dir/$fileName"]; }
php
{ "resource": "" }
q241424
AssetManager.getPublishedUrl
validation
public function getPublishedUrl($path) { $path = Yii::getAlias($path); if (isset($this->_published[$path])) { return $this->_published[$path][1]; } if (is_string($path) && ($path = realpath($path)) !== false) { return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : ''); } return false; }
php
{ "resource": "" }
q241425
FragmentCache.init
validation
public function init() { parent::init(); $this->cache = $this->enabled ? Instance::ensure($this->cache, 'yii\caching\CacheInterface') : null; if ($this->cache instanceof CacheInterface && $this->getCachedContent() === false) { $this->getView()->pushDynamicContent($this); ob_start(); ob_implicit_flush(false); } }
php
{ "resource": "" }
q241426
InputWidget.renderInputHtml
validation
protected function renderInputHtml($type) { if ($this->hasModel()) { return Html::activeInput($type, $this->model, $this->attribute, $this->options); } return Html::input($type, $this->name, $this->value, $this->options); }
php
{ "resource": "" }
q241427
Markdown.renderStrike
validation
protected function renderStrike($element) { return Console::ansiFormat($this->parseInline($this->renderAbsy($element[1])), [Console::CROSSED_OUT]); }
php
{ "resource": "" }
q241428
BatchQueryResult.fetchData
validation
protected function fetchData() { if ($this->_dataReader === null) { $this->_dataReader = $this->query->createCommand($this->db)->query(); } $rows = []; $count = 0; while ($count++ < $this->batchSize && ($row = $this->_dataReader->read())) { $rows[] = $row; } return $this->query->populate($rows); }
php
{ "resource": "" }
q241429
QueryBuilder.getColumnDefinition
validation
private function getColumnDefinition($table, $column) { $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->db->quoteTableName($table))->queryOne(); if ($row === false) { throw new Exception("Unable to find column '$column' in table '$table'."); } if (isset($row['Create Table'])) { $sql = $row['Create Table']; } else { $row = array_values($row); $sql = $row[1]; } $sql = preg_replace('/^[^(]+\((.*)\).*$/', '\1', $sql); $sql = str_replace(', [', ",\n[", $sql); if (preg_match_all('/^\s*\[(.*?)\]\s+(.*?),?$/m', $sql, $matches)) { foreach ($matches[1] as $i => $c) { if ($c === $column) { return $matches[2][$i]; } } } return null; }
php
{ "resource": "" }
q241430
Schema.setTransactionIsolationLevel
validation
public function setTransactionIsolationLevel($level) { switch ($level) { case Transaction::SERIALIZABLE: $this->db->createCommand('PRAGMA read_uncommitted = False;')->execute(); break; case Transaction::READ_UNCOMMITTED: $this->db->createCommand('PRAGMA read_uncommitted = True;')->execute(); break; default: throw new NotSupportedException(get_class($this) . ' only supports transaction isolation levels READ UNCOMMITTED and SERIALIZABLE.'); } }
php
{ "resource": "" }
q241431
Schema.loadTableColumnsInfo
validation
private function loadTableColumnsInfo($tableName) { $tableColumns = $this->db->createCommand('PRAGMA TABLE_INFO (' . $this->quoteValue($tableName) . ')')->queryAll(); $tableColumns = $this->normalizePdoRowKeyCase($tableColumns, true); return ArrayHelper::index($tableColumns, 'cid'); }
php
{ "resource": "" }
q241432
Response.setStatusCodeByException
validation
public function setStatusCodeByException($e) { if ($e instanceof HttpException) { $this->setStatusCode($e->statusCode); } else { $this->setStatusCode(500); } return $this; }
php
{ "resource": "" }
q241433
Response.send
validation
public function send() { if ($this->isSent) { return; } $this->trigger(self::EVENT_BEFORE_SEND); $this->prepare(); $this->trigger(self::EVENT_AFTER_PREPARE); $this->sendHeaders(); $this->sendContent(); $this->trigger(self::EVENT_AFTER_SEND); $this->isSent = true; }
php
{ "resource": "" }
q241434
Response.clear
validation
public function clear() { $this->_headers = null; $this->_cookies = null; $this->_statusCode = 200; $this->statusText = 'OK'; $this->data = null; $this->stream = null; $this->content = null; $this->isSent = false; }
php
{ "resource": "" }
q241435
Response.sendFile
validation
public function sendFile($filePath, $attachmentName = null, $options = []) { if (!isset($options['mimeType'])) { $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath); } if ($attachmentName === null) { $attachmentName = basename($filePath); } $handle = fopen($filePath, 'rb'); $this->sendStreamAsFile($handle, $attachmentName, $options); return $this; }
php
{ "resource": "" }
q241436
Response.sendContentAsFile
validation
public function sendContentAsFile($content, $attachmentName, $options = []) { $headers = $this->getHeaders(); $contentLength = StringHelper::byteLength($content); $range = $this->getHttpRange($contentLength); if ($range === false) { $headers->set('Content-Range', "bytes */$contentLength"); throw new RangeNotSatisfiableHttpException(); } list($begin, $end) = $range; if ($begin != 0 || $end != $contentLength - 1) { $this->setStatusCode(206); $headers->set('Content-Range', "bytes $begin-$end/$contentLength"); $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1); } else { $this->setStatusCode(200); $this->content = $content; } $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream'; $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1); $this->format = self::FORMAT_RAW; return $this; }
php
{ "resource": "" }
q241437
Response.sendStreamAsFile
validation
public function sendStreamAsFile($handle, $attachmentName, $options = []) { $headers = $this->getHeaders(); if (isset($options['fileSize'])) { $fileSize = $options['fileSize']; } else { fseek($handle, 0, SEEK_END); $fileSize = ftell($handle); } $range = $this->getHttpRange($fileSize); if ($range === false) { $headers->set('Content-Range', "bytes */$fileSize"); throw new RangeNotSatisfiableHttpException(); } list($begin, $end) = $range; if ($begin != 0 || $end != $fileSize - 1) { $this->setStatusCode(206); $headers->set('Content-Range', "bytes $begin-$end/$fileSize"); } else { $this->setStatusCode(200); } $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream'; $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1); $this->format = self::FORMAT_RAW; $this->stream = [$handle, $begin, $end]; return $this; }
php
{ "resource": "" }
q241438
Response.setDownloadHeaders
validation
public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null) { $headers = $this->getHeaders(); $disposition = $inline ? 'inline' : 'attachment'; $headers->setDefault('Pragma', 'public') ->setDefault('Accept-Ranges', 'bytes') ->setDefault('Expires', '0') ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName)); if ($mimeType !== null) { $headers->setDefault('Content-Type', $mimeType); } if ($contentLength !== null) { $headers->setDefault('Content-Length', $contentLength); } return $this; }
php
{ "resource": "" }
q241439
Response.xSendFile
validation
public function xSendFile($filePath, $attachmentName = null, $options = []) { if ($attachmentName === null) { $attachmentName = basename($filePath); } if (isset($options['mimeType'])) { $mimeType = $options['mimeType']; } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) { $mimeType = 'application/octet-stream'; } if (isset($options['xHeader'])) { $xHeader = $options['xHeader']; } else { $xHeader = 'X-Sendfile'; } $disposition = empty($options['inline']) ? 'attachment' : 'inline'; $this->getHeaders() ->setDefault($xHeader, $filePath) ->setDefault('Content-Type', $mimeType) ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName)); $this->format = self::FORMAT_RAW; return $this; }
php
{ "resource": "" }
q241440
Response.redirect
validation
public function redirect($url, $statusCode = 302, $checkAjax = true) { if (is_array($url) && isset($url[0])) { // ensure the route is absolute $url[0] = '/' . ltrim($url[0], '/'); } $url = Url::to($url); if (strncmp($url, '/', 1) === 0 && strncmp($url, '//', 2) !== 0) { $url = Yii::$app->getRequest()->getHostInfo() . $url; } if ($checkAjax) { if (Yii::$app->getRequest()->getIsAjax()) { if (Yii::$app->getRequest()->getHeaders()->get('X-Ie-Redirect-Compatibility') !== null && $statusCode === 302) { // Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670 $statusCode = 200; } if (Yii::$app->getRequest()->getIsPjax()) { $this->getHeaders()->set('X-Pjax-Url', $url); } else { $this->getHeaders()->set('X-Redirect', $url); } } else { $this->getHeaders()->set('Location', $url); } } else { $this->getHeaders()->set('Location', $url); } $this->setStatusCode($statusCode); return $this; }
php
{ "resource": "" }
q241441
ExistValidator.checkTargetRelationExistence
validation
private function checkTargetRelationExistence($model, $attribute) { $exists = false; /** @var ActiveQuery $relationQuery */ $relationQuery = $model->{'get' . ucfirst($this->targetRelation)}(); if ($this->filter instanceof \Closure) { call_user_func($this->filter, $relationQuery); } elseif ($this->filter !== null) { $relationQuery->andWhere($this->filter); } if ($this->forceMasterDb && method_exists($model::getDb(), 'useMaster')) { $model::getDb()->useMaster(function() use ($relationQuery, &$exists) { $exists = $relationQuery->exists(); }); } else { $exists = $relationQuery->exists(); } if (!$exists) { $this->addError($model, $attribute, $this->message); } }
php
{ "resource": "" }
q241442
ExistValidator.valueExists
validation
private function valueExists($targetClass, $query, $value) { $db = $targetClass::getDb(); $exists = false; if ($this->forceMasterDb && method_exists($db, 'useMaster')) { $db->useMaster(function ($db) use ($query, $value, &$exists) { $exists = $this->queryValueExists($query, $value); }); } else { $exists = $this->queryValueExists($query, $value); } return $exists; }
php
{ "resource": "" }
q241443
ExistValidator.queryValueExists
validation
private function queryValueExists($query, $value) { if (is_array($value)) { return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ; } return $query->exists(); }
php
{ "resource": "" }
q241444
ExistValidator.createQuery
validation
protected function createQuery($targetClass, $condition) { /* @var $targetClass \yii\db\ActiveRecordInterface */ $query = $targetClass::find()->andWhere($condition); if ($this->filter instanceof \Closure) { call_user_func($this->filter, $query); } elseif ($this->filter !== null) { $query->andWhere($this->filter); } return $query; }
php
{ "resource": "" }
q241445
BaseConsole.moveCursorTo
validation
public static function moveCursorTo($column, $row = null) { if ($row === null) { echo "\033[" . (int) $column . 'G'; } else { echo "\033[" . (int) $row . ';' . (int) $column . 'H'; } }
php
{ "resource": "" }
q241446
BaseConsole.wrapText
validation
public static function wrapText($text, $indent = 0, $refresh = false) { $size = static::getScreenSize($refresh); if ($size === false || $size[0] <= $indent) { return $text; } $pad = str_repeat(' ', $indent); $lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n", true)); $first = true; foreach ($lines as $i => $line) { if ($first) { $first = false; continue; } $lines[$i] = $pad . $line; } return implode("\n", $lines); }
php
{ "resource": "" }
q241447
BaseConsole.stdin
validation
public static function stdin($raw = false) { return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL); }
php
{ "resource": "" }
q241448
BaseConsole.confirm
validation
public static function confirm($message, $default = false) { while (true) { static::stdout($message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:'); $input = trim(static::stdin()); if (empty($input)) { return $default; } if (!strcasecmp($input, 'y') || !strcasecmp($input, 'yes')) { return true; } if (!strcasecmp($input, 'n') || !strcasecmp($input, 'no')) { return false; } } }
php
{ "resource": "" }
q241449
BaseConsole.select
validation
public static function select($prompt, $options = []) { top: static::stdout("$prompt [" . implode(',', array_keys($options)) . ',?]: '); $input = static::stdin(); if ($input === '?') { foreach ($options as $key => $value) { static::output(" $key - $value"); } static::output(' ? - Show help'); goto top; } elseif (!array_key_exists($input, $options)) { goto top; } return $input; }
php
{ "resource": "" }
q241450
XmlResponseFormatter.formatScalarValue
validation
protected function formatScalarValue($value) { if ($value === true) { return 'true'; } if ($value === false) { return 'false'; } if (is_float($value)) { return StringHelper::floatToString($value); } return (string) $value; }
php
{ "resource": "" }
q241451
XmlResponseFormatter.getValidXmlElementName
validation
protected function getValidXmlElementName($name) { if (empty($name) || is_int($name) || !$this->isValidXmlName($name)) { return $this->itemTag; } return $name; }
php
{ "resource": "" }
q241452
MaskedInput.hashPluginOptions
validation
protected function hashPluginOptions($view) { $encOptions = empty($this->clientOptions) ? '{}' : Json::htmlEncode($this->clientOptions); $this->_hashVar = self::PLUGIN_NAME . '_' . hash('crc32', $encOptions); $this->options['data-plugin-' . self::PLUGIN_NAME] = $this->_hashVar; $view->registerJs("var {$this->_hashVar} = {$encOptions};", View::POS_HEAD); }
php
{ "resource": "" }
q241453
MaskedInput.initClientOptions
validation
protected function initClientOptions() { $options = $this->clientOptions; foreach ($options as $key => $value) { if ( !$value instanceof JsExpression && in_array($key, [ 'oncomplete', 'onincomplete', 'oncleared', 'onKeyUp', 'onKeyDown', 'onBeforeMask', 'onBeforePaste', 'onUnMask', 'isComplete', 'determineActiveMasksetIndex', ], true) ) { $options[$key] = new JsExpression($value); } } $this->clientOptions = $options; }
php
{ "resource": "" }
q241454
MaskedInput.registerClientScript
validation
public function registerClientScript() { $js = ''; $view = $this->getView(); $this->initClientOptions(); if (!empty($this->mask)) { $this->clientOptions['mask'] = $this->mask; } $this->hashPluginOptions($view); if (is_array($this->definitions) && !empty($this->definitions)) { $js .= ucfirst(self::PLUGIN_NAME) . '.extendDefinitions(' . Json::htmlEncode($this->definitions) . ');'; } if (is_array($this->aliases) && !empty($this->aliases)) { $js .= ucfirst(self::PLUGIN_NAME) . '.extendAliases(' . Json::htmlEncode($this->aliases) . ');'; } $id = $this->options['id']; $js .= 'jQuery("#' . $id . '").' . self::PLUGIN_NAME . '(' . $this->_hashVar . ');'; MaskedInputAsset::register($view); $view->registerJs($js); }
php
{ "resource": "" }
q241455
Request.getParams
validation
public function getParams() { if ($this->_params === null) { if (isset($_SERVER['argv'])) { $this->_params = $_SERVER['argv']; array_shift($this->_params); } else { $this->_params = []; } } return $this->_params; }
php
{ "resource": "" }
q241456
Request.resolve
validation
public function resolve() { $rawParams = $this->getParams(); $endOfOptionsFound = false; if (isset($rawParams[0])) { $route = array_shift($rawParams); if ($route === '--') { $endOfOptionsFound = true; $route = array_shift($rawParams); } } else { $route = ''; } $params = []; $prevOption = null; foreach ($rawParams as $param) { if ($endOfOptionsFound) { $params[] = $param; } elseif ($param === '--') { $endOfOptionsFound = true; } elseif (preg_match('/^--([\w-]+)(?:=(.*))?$/', $param, $matches)) { $name = $matches[1]; if (is_numeric(substr($name, 0, 1))) { throw new Exception('Parameter "' . $name . '" is not valid'); } if ($name !== Application::OPTION_APPCONFIG) { $params[$name] = isset($matches[2]) ? $matches[2] : true; $prevOption = &$params[$name]; } } elseif (preg_match('/^-([\w-]+)(?:=(.*))?$/', $param, $matches)) { $name = $matches[1]; if (is_numeric($name)) { $params[] = $param; } else { $params['_aliases'][$name] = isset($matches[2]) ? $matches[2] : true; $prevOption = &$params['_aliases'][$name]; } } elseif ($prevOption === true) { // `--option value` syntax $prevOption = $param; } else { $params[] = $param; } } return [$route, $params]; }
php
{ "resource": "" }
q241457
Formatter.asNtext
validation
public function asNtext($value) { if ($value === null) { return $this->nullDisplay; } return nl2br(Html::encode($value)); }
php
{ "resource": "" }
q241458
Formatter.asImage
validation
public function asImage($value, $options = []) { if ($value === null) { return $this->nullDisplay; } return Html::img($value, $options); }
php
{ "resource": "" }
q241459
Formatter.asUrl
validation
public function asUrl($value, $options = []) { if ($value === null) { return $this->nullDisplay; } $url = $value; if (strpos($url, '://') === false) { $url = 'http://' . $url; } return Html::a(Html::encode($value), $url, $options); }
php
{ "resource": "" }
q241460
Formatter.asBoolean
validation
public function asBoolean($value) { if ($value === null) { return $this->nullDisplay; } return $value ? $this->booleanFormat[1] : $this->booleanFormat[0]; }
php
{ "resource": "" }
q241461
Formatter.formatNumber
validation
private function formatNumber($value, $decimals, $maxPosition, $formatBase, $options, $textOptions) { $value = $this->normalizeNumericValue($value); $position = 0; if (is_array($formatBase)) { $maxPosition = count($formatBase) - 1; } do { if (is_array($formatBase)) { if (!isset($formatBase[$position + 1])) { break; } if (abs($value) < $formatBase[$position + 1]) { break; } } else { if (abs($value) < $formatBase) { break; } $value /= $formatBase; } $position++; } while ($position < $maxPosition + 1); if (is_array($formatBase) && $position !== 0) { $value /= $formatBase[$position]; } // no decimals for smallest unit if ($position === 0) { $decimals = 0; } elseif ($decimals !== null) { $value = round($value, $decimals); } // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B $oldThousandSeparator = $this->thousandSeparator; $this->thousandSeparator = ''; if ($this->_intlLoaded && !isset($options[NumberFormatter::GROUPING_USED])) { $options[NumberFormatter::GROUPING_USED] = false; } // format the size value $params = [ // this is the unformatted number used for the plural rule // abs() to make sure the plural rules work correctly on negative numbers, intl does not cover this // http://english.stackexchange.com/questions/9735/is-1-singular-or-plural 'n' => abs($value), // this is the formatted number used for display 'nFormatted' => $this->asDecimal($value, $decimals, $options, $textOptions), ]; $this->thousandSeparator = $oldThousandSeparator; return [$params, $position]; }
php
{ "resource": "" }
q241462
Formatter.normalizeNumericValue
validation
protected function normalizeNumericValue($value) { if (empty($value)) { return 0; } if (is_string($value) && is_numeric($value)) { $value = (float) $value; } if (!is_numeric($value)) { throw new InvalidArgumentException("'$value' is not a numeric value."); } return $value; }
php
{ "resource": "" }
q241463
Formatter.isNormalizedValueMispresented
validation
protected function isNormalizedValueMispresented($value, $normalizedValue) { if (empty($value)) { $value = 0; } return (string) $normalizedValue !== $this->normalizeNumericStringValue((string) $value); }
php
{ "resource": "" }
q241464
Formatter.normalizeNumericStringValue
validation
protected function normalizeNumericStringValue($value) { $powerPosition = strrpos($value, 'E'); if ($powerPosition !== false) { $valuePart = substr($value, 0, $powerPosition); $powerPart = substr($value, $powerPosition + 1); } else { $powerPart = null; $valuePart = $value; } $separatorPosition = strrpos($valuePart, '.'); if ($separatorPosition !== false) { $integerPart = substr($valuePart, 0, $separatorPosition); $fractionalPart = substr($valuePart, $separatorPosition + 1); } else { $integerPart = $valuePart; $fractionalPart = null; } // truncate insignificant zeros, keep minus $integerPart = preg_replace('/^\+?(-?)0*(\d+)$/', '$1$2', $integerPart); // for zeros only leave one zero, keep minus $integerPart = preg_replace('/^\+?(-?)0*$/', '${1}0', $integerPart); if ($fractionalPart !== null) { // truncate insignificant zeros $fractionalPart = rtrim($fractionalPart, '0'); if (empty($fractionalPart)) { $fractionalPart = $powerPart !== null ? '0' : null; } } $normalizedValue = $integerPart; if ($fractionalPart !== null) { $normalizedValue .= '.' . $fractionalPart; } elseif ($normalizedValue === '-0') { $normalizedValue = '0'; } if ($powerPart !== null) { $normalizedValue .= 'E' . $powerPart; } return $normalizedValue; }
php
{ "resource": "" }
q241465
Formatter.asIntegerStringFallback
validation
protected function asIntegerStringFallback($value) { if (empty($value)) { $value = 0; } $value = $this->normalizeNumericStringValue((string) $value); $separatorPosition = strrpos($value, '.'); if ($separatorPosition !== false) { $integerPart = substr($value, 0, $separatorPosition); } else { $integerPart = $value; } return $this->asDecimalStringFallback($integerPart, 0); }
php
{ "resource": "" }
q241466
Formatter.asPercentStringFallback
validation
protected function asPercentStringFallback($value, $decimals = null) { if (empty($value)) { $value = 0; } if ($decimals === null) { $decimals = 0; } $value = $this->normalizeNumericStringValue((string) $value); $separatorPosition = strrpos($value, '.'); if ($separatorPosition !== false) { $integerPart = substr($value, 0, $separatorPosition); $fractionalPart = str_pad(substr($value, $separatorPosition + 1), 2, '0'); $integerPart .= substr($fractionalPart, 0, 2); $fractionalPart = substr($fractionalPart, 2); if ($fractionalPart === '') { $multipliedValue = $integerPart; } else { $multipliedValue = $integerPart . '.' . $fractionalPart; } } else { $multipliedValue = $value . '00'; } return $this->asDecimalStringFallback($multipliedValue, $decimals) . '%'; }
php
{ "resource": "" }
q241467
Formatter.asCurrencyStringFallback
validation
protected function asCurrencyStringFallback($value, $currency = null) { if ($currency === null) { if ($this->currencyCode === null) { throw new InvalidConfigException('The default currency code for the formatter is not defined.'); } $currency = $this->currencyCode; } return $currency . ' ' . $this->asDecimalStringFallback($value, 2); }
php
{ "resource": "" }
q241468
Schema.getSchemaNames
validation
public function getSchemaNames($refresh = false) { if ($this->_schemaNames === null || $refresh) { $this->_schemaNames = $this->findSchemaNames(); } return $this->_schemaNames; }
php
{ "resource": "" }
q241469
Schema.getTableNames
validation
public function getTableNames($schema = '', $refresh = false) { if (!isset($this->_tableNames[$schema]) || $refresh) { $this->_tableNames[$schema] = $this->findTableNames($schema); } return $this->_tableNames[$schema]; }
php
{ "resource": "" }
q241470
Schema.getPdoType
validation
public function getPdoType($data) { static $typeMap = [ // php type => PDO type 'boolean' => \PDO::PARAM_BOOL, 'integer' => \PDO::PARAM_INT, 'string' => \PDO::PARAM_STR, 'resource' => \PDO::PARAM_LOB, 'NULL' => \PDO::PARAM_NULL, ]; $type = gettype($data); return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR; }
php
{ "resource": "" }
q241471
Schema.getLastInsertID
validation
public function getLastInsertID($sequenceName = '') { if ($this->db->isActive) { return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName)); } throw new InvalidCallException('DB Connection is not active.'); }
php
{ "resource": "" }
q241472
Schema.insert
validation
public function insert($table, $columns) { $command = $this->db->createCommand()->insert($table, $columns); if (!$command->execute()) { return false; } $tableSchema = $this->getTableSchema($table); $result = []; foreach ($tableSchema->primaryKey as $name) { if ($tableSchema->columns[$name]->autoIncrement) { $result[$name] = $this->getLastInsertID($tableSchema->sequenceName); break; } $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue; } return $result; }
php
{ "resource": "" }
q241473
Schema.quoteValue
validation
public function quoteValue($str) { if (!is_string($str)) { return $str; } if (($value = $this->db->getSlavePdo()->quote($str)) !== false) { return $value; } // the driver doesn't support quote (e.g. oci) return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; }
php
{ "resource": "" }
q241474
Schema.quoteSimpleTableName
validation
public function quoteSimpleTableName($name) { if (is_string($this->tableQuoteCharacter)) { $startingCharacter = $endingCharacter = $this->tableQuoteCharacter; } else { list($startingCharacter, $endingCharacter) = $this->tableQuoteCharacter; } return strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter; }
php
{ "resource": "" }
q241475
Schema.unquoteSimpleTableName
validation
public function unquoteSimpleTableName($name) { if (is_string($this->tableQuoteCharacter)) { $startingCharacter = $this->tableQuoteCharacter; } else { $startingCharacter = $this->tableQuoteCharacter[0]; } return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1); }
php
{ "resource": "" }
q241476
Schema.getColumnPhpType
validation
protected function getColumnPhpType($column) { static $typeMap = [ // abstract type => php type self::TYPE_TINYINT => 'integer', self::TYPE_SMALLINT => 'integer', self::TYPE_INTEGER => 'integer', self::TYPE_BIGINT => 'integer', self::TYPE_BOOLEAN => 'boolean', self::TYPE_FLOAT => 'double', self::TYPE_DOUBLE => 'double', self::TYPE_BINARY => 'resource', self::TYPE_JSON => 'array', ]; if (isset($typeMap[$column->type])) { if ($column->type === 'bigint') { return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string'; } elseif ($column->type === 'integer') { return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer'; } return $typeMap[$column->type]; } return 'string'; }
php
{ "resource": "" }
q241477
Schema.getCacheKey
validation
protected function getCacheKey($name) { return [ __CLASS__, $this->db->dsn, $this->db->username, $this->getRawTableName($name), ]; }
php
{ "resource": "" }
q241478
Schema.setTableMetadata
validation
protected function setTableMetadata($name, $type, $data) { $this->_tableMetadata[$this->getRawTableName($name)][$type] = $data; }
php
{ "resource": "" }
q241479
Schema.normalizePdoRowKeyCase
validation
protected function normalizePdoRowKeyCase(array $row, $multiple) { if ($this->db->getSlavePdo()->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) { return $row; } if ($multiple) { return array_map(function (array $row) { return array_change_key_case($row, CASE_LOWER); }, $row); } return array_change_key_case($row, CASE_LOWER); }
php
{ "resource": "" }
q241480
Schema.loadTableMetadataFromCache
validation
private function loadTableMetadataFromCache($cache, $name) { if ($cache === null) { $this->_tableMetadata[$name] = []; return; } $metadata = $cache->get($this->getCacheKey($name)); if (!is_array($metadata) || !isset($metadata['cacheVersion']) || $metadata['cacheVersion'] !== static::SCHEMA_CACHE_VERSION) { $this->_tableMetadata[$name] = []; return; } unset($metadata['cacheVersion']); $this->_tableMetadata[$name] = $metadata; }
php
{ "resource": "" }
q241481
Schema.saveTableMetadataToCache
validation
private function saveTableMetadataToCache($cache, $name) { if ($cache === null) { return; } $metadata = $this->_tableMetadata[$name]; $metadata['cacheVersion'] = static::SCHEMA_CACHE_VERSION; $cache->set( $this->getCacheKey($name), $metadata, $this->db->schemaCacheDuration, new TagDependency(['tags' => $this->getCacheTag()]) ); }
php
{ "resource": "" }
q241482
DetailView.init
validation
public function init() { parent::init(); if ($this->model === null) { throw new InvalidConfigException('Please specify the "model" property.'); } if ($this->formatter === null) { $this->formatter = Yii::$app->getFormatter(); } elseif (is_array($this->formatter)) { $this->formatter = Yii::createObject($this->formatter); } if (!$this->formatter instanceof Formatter) { throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.'); } $this->normalizeAttributes(); if (!isset($this->options['id'])) { $this->options['id'] = $this->getId(); } }
php
{ "resource": "" }
q241483
DetailView.run
validation
public function run() { $rows = []; $i = 0; foreach ($this->attributes as $attribute) { $rows[] = $this->renderAttribute($attribute, $i++); } $options = $this->options; $tag = ArrayHelper::remove($options, 'tag', 'table'); echo Html::tag($tag, implode("\n", $rows), $options); }
php
{ "resource": "" }
q241484
DetailView.renderAttribute
validation
protected function renderAttribute($attribute, $index) { if (is_string($this->template)) { $captionOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'captionOptions', [])); $contentOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'contentOptions', [])); return strtr($this->template, [ '{label}' => $attribute['label'], '{value}' => $this->formatter->format($attribute['value'], $attribute['format']), '{captionOptions}' => $captionOptions, '{contentOptions}' => $contentOptions, ]); } return call_user_func($this->template, $attribute, $index, $this); }
php
{ "resource": "" }
q241485
SyslogTarget.export
validation
public function export() { openlog($this->identity, $this->options, $this->facility); foreach ($this->messages as $message) { if (syslog($this->_syslogLevels[$message[1]], $this->formatMessage($message)) === false) { throw new LogRuntimeException('Unable to export log through system log!'); } } closelog(); }
php
{ "resource": "" }
q241486
TableSchema.getColumn
validation
public function getColumn($name) { return isset($this->columns[$name]) ? $this->columns[$name] : null; }
php
{ "resource": "" }
q241487
TableSchema.fixPrimaryKey
validation
public function fixPrimaryKey($keys) { $keys = (array) $keys; $this->primaryKey = $keys; foreach ($this->columns as $column) { $column->isPrimaryKey = false; } foreach ($keys as $key) { if (isset($this->columns[$key])) { $this->columns[$key]->isPrimaryKey = true; } else { throw new InvalidArgumentException("Primary key '$key' cannot be found in table '{$this->name}'."); } } }
php
{ "resource": "" }
q241488
Session.init
validation
public function init() { parent::init(); register_shutdown_function([$this, 'close']); if ($this->getIsActive()) { Yii::warning('Session is already started', __METHOD__); $this->updateFlashCounters(); } }
php
{ "resource": "" }
q241489
Session.destroy
validation
public function destroy() { if ($this->getIsActive()) { $sessionId = session_id(); $this->close(); $this->setId($sessionId); $this->open(); session_unset(); session_destroy(); $this->setId($sessionId); } }
php
{ "resource": "" }
q241490
Session.regenerateID
validation
public function regenerateID($deleteOldSession = false) { if ($this->getIsActive()) { // add @ to inhibit possible warning due to race condition // https://github.com/yiisoft/yii2/pull/1812 if (YII_DEBUG && !headers_sent()) { session_regenerate_id($deleteOldSession); } else { @session_regenerate_id($deleteOldSession); } } }
php
{ "resource": "" }
q241491
Session.setUseCookies
validation
public function setUseCookies($value) { $this->freeze(); if ($value === false) { ini_set('session.use_cookies', '0'); ini_set('session.use_only_cookies', '0'); } elseif ($value === true) { ini_set('session.use_cookies', '1'); ini_set('session.use_only_cookies', '1'); } else { ini_set('session.use_cookies', '1'); ini_set('session.use_only_cookies', '0'); } $this->unfreeze(); }
php
{ "resource": "" }
q241492
Session.removeFlash
validation
public function removeFlash($key) { $counters = $this->get($this->flashParam, []); $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null; unset($counters[$key], $_SESSION[$key]); $_SESSION[$this->flashParam] = $counters; return $value; }
php
{ "resource": "" }
q241493
Session.removeAllFlashes
validation
public function removeAllFlashes() { $counters = $this->get($this->flashParam, []); foreach (array_keys($counters) as $key) { unset($_SESSION[$key]); } unset($_SESSION[$this->flashParam]); }
php
{ "resource": "" }
q241494
Session.freeze
validation
protected function freeze() { if ($this->getIsActive()) { if (isset($_SESSION)) { $this->frozenSessionData = $_SESSION; } $this->close(); Yii::info('Session frozen', __METHOD__); } }
php
{ "resource": "" }
q241495
Widget.end
validation
public static function end() { if (!empty(self::$stack)) { $widget = array_pop(self::$stack); if (get_class($widget) === get_called_class()) { /* @var $widget Widget */ if ($widget->beforeRun()) { $result = $widget->run(); $result = $widget->afterRun($result); echo $result; } return $widget; } throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class()); } throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.'); }
php
{ "resource": "" }
q241496
Widget.beforeRun
validation
public function beforeRun() { $event = new WidgetEvent(); $this->trigger(self::EVENT_BEFORE_RUN, $event); return $event->isValid; }
php
{ "resource": "" }
q241497
Widget.afterRun
validation
public function afterRun($result) { $event = new WidgetEvent(); $event->result = $result; $this->trigger(self::EVENT_AFTER_RUN, $event); return $event->result; }
php
{ "resource": "" }
q241498
View.init
validation
public function init() { parent::init(); if (is_array($this->theme)) { if (!isset($this->theme['class'])) { $this->theme['class'] = 'yii\base\Theme'; } $this->theme = Yii::createObject($this->theme); } elseif (is_string($this->theme)) { $this->theme = Yii::createObject($this->theme); } }
php
{ "resource": "" }
q241499
View.render
validation
public function render($view, $params = [], $context = null) { $viewFile = $this->findViewFile($view, $context); return $this->renderFile($viewFile, $params, $context); }
php
{ "resource": "" }