_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q242000 | SqlToken.setChildren | validation | public function setChildren($children)
{
$this->_children = [];
foreach ($children as $child) {
$child->parent = $this;
$this->_children[] = $child;
}
$this->updateCollectionOffsets();
} | php | {
"resource": ""
} |
q242001 | SqlToken.getIsCollection | validation | public function getIsCollection()
{
return in_array($this->type, [
self::TYPE_CODE,
self::TYPE_STATEMENT,
self::TYPE_PARENTHESIS,
], true);
} | php | {
"resource": ""
} |
q242002 | SqlToken.getSql | validation | public function getSql()
{
$code = $this;
while ($code->parent !== null) {
$code = $code->parent;
}
return mb_substr($code->content, $this->startOffset, $this->endOffset - $this->startOffset, 'UTF-8');
} | php | {
"resource": ""
} |
q242003 | SqlToken.tokensMatch | validation | private function tokensMatch(SqlToken $patternToken, SqlToken $token, $offset = 0, &$firstMatchIndex = null, &$lastMatchIndex = null)
{
if (
$patternToken->getIsCollection() !== $token->getIsCollection()
|| (!$patternToken->getIsCollection() && $patternToken->content !== $token->content)
) {
return false;
}
if ($patternToken->children === $token->children) {
$firstMatchIndex = $lastMatchIndex = $offset;
return true;
}
$firstMatchIndex = $lastMatchIndex = null;
$wildcard = false;
for ($index = 0, $count = count($patternToken->children); $index < $count; $index++) {
// Here we iterate token by token with an exception of "any" that toggles
// an iteration until we matched with a next pattern token or EOF.
if ($patternToken[$index]->content === 'any') {
$wildcard = true;
continue;
}
for ($limit = $wildcard ? count($token->children) : $offset + 1; $offset < $limit; $offset++) {
if (!$wildcard && !isset($token[$offset])) {
break;
}
if (!$this->tokensMatch($patternToken[$index], $token[$offset])) {
continue;
}
if ($firstMatchIndex === null) {
$firstMatchIndex = $offset;
$lastMatchIndex = $offset;
} else {
$lastMatchIndex = $offset;
}
$wildcard = false;
$offset++;
continue 2;
}
return false;
}
return true;
} | php | {
"resource": ""
} |
q242004 | SqlToken.updateCollectionOffsets | validation | private function updateCollectionOffsets()
{
if (!empty($this->_children)) {
$this->startOffset = reset($this->_children)->startOffset;
$this->endOffset = end($this->_children)->endOffset;
}
if ($this->parent !== null) {
$this->parent->updateCollectionOffsets();
}
} | php | {
"resource": ""
} |
q242005 | Command.splitStatements | validation | private function splitStatements($sql, $params)
{
$semicolonIndex = strpos($sql, ';');
if ($semicolonIndex === false || $semicolonIndex === StringHelper::byteLength($sql) - 1) {
return false;
}
$tokenizer = new SqlTokenizer($sql);
$codeToken = $tokenizer->tokenize();
if (count($codeToken->getChildren()) === 1) {
return false;
}
$statements = [];
foreach ($codeToken->getChildren() as $statement) {
$statements[] = [$statement->getSql(), $this->extractUsedParams($statement, $params)];
}
return $statements;
} | php | {
"resource": ""
} |
q242006 | Command.extractUsedParams | validation | private function extractUsedParams(SqlToken $statement, $params)
{
preg_match_all('/(?P<placeholder>[:][a-zA-Z0-9_]+)/', $statement->getSql(), $matches, PREG_SET_ORDER);
$result = [];
foreach ($matches as $match) {
$phName = ltrim($match['placeholder'], ':');
if (isset($params[$phName])) {
$result[$phName] = $params[$phName];
} elseif (isset($params[':' . $phName])) {
$result[':' . $phName] = $params[':' . $phName];
}
}
return $result;
} | php | {
"resource": ""
} |
q242007 | User.setIdentity | validation | public function setIdentity($identity)
{
if ($identity instanceof IdentityInterface) {
$this->_identity = $identity;
} elseif ($identity === null) {
$this->_identity = null;
} else {
throw new InvalidValueException('The identity object must implement IdentityInterface.');
}
$this->_access = [];
} | php | {
"resource": ""
} |
q242008 | User.login | validation | public function login(IdentityInterface $identity, $duration = 0)
{
if ($this->beforeLogin($identity, false, $duration)) {
$this->switchIdentity($identity, $duration);
$id = $identity->getId();
$ip = Yii::$app->getRequest()->getUserIP();
if ($this->enableSession) {
$log = "User '$id' logged in from $ip with duration $duration.";
} else {
$log = "User '$id' logged in from $ip. Session not enabled.";
}
$this->regenerateCsrfToken();
Yii::info($log, __METHOD__);
$this->afterLogin($identity, false, $duration);
}
return !$this->getIsGuest();
} | php | {
"resource": ""
} |
q242009 | User.regenerateCsrfToken | validation | protected function regenerateCsrfToken()
{
$request = Yii::$app->getRequest();
if ($request->enableCsrfCookie || $this->enableSession) {
$request->getCsrfToken(true);
}
} | php | {
"resource": ""
} |
q242010 | ErrorException.isFatalError | validation | public static function isFatalError($error)
{
return isset($error['type']) && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, self::E_HHVM_FATAL_ERROR]);
} | php | {
"resource": ""
} |
q242011 | ArrayExpression.getIterator | validation | public function getIterator()
{
$value = $this->getValue();
if ($value instanceof QueryInterface) {
throw new InvalidConfigException('The ArrayExpression class can not be iterated when the value is a QueryInterface object');
}
if ($value === null) {
$value = [];
}
return new \ArrayIterator($value);
} | php | {
"resource": ""
} |
q242012 | MessageController.actionConfig | validation | public function actionConfig($filePath)
{
$filePath = Yii::getAlias($filePath);
$dir = dirname($filePath);
if (file_exists($filePath)) {
if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
return ExitCode::OK;
}
}
$array = VarDumper::export($this->getOptionValues($this->action->id));
$content = <<<EOD
<?php
/**
* Configuration file for 'yii {$this->id}/{$this->defaultAction}' command.
*
* This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
* It contains parameters for source code messages extraction.
* You may modify this file to suit your needs.
*
* You can use 'yii {$this->id}/{$this->action->id}-template' command to create
* template configuration file with detailed description for each parameter.
*/
return $array;
EOD;
if (FileHelper::createDirectory($dir) === false || file_put_contents($filePath, $content, LOCK_EX) === false) {
$this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
return ExitCode::OK;
} | php | {
"resource": ""
} |
q242013 | MessageController.actionConfigTemplate | validation | public function actionConfigTemplate($filePath)
{
$filePath = Yii::getAlias($filePath);
if (file_exists($filePath)) {
if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
return ExitCode::OK;
}
}
if (!copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath)) {
$this->stdout("Configuration file template was NOT created at '{$filePath}'.\n\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
return ExitCode::OK;
} | php | {
"resource": ""
} |
q242014 | MessageController.actionExtract | validation | public function actionExtract($configFile = null)
{
$this->initConfig($configFile);
$files = FileHelper::findFiles(realpath($this->config['sourcePath']), $this->config);
$messages = [];
foreach ($files as $file) {
$messages = array_merge_recursive($messages, $this->extractMessages($file, $this->config['translator'], $this->config['ignoreCategories']));
}
$catalog = isset($this->config['catalog']) ? $this->config['catalog'] : 'messages';
if (in_array($this->config['format'], ['php', 'po'])) {
foreach ($this->config['languages'] as $language) {
$dir = $this->config['messagePath'] . DIRECTORY_SEPARATOR . $language;
if (!is_dir($dir) && !@mkdir($dir)) {
throw new Exception("Directory '{$dir}' can not be created.");
}
if ($this->config['format'] === 'po') {
$this->saveMessagesToPO($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $catalog, $this->config['markUnused']);
} else {
$this->saveMessagesToPHP($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $this->config['markUnused']);
}
}
} elseif ($this->config['format'] === 'db') {
/** @var Connection $db */
$db = Instance::ensure($this->config['db'], Connection::className());
$sourceMessageTable = isset($this->config['sourceMessageTable']) ? $this->config['sourceMessageTable'] : '{{%source_message}}';
$messageTable = isset($this->config['messageTable']) ? $this->config['messageTable'] : '{{%message}}';
$this->saveMessagesToDb(
$messages,
$db,
$sourceMessageTable,
$messageTable,
$this->config['removeUnused'],
$this->config['languages'],
$this->config['markUnused']
);
} elseif ($this->config['format'] === 'pot') {
$this->saveMessagesToPOT($messages, $this->config['messagePath'], $catalog);
}
} | php | {
"resource": ""
} |
q242015 | MessageController.extractMessages | validation | protected function extractMessages($fileName, $translator, $ignoreCategories = [])
{
$this->stdout('Extracting messages from ');
$this->stdout($fileName, Console::FG_CYAN);
$this->stdout("...\n");
$subject = file_get_contents($fileName);
$messages = [];
$tokens = token_get_all($subject);
foreach ((array) $translator as $currentTranslator) {
$translatorTokens = token_get_all('<?php ' . $currentTranslator);
array_shift($translatorTokens);
$messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($tokens, $translatorTokens, $ignoreCategories));
}
$this->stdout("\n");
return $messages;
} | php | {
"resource": ""
} |
q242016 | QueryBuilder.resetSequence | validation | public function resetSequence($tableName, $value = null)
{
$table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
$tableName = $this->db->quoteTableName($tableName);
if ($value === null) {
$key = reset($table->primaryKey);
$value = $this->db->createCommand("SELECT MAX(`$key`) FROM $tableName")->queryScalar() + 1;
} else {
$value = (int) $value;
}
return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
} elseif ($table === null) {
throw new InvalidArgumentException("Table not found: $tableName");
}
throw new InvalidArgumentException("There is no sequence associated with table '$tableName'.");
} | php | {
"resource": ""
} |
q242017 | QueryBuilder.supportsFractionalSeconds | validation | private function supportsFractionalSeconds()
{
$version = $this->db->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
return version_compare($version, '5.6.4', '>=');
} | php | {
"resource": ""
} |
q242018 | QueryBuilder.defaultTimeTypeMap | validation | private function defaultTimeTypeMap()
{
$map = [
Schema::TYPE_DATETIME => 'datetime',
Schema::TYPE_TIMESTAMP => 'timestamp',
Schema::TYPE_TIME => 'time',
];
if ($this->supportsFractionalSeconds()) {
$map = [
Schema::TYPE_DATETIME => 'datetime(0)',
Schema::TYPE_TIMESTAMP => 'timestamp(0)',
Schema::TYPE_TIME => 'time(0)',
];
}
return $map;
} | php | {
"resource": ""
} |
q242019 | Captcha.checkRequirements | validation | public static function checkRequirements()
{
if (extension_loaded('imagick')) {
$imagickFormats = (new \Imagick())->queryFormats('PNG');
if (in_array('PNG', $imagickFormats, true)) {
return 'imagick';
}
}
if (extension_loaded('gd')) {
$gdInfo = gd_info();
if (!empty($gdInfo['FreeType Support'])) {
return 'gd';
}
}
throw new InvalidConfigException('Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required.');
} | php | {
"resource": ""
} |
q242020 | CookieCollection.get | validation | public function get($name)
{
return isset($this->_cookies[$name]) ? $this->_cookies[$name] : null;
} | php | {
"resource": ""
} |
q242021 | CookieCollection.getValue | validation | public function getValue($name, $defaultValue = null)
{
return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue;
} | php | {
"resource": ""
} |
q242022 | CookieCollection.has | validation | public function has($name)
{
return isset($this->_cookies[$name]) && $this->_cookies[$name]->value !== ''
&& ($this->_cookies[$name]->expire === null || $this->_cookies[$name]->expire === 0 || $this->_cookies[$name]->expire >= time());
} | php | {
"resource": ""
} |
q242023 | CookieCollection.add | validation | public function add($cookie)
{
if ($this->readOnly) {
throw new InvalidCallException('The cookie collection is read only.');
}
$this->_cookies[$cookie->name] = $cookie;
} | php | {
"resource": ""
} |
q242024 | TranslationController.actionReport | validation | public function actionReport($sourcePath, $translationPath, $title = 'Translation report')
{
$sourcePath = trim($sourcePath, '/\\');
$translationPath = trim($translationPath, '/\\');
$results = [];
$dir = new DirectoryIterator($sourcePath);
foreach ($dir as $fileinfo) {
/* @var $fileinfo DirectoryIterator */
if (!$fileinfo->isDot() && !$fileinfo->isDir()) {
$translatedFilePath = $translationPath . '/' . $fileinfo->getFilename();
$sourceFilePath = $sourcePath . '/' . $fileinfo->getFilename();
$errors = $this->checkFiles($translatedFilePath);
$diff = empty($errors) ? $this->getDiff($translatedFilePath, $sourceFilePath) : '';
if (!empty($diff)) {
$errors[] = 'Translation outdated.';
}
$result = [
'errors' => $errors,
'diff' => $diff,
];
$results[$fileinfo->getFilename()] = $result;
}
}
// checking if there are obsolete translation files
$dir = new DirectoryIterator($translationPath);
foreach ($dir as $fileinfo) {
/* @var $fileinfo \DirectoryIterator */
if (!$fileinfo->isDot() && !$fileinfo->isDir()) {
$translatedFilePath = $translationPath . '/' . $fileinfo->getFilename();
$errors = $this->checkFiles(null, $translatedFilePath);
if (!empty($errors)) {
$results[$fileinfo->getFilename()]['errors'] = $errors;
}
}
}
echo $this->renderFile(__DIR__ . '/views/translation/report_html.php', [
'results' => $results,
'sourcePath' => $sourcePath,
'translationPath' => $translationPath,
'title' => $title,
]);
} | php | {
"resource": ""
} |
q242025 | HttpCache.validateCache | validation | protected function validateCache($lastModified, $etag)
{
if (Yii::$app->request->headers->has('If-None-Match')) {
// HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
// http://tools.ietf.org/html/rfc7232#section-3.3
return $etag !== null && in_array($etag, Yii::$app->request->getETags(), true);
} elseif (Yii::$app->request->headers->has('If-Modified-Since')) {
return $lastModified !== null && @strtotime(Yii::$app->request->headers->get('If-Modified-Since')) >= $lastModified;
}
return false;
} | php | {
"resource": ""
} |
q242026 | HttpCache.generateEtag | validation | protected function generateEtag($seed)
{
$etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"';
return $this->weakEtag ? 'W/' . $etag : $etag;
} | php | {
"resource": ""
} |
q242027 | Model.scenarios | validation | public function scenarios()
{
$scenarios = [self::SCENARIO_DEFAULT => []];
foreach ($this->getValidators() as $validator) {
foreach ($validator->on as $scenario) {
$scenarios[$scenario] = [];
}
foreach ($validator->except as $scenario) {
$scenarios[$scenario] = [];
}
}
$names = array_keys($scenarios);
foreach ($this->getValidators() as $validator) {
if (empty($validator->on) && empty($validator->except)) {
foreach ($names as $name) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
} elseif (empty($validator->on)) {
foreach ($names as $name) {
if (!in_array($name, $validator->except, true)) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
} else {
foreach ($validator->on as $name) {
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
}
foreach ($scenarios as $scenario => $attributes) {
if (!empty($attributes)) {
$scenarios[$scenario] = array_keys($attributes);
}
}
return $scenarios;
} | php | {
"resource": ""
} |
q242028 | Model.formName | validation | public function formName()
{
$reflector = new ReflectionClass($this);
if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
}
return $reflector->getShortName();
} | php | {
"resource": ""
} |
q242029 | Model.getAttributeHint | validation | public function getAttributeHint($attribute)
{
$hints = $this->attributeHints();
return isset($hints[$attribute]) ? $hints[$attribute] : '';
} | php | {
"resource": ""
} |
q242030 | Model.getFirstError | validation | public function getFirstError($attribute)
{
return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
} | php | {
"resource": ""
} |
q242031 | Model.getErrorSummary | validation | public function getErrorSummary($showAllErrors)
{
$lines = [];
$errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
foreach ($errors as $es) {
$lines = array_merge((array)$es, $lines);
}
return $lines;
} | php | {
"resource": ""
} |
q242032 | Model.addErrors | validation | public function addErrors(array $items)
{
foreach ($items as $attribute => $errors) {
if (is_array($errors)) {
foreach ($errors as $error) {
$this->addError($attribute, $error);
}
} else {
$this->addError($attribute, $errors);
}
}
} | php | {
"resource": ""
} |
q242033 | Model.clearErrors | validation | public function clearErrors($attribute = null)
{
if ($attribute === null) {
$this->_errors = [];
} else {
unset($this->_errors[$attribute]);
}
} | php | {
"resource": ""
} |
q242034 | Model.getAttributes | validation | public function getAttributes($names = null, $except = [])
{
$values = [];
if ($names === null) {
$names = $this->attributes();
}
foreach ($names as $name) {
$values[$name] = $this->$name;
}
foreach ($except as $name) {
unset($values[$name]);
}
return $values;
} | php | {
"resource": ""
} |
q242035 | Model.activeAttributes | validation | public function activeAttributes()
{
$scenario = $this->getScenario();
$scenarios = $this->scenarios();
if (!isset($scenarios[$scenario])) {
return [];
}
$attributes = array_keys(array_flip($scenarios[$scenario]));
foreach ($attributes as $i => $attribute) {
if ($attribute[0] === '!') {
$attributes[$i] = substr($attribute, 1);
}
}
return $attributes;
} | php | {
"resource": ""
} |
q242036 | Model.load | validation | public function load($data, $formName = null)
{
$scope = $formName === null ? $this->formName() : $formName;
if ($scope === '' && !empty($data)) {
$this->setAttributes($data);
return true;
} elseif (isset($data[$scope])) {
$this->setAttributes($data[$scope]);
return true;
}
return false;
} | php | {
"resource": ""
} |
q242037 | Tokens.getAnnotationEnd | validation | public function getAnnotationEnd($index)
{
$currentIndex = null;
if (isset($this[$index + 2])) {
if ($this[$index + 2]->isType(DocLexer::T_OPEN_PARENTHESIS)) {
$currentIndex = $index + 2;
} elseif (
isset($this[$index + 3])
&& $this[$index + 2]->isType(DocLexer::T_NONE)
&& $this[$index + 3]->isType(DocLexer::T_OPEN_PARENTHESIS)
&& Preg::match('/^(\R\s*\*\s*)*\s*$/', $this[$index + 2]->getContent())
) {
$currentIndex = $index + 3;
}
}
if (null !== $currentIndex) {
$level = 0;
for ($max = \count($this); $currentIndex < $max; ++$currentIndex) {
if ($this[$currentIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) {
++$level;
} elseif ($this[$currentIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) {
--$level;
}
if (0 === $level) {
return $currentIndex;
}
}
return null;
}
return $index + 1;
} | php | {
"resource": ""
} |
q242038 | Tokens.getArrayEnd | validation | public function getArrayEnd($index)
{
$level = 1;
for (++$index, $max = \count($this); $index < $max; ++$index) {
if ($this[$index]->isType(DocLexer::T_OPEN_CURLY_BRACES)) {
++$level;
} elseif ($this[$index]->isType($index, DocLexer::T_CLOSE_CURLY_BRACES)) {
--$level;
}
if (0 === $level) {
return $index;
}
}
return null;
} | php | {
"resource": ""
} |
q242039 | Tokens.insertAt | validation | public function insertAt($index, Token $token)
{
$this->setSize($this->getSize() + 1);
for ($i = $this->getSize() - 1; $i > $index; --$i) {
$this[$i] = isset($this[$i - 1]) ? $this[$i - 1] : new Token();
}
$this[$index] = $token;
} | php | {
"resource": ""
} |
q242040 | NoSpacesInsideParenthesisFixer.removeSpaceAroundToken | validation | private function removeSpaceAroundToken(Tokens $tokens, $index)
{
$token = $tokens[$index];
if ($token->isWhitespace() && false === strpos($token->getContent(), "\n")) {
$tokens->clearAt($index);
}
} | php | {
"resource": ""
} |
q242041 | StandardizeIncrementFixer.findStart | validation | private function findStart(Tokens $tokens, $index)
{
while (!$tokens[$index]->equalsAny(['$', [T_VARIABLE]])) {
if ($tokens[$index]->equals(']')) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index);
} elseif ($tokens[$index]->isGivenKind(CT::T_DYNAMIC_PROP_BRACE_CLOSE)) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, $index);
} elseif ($tokens[$index]->isGivenKind(CT::T_DYNAMIC_VAR_BRACE_CLOSE)) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, $index);
} elseif ($tokens[$index]->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE)) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, $index);
} else {
$index = $tokens->getPrevMeaningfulToken($index);
}
}
while ($tokens[$tokens->getPrevMeaningfulToken($index)]->equals('$')) {
$index = $tokens->getPrevMeaningfulToken($index);
}
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_OBJECT_OPERATOR)) {
return $this->findStart($tokens, $tokens->getPrevMeaningfulToken($index));
}
return $index;
} | php | {
"resource": ""
} |
q242042 | StandardizeIncrementFixer.clearRangeLeaveComments | validation | private function clearRangeLeaveComments(Tokens $tokens, $indexStart, $indexEnd)
{
for ($i = $indexStart; $i <= $indexEnd; ++$i) {
$token = $tokens[$i];
if ($token->isComment()) {
continue;
}
if ($token->isWhitespace("\n\r")) {
continue;
}
$tokens->clearAt($i);
}
} | php | {
"resource": ""
} |
q242043 | TagComparator.shouldBeTogether | validation | public static function shouldBeTogether(Tag $first, Tag $second)
{
$firstName = $first->getName();
$secondName = $second->getName();
if ($firstName === $secondName) {
return true;
}
foreach (self::$groups as $group) {
if (\in_array($firstName, $group, true) && \in_array($secondName, $group, true)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q242044 | VoidReturnFixer.hasVoidReturnAnnotation | validation | private function hasVoidReturnAnnotation(Tokens $tokens, $index)
{
foreach ($this->findReturnAnnotations($tokens, $index) as $return) {
if (['void'] === $return->getTypes()) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q242045 | VoidReturnFixer.hasReturnTypeHint | validation | private function hasReturnTypeHint(Tokens $tokens, $index)
{
$endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']);
$nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex);
return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON);
} | php | {
"resource": ""
} |
q242046 | VoidReturnFixer.hasVoidReturn | validation | private function hasVoidReturn(Tokens $tokens, $startIndex, $endIndex)
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
for ($i = $startIndex; $i < $endIndex; ++$i) {
if (
// skip anonymous classes
($tokens[$i]->isGivenKind(T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) ||
// skip lambda functions
($tokens[$i]->isGivenKind(T_FUNCTION) && $tokensAnalyzer->isLambda($i))
) {
$i = $tokens->getNextTokenOfKind($i, ['{']);
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i);
continue;
}
if ($tokens[$i]->isGivenKind([T_YIELD, T_YIELD_FROM])) {
return false; // Generators cannot return void.
}
if (!$tokens[$i]->isGivenKind(T_RETURN)) {
continue;
}
$i = $tokens->getNextMeaningfulToken($i);
if (!$tokens[$i]->equals(';')) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q242047 | VoidReturnFixer.findReturnAnnotations | validation | private function findReturnAnnotations(Tokens $tokens, $index)
{
do {
$index = $tokens->getPrevNonWhitespace($index);
} while ($tokens[$index]->isGivenKind([
T_ABSTRACT,
T_FINAL,
T_PRIVATE,
T_PROTECTED,
T_PUBLIC,
T_STATIC,
]));
if (!$tokens[$index]->isGivenKind(T_DOC_COMMENT)) {
return [];
}
$doc = new DocBlock($tokens[$index]->getContent());
return $doc->getAnnotationsOfType('return');
} | php | {
"resource": ""
} |
q242048 | NamespacedStringTokenGenerator.generate | validation | public function generate($input)
{
$tokens = [];
$parts = explode('\\', $input);
foreach ($parts as $index => $part) {
$tokens[] = new Token([T_STRING, $part]);
if ($index !== \count($parts) - 1) {
$tokens[] = new Token([T_NS_SEPARATOR, '\\']);
}
}
return $tokens;
} | php | {
"resource": ""
} |
q242049 | OrderedImportsFixer.sortAlphabetically | validation | private function sortAlphabetically(array $first, array $second)
{
// Replace backslashes by spaces before sorting for correct sort order
$firstNamespace = str_replace('\\', ' ', $this->prepareNamespace($first['namespace']));
$secondNamespace = str_replace('\\', ' ', $this->prepareNamespace($second['namespace']));
return strcasecmp($firstNamespace, $secondNamespace);
} | php | {
"resource": ""
} |
q242050 | OrderedImportsFixer.sortByLength | validation | private function sortByLength(array $first, array $second)
{
$firstNamespace = (self::IMPORT_TYPE_CLASS === $first['importType'] ? '' : $first['importType'].' ').$this->prepareNamespace($first['namespace']);
$secondNamespace = (self::IMPORT_TYPE_CLASS === $second['importType'] ? '' : $second['importType'].' ').$this->prepareNamespace($second['namespace']);
$firstNamespaceLength = \strlen($firstNamespace);
$secondNamespaceLength = \strlen($secondNamespace);
if ($firstNamespaceLength === $secondNamespaceLength) {
$sortResult = strcasecmp($firstNamespace, $secondNamespace);
} else {
$sortResult = $firstNamespaceLength > $secondNamespaceLength ? 1 : -1;
}
return $sortResult;
} | php | {
"resource": ""
} |
q242051 | NoSuperfluousPhpdocTagsFixer.toComparableNames | validation | private function toComparableNames(array $types, array $symbolShortNames)
{
$normalized = array_map(
function ($type) use ($symbolShortNames) {
$type = strtolower($type);
if (isset($symbolShortNames[$type])) {
return $symbolShortNames[$type];
}
return $type;
},
$types
);
sort($normalized);
return $normalized;
} | php | {
"resource": ""
} |
q242052 | ClassAttributesSeparationFixer.fixSpaceBelowClassElement | validation | private function fixSpaceBelowClassElement(Tokens $tokens, $classEndIndex, $elementEndIndex)
{
for ($nextNotWhite = $elementEndIndex + 1;; ++$nextNotWhite) {
if (($tokens[$nextNotWhite]->isComment() || $tokens[$nextNotWhite]->isWhitespace()) && false === strpos($tokens[$nextNotWhite]->getContent(), "\n")) {
continue;
}
break;
}
if ($tokens[$nextNotWhite]->isWhitespace()) {
$nextNotWhite = $tokens->getNextNonWhitespace($nextNotWhite);
}
$this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, $nextNotWhite === $classEndIndex ? 1 : 2);
} | php | {
"resource": ""
} |
q242053 | ClassAttributesSeparationFixer.fixSpaceBelowClassMethod | validation | private function fixSpaceBelowClassMethod(Tokens $tokens, $classEndIndex, $elementEndIndex)
{
$nextNotWhite = $tokens->getNextNonWhitespace($elementEndIndex);
$this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, $nextNotWhite === $classEndIndex ? 1 : 2);
} | php | {
"resource": ""
} |
q242054 | ClassAttributesSeparationFixer.fixSpaceAboveClassElement | validation | private function fixSpaceAboveClassElement(Tokens $tokens, $classStartIndex, $elementIndex)
{
static $methodAttr = [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_ABSTRACT, T_FINAL, T_STATIC];
// find out where the element definition starts
$firstElementAttributeIndex = $elementIndex;
for ($i = $elementIndex; $i > $classStartIndex; --$i) {
$nonWhiteAbove = $tokens->getNonWhitespaceSibling($i, -1);
if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind($methodAttr)) {
$firstElementAttributeIndex = $nonWhiteAbove;
} else {
break;
}
}
// deal with comments above a element
if ($tokens[$nonWhiteAbove]->isGivenKind(T_COMMENT)) {
if (1 === $firstElementAttributeIndex - $nonWhiteAbove) {
// no white space found between comment and element start
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1);
return;
}
// $tokens[$nonWhiteAbove+1] is always a white space token here
if (substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) {
// more than one line break, always bring it back to 2 line breaks between the element start and what is above it
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 2);
return;
}
// there are 2 cases:
if ($tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0) {
// 1. The comment is meant for the element (although not a PHPDoc),
// make sure there is one line break between the element and the comment...
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1);
// ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening)
$nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove);
$nonWhiteAboveComment = $tokens->getNonWhitespaceSibling($nonWhiteAbove, -1);
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $classStartIndex ? 1 : 2);
} else {
// 2. The comment belongs to the code above the element,
// make sure there is a blank line above the element (i.e. 2 line breaks)
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 2);
}
return;
}
// deal with element without a PHPDoc above it
if (false === $tokens[$nonWhiteAbove]->isGivenKind(T_DOC_COMMENT)) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, $nonWhiteAbove === $classStartIndex ? 1 : 2);
return;
}
// there should be one linebreak between the element and the PHPDoc above it
$this->correctLineBreaks($tokens, $nonWhiteAbove, $firstElementAttributeIndex, 1);
// there should be one blank line between the PHPDoc and whatever is above (with the exception when it is directly after a class opening)
$nonWhiteAbovePHPDoc = $tokens->getNonWhitespaceSibling($nonWhiteAbove, -1);
$this->correctLineBreaks($tokens, $nonWhiteAbovePHPDoc, $nonWhiteAbove, $nonWhiteAbovePHPDoc === $classStartIndex ? 1 : 2);
} | php | {
"resource": ""
} |
q242055 | MultilineWhitespaceBeforeSemicolonsFixer.getNewLineIndex | validation | private function getNewLineIndex($index, Tokens $tokens)
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
for ($index, $count = \count($tokens); $index < $count; ++$index) {
if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) {
return $index;
}
}
return $index;
} | php | {
"resource": ""
} |
q242056 | PhpdocNoEmptyReturnFixer.fixAnnotation | validation | private function fixAnnotation(DocBlock $doc, Annotation $annotation)
{
$types = $annotation->getNormalizedTypes();
if (1 === \count($types) && ('null' === $types[0] || 'void' === $types[0])) {
$annotation->remove();
}
} | php | {
"resource": ""
} |
q242057 | TernaryToNullCoalescingFixer.getMeaningfulSequence | validation | private function getMeaningfulSequence(Tokens $tokens, $start, $end)
{
$sequence = [];
$index = $start;
while ($index < $end) {
$index = $tokens->getNextMeaningfulToken($index);
if ($index >= $end || null === $index) {
break;
}
$sequence[] = $tokens[$index];
}
return Tokens::fromArray($sequence);
} | php | {
"resource": ""
} |
q242058 | MethodArgumentSpaceFixer.fixFunction | validation | private function fixFunction(Tokens $tokens, $startFunctionIndex)
{
$endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex);
$isMultiline = false;
$firstWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $startFunctionIndex, $endFunctionIndex);
$lastWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $endFunctionIndex, $startFunctionIndex);
foreach ([$firstWhitespaceIndex, $lastWhitespaceIndex] as $index) {
if (null === $index || !Preg::match('/\R/', $tokens[$index]->getContent())) {
continue;
}
if ('ensure_single_line' !== $this->configuration['on_multiline']) {
$isMultiline = true;
continue;
}
$newLinesRemoved = $this->ensureSingleLine($tokens, $index);
if (!$newLinesRemoved) {
$isMultiline = true;
}
}
for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) {
$token = $tokens[$index];
if ($token->equals(')')) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}
if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index);
continue;
}
if ($token->equals('}')) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if ($token->equals(',')) {
$this->fixSpace2($tokens, $index);
if (!$isMultiline && $this->isNewline($tokens[$index + 1])) {
$isMultiline = true;
break;
}
}
}
return $isMultiline;
} | php | {
"resource": ""
} |
q242059 | MethodArgumentSpaceFixer.fixNewline | validation | private function fixNewline(Tokens $tokens, $index, $indentation, $override = true)
{
if ($tokens[$index + 1]->isComment()) {
return;
}
if ($tokens[$index + 2]->isComment()) {
$nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index + 2);
if (!$this->isNewline($tokens[$nextMeaningfulTokenIndex - 1])) {
$tokens->ensureWhitespaceAtIndex($nextMeaningfulTokenIndex, 0, $this->whitespacesConfig->getLineEnding().$indentation);
}
return;
}
$tokens->ensureWhitespaceAtIndex($index + 1, 0, $this->whitespacesConfig->getLineEnding().$indentation);
} | php | {
"resource": ""
} |
q242060 | MethodArgumentSpaceFixer.isCommentLastLineToken | validation | private function isCommentLastLineToken(Tokens $tokens, $index)
{
if (!$tokens[$index]->isComment() || !$tokens[$index + 1]->isWhitespace()) {
return false;
}
$content = $tokens[$index + 1]->getContent();
return $content !== ltrim($content, "\r\n");
} | php | {
"resource": ""
} |
q242061 | BacktickToShellExecFixer.fixBackticks | validation | private function fixBackticks(Tokens $tokens, array $backtickTokens)
{
// Track indexes for final override
ksort($backtickTokens);
$openingBacktickIndex = key($backtickTokens);
end($backtickTokens);
$closingBacktickIndex = key($backtickTokens);
// Strip enclosing backticks
array_shift($backtickTokens);
array_pop($backtickTokens);
// Double-quoted strings are parsed differently if they contain
// variables or not, so we need to build the new token array accordingly
$count = \count($backtickTokens);
$newTokens = [
new Token([T_STRING, 'shell_exec']),
new Token('('),
];
if (1 !== $count) {
$newTokens[] = new Token('"');
}
foreach ($backtickTokens as $token) {
if (!$token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) {
$newTokens[] = $token;
continue;
}
$content = $token->getContent();
// Escaping special chars depends on the context: too tricky
if (Preg::match('/[`"\']/u', $content)) {
return;
}
$kind = T_ENCAPSED_AND_WHITESPACE;
if (1 === $count) {
$content = '"'.$content.'"';
$kind = T_CONSTANT_ENCAPSED_STRING;
}
$newTokens[] = new Token([$kind, $content]);
}
if (1 !== $count) {
$newTokens[] = new Token('"');
}
$newTokens[] = new Token(')');
$tokens->overrideRange($openingBacktickIndex, $closingBacktickIndex, $newTokens);
} | php | {
"resource": ""
} |
q242062 | PhpUnitInternalClassFixer.splitUpDocBlock | validation | private function splitUpDocBlock($lines, Tokens $tokens, $docBlockIndex)
{
$lineContent = $this->getSingleLineDocBlockEntry($lines);
$lineEnd = $this->whitespacesConfig->getLineEnding();
$originalIndent = $this->detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex));
return [
new Line('/**'.$lineEnd),
new Line($originalIndent.' * '.$lineContent.$lineEnd),
new Line($originalIndent.' */'),
];
} | php | {
"resource": ""
} |
q242063 | NoEmptyStatementFixer.fixSemicolonAfterCurlyBraceClose | validation | private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, $index, $curlyCloseIndex)
{
static $beforeCurlyOpeningKinds = null;
if (null === $beforeCurlyOpeningKinds) {
$beforeCurlyOpeningKinds = [T_ELSE, T_FINALLY, T_NAMESPACE, T_OPEN_TAG];
}
$curlyOpeningIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $curlyCloseIndex);
$beforeCurlyOpening = $tokens->getPrevMeaningfulToken($curlyOpeningIndex);
if ($tokens[$beforeCurlyOpening]->isGivenKind($beforeCurlyOpeningKinds) || $tokens[$beforeCurlyOpening]->equalsAny([';', '{', '}'])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
// check for namespaces and class, interface and trait definitions
if ($tokens[$beforeCurlyOpening]->isGivenKind(T_STRING)) {
$classyTest = $tokens->getPrevMeaningfulToken($beforeCurlyOpening);
while ($tokens[$classyTest]->equals(',') || $tokens[$classyTest]->isGivenKind([T_STRING, T_NS_SEPARATOR, T_EXTENDS, T_IMPLEMENTS])) {
$classyTest = $tokens->getPrevMeaningfulToken($classyTest);
}
$tokensAnalyzer = new TokensAnalyzer($tokens);
if (
$tokens[$classyTest]->isGivenKind(T_NAMESPACE) ||
($tokens[$classyTest]->isClassy() && !$tokensAnalyzer->isAnonymousClass($classyTest))
) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
return;
}
// early return check, below only control structures with conditions are fixed
if (!$tokens[$beforeCurlyOpening]->equals(')')) {
return;
}
$openingBrace = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeCurlyOpening);
$beforeOpeningBrace = $tokens->getPrevMeaningfulToken($openingBrace);
if ($tokens[$beforeOpeningBrace]->isGivenKind([T_IF, T_ELSEIF, T_FOR, T_FOREACH, T_WHILE, T_SWITCH, T_CATCH, T_DECLARE])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
// check for function definition
if ($tokens[$beforeOpeningBrace]->isGivenKind(T_STRING)) {
$beforeString = $tokens->getPrevMeaningfulToken($beforeOpeningBrace);
if ($tokens[$beforeString]->isGivenKind(T_FUNCTION)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index); // implicit return
}
}
} | php | {
"resource": ""
} |
q242064 | CombineConsecutiveUnsetsFixer.getPreviousUnsetCall | validation | private function getPreviousUnsetCall(Tokens $tokens, $index)
{
$previousUnsetSemicolon = $tokens->getPrevMeaningfulToken($index);
if (null === $previousUnsetSemicolon) {
return $index;
}
if (!$tokens[$previousUnsetSemicolon]->equals(';')) {
return $previousUnsetSemicolon;
}
$previousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetSemicolon);
if (null === $previousUnsetBraceEnd) {
return $index;
}
if (!$tokens[$previousUnsetBraceEnd]->equals(')')) {
return $previousUnsetBraceEnd;
}
$previousUnsetBraceStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $previousUnsetBraceEnd);
$previousUnset = $tokens->getPrevMeaningfulToken($previousUnsetBraceStart);
if (null === $previousUnset) {
return $index;
}
if (!$tokens[$previousUnset]->isGivenKind(T_UNSET)) {
return $previousUnset;
}
return [
$previousUnset,
$previousUnsetBraceStart,
$previousUnsetBraceEnd,
$previousUnsetSemicolon,
];
} | php | {
"resource": ""
} |
q242065 | Tag.getName | validation | public function getName()
{
if (null === $this->name) {
Preg::matchAll('/@[a-zA-Z0-9_-]+(?=\s|$)/', $this->line->getContent(), $matches);
if (isset($matches[0][0])) {
$this->name = ltrim($matches[0][0], '@');
} else {
$this->name = 'other';
}
}
return $this->name;
} | php | {
"resource": ""
} |
q242066 | Tag.setName | validation | public function setName($name)
{
$current = $this->getName();
if ('other' === $current) {
throw new \RuntimeException('Cannot set name on unknown tag.');
}
$this->line->setContent(Preg::replace("/@{$current}/", "@{$name}", $this->line->getContent(), 1));
$this->name = $name;
} | php | {
"resource": ""
} |
q242067 | CommentsAnalyzer.isBeforeStructuralElement | validation | public function isBeforeStructuralElement(Tokens $tokens, $index)
{
$token = $tokens[$index];
if (!$token->isGivenKind([T_COMMENT, T_DOC_COMMENT])) {
throw new \InvalidArgumentException('Given index must point to a comment.');
}
$nextIndex = $index;
do {
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
} while (null !== $nextIndex && $tokens[$nextIndex]->equals('('));
if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) {
return false;
}
$nextToken = $tokens[$nextIndex];
if ($this->isStructuralElement($nextToken)) {
return true;
}
if ($this->isValidControl($tokens, $token, $nextIndex)) {
return true;
}
if ($this->isValidVariable($tokens, $nextIndex)) {
return true;
}
if ($this->isValidLanguageConstruct($tokens, $token, $nextIndex)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q242068 | CommentsAnalyzer.getCommentBlockIndices | validation | public function getCommentBlockIndices(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind(T_COMMENT)) {
throw new \InvalidArgumentException('Given index must point to a comment.');
}
$commentType = $this->getCommentType($tokens[$index]->getContent());
$indices = [$index];
if (self::TYPE_SLASH_ASTERISK === $commentType) {
return $indices;
}
$count = \count($tokens);
++$index;
for (; $index < $count; ++$index) {
if ($tokens[$index]->isComment()) {
if ($commentType === $this->getCommentType($tokens[$index]->getContent())) {
$indices[] = $index;
continue;
}
break;
}
if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) {
break;
}
}
return $indices;
} | php | {
"resource": ""
} |
q242069 | CommentsAnalyzer.isValidVariable | validation | private function isValidVariable(Tokens $tokens, $index)
{
if (!$tokens[$index]->isGivenKind(T_VARIABLE)) {
return false;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
return $tokens[$nextIndex]->equals('=');
} | php | {
"resource": ""
} |
q242070 | ExplicitStringVariableFixer.isStringPartToken | validation | private function isStringPartToken(Token $token)
{
return $token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)
|| $token->isGivenKind(T_START_HEREDOC)
|| '"' === $token->getContent()
|| 'b"' === strtolower($token->getContent())
;
} | php | {
"resource": ""
} |
q242071 | Runner.processException | validation | private function processException($name, $e)
{
$this->dispatchEvent(
FixerFileProcessedEvent::NAME,
new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_EXCEPTION)
);
$this->errorsManager->report(new Error(Error::TYPE_EXCEPTION, $name, $e));
} | php | {
"resource": ""
} |
q242072 | NoPhp4ConstructorFixer.fixConstructor | validation | private function fixConstructor(Tokens $tokens, $className, $classStart, $classEnd)
{
$php4 = $this->findFunction($tokens, $className, $classStart, $classEnd);
if (null === $php4) {
// no PHP4-constructor!
return;
}
if (!empty($php4['modifiers'][T_ABSTRACT]) || !empty($php4['modifiers'][T_STATIC])) {
// PHP4 constructor can't be abstract or static
return;
}
$php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd);
if (null === $php5) {
// no PHP5-constructor, we can rename the old one to __construct
$tokens[$php4['nameIndex']] = new Token([T_STRING, '__construct']);
// in some (rare) cases we might have just created an infinite recursion issue
$this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']);
return;
}
// does the PHP4-constructor only call $this->__construct($args, ...)?
list($seq, $case) = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']);
if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) {
// good, delete it!
for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) {
$tokens->clearAt($i);
}
return;
}
// does __construct only call the PHP4-constructor (with the same args)?
list($seq, $case) = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']);
if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) {
// that was a weird choice, but we can safely delete it and...
for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) {
$tokens->clearAt($i);
}
// rename the PHP4 one to __construct
$tokens[$php4['nameIndex']] = new Token([T_STRING, '__construct']);
}
} | php | {
"resource": ""
} |
q242073 | NoPhp4ConstructorFixer.fixParent | validation | private function fixParent(Tokens $tokens, $classStart, $classEnd)
{
// check calls to the parent constructor
foreach ($tokens->findGivenKind(T_EXTENDS) as $index => $token) {
$parentIndex = $tokens->getNextMeaningfulToken($index);
$parentClass = $tokens[$parentIndex]->getContent();
// using parent::ParentClassName() or ParentClassName::ParentClassName()
$parentSeq = $tokens->findSequence([
[T_STRING],
[T_DOUBLE_COLON],
[T_STRING, $parentClass],
'(',
], $classStart, $classEnd, [2 => false]);
if (null !== $parentSeq) {
// we only need indexes
$parentSeq = array_keys($parentSeq);
// match either of the possibilities
if ($tokens[$parentSeq[0]]->equalsAny([[T_STRING, 'parent'], [T_STRING, $parentClass]], false)) {
// replace with parent::__construct
$tokens[$parentSeq[0]] = new Token([T_STRING, 'parent']);
$tokens[$parentSeq[2]] = new Token([T_STRING, '__construct']);
}
}
// using $this->ParentClassName()
$parentSeq = $tokens->findSequence([
[T_VARIABLE, '$this'],
[T_OBJECT_OPERATOR],
[T_STRING, $parentClass],
'(',
], $classStart, $classEnd, [2 => false]);
if (null !== $parentSeq) {
// we only need indexes
$parentSeq = array_keys($parentSeq);
// replace call with parent::__construct()
$tokens[$parentSeq[0]] = new Token([
T_STRING,
'parent',
]);
$tokens[$parentSeq[1]] = new Token([
T_DOUBLE_COLON,
'::',
]);
$tokens[$parentSeq[2]] = new Token([T_STRING, '__construct']);
}
}
} | php | {
"resource": ""
} |
q242074 | NoPhp4ConstructorFixer.findFunction | validation | private function findFunction(Tokens $tokens, $name, $startIndex, $endIndex)
{
$function = $tokens->findSequence([
[T_FUNCTION],
[T_STRING, $name],
'(',
], $startIndex, $endIndex, false);
if (null === $function) {
return null;
}
// keep only the indexes
$function = array_keys($function);
// find previous block, saving method modifiers for later use
$possibleModifiers = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_ABSTRACT, T_FINAL];
$modifiers = [];
$prevBlock = $tokens->getPrevMeaningfulToken($function[0]);
while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) {
$modifiers[$tokens[$prevBlock]->getId()] = $prevBlock;
$prevBlock = $tokens->getPrevMeaningfulToken($prevBlock);
}
if (isset($modifiers[T_ABSTRACT])) {
// abstract methods have no body
$bodyStart = null;
$funcEnd = $tokens->getNextTokenOfKind($function[2], [';']);
} else {
// find method body start and the end of the function definition
$bodyStart = $tokens->getNextTokenOfKind($function[2], ['{']);
$funcEnd = null !== $bodyStart ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStart) : null;
}
return [
'nameIndex' => $function[1],
'startIndex' => $prevBlock + 1,
'endIndex' => $funcEnd,
'bodyIndex' => $bodyStart,
'modifiers' => $modifiers,
];
} | php | {
"resource": ""
} |
q242075 | NoSpacesAfterFunctionNameFixer.getFunctionyTokenKinds | validation | private function getFunctionyTokenKinds()
{
static $tokens = [
T_ARRAY,
T_ECHO,
T_EMPTY,
T_EVAL,
T_EXIT,
T_INCLUDE,
T_INCLUDE_ONCE,
T_ISSET,
T_LIST,
T_PRINT,
T_REQUIRE,
T_REQUIRE_ONCE,
T_UNSET,
T_VARIABLE,
];
return $tokens;
} | php | {
"resource": ""
} |
q242076 | AbstractFunctionReferenceFixer.find | validation | protected function find($functionNameToSearch, Tokens $tokens, $start = 0, $end = null)
{
// make interface consistent with findSequence
$end = null === $end ? $tokens->count() : $end;
// find raw sequence which we can analyse for context
$candidateSequence = [[T_STRING, $functionNameToSearch], '('];
$matches = $tokens->findSequence($candidateSequence, $start, $end, false);
if (null === $matches) {
// not found, simply return without further attempts
return null;
}
// translate results for humans
list($functionName, $openParenthesis) = array_keys($matches);
$functionsAnalyzer = new FunctionsAnalyzer();
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $functionName)) {
return $this->find($functionNameToSearch, $tokens, $openParenthesis, $end);
}
return [$functionName, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)];
} | php | {
"resource": ""
} |
q242077 | Tokens.clearCache | validation | public static function clearCache($key = null)
{
if (null === $key) {
self::$cache = [];
return;
}
if (self::hasCache($key)) {
unset(self::$cache[$key]);
}
} | php | {
"resource": ""
} |
q242078 | Tokens.detectBlockType | validation | public static function detectBlockType(Token $token)
{
foreach (self::getBlockEdgeDefinitions() as $type => $definition) {
if ($token->equals($definition['start'])) {
return ['type' => $type, 'isStart' => true];
}
if ($token->equals($definition['end'])) {
return ['type' => $type, 'isStart' => false];
}
}
} | php | {
"resource": ""
} |
q242079 | Tokens.fromArray | validation | public static function fromArray($array, $saveIndexes = null)
{
$tokens = new self(\count($array));
if (null === $saveIndexes || $saveIndexes) {
foreach ($array as $key => $val) {
$tokens[$key] = $val;
}
} else {
$index = 0;
foreach ($array as $val) {
$tokens[$index++] = $val;
}
}
$tokens->generateCode(); // regenerate code to calculate code hash
return $tokens;
} | php | {
"resource": ""
} |
q242080 | Tokens.fromCode | validation | public static function fromCode($code)
{
$codeHash = self::calculateCodeHash($code);
if (self::hasCache($codeHash)) {
$tokens = self::getCache($codeHash);
// generate the code to recalculate the hash
$tokens->generateCode();
if ($codeHash === $tokens->codeHash) {
$tokens->clearEmptyTokens();
$tokens->clearChanged();
return $tokens;
}
}
$tokens = new self();
$tokens->setCode($code);
$tokens->clearChanged();
return $tokens;
} | php | {
"resource": ""
} |
q242081 | Tokens.setSize | validation | public function setSize($size)
{
if ($this->getSize() !== $size) {
$this->changed = true;
parent::setSize($size);
}
} | php | {
"resource": ""
} |
q242082 | Tokens.offsetUnset | validation | public function offsetUnset($index)
{
$this->changed = true;
$this->unregisterFoundToken($this[$index]);
parent::offsetUnset($index);
} | php | {
"resource": ""
} |
q242083 | Tokens.offsetSet | validation | public function offsetSet($index, $newval)
{
$this->blockEndCache = [];
if (!$this[$index] || !$this[$index]->equals($newval)) {
$this->changed = true;
if (isset($this[$index])) {
$this->unregisterFoundToken($this[$index]);
}
$this->registerFoundToken($newval);
}
parent::offsetSet($index, $newval);
} | php | {
"resource": ""
} |
q242084 | Tokens.clearChanged | validation | public function clearChanged()
{
$this->changed = false;
if (self::isLegacyMode()) {
foreach ($this as $token) {
$token->clearChanged();
}
}
} | php | {
"resource": ""
} |
q242085 | Tokens.clearEmptyTokens | validation | public function clearEmptyTokens()
{
$limit = $this->count();
$index = 0;
for (; $index < $limit; ++$index) {
if ($this->isEmptyAt($index)) {
break;
}
}
// no empty token found, therefore there is no need to override collection
if ($limit === $index) {
return;
}
for ($count = $index; $index < $limit; ++$index) {
if (!$this->isEmptyAt($index)) {
$this[$count++] = $this[$index];
}
}
$this->setSize($count);
} | php | {
"resource": ""
} |
q242086 | Tokens.ensureWhitespaceAtIndex | validation | public function ensureWhitespaceAtIndex($index, $indexOffset, $whitespace)
{
$removeLastCommentLine = static function (self $tokens, $index, $indexOffset, $whitespace) {
$token = $tokens[$index];
if (1 === $indexOffset && $token->isGivenKind(T_OPEN_TAG)) {
if (0 === strpos($whitespace, "\r\n")) {
$tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent())."\r\n"]);
return \strlen($whitespace) > 2 // can be removed on PHP 7; https://php.net/manual/en/function.substr.php
? substr($whitespace, 2)
: ''
;
}
$tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent()).$whitespace[0]]);
return \strlen($whitespace) > 1 // can be removed on PHP 7; https://php.net/manual/en/function.substr.php
? substr($whitespace, 1)
: ''
;
}
return $whitespace;
};
if ($this[$index]->isWhitespace()) {
$whitespace = $removeLastCommentLine($this, $index - 1, $indexOffset, $whitespace);
if ('' === $whitespace) {
$this->clearAt($index);
} else {
$this[$index] = new Token([T_WHITESPACE, $whitespace]);
}
return false;
}
$whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace);
if ('' === $whitespace) {
return false;
}
$this->insertAt(
$index + $indexOffset,
[
new Token([T_WHITESPACE, $whitespace]),
]
);
return true;
} | php | {
"resource": ""
} |
q242087 | Tokens.generatePartialCode | validation | public function generatePartialCode($start, $end)
{
$code = '';
for ($i = $start; $i <= $end; ++$i) {
$code .= $this[$i]->getContent();
}
return $code;
} | php | {
"resource": ""
} |
q242088 | Tokens.getNextTokenOfKind | validation | public function getNextTokenOfKind($index, array $tokens = [], $caseSensitive = true)
{
return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive);
} | php | {
"resource": ""
} |
q242089 | Tokens.getNonWhitespaceSibling | validation | public function getNonWhitespaceSibling($index, $direction, $whitespaces = null)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
$token = $this[$index];
if (!$token->isWhitespace($whitespaces)) {
return $index;
}
}
} | php | {
"resource": ""
} |
q242090 | Tokens.getPrevTokenOfKind | validation | public function getPrevTokenOfKind($index, array $tokens = [], $caseSensitive = true)
{
return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive);
} | php | {
"resource": ""
} |
q242091 | Tokens.getTokenOfKindSibling | validation | public function getTokenOfKindSibling($index, $direction, array $tokens = [], $caseSensitive = true)
{
if (!self::isLegacyMode()) {
$tokens = array_filter($tokens, function ($token) {
return $this->isTokenKindFound($this->extractTokenKind($token));
});
}
if (!\count($tokens)) {
return null;
}
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
$token = $this[$index];
if ($token->equalsAny($tokens, $caseSensitive)) {
return $index;
}
}
} | php | {
"resource": ""
} |
q242092 | Tokens.getTokenNotOfKindSibling | validation | public function getTokenNotOfKindSibling($index, $direction, array $tokens = [])
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
if ($this->isEmptyAt($index)) {
continue;
}
if ($this[$index]->equalsAny($tokens)) {
continue;
}
return $index;
}
} | php | {
"resource": ""
} |
q242093 | Tokens.getMeaningfulTokenSibling | validation | public function getMeaningfulTokenSibling($index, $direction)
{
return $this->getTokenNotOfKindSibling(
$index,
$direction,
[[T_WHITESPACE], [T_COMMENT], [T_DOC_COMMENT]]
);
} | php | {
"resource": ""
} |
q242094 | Tokens.getNonEmptySibling | validation | public function getNonEmptySibling($index, $direction)
{
while (true) {
$index += $direction;
if (!$this->offsetExists($index)) {
return null;
}
if (!$this->isEmptyAt($index)) {
return $index;
}
}
} | php | {
"resource": ""
} |
q242095 | Tokens.findSequence | validation | public function findSequence(array $sequence, $start = 0, $end = null, $caseSensitive = true)
{
$sequenceCount = \count($sequence);
if (0 === $sequenceCount) {
throw new \InvalidArgumentException('Invalid sequence.');
}
// $end defaults to the end of the collection
$end = null === $end ? \count($this) - 1 : min($end, \count($this) - 1);
if ($start + $sequenceCount - 1 > $end) {
return null;
}
// make sure the sequence content is "meaningful"
foreach ($sequence as $key => $token) {
// if not a Token instance already, we convert it to verify the meaningfulness
if (!$token instanceof Token) {
if (\is_array($token) && !isset($token[1])) {
// fake some content as it is required by the Token constructor,
// although optional for search purposes
$token[1] = 'DUMMY';
}
$token = new Token($token);
}
if ($token->isWhitespace() || $token->isComment() || '' === $token->getContent()) {
throw new \InvalidArgumentException(sprintf('Non-meaningful token at position: %s.', $key));
}
}
if (!self::isLegacyMode()) {
foreach ($sequence as $token) {
if (!$this->isTokenKindFound($this->extractTokenKind($token))) {
return null;
}
}
}
// remove the first token from the sequence, so we can freely iterate through the sequence after a match to
// the first one is found
$key = key($sequence);
$firstCs = Token::isKeyCaseSensitive($caseSensitive, $key);
$firstToken = $sequence[$key];
unset($sequence[$key]);
// begin searching for the first token in the sequence (start included)
$index = $start - 1;
while (null !== $index && $index <= $end) {
$index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs);
// ensure we found a match and didn't get past the end index
if (null === $index || $index > $end) {
return null;
}
// initialise the result array with the current index
$result = [$index => $this[$index]];
// advance cursor to the current position
$currIdx = $index;
// iterate through the remaining tokens in the sequence
foreach ($sequence as $key => $token) {
$currIdx = $this->getNextMeaningfulToken($currIdx);
// ensure we didn't go too far
if (null === $currIdx || $currIdx > $end) {
return null;
}
if (!$this[$currIdx]->equals($token, Token::isKeyCaseSensitive($caseSensitive, $key))) {
// not a match, restart the outer loop
continue 2;
}
// append index to the result array
$result[$currIdx] = $this[$currIdx];
}
// do we have a complete match?
// hint: $result is bigger than $sequence since the first token has been removed from the latter
if (\count($sequence) < \count($result)) {
return $result;
}
}
} | php | {
"resource": ""
} |
q242096 | Tokens.insertAt | validation | public function insertAt($index, $items)
{
$items = \is_array($items) || $items instanceof self ? $items : [$items];
$itemsCnt = \count($items);
if (0 === $itemsCnt) {
return;
}
$oldSize = \count($this);
$this->changed = true;
$this->blockEndCache = [];
$this->setSize($oldSize + $itemsCnt);
// since we only move already existing items around, we directly call into SplFixedArray::offset* methods.
// that way we get around additional overhead this class adds with overridden offset* methods.
for ($i = $oldSize + $itemsCnt - 1; $i >= $index; --$i) {
$oldItem = parent::offsetExists($i - $itemsCnt) ? parent::offsetGet($i - $itemsCnt) : new Token('');
parent::offsetSet($i, $oldItem);
}
for ($i = 0; $i < $itemsCnt; ++$i) {
if ('' === $items[$i]->getContent()) {
throw new \InvalidArgumentException('Must not add empty token to collection.');
}
$this->registerFoundToken($items[$i]);
parent::offsetSet($i + $index, $items[$i]);
}
} | php | {
"resource": ""
} |
q242097 | Tokens.overrideAt | validation | public function overrideAt($index, $token)
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0, use offsetSet instead.', E_USER_DEPRECATED);
self::$isLegacyMode = true;
$this[$index]->override($token);
$this->registerFoundToken($token);
} | php | {
"resource": ""
} |
q242098 | Tokens.overrideRange | validation | public function overrideRange($indexStart, $indexEnd, $items)
{
$oldCode = $this->generatePartialCode($indexStart, $indexEnd);
$newCode = '';
foreach ($items as $item) {
$newCode .= $item->getContent();
}
// no changes, return
if ($oldCode === $newCode) {
return;
}
$indexToChange = $indexEnd - $indexStart + 1;
$itemsCount = \count($items);
// If we want to add more items than passed range contains we need to
// add placeholders for overhead items.
if ($itemsCount > $indexToChange) {
$placeholders = [];
while ($itemsCount > $indexToChange) {
$placeholders[] = new Token('__PLACEHOLDER__');
++$indexToChange;
}
$this->insertAt($indexEnd + 1, $placeholders);
}
// Override each items.
foreach ($items as $itemIndex => $item) {
$this[$indexStart + $itemIndex] = $item;
}
// If we want to add less tokens than passed range contains then clear
// not needed tokens.
if ($itemsCount < $indexToChange) {
$this->clearRange($indexStart + $itemsCount, $indexEnd);
}
} | php | {
"resource": ""
} |
q242099 | Tokens.setCode | validation | public function setCode($code)
{
// No need to work when the code is the same.
// That is how we avoid a lot of work and setting changed flag.
if ($code === $this->generateCode()) {
return;
}
// clear memory
$this->setSize(0);
$tokens = \defined('TOKEN_PARSE')
? token_get_all($code, TOKEN_PARSE)
: token_get_all($code);
$this->setSize(\count($tokens));
foreach ($tokens as $index => $token) {
$this[$index] = new Token($token);
}
$transformers = Transformers::create();
$transformers->transform($this);
$this->foundTokenKinds = [];
foreach ($this as $token) {
$this->registerFoundToken($token);
}
$this->rewind();
$this->changeCodeHash(self::calculateCodeHash($code));
$this->changed = true;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.