_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q241500 | View.findViewFile | validation | protected function findViewFile($view, $context = null)
{
if (strncmp($view, '@', 1) === 0) {
// e.g. "@app/views/main"
$file = Yii::getAlias($view);
} elseif (strncmp($view, '//', 2) === 0) {
// e.g. "//layouts/main"
$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
} elseif (strncmp($view, '/', 1) === 0) {
// e.g. "/site/index"
if (Yii::$app->controller !== null) {
$file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
} else {
throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
}
} elseif ($context instanceof ViewContextInterface) {
$file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
} elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
$file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
} else {
throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
}
if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
return $file;
}
$path = $file . '.' . $this->defaultExtension;
if ($this->defaultExtension !== 'php' && !is_file($path)) {
$path = $file . '.php';
}
return $path;
} | php | {
"resource": ""
} |
q241501 | View.renderFile | validation | public function renderFile($viewFile, $params = [], $context = null)
{
$viewFile = $requestedFile = Yii::getAlias($viewFile);
if ($this->theme !== null) {
$viewFile = $this->theme->applyTo($viewFile);
}
if (is_file($viewFile)) {
$viewFile = FileHelper::localize($viewFile);
} else {
throw new ViewNotFoundException("The view file does not exist: $viewFile");
}
$oldContext = $this->context;
if ($context !== null) {
$this->context = $context;
}
$output = '';
$this->_viewFiles[] = [
'resolved' => $viewFile,
'requested' => $requestedFile
];
if ($this->beforeRender($viewFile, $params)) {
Yii::debug("Rendering view file: $viewFile", __METHOD__);
$ext = pathinfo($viewFile, PATHINFO_EXTENSION);
if (isset($this->renderers[$ext])) {
if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
$this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
}
/* @var $renderer ViewRenderer */
$renderer = $this->renderers[$ext];
$output = $renderer->render($this, $viewFile, $params);
} else {
$output = $this->renderPhpFile($viewFile, $params);
}
$this->afterRender($viewFile, $params, $output);
}
array_pop($this->_viewFiles);
$this->context = $oldContext;
return $output;
} | php | {
"resource": ""
} |
q241502 | AttributeTypecastBehavior.typecastValue | validation | protected function typecastValue($value, $type)
{
if (is_scalar($type)) {
if (is_object($value) && method_exists($value, '__toString')) {
$value = $value->__toString();
}
switch ($type) {
case self::TYPE_INTEGER:
return (int) $value;
case self::TYPE_FLOAT:
return (float) $value;
case self::TYPE_BOOLEAN:
return (bool) $value;
case self::TYPE_STRING:
if (is_float($value)) {
return StringHelper::floatToString($value);
}
return (string) $value;
default:
throw new InvalidArgumentException("Unsupported type '{$type}'");
}
}
return call_user_func($type, $value);
} | php | {
"resource": ""
} |
q241503 | DeleteAction.run | validation | public function run($id)
{
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
if ($model->delete() === false) {
throw new ServerErrorHttpException('Failed to delete the object for unknown reason.');
}
Yii::$app->getResponse()->setStatusCode(204);
} | php | {
"resource": ""
} |
q241504 | DbSession.close | validation | public function close()
{
if ($this->getIsActive()) {
// prepare writeCallback fields before session closes
$this->fields = $this->composeFields();
YII_DEBUG ? session_write_close() : @session_write_close();
}
} | php | {
"resource": ""
} |
q241505 | BetweenColumnsConditionBuilder.escapeColumnName | validation | protected function escapeColumnName($columnName, &$params = [])
{
if ($columnName instanceof Query) {
list($sql, $params) = $this->queryBuilder->build($columnName, $params);
return "($sql)";
} elseif ($columnName instanceof ExpressionInterface) {
return $this->queryBuilder->buildExpression($columnName, $params);
} elseif (strpos($columnName, '(') === false) {
return $this->queryBuilder->db->quoteColumnName($columnName);
}
return $columnName;
} | php | {
"resource": ""
} |
q241506 | Dispatcher.setLogger | validation | public function setLogger($value)
{
if (is_string($value) || is_array($value)) {
$value = Yii::createObject($value);
}
$this->_logger = $value;
$this->_logger->dispatcher = $this;
} | php | {
"resource": ""
} |
q241507 | DbMessageSource.loadMessages | validation | protected function loadMessages($category, $language)
{
if ($this->enableCaching) {
$key = [
__CLASS__,
$category,
$language,
];
$messages = $this->cache->get($key);
if ($messages === false) {
$messages = $this->loadMessagesFromDb($category, $language);
$this->cache->set($key, $messages, $this->cachingDuration);
}
return $messages;
}
return $this->loadMessagesFromDb($category, $language);
} | php | {
"resource": ""
} |
q241508 | DbMessageSource.loadMessagesFromDb | validation | protected function loadMessagesFromDb($category, $language)
{
$mainQuery = (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
->where([
't1.id' => new Expression('[[t2.id]]'),
't1.category' => $category,
't2.language' => $language,
]);
$fallbackLanguage = substr($language, 0, 2);
$fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
if ($fallbackLanguage !== $language) {
$mainQuery->union($this->createFallbackQuery($category, $language, $fallbackLanguage), true);
} elseif ($language === $fallbackSourceLanguage) {
$mainQuery->union($this->createFallbackQuery($category, $language, $fallbackSourceLanguage), true);
}
$messages = $mainQuery->createCommand($this->db)->queryAll();
return ArrayHelper::map($messages, 'message', 'translation');
} | php | {
"resource": ""
} |
q241509 | Target.getContextMessage | validation | protected function getContextMessage()
{
$context = ArrayHelper::filter($GLOBALS, $this->logVars);
foreach ($this->maskVars as $var) {
if (ArrayHelper::getValue($context, $var) !== null) {
ArrayHelper::setValue($context, $var, '***');
}
}
$result = [];
foreach ($context as $key => $value) {
$result[] = "\${$key} = " . VarDumper::dumpAsString($value);
}
return implode("\n\n", $result);
} | php | {
"resource": ""
} |
q241510 | Target.formatMessage | validation | public function formatMessage($message)
{
list($text, $level, $category, $timestamp) = $message;
$level = Logger::getLevelName($level);
if (!is_string($text)) {
// exceptions may not be serializable if in the call stack somewhere is a Closure
if ($text instanceof \Throwable || $text instanceof \Exception) {
$text = (string) $text;
} else {
$text = VarDumper::export($text);
}
}
$traces = [];
if (isset($message[4])) {
foreach ($message[4] as $trace) {
$traces[] = "in {$trace['file']}:{$trace['line']}";
}
}
$prefix = $this->getMessagePrefix($message);
return $this->getTime($timestamp) . " {$prefix}[$level][$category] $text"
. (empty($traces) ? '' : "\n " . implode("\n ", $traces));
} | php | {
"resource": ""
} |
q241511 | Target.getEnabled | validation | public function getEnabled()
{
if (is_callable($this->_enabled)) {
return call_user_func($this->_enabled, $this);
}
return $this->_enabled;
} | php | {
"resource": ""
} |
q241512 | Table.renderSeparator | validation | protected function renderSeparator($spanLeft, $spanMid, $spanMidMid, $spanRight)
{
$separator = $spanLeft;
foreach ($this->_columnWidths as $index => $rowSize) {
if ($index !== 0) {
$separator .= $spanMid;
}
$separator .= str_repeat($spanMidMid, $rowSize);
}
$separator .= $spanRight . "\n";
return $separator;
} | php | {
"resource": ""
} |
q241513 | Controller.asJson | validation | public function asJson($data)
{
$response = Yii::$app->getResponse();
$response->format = Response::FORMAT_JSON;
$response->data = $data;
return $response;
} | php | {
"resource": ""
} |
q241514 | Controller.asXml | validation | public function asXml($data)
{
$response = Yii::$app->getResponse();
$response->format = Response::FORMAT_XML;
$response->data = $data;
return $response;
} | php | {
"resource": ""
} |
q241515 | Column.renderDataCell | validation | public function renderDataCell($model, $key, $index)
{
if ($this->contentOptions instanceof Closure) {
$options = call_user_func($this->contentOptions, $model, $key, $index, $this);
} else {
$options = $this->contentOptions;
}
return Html::tag('td', $this->renderDataCellContent($model, $key, $index), $options);
} | php | {
"resource": ""
} |
q241516 | Column.renderDataCellContent | validation | protected function renderDataCellContent($model, $key, $index)
{
if ($this->content !== null) {
return call_user_func($this->content, $model, $key, $index, $this);
}
return $this->grid->emptyCell;
} | php | {
"resource": ""
} |
q241517 | FixtureController.printHelpMessage | validation | private function printHelpMessage()
{
$this->stdout($this->getHelpSummary() . "\n");
$helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]);
$this->stdout("Use $helpCommand to get usage info.\n");
} | php | {
"resource": ""
} |
q241518 | FixtureController.notifyNothingToUnload | validation | public function notifyNothingToUnload($foundFixtures, $except)
{
$this->stdout("Fixtures to unload could not be found according to given conditions:\n\n", Console::FG_RED);
$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
$this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN);
if (count($foundFixtures)) {
$this->stdout("\nFixtures found under the namespace:\n\n", Console::FG_YELLOW);
$this->outputList($foundFixtures);
}
if (count($except)) {
$this->stdout("\nFixtures that will NOT be unloaded: \n\n", Console::FG_YELLOW);
$this->outputList($except);
}
} | php | {
"resource": ""
} |
q241519 | FixtureController.notifyUnloaded | validation | private function notifyUnloaded($fixtures)
{
$this->stdout("\nFixtures were successfully unloaded from namespace: ", Console::FG_YELLOW);
$this->stdout(Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN);
$this->outputList($fixtures);
} | php | {
"resource": ""
} |
q241520 | FixtureController.notifyNotFound | validation | private function notifyNotFound($fixtures)
{
$this->stdout("Some fixtures were not found under path:\n", Console::BG_RED);
$this->stdout("\t" . $this->getFixturePath() . "\n\n", Console::FG_GREEN);
$this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED);
$this->outputList($fixtures);
$this->stdout("\n");
} | php | {
"resource": ""
} |
q241521 | FixtureController.confirmLoad | validation | private function confirmLoad($fixtures, $except)
{
$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
$this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
if (count($this->globalFixtures)) {
$this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
$this->outputList($this->globalFixtures);
}
if (count($fixtures)) {
$this->stdout("\nFixtures below will be loaded:\n\n", Console::FG_YELLOW);
$this->outputList($fixtures);
}
if (count($except)) {
$this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW);
$this->outputList($except);
}
$this->stdout("\nBe aware that:\n", Console::BOLD);
$this->stdout("Applying leads to purging of certain data in the database!\n", Console::FG_RED);
return $this->confirm("\nLoad above fixtures?");
} | php | {
"resource": ""
} |
q241522 | FixtureController.confirmUnload | validation | private function confirmUnload($fixtures, $except)
{
$this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW);
$this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN);
if (count($this->globalFixtures)) {
$this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW);
$this->outputList($this->globalFixtures);
}
if (count($fixtures)) {
$this->stdout("\nFixtures below will be unloaded:\n\n", Console::FG_YELLOW);
$this->outputList($fixtures);
}
if (count($except)) {
$this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW);
$this->outputList($except);
}
return $this->confirm("\nUnload fixtures?");
} | php | {
"resource": ""
} |
q241523 | FixtureController.outputList | validation | private function outputList($data)
{
foreach ($data as $index => $item) {
$this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN);
}
} | php | {
"resource": ""
} |
q241524 | FixtureController.findFixtures | validation | private function findFixtures(array $fixtures = [])
{
$fixturesPath = $this->getFixturePath();
$filesToSearch = ['*Fixture.php'];
$findAll = ($fixtures === []);
if (!$findAll) {
$filesToSearch = [];
foreach ($fixtures as $fileName) {
$filesToSearch[] = $fileName . 'Fixture.php';
}
}
$files = FileHelper::findFiles($fixturesPath, ['only' => $filesToSearch]);
$foundFixtures = [];
foreach ($files as $fixture) {
$foundFixtures[] = $this->getFixtureRelativeName($fixture);
}
return $foundFixtures;
} | php | {
"resource": ""
} |
q241525 | FixtureController.getFixturesConfig | validation | private function getFixturesConfig($fixtures)
{
$config = [];
foreach ($fixtures as $fixture) {
$isNamespaced = (strpos($fixture, '\\') !== false);
// replace linux' path slashes to namespace backslashes, in case if $fixture is non-namespaced relative path
$fixture = str_replace('/', '\\', $fixture);
$fullClassName = $isNamespaced ? $fixture : $this->namespace . '\\' . $fixture;
if (class_exists($fullClassName)) {
$config[] = $fullClassName;
} elseif (class_exists($fullClassName . 'Fixture')) {
$config[] = $fullClassName . 'Fixture';
}
}
return $config;
} | php | {
"resource": ""
} |
q241526 | HeaderCollection.setDefault | validation | public function setDefault($name, $value)
{
$name = strtolower($name);
if (empty($this->_headers[$name])) {
$this->_headers[$name][] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q241527 | HeaderCollection.remove | validation | public function remove($name)
{
$name = strtolower($name);
if (isset($this->_headers[$name])) {
$value = $this->_headers[$name];
unset($this->_headers[$name]);
return $value;
}
return null;
} | php | {
"resource": ""
} |
q241528 | ContentNegotiator.negotiate | validation | public function negotiate()
{
$request = $this->request ?: Yii::$app->getRequest();
$response = $this->response ?: Yii::$app->getResponse();
if (!empty($this->formats)) {
if (\count($this->formats) > 1) {
$response->getHeaders()->add('Vary', 'Accept');
}
$this->negotiateContentType($request, $response);
}
if (!empty($this->languages)) {
if (\count($this->languages) > 1) {
$response->getHeaders()->add('Vary', 'Accept-Language');
}
Yii::$app->language = $this->negotiateLanguage($request);
}
} | php | {
"resource": ""
} |
q241529 | ContentNegotiator.negotiateLanguage | validation | protected function negotiateLanguage($request)
{
if (!empty($this->languageParam) && ($language = $request->get($this->languageParam)) !== null) {
if (is_array($language)) {
// If an array received, then skip it and use the first of supported languages
return reset($this->languages);
}
if (isset($this->languages[$language])) {
return $this->languages[$language];
}
foreach ($this->languages as $key => $supported) {
if (is_int($key) && $this->isLanguageSupported($language, $supported)) {
return $supported;
}
}
return reset($this->languages);
}
foreach ($request->getAcceptableLanguages() as $language) {
if (isset($this->languages[$language])) {
return $this->languages[$language];
}
foreach ($this->languages as $key => $supported) {
if (is_int($key) && $this->isLanguageSupported($language, $supported)) {
return $supported;
}
}
}
return reset($this->languages);
} | php | {
"resource": ""
} |
q241530 | ContentNegotiator.isLanguageSupported | validation | protected function isLanguageSupported($requested, $supported)
{
$supported = str_replace('_', '-', strtolower($supported));
$requested = str_replace('_', '-', strtolower($requested));
return strpos($requested . '-', $supported . '-') === 0;
} | php | {
"resource": ""
} |
q241531 | BaseActiveRecord.__isset | validation | public function __isset($name)
{
try {
return $this->__get($name) !== null;
} catch (\Throwable $t) {
return false;
} catch (\Exception $e) {
return false;
}
} | php | {
"resource": ""
} |
q241532 | BaseActiveRecord.populateRelation | validation | public function populateRelation($name, $records)
{
foreach ($this->_relationsDependencies as &$relationNames) {
unset($relationNames[$name]);
}
$this->_related[$name] = $records;
} | php | {
"resource": ""
} |
q241533 | BaseActiveRecord.hasAttribute | validation | public function hasAttribute($name)
{
return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
} | php | {
"resource": ""
} |
q241534 | BaseActiveRecord.getAttribute | validation | public function getAttribute($name)
{
return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
} | php | {
"resource": ""
} |
q241535 | BaseActiveRecord.setAttribute | validation | public function setAttribute($name, $value)
{
if ($this->hasAttribute($name)) {
if (
!empty($this->_relationsDependencies[$name])
&& (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
) {
$this->resetDependentRelations($name);
}
$this->_attributes[$name] = $value;
} else {
throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
}
} | php | {
"resource": ""
} |
q241536 | BaseActiveRecord.getOldAttribute | validation | public function getOldAttribute($name)
{
return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
} | php | {
"resource": ""
} |
q241537 | BaseActiveRecord.isAttributeChanged | validation | public function isAttributeChanged($name, $identical = true)
{
if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
if ($identical) {
return $this->_attributes[$name] !== $this->_oldAttributes[$name];
}
return $this->_attributes[$name] != $this->_oldAttributes[$name];
}
return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
} | php | {
"resource": ""
} |
q241538 | BaseActiveRecord.getDirtyAttributes | validation | public function getDirtyAttributes($names = null)
{
if ($names === null) {
$names = $this->attributes();
}
$names = array_flip($names);
$attributes = [];
if ($this->_oldAttributes === null) {
foreach ($this->_attributes as $name => $value) {
if (isset($names[$name])) {
$attributes[$name] = $value;
}
}
} else {
foreach ($this->_attributes as $name => $value) {
if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $value !== $this->_oldAttributes[$name])) {
$attributes[$name] = $value;
}
}
}
return $attributes;
} | php | {
"resource": ""
} |
q241539 | BaseActiveRecord.updateAttributes | validation | public function updateAttributes($attributes)
{
$attrs = [];
foreach ($attributes as $name => $value) {
if (is_int($name)) {
$attrs[] = $value;
} else {
$this->$name = $value;
$attrs[] = $name;
}
}
$values = $this->getDirtyAttributes($attrs);
if (empty($values) || $this->getIsNewRecord()) {
return 0;
}
$rows = static::updateAll($values, $this->getOldPrimaryKey(true));
foreach ($values as $name => $value) {
$this->_oldAttributes[$name] = $this->_attributes[$name];
}
return $rows;
} | php | {
"resource": ""
} |
q241540 | BaseActiveRecord.beforeSave | validation | public function beforeSave($insert)
{
$event = new ModelEvent();
$this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
return $event->isValid;
} | php | {
"resource": ""
} |
q241541 | BaseActiveRecord.refreshInternal | validation | protected function refreshInternal($record)
{
if ($record === null) {
return false;
}
foreach ($this->attributes() as $name) {
$this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
}
$this->_oldAttributes = $record->_oldAttributes;
$this->_related = [];
$this->_relationsDependencies = [];
$this->afterRefresh();
return true;
} | php | {
"resource": ""
} |
q241542 | BaseActiveRecord.isPrimaryKey | validation | public static function isPrimaryKey($keys)
{
$pks = static::primaryKey();
if (count($keys) === count($pks)) {
return count(array_intersect($keys, $pks)) === count($pks);
}
return false;
} | php | {
"resource": ""
} |
q241543 | BaseActiveRecord.getAttributeLabel | validation | public function getAttributeLabel($attribute)
{
$labels = $this->attributeLabels();
if (isset($labels[$attribute])) {
return $labels[$attribute];
} elseif (strpos($attribute, '.')) {
$attributeParts = explode('.', $attribute);
$neededAttribute = array_pop($attributeParts);
$relatedModel = $this;
foreach ($attributeParts as $relationName) {
if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
$relatedModel = $relatedModel->$relationName;
} else {
try {
$relation = $relatedModel->getRelation($relationName);
} catch (InvalidParamException $e) {
return $this->generateAttributeLabel($attribute);
}
/* @var $modelClass ActiveRecordInterface */
$modelClass = $relation->modelClass;
$relatedModel = $modelClass::instance();
}
}
$labels = $relatedModel->attributeLabels();
if (isset($labels[$neededAttribute])) {
return $labels[$neededAttribute];
}
}
return $this->generateAttributeLabel($attribute);
} | php | {
"resource": ""
} |
q241544 | BaseActiveRecord.getAttributeHint | validation | public function getAttributeHint($attribute)
{
$hints = $this->attributeHints();
if (isset($hints[$attribute])) {
return $hints[$attribute];
} elseif (strpos($attribute, '.')) {
$attributeParts = explode('.', $attribute);
$neededAttribute = array_pop($attributeParts);
$relatedModel = $this;
foreach ($attributeParts as $relationName) {
if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
$relatedModel = $relatedModel->$relationName;
} else {
try {
$relation = $relatedModel->getRelation($relationName);
} catch (InvalidParamException $e) {
return '';
}
/* @var $modelClass ActiveRecordInterface */
$modelClass = $relation->modelClass;
$relatedModel = $modelClass::instance();
}
}
$hints = $relatedModel->attributeHints();
if (isset($hints[$neededAttribute])) {
return $hints[$neededAttribute];
}
}
return '';
} | php | {
"resource": ""
} |
q241545 | BaseActiveRecord.resetDependentRelations | validation | private function resetDependentRelations($attribute)
{
foreach ($this->_relationsDependencies[$attribute] as $relation) {
unset($this->_related[$relation]);
}
unset($this->_relationsDependencies[$attribute]);
} | php | {
"resource": ""
} |
q241546 | BaseActiveRecord.setRelationDependencies | validation | private function setRelationDependencies($name, $relation, $viaRelationName = null)
{
if (empty($relation->via) && $relation->link) {
foreach ($relation->link as $attribute) {
$this->_relationsDependencies[$attribute][$name] = $name;
if ($viaRelationName !== null) {
$this->_relationsDependencies[$attribute][] = $viaRelationName;
}
}
} elseif ($relation->via instanceof ActiveQueryInterface) {
$this->setRelationDependencies($name, $relation->via);
} elseif (is_array($relation->via)) {
list($viaRelationName, $viaQuery) = $relation->via;
$this->setRelationDependencies($name, $viaQuery, $viaRelationName);
}
} | php | {
"resource": ""
} |
q241547 | FileValidator.getSizeLimit | validation | public function getSizeLimit()
{
// Get the lowest between post_max_size and upload_max_filesize, log a warning if the first is < than the latter
$limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
$postLimit = $this->sizeToBytes(ini_get('post_max_size'));
if ($postLimit > 0 && $postLimit < $limit) {
Yii::warning('PHP.ini\'s \'post_max_size\' is less than \'upload_max_filesize\'.', __METHOD__);
$limit = $postLimit;
}
if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
$limit = $this->maxSize;
}
if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
$limit = (int) $_POST['MAX_FILE_SIZE'];
}
return $limit;
} | php | {
"resource": ""
} |
q241548 | FileValidator.sizeToBytes | validation | private function sizeToBytes($sizeStr)
{
switch (substr($sizeStr, -1)) {
case 'M':
case 'm':
return (int) $sizeStr * 1048576;
case 'K':
case 'k':
return (int) $sizeStr * 1024;
case 'G':
case 'g':
return (int) $sizeStr * 1073741824;
default:
return (int) $sizeStr;
}
} | php | {
"resource": ""
} |
q241549 | UrlRule.createRule | validation | protected function createRule($pattern, $prefix, $action)
{
$verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
$verbs = explode(',', $matches[1]);
$pattern = isset($matches[4]) ? $matches[4] : '';
} else {
$verbs = [];
}
$config = $this->ruleConfig;
$config['verb'] = $verbs;
$config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
$config['route'] = $action;
if (!empty($verbs) && !in_array('GET', $verbs)) {
$config['mode'] = WebUrlRule::PARSING_ONLY;
}
$config['suffix'] = $this->suffix;
return Yii::createObject($config);
} | php | {
"resource": ""
} |
q241550 | EmailTarget.export | validation | public function export()
{
// moved initialization of subject here because of the following issue
// https://github.com/yiisoft/yii2/issues/1446
if (empty($this->message['subject'])) {
$this->message['subject'] = 'Application Log';
}
$messages = array_map([$this, 'formatMessage'], $this->messages);
$body = wordwrap(implode("\n", $messages), 70);
$message = $this->composeMessage($body);
if (!$message->send($this->mailer)) {
throw new LogRuntimeException('Unable to export log through email!');
}
} | php | {
"resource": ""
} |
q241551 | EmailTarget.composeMessage | validation | protected function composeMessage($body)
{
$message = $this->mailer->compose();
Yii::configure($message, $this->message);
$message->setTextBody($body);
return $message;
} | php | {
"resource": ""
} |
q241552 | UniqueValidator.applyTableAlias | validation | private function applyTableAlias($query, $conditions, $alias = null)
{
if ($alias === null) {
$alias = array_keys($query->getTablesUsedInFrom())[0];
}
$prefixedConditions = [];
foreach ($conditions as $columnName => $columnValue) {
if (strpos($columnName, '(') === false) {
$columnName = preg_replace('/^' . preg_quote($alias) . '\.(.*)$/', '$1', $columnName);
if (strpos($columnName, '[[') === 0) {
$prefixedColumn = "{$alias}.{$columnName}";
} else {
$prefixedColumn = "{$alias}.[[{$columnName}]]";
}
} else {
// there is an expression, can't prefix it reliably
$prefixedColumn = $columnName;
}
$prefixedConditions[$prefixedColumn] = $columnValue;
}
return $prefixedConditions;
} | php | {
"resource": ""
} |
q241553 | Application.run | validation | public function run()
{
try {
$this->state = self::STATE_BEFORE_REQUEST;
$this->trigger(self::EVENT_BEFORE_REQUEST);
$this->state = self::STATE_HANDLING_REQUEST;
$response = $this->handleRequest($this->getRequest());
$this->state = self::STATE_AFTER_REQUEST;
$this->trigger(self::EVENT_AFTER_REQUEST);
$this->state = self::STATE_SENDING_RESPONSE;
$response->send();
$this->state = self::STATE_END;
return $response->exitStatus;
} catch (ExitException $e) {
$this->end($e->statusCode, isset($response) ? $response : null);
return $e->statusCode;
}
} | php | {
"resource": ""
} |
q241554 | Application.setRuntimePath | validation | public function setRuntimePath($path)
{
$this->_runtimePath = Yii::getAlias($path);
Yii::setAlias('@runtime', $this->_runtimePath);
} | php | {
"resource": ""
} |
q241555 | Application.getVendorPath | validation | public function getVendorPath()
{
if ($this->_vendorPath === null) {
$this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
}
return $this->_vendorPath;
} | php | {
"resource": ""
} |
q241556 | Application.setVendorPath | validation | public function setVendorPath($path)
{
$this->_vendorPath = Yii::getAlias($path);
Yii::setAlias('@vendor', $this->_vendorPath);
Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower');
Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');
} | php | {
"resource": ""
} |
q241557 | View.renderAjax | validation | public function renderAjax($view, $params = [], $context = null)
{
$viewFile = $this->findViewFile($view, $context);
ob_start();
ob_implicit_flush(false);
$this->beginPage();
$this->head();
$this->beginBody();
echo $this->renderFile($viewFile, $params, $context);
$this->endBody();
$this->endPage(true);
return ob_get_clean();
} | php | {
"resource": ""
} |
q241558 | View.registerAssetBundle | validation | public function registerAssetBundle($name, $position = null)
{
if (!isset($this->assetBundles[$name])) {
$am = $this->getAssetManager();
$bundle = $am->getBundle($name);
$this->assetBundles[$name] = false;
// register dependencies
$pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
foreach ($bundle->depends as $dep) {
$this->registerAssetBundle($dep, $pos);
}
$this->assetBundles[$name] = $bundle;
} elseif ($this->assetBundles[$name] === false) {
throw new InvalidConfigException("A circular dependency is detected for bundle '$name'.");
} else {
$bundle = $this->assetBundles[$name];
}
if ($position !== null) {
$pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
if ($pos === null) {
$bundle->jsOptions['position'] = $pos = $position;
} elseif ($pos > $position) {
throw new InvalidConfigException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
}
// update position for all dependencies
foreach ($bundle->depends as $dep) {
$this->registerAssetBundle($dep, $pos);
}
}
return $bundle;
} | php | {
"resource": ""
} |
q241559 | View.registerCssFile | validation | public function registerCssFile($url, $options = [], $key = null)
{
$url = Yii::getAlias($url);
$key = $key ?: $url;
$depends = ArrayHelper::remove($options, 'depends', []);
if (empty($depends)) {
$this->cssFiles[$key] = Html::cssFile($url, $options);
} else {
$this->getAssetManager()->bundles[$key] = Yii::createObject([
'class' => AssetBundle::className(),
'baseUrl' => '',
'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
'cssOptions' => $options,
'depends' => (array) $depends,
]);
$this->registerAssetBundle($key);
}
} | php | {
"resource": ""
} |
q241560 | View.registerJsFile | validation | public function registerJsFile($url, $options = [], $key = null)
{
$url = Yii::getAlias($url);
$key = $key ?: $url;
$depends = ArrayHelper::remove($options, 'depends', []);
if (empty($depends)) {
$position = ArrayHelper::remove($options, 'position', self::POS_END);
$this->jsFiles[$position][$key] = Html::jsFile($url, $options);
} else {
$this->getAssetManager()->bundles[$key] = Yii::createObject([
'class' => AssetBundle::className(),
'baseUrl' => '',
'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
'jsOptions' => $options,
'depends' => (array) $depends,
]);
$this->registerAssetBundle($key);
}
} | php | {
"resource": ""
} |
q241561 | View.renderBodyEndHtml | validation | protected function renderBodyEndHtml($ajaxMode)
{
$lines = [];
if (!empty($this->jsFiles[self::POS_END])) {
$lines[] = implode("\n", $this->jsFiles[self::POS_END]);
}
if ($ajaxMode) {
$scripts = [];
if (!empty($this->js[self::POS_END])) {
$scripts[] = implode("\n", $this->js[self::POS_END]);
}
if (!empty($this->js[self::POS_READY])) {
$scripts[] = implode("\n", $this->js[self::POS_READY]);
}
if (!empty($this->js[self::POS_LOAD])) {
$scripts[] = implode("\n", $this->js[self::POS_LOAD]);
}
if (!empty($scripts)) {
$lines[] = Html::script(implode("\n", $scripts));
}
} else {
if (!empty($this->js[self::POS_END])) {
$lines[] = Html::script(implode("\n", $this->js[self::POS_END]));
}
if (!empty($this->js[self::POS_READY])) {
$js = "jQuery(function ($) {\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
$lines[] = Html::script($js);
}
if (!empty($this->js[self::POS_LOAD])) {
$js = "jQuery(window).on('load', function () {\n" . implode("\n", $this->js[self::POS_LOAD]) . "\n});";
$lines[] = Html::script($js);
}
}
return empty($lines) ? '' : implode("\n", $lines);
} | php | {
"resource": ""
} |
q241562 | UrlNormalizer.normalizePathInfo | validation | public function normalizePathInfo($pathInfo, $suffix, &$normalized = false)
{
if (empty($pathInfo)) {
return $pathInfo;
}
$sourcePathInfo = $pathInfo;
if ($this->collapseSlashes) {
$pathInfo = $this->collapseSlashes($pathInfo);
}
if ($this->normalizeTrailingSlash === true) {
$pathInfo = $this->normalizeTrailingSlash($pathInfo, $suffix);
}
$normalized = $sourcePathInfo !== $pathInfo;
return $pathInfo;
} | php | {
"resource": ""
} |
q241563 | BaseInflector.pluralize | validation | public static function pluralize($word)
{
if (isset(static::$specials[$word])) {
return static::$specials[$word];
}
foreach (static::$plurals as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
}
}
return $word;
} | php | {
"resource": ""
} |
q241564 | BaseInflector.titleize | validation | public static function titleize($words, $ucAll = false)
{
$words = static::humanize(static::underscore($words), $ucAll);
return $ucAll ? StringHelper::mb_ucwords($words, self::encoding()) : StringHelper::mb_ucfirst($words, self::encoding());
} | php | {
"resource": ""
} |
q241565 | BaseInflector.camel2words | validation | public static function camel2words($name, $ucwords = true)
{
$label = mb_strtolower(trim(str_replace([
'-',
'_',
'.',
], ' ', preg_replace('/(?<!\p{Lu})(\p{Lu})|(\p{Lu})(?=\p{Ll})/u', ' \0', $name))), self::encoding());
return $ucwords ? StringHelper::mb_ucwords($label, self::encoding()) : $label;
} | php | {
"resource": ""
} |
q241566 | BaseInflector.variablize | validation | public static function variablize($word)
{
$word = static::camelize($word);
return mb_strtolower(mb_substr($word, 0, 1, self::encoding())) . mb_substr($word, 1, null, self::encoding());
} | php | {
"resource": ""
} |
q241567 | BaseInflector.sentence | validation | public static function sentence(array $words, $twoWordsConnector = null, $lastWordConnector = null, $connector = ', ')
{
if ($twoWordsConnector === null) {
$twoWordsConnector = Yii::t('yii', ' and ');
}
if ($lastWordConnector === null) {
$lastWordConnector = $twoWordsConnector;
}
switch (count($words)) {
case 0:
return '';
case 1:
return reset($words);
case 2:
return implode($twoWordsConnector, $words);
default:
return implode($connector, array_slice($words, 0, -1)) . $lastWordConnector . end($words);
}
} | php | {
"resource": ""
} |
q241568 | BaseMessage.send | validation | public function send(MailerInterface $mailer = null)
{
if ($mailer === null && $this->mailer === null) {
$mailer = Yii::$app->getMailer();
} elseif ($mailer === null) {
$mailer = $this->mailer;
}
return $mailer->send($this);
} | php | {
"resource": ""
} |
q241569 | StaticInstanceTrait.instance | validation | public static function instance($refresh = false)
{
$className = get_called_class();
if ($refresh || !isset(self::$_instances[$className])) {
self::$_instances[$className] = Yii::createObject($className);
}
return self::$_instances[$className];
} | php | {
"resource": ""
} |
q241570 | Cache.buildKey | validation | public function buildKey($key)
{
if (is_string($key)) {
$key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
} else {
if ($this->_igbinaryAvailable) {
$serializedKey = igbinary_serialize($key);
} else {
$serializedKey = serialize($key);
}
$key = md5($serializedKey);
}
return $this->keyPrefix . $key;
} | php | {
"resource": ""
} |
q241571 | Cache.get | validation | public function get($key)
{
$key = $this->buildKey($key);
$value = $this->getValue($key);
if ($value === false || $this->serializer === false) {
return $value;
} elseif ($this->serializer === null) {
$value = unserialize($value);
} else {
$value = call_user_func($this->serializer[1], $value);
}
if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
return $value[0];
}
return false;
} | php | {
"resource": ""
} |
q241572 | Cache.mset | validation | public function mset($items, $duration = 0, $dependency = null)
{
return $this->multiSet($items, $duration, $dependency);
} | php | {
"resource": ""
} |
q241573 | Cache.madd | validation | public function madd($items, $duration = 0, $dependency = null)
{
return $this->multiAdd($items, $duration, $dependency);
} | php | {
"resource": ""
} |
q241574 | Cache.add | validation | public function add($key, $value, $duration = 0, $dependency = null)
{
if ($dependency !== null && $this->serializer !== false) {
$dependency->evaluateDependency($this);
}
if ($this->serializer === null) {
$value = serialize([$value, $dependency]);
} elseif ($this->serializer !== false) {
$value = call_user_func($this->serializer[0], [$value, $dependency]);
}
$key = $this->buildKey($key);
return $this->addValue($key, $value, $duration);
} | php | {
"resource": ""
} |
q241575 | Schema.getTableSequenceName | validation | protected function getTableSequenceName($tableName)
{
$sequenceNameSql = <<<'SQL'
SELECT
UD.REFERENCED_NAME AS SEQUENCE_NAME
FROM USER_DEPENDENCIES UD
JOIN USER_TRIGGERS UT ON (UT.TRIGGER_NAME = UD.NAME)
WHERE
UT.TABLE_NAME = :tableName
AND UD.TYPE = 'TRIGGER'
AND UD.REFERENCED_TYPE = 'SEQUENCE'
SQL;
$sequenceName = $this->db->createCommand($sequenceNameSql, [':tableName' => $tableName])->queryScalar();
return $sequenceName === false ? null : $sequenceName;
} | php | {
"resource": ""
} |
q241576 | Schema.createColumn | validation | protected function createColumn($column)
{
$c = $this->createColumnSchema();
$c->name = $column['COLUMN_NAME'];
$c->allowNull = $column['NULLABLE'] === 'Y';
$c->comment = $column['COLUMN_COMMENT'] === null ? '' : $column['COLUMN_COMMENT'];
$c->isPrimaryKey = false;
$this->extractColumnType($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
$this->extractColumnSize($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
$c->phpType = $this->getColumnPhpType($c);
if (!$c->isPrimaryKey) {
if (stripos($column['DATA_DEFAULT'], 'timestamp') !== false) {
$c->defaultValue = null;
} else {
$defaultValue = $column['DATA_DEFAULT'];
if ($c->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') {
$c->defaultValue = new Expression('CURRENT_TIMESTAMP');
} else {
if ($defaultValue !== null) {
if (($len = strlen($defaultValue)) > 2 && $defaultValue[0] === "'"
&& $defaultValue[$len - 1] === "'"
) {
$defaultValue = substr($column['DATA_DEFAULT'], 1, -1);
} else {
$defaultValue = trim($defaultValue);
}
}
$c->defaultValue = $c->phpTypecast($defaultValue);
}
}
}
return $c;
} | php | {
"resource": ""
} |
q241577 | Schema.findConstraints | validation | protected function findConstraints($table)
{
$sql = <<<'SQL'
SELECT
/*+ PUSH_PRED(C) PUSH_PRED(D) PUSH_PRED(E) */
D.CONSTRAINT_NAME,
D.CONSTRAINT_TYPE,
C.COLUMN_NAME,
C.POSITION,
D.R_CONSTRAINT_NAME,
E.TABLE_NAME AS TABLE_REF,
F.COLUMN_NAME AS COLUMN_REF,
C.TABLE_NAME
FROM ALL_CONS_COLUMNS C
INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
WHERE
C.OWNER = :schemaName
AND C.TABLE_NAME = :tableName
ORDER BY D.CONSTRAINT_NAME, C.POSITION
SQL;
$command = $this->db->createCommand($sql, [
':tableName' => $table->name,
':schemaName' => $table->schemaName,
]);
$constraints = [];
foreach ($command->queryAll() as $row) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
$row = array_change_key_case($row, CASE_UPPER);
}
if ($row['CONSTRAINT_TYPE'] === 'P') {
$table->columns[$row['COLUMN_NAME']]->isPrimaryKey = true;
$table->primaryKey[] = $row['COLUMN_NAME'];
if (empty($table->sequenceName)) {
$table->sequenceName = $this->getTableSequenceName($table->name);
}
}
if ($row['CONSTRAINT_TYPE'] !== 'R') {
// this condition is not checked in SQL WHERE because of an Oracle Bug:
// see https://github.com/yiisoft/yii2/pull/8844
continue;
}
$name = $row['CONSTRAINT_NAME'];
if (!isset($constraints[$name])) {
$constraints[$name] = [
'tableName' => $row['TABLE_REF'],
'columns' => [],
];
}
$constraints[$name]['columns'][$row['COLUMN_NAME']] = $row['COLUMN_REF'];
}
foreach ($constraints as $constraint) {
$name = current(array_keys($constraint));
$table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
}
} | php | {
"resource": ""
} |
q241578 | Schema.extractColumnType | validation | protected function extractColumnType($column, $dbType, $precision, $scale, $length)
{
$column->dbType = $dbType;
if (strpos($dbType, 'FLOAT') !== false || strpos($dbType, 'DOUBLE') !== false) {
$column->type = 'double';
} elseif (strpos($dbType, 'NUMBER') !== false) {
if ($scale === null || $scale > 0) {
$column->type = 'decimal';
} else {
$column->type = 'integer';
}
} elseif (strpos($dbType, 'INTEGER') !== false) {
$column->type = 'integer';
} elseif (strpos($dbType, 'BLOB') !== false) {
$column->type = 'binary';
} elseif (strpos($dbType, 'CLOB') !== false) {
$column->type = 'text';
} elseif (strpos($dbType, 'TIMESTAMP') !== false) {
$column->type = 'timestamp';
} else {
$column->type = 'string';
}
} | php | {
"resource": ""
} |
q241579 | Schema.extractColumnSize | validation | protected function extractColumnSize($column, $dbType, $precision, $scale, $length)
{
$column->size = trim($length) === '' ? null : (int) $length;
$column->precision = trim($precision) === '' ? null : (int) $precision;
$column->scale = trim($scale) === '' ? null : (int) $scale;
} | php | {
"resource": ""
} |
q241580 | ActiveForm.registerClientScript | validation | public function registerClientScript()
{
$id = $this->options['id'];
$options = Json::htmlEncode($this->getClientOptions());
$attributes = Json::htmlEncode($this->attributes);
$view = $this->getView();
ActiveFormAsset::register($view);
$view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
} | php | {
"resource": ""
} |
q241581 | ActiveForm.field | validation | public function field($model, $attribute, $options = [])
{
$config = $this->fieldConfig;
if ($config instanceof \Closure) {
$config = call_user_func($config, $model, $attribute);
}
if (!isset($config['class'])) {
$config['class'] = $this->fieldClass;
}
return Yii::createObject(ArrayHelper::merge($config, $options, [
'model' => $model,
'attribute' => $attribute,
'form' => $this,
]));
} | php | {
"resource": ""
} |
q241582 | ActiveForm.validate | validation | public static function validate($model, $attributes = null)
{
$result = [];
if ($attributes instanceof Model) {
// validating multiple models
$models = func_get_args();
$attributes = null;
} else {
$models = [$model];
}
/* @var $model Model */
foreach ($models as $model) {
$model->validate($attributes);
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, $attribute)] = $errors;
}
}
return $result;
} | php | {
"resource": ""
} |
q241583 | ActiveForm.validateMultiple | validation | public static function validateMultiple($models, $attributes = null)
{
$result = [];
/* @var $model Model */
foreach ($models as $i => $model) {
$model->validate($attributes);
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, "[$i]" . $attribute)] = $errors;
}
}
return $result;
} | php | {
"resource": ""
} |
q241584 | LinkSorter.renderSortLinks | validation | protected function renderSortLinks()
{
$attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
$links = [];
foreach ($attributes as $name) {
$links[] = $this->sort->link($name, $this->linkOptions);
}
return Html::ul($links, array_merge($this->options, ['encode' => false]));
} | php | {
"resource": ""
} |
q241585 | BaseHtml.mailto | validation | public static function mailto($text, $email = null, $options = [])
{
$options['href'] = 'mailto:' . ($email === null ? $text : $email);
return static::tag('a', $text, $options);
} | php | {
"resource": ""
} |
q241586 | BaseHtml.setActivePlaceholder | validation | protected static function setActivePlaceholder($model, $attribute, &$options = [])
{
if (isset($options['placeholder']) && $options['placeholder'] === true) {
$attribute = static::getAttributeName($attribute);
$options['placeholder'] = $model->getAttributeLabel($attribute);
}
} | php | {
"resource": ""
} |
q241587 | BaseHtml.mergeCssClasses | validation | private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
{
foreach ($additionalClasses as $key => $class) {
if (is_int($key) && !in_array($class, $existingClasses)) {
$existingClasses[] = $class;
} elseif (!isset($existingClasses[$key])) {
$existingClasses[$key] = $class;
}
}
return array_unique($existingClasses);
} | php | {
"resource": ""
} |
q241588 | BaseHtml.removeCssClass | validation | public static function removeCssClass(&$options, $class)
{
if (isset($options['class'])) {
if (is_array($options['class'])) {
$classes = array_diff($options['class'], (array) $class);
if (empty($classes)) {
unset($options['class']);
} else {
$options['class'] = $classes;
}
} else {
$classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
$classes = array_diff($classes, (array) $class);
if (empty($classes)) {
unset($options['class']);
} else {
$options['class'] = implode(' ', $classes);
}
}
}
} | php | {
"resource": ""
} |
q241589 | BaseHtml.cssStyleFromArray | validation | public static function cssStyleFromArray(array $style)
{
$result = '';
foreach ($style as $name => $value) {
$result .= "$name: $value; ";
}
// return null if empty to avoid rendering the "style" attribute
return $result === '' ? null : rtrim($result);
} | php | {
"resource": ""
} |
q241590 | BaseHtml.cssStyleToArray | validation | public static function cssStyleToArray($style)
{
$result = [];
foreach (explode(';', $style) as $property) {
$property = explode(':', $property);
if (count($property) > 1) {
$result[trim($property[0])] = trim($property[1]);
}
}
return $result;
} | php | {
"resource": ""
} |
q241591 | BaseHtml.getAttributeValue | validation | public static function getAttributeValue($model, $attribute)
{
if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
throw new InvalidArgumentException('Attribute name must contain word characters only.');
}
$attribute = $matches[2];
$value = $model->$attribute;
if ($matches[3] !== '') {
foreach (explode('][', trim($matches[3], '[]')) as $id) {
if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
$value = $value[$id];
} else {
return null;
}
}
}
// https://github.com/yiisoft/yii2/issues/1457
if (is_array($value)) {
foreach ($value as $i => $v) {
if ($v instanceof ActiveRecordInterface) {
$v = $v->getPrimaryKey(false);
$value[$i] = is_array($v) ? json_encode($v) : $v;
}
}
} elseif ($value instanceof ActiveRecordInterface) {
$value = $value->getPrimaryKey(false);
return is_array($value) ? json_encode($value) : $value;
}
return $value;
} | php | {
"resource": ""
} |
q241592 | BaseHtml.getInputName | validation | public static function getInputName($model, $attribute)
{
$formName = $model->formName();
if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
throw new InvalidArgumentException('Attribute name must contain word characters only.');
}
$prefix = $matches[1];
$attribute = $matches[2];
$suffix = $matches[3];
if ($formName === '' && $prefix === '') {
return $attribute . $suffix;
} elseif ($formName !== '') {
return $formName . $prefix . "[$attribute]" . $suffix;
}
throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
} | php | {
"resource": ""
} |
q241593 | BaseHtml.getInputId | validation | public static function getInputId($model, $attribute)
{
$charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
$name = mb_strtolower(static::getInputName($model, $attribute), $charset);
return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
} | php | {
"resource": ""
} |
q241594 | BaseHtml.escapeJsRegularExpression | validation | public static function escapeJsRegularExpression($regexp)
{
$pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
$deliminator = substr($pattern, 0, 1);
$pos = strrpos($pattern, $deliminator, 1);
$flag = substr($pattern, $pos + 1);
if ($deliminator !== '/') {
$pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
} else {
$pattern = substr($pattern, 0, $pos + 1);
}
if (!empty($flag)) {
$pattern .= preg_replace('/[^igmu]/', '', $flag);
}
return $pattern;
} | php | {
"resource": ""
} |
q241595 | MessageFormatter.tokenizePattern | validation | private static function tokenizePattern($pattern)
{
$charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
$depth = 1;
if (($start = $pos = mb_strpos($pattern, '{', 0, $charset)) === false) {
return [$pattern];
}
$tokens = [mb_substr($pattern, 0, $pos, $charset)];
while (true) {
$open = mb_strpos($pattern, '{', $pos + 1, $charset);
$close = mb_strpos($pattern, '}', $pos + 1, $charset);
if ($open === false && $close === false) {
break;
}
if ($open === false) {
$open = mb_strlen($pattern, $charset);
}
if ($close > $open) {
$depth++;
$pos = $open;
} else {
$depth--;
$pos = $close;
}
if ($depth === 0) {
$tokens[] = explode(',', mb_substr($pattern, $start + 1, $pos - $start - 1, $charset), 3);
$start = $pos + 1;
$tokens[] = mb_substr($pattern, $start, $open - $start, $charset);
$start = $open;
}
if ($depth !== 0 && ($open === false || $close === false)) {
break;
}
}
if ($depth !== 0) {
return false;
}
return $tokens;
} | php | {
"resource": ""
} |
q241596 | BaseDataProvider.prepare | validation | public function prepare($forcePrepare = false)
{
if ($forcePrepare || $this->_models === null) {
$this->_models = $this->prepareModels();
}
if ($forcePrepare || $this->_keys === null) {
$this->_keys = $this->prepareKeys($this->_models);
}
} | php | {
"resource": ""
} |
q241597 | Application.init | validation | public function init()
{
parent::init();
if ($this->enableCoreCommands) {
foreach ($this->coreCommands() as $id => $command) {
if (!isset($this->controllerMap[$id])) {
$this->controllerMap[$id] = $command;
}
}
}
// ensure we have the 'help' command so that we can list the available commands
if (!isset($this->controllerMap['help'])) {
$this->controllerMap['help'] = 'yii\console\controllers\HelpController';
}
} | php | {
"resource": ""
} |
q241598 | YiiRequirementChecker.checkPhpExtensionVersion | validation | function checkPhpExtensionVersion($extensionName, $version, $compare = '>=')
{
if (!extension_loaded($extensionName)) {
return false;
}
$extensionVersion = phpversion($extensionName);
if (empty($extensionVersion)) {
return false;
}
if (strncasecmp($extensionVersion, 'PECL-', 5) === 0) {
$extensionVersion = substr($extensionVersion, 5);
}
return version_compare($extensionVersion, $version, $compare);
} | php | {
"resource": ""
} |
q241599 | YiiRequirementChecker.compareByteSize | validation | function compareByteSize($a, $b, $compare = '>=')
{
$compareExpression = '(' . $this->getByteSize($a) . $compare . $this->getByteSize($b) . ')';
return $this->evaluateExpression($compareExpression);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.