_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q242100 | Tokens.isAllTokenKindsFound | validation | public function isAllTokenKindsFound(array $tokenKinds)
{
foreach ($tokenKinds as $tokenKind) {
if (empty($this->foundTokenKinds[$tokenKind])) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q242101 | Tokens.clearRange | validation | public function clearRange($indexStart, $indexEnd)
{
for ($i = $indexStart; $i <= $indexEnd; ++$i) {
$this->clearAt($i);
}
} | php | {
"resource": ""
} |
q242102 | Tokens.isMonolithicPhp | validation | public function isMonolithicPhp()
{
$size = $this->count();
if (0 === $size) {
return false;
}
if (self::isLegacyMode()) {
// If code is not monolithic there is a great chance that first or last token is `T_INLINE_HTML`:
if ($this[0]->isGivenKind(T_INLINE_HTML) || $this[$size - 1]->isGivenKind(T_INLINE_HTML)) {
return false;
}
for ($index = 1; $index < $size; ++$index) {
if ($this[$index]->isGivenKind([T_INLINE_HTML, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO])) {
return false;
}
}
return true;
}
if ($this->isTokenKindFound(T_INLINE_HTML)) {
return false;
}
return 1 >= ($this->countTokenKind(T_OPEN_TAG) + $this->countTokenKind(T_OPEN_TAG_WITH_ECHO));
} | php | {
"resource": ""
} |
q242103 | Tokens.getCache | validation | private static function getCache($key)
{
if (!self::hasCache($key)) {
throw new \OutOfBoundsException(sprintf('Unknown cache key: "%s".', $key));
}
return self::$cache[$key];
} | php | {
"resource": ""
} |
q242104 | Tokens.changeCodeHash | validation | private function changeCodeHash($codeHash)
{
if (null !== $this->codeHash) {
self::clearCache($this->codeHash);
}
$this->codeHash = $codeHash;
self::setCache($this->codeHash, $this);
} | php | {
"resource": ""
} |
q242105 | Tokens.registerFoundToken | validation | private function registerFoundToken($token)
{
// inlined extractTokenKind() call on the hot path
$tokenKind = $token instanceof Token
? ($token->isArray() ? $token->getId() : $token->getContent())
: (\is_array($token) ? $token[0] : $token)
;
if (!isset($this->foundTokenKinds[$tokenKind])) {
$this->foundTokenKinds[$tokenKind] = 0;
}
++$this->foundTokenKinds[$tokenKind];
} | php | {
"resource": ""
} |
q242106 | NoWhitespaceBeforeCommaInArrayFixer.skipNonArrayElements | validation | private function skipNonArrayElements($index, Tokens $tokens)
{
if ($tokens[$index]->equals('}')) {
return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
}
if ($tokens[$index]->equals(')')) {
$startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$startIndex = $tokens->getPrevMeaningfulToken($startIndex);
if (!$tokens[$startIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
return $startIndex;
}
}
return $index;
} | php | {
"resource": ""
} |
q242107 | Token.isType | validation | public function isType($types)
{
if (!\is_array($types)) {
$types = [$types];
}
return \in_array($this->getType(), $types, true);
} | php | {
"resource": ""
} |
q242108 | AbstractNoUselessElseFixer.getPreviousBlock | validation | private function getPreviousBlock(Tokens $tokens, $index)
{
$close = $previous = $tokens->getPrevMeaningfulToken($index);
// short 'if' detection
if ($tokens[$close]->equals('}')) {
$previous = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $close);
}
$open = $tokens->getPrevTokenOfKind($previous, [[T_IF], [T_ELSE], [T_ELSEIF]]);
if ($tokens[$open]->isGivenKind(T_IF)) {
$elseCandidate = $tokens->getPrevMeaningfulToken($open);
if ($tokens[$elseCandidate]->isGivenKind(T_ELSE)) {
$open = $elseCandidate;
}
}
return [$open, $close];
} | php | {
"resource": ""
} |
q242109 | AbstractNoUselessElseFixer.isInConditionWithoutBraces | validation | private function isInConditionWithoutBraces(Tokens $tokens, $index, $lowerLimitIndex)
{
do {
if ($tokens[$index]->isComment() || $tokens[$index]->isWhitespace()) {
$index = $tokens->getPrevMeaningfulToken($index);
}
$token = $tokens[$index];
if ($token->isGivenKind([T_IF, T_ELSEIF, T_ELSE])) {
return true;
}
if ($token->equals(';', '}')) {
return false;
}
if ($token->equals('{')) {
$index = $tokens->getPrevMeaningfulToken($index);
// OK if belongs to: for, do, while, foreach
// Not OK if belongs to: if, else, elseif
if ($tokens[$index]->isGivenKind(T_DO)) {
--$index;
continue;
}
if (!$tokens[$index]->equals(')')) {
return false; // like `else {`
}
$index = $tokens->findBlockStart(
Tokens::BLOCK_TYPE_PARENTHESIS_BRACE,
$index
);
$index = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$index]->isGivenKind([T_IF, T_ELSEIF])) {
return false;
}
} elseif ($token->equals(')')) {
$type = Tokens::detectBlockType($token);
$index = $tokens->findBlockStart(
$type['type'],
$index
);
$index = $tokens->getPrevMeaningfulToken($index);
} else {
--$index;
}
} while ($index > $lowerLimitIndex);
return false;
} | php | {
"resource": ""
} |
q242110 | ProcessLinter.createProcessForSource | validation | private function createProcessForSource($source)
{
if (null === $this->temporaryFile) {
$this->temporaryFile = tempnam('.', 'cs_fixer_tmp_');
$this->fileRemoval->observe($this->temporaryFile);
}
if (false === @file_put_contents($this->temporaryFile, $source)) {
throw new IOException(sprintf('Failed to write file "%s".', $this->temporaryFile), 0, null, $this->temporaryFile);
}
return $this->createProcessForFile($this->temporaryFile);
} | php | {
"resource": ""
} |
q242111 | ListSyntaxFixer.configure | validation | public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN : T_LIST;
} | php | {
"resource": ""
} |
q242112 | HelpCommand.getDisplayableAllowedValues | validation | public static function getDisplayableAllowedValues(FixerOptionInterface $option)
{
$allowed = $option->getAllowedValues();
if (null !== $allowed) {
$allowed = array_filter($allowed, static function ($value) {
return !($value instanceof \Closure);
});
usort($allowed, static function ($valueA, $valueB) {
if ($valueA instanceof AllowedValueSubset) {
return -1;
}
if ($valueB instanceof AllowedValueSubset) {
return 1;
}
return strcasecmp(
self::toString($valueA),
self::toString($valueB)
);
});
if (0 === \count($allowed)) {
$allowed = null;
}
}
return $allowed;
} | php | {
"resource": ""
} |
q242113 | HelpCommand.wordwrap | validation | private static function wordwrap($string, $width)
{
$result = [];
$currentLine = 0;
$lineLength = 0;
foreach (explode(' ', $string) as $word) {
$wordLength = \strlen(Preg::replace('~</?(\w+)>~', '', $word));
if (0 !== $lineLength) {
++$wordLength; // space before word
}
if ($lineLength + $wordLength > $width) {
++$currentLine;
$lineLength = 0;
}
$result[$currentLine][] = $word;
$lineLength += $wordLength;
}
return array_map(static function ($line) {
return implode(' ', $line);
}, $result);
} | php | {
"resource": ""
} |
q242114 | DocBlock.getAnnotations | validation | public function getAnnotations()
{
if (null === $this->annotations) {
$this->annotations = [];
$total = \count($this->lines);
for ($index = 0; $index < $total; ++$index) {
if ($this->lines[$index]->containsATag()) {
// get all the lines that make up the annotation
$lines = \array_slice($this->lines, $index, $this->findAnnotationLength($index), true);
$annotation = new Annotation($lines);
// move the index to the end of the annotation to avoid
// checking it again because we know the lines inside the
// current annotation cannot be part of another annotation
$index = $annotation->getEnd();
// add the current annotation to the list of annotations
$this->annotations[] = $annotation;
}
}
}
return $this->annotations;
} | php | {
"resource": ""
} |
q242115 | DocBlock.getAnnotationsOfType | validation | public function getAnnotationsOfType($types)
{
$annotations = [];
$types = (array) $types;
foreach ($this->getAnnotations() as $annotation) {
$tag = $annotation->getTag()->getName();
foreach ($types as $type) {
if ($type === $tag) {
$annotations[] = $annotation;
}
}
}
return $annotations;
} | php | {
"resource": ""
} |
q242116 | HeredocToNowdocFixer.convertToNowdoc | validation | private function convertToNowdoc(Token $token)
{
return new Token([
$token->getId(),
Preg::replace('/^([Bb]?<<<)([ \t]*)"?([^\s"]+)"?/', '$1$2\'$3\'', $token->getContent()),
]);
} | php | {
"resource": ""
} |
q242117 | BracesFixer.isCommentWithFixableIndentation | validation | private function isCommentWithFixableIndentation(Tokens $tokens, $index)
{
if (!$tokens[$index]->isComment()) {
return false;
}
if (0 === strpos($tokens[$index]->getContent(), '/*')) {
return true;
}
$firstCommentIndex = $index;
while (true) {
$i = $this->getSiblingContinuousSingleLineComment($tokens, $firstCommentIndex, false);
if (null === $i) {
break;
}
$firstCommentIndex = $i;
}
$lastCommentIndex = $index;
while (true) {
$i = $this->getSiblingContinuousSingleLineComment($tokens, $lastCommentIndex, true);
if (null === $i) {
break;
}
$lastCommentIndex = $i;
}
if ($firstCommentIndex === $lastCommentIndex) {
return true;
}
for ($i = $firstCommentIndex + 1; $i < $lastCommentIndex; ++$i) {
if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isComment()) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q242118 | ProtectedToPrivateFixer.skipClass | validation | private function skipClass(Tokens $tokens, $classIndex, $classOpenIndex, $classCloseIndex)
{
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($classIndex)];
if (!$prevToken->isGivenKind(T_FINAL)) {
return true;
}
for ($index = $classIndex; $index < $classOpenIndex; ++$index) {
if ($tokens[$index]->isGivenKind(T_EXTENDS)) {
return true;
}
}
$useIndex = $tokens->getNextTokenOfKind($classIndex, [[CT::T_USE_TRAIT]]);
return $useIndex && $useIndex < $classCloseIndex;
} | php | {
"resource": ""
} |
q242119 | FixerFactory.useRuleSet | validation | public function useRuleSet(RuleSetInterface $ruleSet)
{
$fixers = [];
$fixersByName = [];
$fixerConflicts = [];
$fixerNames = array_keys($ruleSet->getRules());
foreach ($fixerNames as $name) {
if (!\array_key_exists($name, $this->fixersByName)) {
throw new \UnexpectedValueException(sprintf('Rule "%s" does not exist.', $name));
}
$fixer = $this->fixersByName[$name];
$config = $ruleSet->getRuleConfiguration($name);
if (null !== $config) {
if ($fixer instanceof ConfigurableFixerInterface) {
if (!\is_array($config) || !\count($config)) {
throw new InvalidFixerConfigurationException($fixer->getName(), 'Configuration must be an array and may not be empty.');
}
$fixer->configure($config);
} else {
throw new InvalidFixerConfigurationException($fixer->getName(), 'Is not configurable.');
}
}
$fixers[] = $fixer;
$fixersByName[$name] = $fixer;
$conflicts = array_intersect($this->getFixersConflicts($fixer), $fixerNames);
if (\count($conflicts) > 0) {
$fixerConflicts[$name] = $conflicts;
}
}
if (\count($fixerConflicts) > 0) {
throw new \UnexpectedValueException($this->generateConflictMessage($fixerConflicts));
}
$this->fixers = $fixers;
$this->fixersByName = $fixersByName;
return $this;
} | php | {
"resource": ""
} |
q242120 | RuleSet.resolveSet | validation | private function resolveSet()
{
$rules = $this->set;
$resolvedRules = [];
// expand sets
foreach ($rules as $name => $value) {
if ('@' === $name[0]) {
if (!\is_bool($value)) {
throw new \UnexpectedValueException(sprintf('Nested rule set "%s" configuration must be a boolean.', $name));
}
$set = $this->resolveSubset($name, $value);
$resolvedRules = array_merge($resolvedRules, $set);
} else {
$resolvedRules[$name] = $value;
}
}
// filter out all resolvedRules that are off
$resolvedRules = array_filter($resolvedRules);
$this->rules = $resolvedRules;
return $this;
} | php | {
"resource": ""
} |
q242121 | RuleSet.resolveSubset | validation | private function resolveSubset($setName, $setValue)
{
$rules = $this->getSetDefinition($setName);
foreach ($rules as $name => $value) {
if ('@' === $name[0]) {
$set = $this->resolveSubset($name, $setValue);
unset($rules[$name]);
$rules = array_merge($rules, $set);
} elseif (!$setValue) {
$rules[$name] = false;
} else {
$rules[$name] = $value;
}
}
return $rules;
} | php | {
"resource": ""
} |
q242122 | AbstractPhpdocTypesFixer.fixTypes | validation | private function fixTypes(Annotation $annotation)
{
$types = $annotation->getTypes();
$new = $this->normalizeTypes($types);
if ($types !== $new) {
$annotation->setTypes($new);
}
} | php | {
"resource": ""
} |
q242123 | AbstractPhpdocTypesFixer.normalizeType | validation | private function normalizeType($type)
{
if ('[]' === substr($type, -2)) {
return $this->normalize(substr($type, 0, -2)).'[]';
}
return $this->normalize($type);
} | php | {
"resource": ""
} |
q242124 | UseTransformer.isUseForLambda | validation | private function isUseForLambda(Tokens $tokens, $index)
{
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
// test `function () use ($foo) {}` case
return $nextToken->equals('(');
} | php | {
"resource": ""
} |
q242125 | EregToPregFixer.getBestDelimiter | validation | private function getBestDelimiter($pattern)
{
// try do find something that's not used
$delimiters = [];
foreach (self::$delimiters as $k => $d) {
if (false === strpos($pattern, $d)) {
return $d;
}
$delimiters[$d] = [substr_count($pattern, $d), $k];
}
// return the least used delimiter, using the position in the list as a tie breaker
uasort($delimiters, static function ($a, $b) {
if ($a[0] === $b[0]) {
return Utils::cmpInt($a, $b);
}
return $a[0] < $b[0] ? -1 : 1;
});
return key($delimiters);
} | php | {
"resource": ""
} |
q242126 | CT.getName | validation | public static function getName($value)
{
if (!self::has($value)) {
throw new \InvalidArgumentException(sprintf('No custom token was found for "%s".', $value));
}
$tokens = self::getMapById();
return 'CT::'.$tokens[$value];
} | php | {
"resource": ""
} |
q242127 | SimplifiedNullReturnFixer.clear | validation | private function clear(Tokens $tokens, $index)
{
while (!$tokens[++$index]->equals(';')) {
if ($this->shouldClearToken($tokens, $index)) {
$tokens->clearAt($index);
}
}
} | php | {
"resource": ""
} |
q242128 | SimplifiedNullReturnFixer.needFixing | validation | private function needFixing(Tokens $tokens, $index)
{
if ($this->isStrictOrNullableReturnTypeFunction($tokens, $index)) {
return false;
}
$content = '';
while (!$tokens[$index]->equals(';')) {
$index = $tokens->getNextMeaningfulToken($index);
$content .= $tokens[$index]->getContent();
}
$content = ltrim($content, '(');
$content = rtrim($content, ');');
return 'null' === strtolower($content);
} | php | {
"resource": ""
} |
q242129 | SimplifiedNullReturnFixer.isStrictOrNullableReturnTypeFunction | validation | private function isStrictOrNullableReturnTypeFunction(Tokens $tokens, $returnIndex)
{
$functionIndex = $returnIndex;
do {
$functionIndex = $tokens->getPrevTokenOfKind($functionIndex, [[T_FUNCTION]]);
if (null === $functionIndex) {
return false;
}
$openingCurlyBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['{']);
$closingCurlyBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingCurlyBraceIndex);
} while ($closingCurlyBraceIndex < $returnIndex);
$possibleVoidIndex = $tokens->getPrevMeaningfulToken($openingCurlyBraceIndex);
$isStrictReturnType = $tokens[$possibleVoidIndex]->isGivenKind(T_STRING) && 'void' !== $tokens[$possibleVoidIndex]->getContent();
$nullableTypeIndex = $tokens->getNextTokenOfKind($functionIndex, [[CT::T_NULLABLE_TYPE]]);
$isNullableReturnType = null !== $nullableTypeIndex && $nullableTypeIndex < $openingCurlyBraceIndex;
return $isStrictReturnType || $isNullableReturnType;
} | php | {
"resource": ""
} |
q242130 | SimplifiedNullReturnFixer.shouldClearToken | validation | private function shouldClearToken(Tokens $tokens, $index)
{
$token = $tokens[$index];
return !$token->isComment() && !($token->isWhitespace() && $tokens[$index + 1]->isComment());
} | php | {
"resource": ""
} |
q242131 | Annotation.getTypes | validation | public function getTypes()
{
if (null === $this->types) {
$this->types = [];
$content = $this->getTypesContent();
while ('' !== $content && false !== $content) {
Preg::match(
'{^'.self::REGEX_TYPES.'$}x',
$content,
$matches
);
$this->types[] = $matches['type'];
$content = substr($content, \strlen($matches['type']) + 1);
}
}
return $this->types;
} | php | {
"resource": ""
} |
q242132 | Annotation.setTypes | validation | public function setTypes(array $types)
{
$pattern = '/'.preg_quote($this->getTypesContent(), '/').'/';
$this->lines[0]->setContent(Preg::replace($pattern, implode('|', $types), $this->lines[0]->getContent(), 1));
$this->clearCache();
} | php | {
"resource": ""
} |
q242133 | Annotation.getNormalizedTypes | validation | public function getNormalizedTypes()
{
$normalized = array_map(static function ($type) {
return strtolower($type);
}, $this->getTypes());
sort($normalized);
return $normalized;
} | php | {
"resource": ""
} |
q242134 | Annotation.getTypesContent | validation | private function getTypesContent()
{
if (null === $this->typesContent) {
$name = $this->getTag()->getName();
if (!$this->supportTypes()) {
throw new \RuntimeException('This tag does not support types.');
}
$matchingResult = Preg::match(
'{^(?:\s*\*|/\*\*)\s*@'.$name.'\s+'.self::REGEX_TYPES.'(?:[ \t].*)?$}sx',
$this->lines[0]->getContent(),
$matches
);
$this->typesContent = 1 === $matchingResult
? $matches['types']
: '';
}
return $this->typesContent;
} | php | {
"resource": ""
} |
q242135 | ArgumentsAnalyzer.getArguments | validation | public function getArguments(Tokens $tokens, $openParenthesis, $closeParenthesis)
{
$arguments = [];
$firstSensibleToken = $tokens->getNextMeaningfulToken($openParenthesis);
if ($tokens[$firstSensibleToken]->equals(')')) {
return $arguments;
}
$paramContentIndex = $openParenthesis + 1;
$argumentsStart = $paramContentIndex;
for (; $paramContentIndex < $closeParenthesis; ++$paramContentIndex) {
$token = $tokens[$paramContentIndex];
// skip nested (), [], {} constructs
$blockDefinitionProbe = Tokens::detectBlockType($token);
if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) {
$paramContentIndex = $tokens->findBlockEnd($blockDefinitionProbe['type'], $paramContentIndex);
continue;
}
// if comma matched, increase arguments counter
if ($token->equals(',')) {
if ($tokens->getNextMeaningfulToken($paramContentIndex) === $closeParenthesis) {
break; // trailing ',' in function call (PHP 7.3)
}
$arguments[$argumentsStart] = $paramContentIndex - 1;
$argumentsStart = $paramContentIndex + 1;
}
}
$arguments[$argumentsStart] = $paramContentIndex - 1;
return $arguments;
} | php | {
"resource": ""
} |
q242136 | YodaStyleFixer.findComparisonEnd | validation | private function findComparisonEnd(Tokens $tokens, $index)
{
++$index;
$count = \count($tokens);
while ($index < $count) {
$token = $tokens[$index];
if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
++$index;
continue;
}
if ($this->isOfLowerPrecedence($token)) {
break;
}
$block = Tokens::detectBlockType($token);
if (null === $block) {
++$index;
continue;
}
if (!$block['isStart']) {
break;
}
$index = $tokens->findBlockEnd($block['type'], $index) + 1;
}
$prev = $tokens->getPrevMeaningfulToken($index);
return $tokens[$prev]->isGivenKind(T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev;
} | php | {
"resource": ""
} |
q242137 | YodaStyleFixer.findComparisonStart | validation | private function findComparisonStart(Tokens $tokens, $index)
{
--$index;
$nonBlockFound = false;
while (0 <= $index) {
$token = $tokens[$index];
if ($token->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
--$index;
continue;
}
if ($this->isOfLowerPrecedence($token)) {
break;
}
$block = Tokens::detectBlockType($token);
if (null === $block) {
--$index;
$nonBlockFound = true;
continue;
}
if (
$block['isStart']
|| ($nonBlockFound && Tokens::BLOCK_TYPE_CURLY_BRACE === $block['type']) // closing of structure not related to the comparison
) {
break;
}
$index = $tokens->findBlockStart($block['type'], $index) - 1;
}
return $tokens->getNextMeaningfulToken($index);
} | php | {
"resource": ""
} |
q242138 | YodaStyleFixer.fixTokensCompare | validation | private function fixTokensCompare(
Tokens $tokens,
$startLeft,
$endLeft,
$compareOperatorIndex,
$startRight,
$endRight
) {
$type = $tokens[$compareOperatorIndex]->getId();
$content = $tokens[$compareOperatorIndex]->getContent();
if (\array_key_exists($type, $this->candidatesMap)) {
$tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type];
} elseif (\array_key_exists($content, $this->candidatesMap)) {
$tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content];
}
$right = $this->fixTokensComparePart($tokens, $startRight, $endRight);
$left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft);
for ($i = $startRight; $i <= $endRight; ++$i) {
$tokens->clearAt($i);
}
for ($i = $startLeft; $i <= $endLeft; ++$i) {
$tokens->clearAt($i);
}
$tokens->insertAt($startRight, $left);
$tokens->insertAt($startLeft, $right);
return $startLeft;
} | php | {
"resource": ""
} |
q242139 | YodaStyleFixer.isOfLowerPrecedence | validation | private function isOfLowerPrecedence(Token $token)
{
static $tokens;
if (null === $tokens) {
$tokens = [
T_AND_EQUAL, // &=
T_BOOLEAN_AND, // &&
T_BOOLEAN_OR, // ||
T_CASE, // case
T_CONCAT_EQUAL, // .=
T_DIV_EQUAL, // /=
T_DOUBLE_ARROW, // =>
T_GOTO, // goto
T_LOGICAL_AND, // and
T_LOGICAL_OR, // or
T_LOGICAL_XOR, // xor
T_MINUS_EQUAL, // -=
T_MUL_EQUAL, // *=
T_OR_EQUAL, // |=
T_PLUS_EQUAL, // +=
T_RETURN, // return
T_SL_EQUAL, // <<
T_SR_EQUAL, // >>=
T_THROW, // throw
T_XOR_EQUAL, // ^=
T_ECHO,
T_PRINT,
T_OPEN_TAG,
T_OPEN_TAG_WITH_ECHO,
];
if (\defined('T_POW_EQUAL')) {
$tokens[] = T_POW_EQUAL; // **=
}
if (\defined('T_COALESCE')) {
$tokens[] = T_COALESCE; // ??
}
}
static $otherTokens = [
// bitwise and, or, xor
'&', '|', '^',
// ternary operators
'?', ':',
// assignment
'=',
// end of PHP statement
',', ';',
];
return $token->isGivenKind($tokens) || $token->equalsAny($otherTokens);
} | php | {
"resource": ""
} |
q242140 | TokensAnalyzer.getImportUseIndexes | validation | public function getImportUseIndexes($perNamespace = false)
{
$tokens = $this->tokens;
$tokens->rewind();
$uses = [];
$namespaceIndex = 0;
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(T_NAMESPACE)) {
$nextTokenIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
$nextToken = $tokens[$nextTokenIndex];
if ($nextToken->equals('{')) {
$index = $nextTokenIndex;
}
if ($perNamespace) {
++$namespaceIndex;
}
continue;
}
if ($token->isGivenKind(T_USE)) {
$uses[$namespaceIndex][] = $index;
}
}
if (!$perNamespace && isset($uses[$namespaceIndex])) {
return $uses[$namespaceIndex];
}
return $uses;
} | php | {
"resource": ""
} |
q242141 | TokensAnalyzer.isArrayMultiLine | validation | public function isArrayMultiLine($index)
{
if (!$this->isArray($index)) {
throw new \InvalidArgumentException(sprintf('Not an array at given index %d.', $index));
}
$tokens = $this->tokens;
// Skip only when its an array, for short arrays we need the brace for correct
// level counting
if ($tokens[$index]->isGivenKind(T_ARRAY)) {
$index = $tokens->getNextMeaningfulToken($index);
}
$endIndex = $tokens[$index]->equals('(')
? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index)
: $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index)
;
for (++$index; $index < $endIndex; ++$index) {
$token = $tokens[$index];
$blockType = Tokens::detectBlockType($token);
if ($blockType && $blockType['isStart']) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
continue;
}
if (
$token->isWhitespace() &&
!$tokens[$index - 1]->isGivenKind(T_END_HEREDOC) &&
false !== strpos($token->getContent(), "\n")
) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q242142 | TokensAnalyzer.getMethodAttributes | validation | public function getMethodAttributes($index)
{
$tokens = $this->tokens;
$token = $tokens[$index];
if (!$token->isGivenKind(T_FUNCTION)) {
throw new \LogicException(sprintf('No T_FUNCTION at given index %d, got %s.', $index, $token->getName()));
}
$attributes = [
'visibility' => null,
'static' => false,
'abstract' => false,
'final' => false,
];
for ($i = $index; $i >= 0; --$i) {
$tokenIndex = $tokens->getPrevMeaningfulToken($i);
$i = $tokenIndex;
$token = $tokens[$tokenIndex];
if ($token->isGivenKind(T_STATIC)) {
$attributes['static'] = true;
continue;
}
if ($token->isGivenKind(T_FINAL)) {
$attributes['final'] = true;
continue;
}
if ($token->isGivenKind(T_ABSTRACT)) {
$attributes['abstract'] = true;
continue;
}
// visibility
if ($token->isGivenKind(T_PRIVATE)) {
$attributes['visibility'] = T_PRIVATE;
continue;
}
if ($token->isGivenKind(T_PROTECTED)) {
$attributes['visibility'] = T_PROTECTED;
continue;
}
if ($token->isGivenKind(T_PUBLIC)) {
$attributes['visibility'] = T_PUBLIC;
continue;
}
// found a meaningful token that is not part of
// the function signature; stop looking
break;
}
return $attributes;
} | php | {
"resource": ""
} |
q242143 | TokensAnalyzer.isAnonymousClass | validation | public function isAnonymousClass($index)
{
$tokens = $this->tokens;
$token = $tokens[$index];
if (!$token->isClassy()) {
throw new \LogicException(sprintf('No classy token at given index %d.', $index));
}
if (!$token->isGivenKind(T_CLASS)) {
return false;
}
return $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW);
} | php | {
"resource": ""
} |
q242144 | TokensAnalyzer.isLambda | validation | public function isLambda($index)
{
if (!$this->tokens[$index]->isGivenKind(T_FUNCTION)) {
throw new \LogicException(sprintf('No T_FUNCTION at given index %d, got %s.', $index, $this->tokens[$index]->getName()));
}
$startParenthesisIndex = $this->tokens->getNextMeaningfulToken($index);
$startParenthesisToken = $this->tokens[$startParenthesisIndex];
// skip & for `function & () {}` syntax
if ($startParenthesisToken->isGivenKind(CT::T_RETURN_REF)) {
$startParenthesisIndex = $this->tokens->getNextMeaningfulToken($startParenthesisIndex);
$startParenthesisToken = $this->tokens[$startParenthesisIndex];
}
return $startParenthesisToken->equals('(');
} | php | {
"resource": ""
} |
q242145 | TokensAnalyzer.isUnarySuccessorOperator | validation | public function isUnarySuccessorOperator($index)
{
static $allowedPrevToken = [
']',
[T_STRING],
[T_VARIABLE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
];
$tokens = $this->tokens;
$token = $tokens[$index];
if (!$token->isGivenKind([T_INC, T_DEC])) {
return false;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
return $prevToken->equalsAny($allowedPrevToken);
} | php | {
"resource": ""
} |
q242146 | TokensAnalyzer.isUnaryPredecessorOperator | validation | public function isUnaryPredecessorOperator($index)
{
static $potentialSuccessorOperator = [T_INC, T_DEC];
static $potentialBinaryOperator = ['+', '-', '&', [CT::T_RETURN_REF]];
static $otherOperators;
if (null === $otherOperators) {
$otherOperators = ['!', '~', '@', [T_ELLIPSIS]];
}
static $disallowedPrevTokens;
if (null === $disallowedPrevTokens) {
$disallowedPrevTokens = [
']',
'}',
')',
'"',
'`',
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[T_CLASS_C],
[T_CONSTANT_ENCAPSED_STRING],
[T_DEC],
[T_DIR],
[T_DNUMBER],
[T_FILE],
[T_FUNC_C],
[T_INC],
[T_LINE],
[T_LNUMBER],
[T_METHOD_C],
[T_NS_C],
[T_STRING],
[T_TRAIT_C],
[T_VARIABLE],
];
}
$tokens = $this->tokens;
$token = $tokens[$index];
if ($token->isGivenKind($potentialSuccessorOperator)) {
return !$this->isUnarySuccessorOperator($index);
}
if ($token->equalsAny($otherOperators)) {
return true;
}
if (!$token->equalsAny($potentialBinaryOperator)) {
return false;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if (!$prevToken->equalsAny($disallowedPrevTokens)) {
return true;
}
if (!$token->equals('&') || !$prevToken->isGivenKind(T_STRING)) {
return false;
}
static $searchTokens = [
';',
'{',
'}',
[T_FUNCTION],
[T_OPEN_TAG],
[T_OPEN_TAG_WITH_ECHO],
];
$prevToken = $tokens[$tokens->getPrevTokenOfKind($index, $searchTokens)];
return $prevToken->isGivenKind(T_FUNCTION);
} | php | {
"resource": ""
} |
q242147 | TokensAnalyzer.isBinaryOperator | validation | public function isBinaryOperator($index)
{
static $nonArrayOperators = [
'=' => true,
'*' => true,
'/' => true,
'%' => true,
'<' => true,
'>' => true,
'|' => true,
'^' => true,
'.' => true,
];
static $potentialUnaryNonArrayOperators = [
'+' => true,
'-' => true,
'&' => true,
];
static $arrayOperators;
if (null === $arrayOperators) {
$arrayOperators = [
T_AND_EQUAL => true, // &=
T_BOOLEAN_AND => true, // &&
T_BOOLEAN_OR => true, // ||
T_CONCAT_EQUAL => true, // .=
T_DIV_EQUAL => true, // /=
T_DOUBLE_ARROW => true, // =>
T_IS_EQUAL => true, // ==
T_IS_GREATER_OR_EQUAL => true, // >=
T_IS_IDENTICAL => true, // ===
T_IS_NOT_EQUAL => true, // !=, <>
T_IS_NOT_IDENTICAL => true, // !==
T_IS_SMALLER_OR_EQUAL => true, // <=
T_LOGICAL_AND => true, // and
T_LOGICAL_OR => true, // or
T_LOGICAL_XOR => true, // xor
T_MINUS_EQUAL => true, // -=
T_MOD_EQUAL => true, // %=
T_MUL_EQUAL => true, // *=
T_OR_EQUAL => true, // |=
T_PLUS_EQUAL => true, // +=
T_POW => true, // **
T_POW_EQUAL => true, // **=
T_SL => true, // <<
T_SL_EQUAL => true, // <<=
T_SR => true, // >>
T_SR_EQUAL => true, // >>=
T_XOR_EQUAL => true, // ^=
CT::T_TYPE_ALTERNATION => true, // |
];
if (\defined('T_SPACESHIP')) {
$arrayOperators[T_SPACESHIP] = true; // <=>
}
if (\defined('T_COALESCE')) {
$arrayOperators[T_COALESCE] = true; // ??
}
}
$tokens = $this->tokens;
$token = $tokens[$index];
if ($token->isArray()) {
return isset($arrayOperators[$token->getId()]);
}
if (isset($nonArrayOperators[$token->getContent()])) {
return true;
}
if (isset($potentialUnaryNonArrayOperators[$token->getContent()])) {
return !$this->isUnaryPredecessorOperator($index);
}
return false;
} | php | {
"resource": ""
} |
q242148 | TokensAnalyzer.findClassyElements | validation | private function findClassyElements($index)
{
$elements = [];
$curlyBracesLevel = 0;
$bracesLevel = 0;
$classIndex = $index;
++$index; // skip the classy index itself
for ($count = \count($this->tokens); $index < $count; ++$index) {
$token = $this->tokens[$index];
if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) {
continue;
}
if ($token->isClassy()) { // anonymous class in class
list($index, $newElements) = $this->findClassyElements($index);
$elements += $newElements;
continue;
}
if ($token->equals('(')) {
++$bracesLevel;
continue;
}
if ($token->equals(')')) {
--$bracesLevel;
continue;
}
if ($token->equals('{')) {
++$curlyBracesLevel;
continue;
}
if ($token->equals('}')) {
--$curlyBracesLevel;
if (0 === $curlyBracesLevel) {
break;
}
continue;
}
if (1 !== $curlyBracesLevel || !$token->isArray()) {
continue;
}
if (0 === $bracesLevel && $token->isGivenKind(T_VARIABLE)) {
$elements[$index] = [
'token' => $token,
'type' => 'property',
'classIndex' => $classIndex,
];
continue;
}
if ($token->isGivenKind(T_FUNCTION)) {
$elements[$index] = [
'token' => $token,
'type' => 'method',
'classIndex' => $classIndex,
];
} elseif ($token->isGivenKind(T_CONST)) {
$elements[$index] = [
'token' => $token,
'type' => 'const',
'classIndex' => $classIndex,
];
}
}
return [$index, $elements];
} | php | {
"resource": ""
} |
q242149 | SquareBraceTransformer.isShortArray | validation | private function isShortArray(Tokens $tokens, $index)
{
if (!$tokens[$index]->equals('[')) {
return false;
}
static $disallowedPrevTokens = [
')',
']',
'}',
'"',
[T_CONSTANT_ENCAPSED_STRING],
[T_STRING],
[T_STRING_VARNAME],
[T_VARIABLE],
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE],
];
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevToken->equalsAny($disallowedPrevTokens)) {
return false;
}
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if ($nextToken->equals(']')) {
return true;
}
return !$this->isArrayDestructing($tokens, $index);
} | php | {
"resource": ""
} |
q242150 | HeaderCommentFixer.getHeaderAsComment | validation | private function getHeaderAsComment()
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
$comment = (self::HEADER_COMMENT === $this->configuration['comment_type'] ? '/*' : '/**').$lineEnding;
$lines = explode("\n", str_replace("\r", '', $this->configuration['header']));
foreach ($lines as $line) {
$comment .= rtrim(' * '.$line).$lineEnding;
}
return $comment.' */';
} | php | {
"resource": ""
} |
q242151 | HeaderCommentFixer.findHeaderCommentInsertionIndex | validation | private function findHeaderCommentInsertionIndex(Tokens $tokens)
{
if ('after_open' === $this->configuration['location']) {
return 1;
}
$index = $tokens->getNextMeaningfulToken(0);
if (null === $index) {
// file without meaningful tokens but an open tag, comment should always be placed directly after the open tag
return 1;
}
if (!$tokens[$index]->isGivenKind(T_DECLARE)) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($index);
if (null === $next || !$tokens[$next]->equals('(')) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals([T_STRING, 'strict_types'], false)) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals('=')) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->isGivenKind(T_LNUMBER)) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(')')) {
return 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(';')) { // don't insert after close tag
return 1;
}
return $next + 1;
} | php | {
"resource": ""
} |
q242152 | Line.addBlank | validation | public function addBlank()
{
$matched = Preg::match('/^([ \t]*\*)[^\r\n]*(\r?\n)$/', $this->content, $matches);
if (1 !== $matched) {
return;
}
$this->content .= $matches[1].$matches[2];
} | php | {
"resource": ""
} |
q242153 | PhpdocOrderFixer.moveParamAnnotations | validation | private function moveParamAnnotations($content)
{
$doc = new DocBlock($content);
$params = $doc->getAnnotationsOfType('param');
// nothing to do if there are no param annotations
if (empty($params)) {
return $content;
}
$others = $doc->getAnnotationsOfType(['throws', 'return']);
if (empty($others)) {
return $content;
}
// get the index of the final line of the final param annotation
$end = end($params)->getEnd();
$line = $doc->getLine($end);
// move stuff about if required
foreach ($others as $other) {
if ($other->getStart() < $end) {
// we're doing this to maintain the original line indexes
$line->setContent($line->getContent().$other->getContent());
$other->remove();
}
}
return $doc->getContent();
} | php | {
"resource": ""
} |
q242154 | PhpdocOrderFixer.moveReturnAnnotations | validation | private function moveReturnAnnotations($content)
{
$doc = new DocBlock($content);
$returns = $doc->getAnnotationsOfType('return');
// nothing to do if there are no return annotations
if (empty($returns)) {
return $content;
}
$others = $doc->getAnnotationsOfType(['param', 'throws']);
// nothing to do if there are no other annotations
if (empty($others)) {
return $content;
}
// get the index of the first line of the first return annotation
$start = $returns[0]->getStart();
$line = $doc->getLine($start);
// move stuff about if required
foreach (array_reverse($others) as $other) {
if ($other->getEnd() > $start) {
// we're doing this to maintain the original line indexes
$line->setContent($other->getContent().$line->getContent());
$other->remove();
}
}
return $doc->getContent();
} | php | {
"resource": ""
} |
q242155 | Utils.calculateBitmask | validation | public static function calculateBitmask(array $options)
{
$bitmask = 0;
foreach ($options as $optionName) {
if (\defined($optionName)) {
$bitmask |= \constant($optionName);
}
}
return $bitmask;
} | php | {
"resource": ""
} |
q242156 | Utils.camelCaseToUnderscore | validation | public static function camelCaseToUnderscore($string)
{
return Preg::replaceCallback(
'/(^|[a-z0-9])([A-Z])/',
static function (array $matches) {
return strtolower('' !== $matches[1] ? $matches[1].'_'.$matches[2] : $matches[2]);
},
$string
);
} | php | {
"resource": ""
} |
q242157 | Utils.calculateTrailingWhitespaceIndent | validation | public static function calculateTrailingWhitespaceIndent(Token $token)
{
if (!$token->isWhitespace()) {
throw new \InvalidArgumentException(sprintf('The given token must be whitespace, got "%s".', $token->getName()));
}
$str = strrchr(
str_replace(["\r\n", "\r"], "\n", $token->getContent()),
"\n"
);
if (false === $str) {
return '';
}
return ltrim($str, "\n");
} | php | {
"resource": ""
} |
q242158 | Utils.stableSort | validation | public static function stableSort(array $elements, callable $getComparedValue, callable $compareValues)
{
array_walk($elements, static function (&$element, $index) use ($getComparedValue) {
$element = [$element, $index, $getComparedValue($element)];
});
usort($elements, static function ($a, $b) use ($compareValues) {
$comparison = $compareValues($a[2], $b[2]);
if (0 !== $comparison) {
return $comparison;
}
return self::cmpInt($a[1], $b[1]);
});
return array_map(static function (array $item) {
return $item[0];
}, $elements);
} | php | {
"resource": ""
} |
q242159 | Utils.sortFixers | validation | public static function sortFixers(array $fixers)
{
// Schwartzian transform is used to improve the efficiency and avoid
// `usort(): Array was modified by the user comparison function` warning for mocked objects.
return self::stableSort(
$fixers,
static function (FixerInterface $fixer) {
return $fixer->getPriority();
},
static function ($a, $b) {
return self::cmpInt($b, $a);
}
);
} | php | {
"resource": ""
} |
q242160 | ShortDescription.getEnd | validation | public function getEnd()
{
$reachedContent = false;
foreach ($this->doc->getLines() as $index => $line) {
// we went past a description, then hit a tag or blank line, so
// the last line of the description must be the one before this one
if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) {
return $index - 1;
}
// no short description was found
if ($line->containsATag()) {
return null;
}
// we've reached content, but need to check the next lines too
// in case the short description is multi-line
if ($line->containsUsefulContent()) {
$reachedContent = true;
}
}
} | php | {
"resource": ""
} |
q242161 | PhpdocSeparationFixer.fixDescription | validation | private function fixDescription(DocBlock $doc)
{
foreach ($doc->getLines() as $index => $line) {
if ($line->containsATag()) {
break;
}
if ($line->containsUsefulContent()) {
$next = $doc->getLine($index + 1);
if ($next->containsATag()) {
$line->addBlank();
break;
}
}
}
} | php | {
"resource": ""
} |
q242162 | PhpdocSeparationFixer.fixAnnotations | validation | private function fixAnnotations(DocBlock $doc)
{
foreach ($doc->getAnnotations() as $index => $annotation) {
$next = $doc->getAnnotation($index + 1);
if (null === $next) {
break;
}
if (true === $next->getTag()->valid()) {
if (TagComparator::shouldBeTogether($annotation->getTag(), $next->getTag())) {
$this->ensureAreTogether($doc, $annotation, $next);
} else {
$this->ensureAreSeparate($doc, $annotation, $next);
}
}
}
return $doc->getContent();
} | php | {
"resource": ""
} |
q242163 | PhpdocSeparationFixer.ensureAreTogether | validation | private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second)
{
$pos = $first->getEnd();
$final = $second->getStart();
for ($pos = $pos + 1; $pos < $final; ++$pos) {
$doc->getLine($pos)->remove();
}
} | php | {
"resource": ""
} |
q242164 | PhpdocSeparationFixer.ensureAreSeparate | validation | private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second)
{
$pos = $first->getEnd();
$final = $second->getStart() - 1;
// check if we need to add a line, or need to remove one or more lines
if ($pos === $final) {
$doc->getLine($pos)->addBlank();
return;
}
for ($pos = $pos + 1; $pos < $final; ++$pos) {
$doc->getLine($pos)->remove();
}
} | php | {
"resource": ""
} |
q242165 | ErrorsManager.getInvalidErrors | validation | public function getInvalidErrors()
{
return array_filter($this->errors, static function (Error $error) {
return Error::TYPE_INVALID === $error->getType();
});
} | php | {
"resource": ""
} |
q242166 | ErrorsManager.getExceptionErrors | validation | public function getExceptionErrors()
{
return array_filter($this->errors, static function (Error $error) {
return Error::TYPE_EXCEPTION === $error->getType();
});
} | php | {
"resource": ""
} |
q242167 | ErrorsManager.getLintErrors | validation | public function getLintErrors()
{
return array_filter($this->errors, static function (Error $error) {
return Error::TYPE_LINT === $error->getType();
});
} | php | {
"resource": ""
} |
q242168 | NoEmptyCommentFixer.getCommentBlock | validation | private function getCommentBlock(Tokens $tokens, $index)
{
$commentType = $this->getCommentType($tokens[$index]->getContent());
$empty = $this->isEmptyComment($tokens[$index]->getContent());
$start = $index;
$count = \count($tokens);
++$index;
for (; $index < $count; ++$index) {
if ($tokens[$index]->isComment()) {
if ($commentType !== $this->getCommentType($tokens[$index]->getContent())) {
break;
}
if ($empty) { // don't retest if already known the block not being empty
$empty = $this->isEmptyComment($tokens[$index]->getContent());
}
continue;
}
if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) {
break;
}
}
return [$start, $index - 1, $empty];
} | php | {
"resource": ""
} |
q242169 | FileRemoval.delete | validation | public function delete($path)
{
if (isset($this->files[$path])) {
unset($this->files[$path]);
}
$this->unlink($path);
} | php | {
"resource": ""
} |
q242170 | FileRemoval.clean | validation | public function clean()
{
foreach ($this->files as $file => $value) {
$this->unlink($file);
}
$this->files = [];
} | php | {
"resource": ""
} |
q242171 | Transformers.transform | validation | public function transform(Tokens $tokens)
{
foreach ($this->items as $transformer) {
foreach ($tokens as $index => $token) {
$transformer->process($tokens, $token, $index);
}
}
} | php | {
"resource": ""
} |
q242172 | Token.clear | validation | public function clear()
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
Tokens::setLegacyMode(true);
$this->content = '';
$this->id = null;
$this->isArray = false;
} | php | {
"resource": ""
} |
q242173 | Token.clearChanged | validation | public function clearChanged()
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
Tokens::setLegacyMode(true);
$this->changed = false;
} | php | {
"resource": ""
} |
q242174 | Token.equals | validation | public function equals($other, $caseSensitive = true)
{
if ($other instanceof self) {
// Inlined getPrototype() on this very hot path.
// We access the private properties of $other directly to save function call overhead.
// This is only possible because $other is of the same class as `self`.
if (!$other->isArray) {
$otherPrototype = $other->content;
} else {
$otherPrototype = [
$other->id,
$other->content,
];
}
} else {
$otherPrototype = $other;
}
if ($this->isArray !== \is_array($otherPrototype)) {
return false;
}
if (!$this->isArray) {
return $this->content === $otherPrototype;
}
if ($this->id !== $otherPrototype[0]) {
return false;
}
if (isset($otherPrototype[1])) {
if ($caseSensitive) {
if ($this->content !== $otherPrototype[1]) {
return false;
}
} elseif (0 !== strcasecmp($this->content, $otherPrototype[1])) {
return false;
}
}
// detect unknown keys
unset($otherPrototype[0], $otherPrototype[1]);
return empty($otherPrototype);
} | php | {
"resource": ""
} |
q242175 | Token.equalsAny | validation | public function equalsAny(array $others, $caseSensitive = true)
{
foreach ($others as $other) {
if ($this->equals($other, $caseSensitive)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q242176 | Token.isKeyCaseSensitive | validation | public static function isKeyCaseSensitive($caseSensitive, $key)
{
if (\is_array($caseSensitive)) {
return isset($caseSensitive[$key]) ? $caseSensitive[$key] : true;
}
return $caseSensitive;
} | php | {
"resource": ""
} |
q242177 | Token.getNameForId | validation | public static function getNameForId($id)
{
if (CT::has($id)) {
return CT::getName($id);
}
$name = token_name($id);
return 'UNKNOWN' === $name ? null : $name;
} | php | {
"resource": ""
} |
q242178 | Token.getKeywords | validation | public static function getKeywords()
{
static $keywords = null;
if (null === $keywords) {
$keywords = self::getTokenKindsForNames(['T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE',
'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO',
'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH',
'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL',
'T_FINALLY', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER',
'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF',
'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
'T_NAMESPACE', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE',
'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY',
'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'T_YIELD_FROM',
]) + [
CT::T_ARRAY_TYPEHINT => CT::T_ARRAY_TYPEHINT,
CT::T_CLASS_CONSTANT => CT::T_CLASS_CONSTANT,
CT::T_CONST_IMPORT => CT::T_CONST_IMPORT,
CT::T_FUNCTION_IMPORT => CT::T_FUNCTION_IMPORT,
CT::T_NAMESPACE_OPERATOR => CT::T_NAMESPACE_OPERATOR,
CT::T_USE_TRAIT => CT::T_USE_TRAIT,
CT::T_USE_LAMBDA => CT::T_USE_LAMBDA,
];
}
return $keywords;
} | php | {
"resource": ""
} |
q242179 | Token.isGivenKind | validation | public function isGivenKind($possibleKind)
{
return $this->isArray && (\is_array($possibleKind) ? \in_array($this->id, $possibleKind, true) : $this->id === $possibleKind);
} | php | {
"resource": ""
} |
q242180 | Token.isWhitespace | validation | public function isWhitespace($whitespaces = " \t\n\r\0\x0B")
{
if (null === $whitespaces) {
$whitespaces = " \t\n\r\0\x0B";
}
if ($this->isArray && !$this->isGivenKind(T_WHITESPACE)) {
return false;
}
return '' === trim($this->content, $whitespaces);
} | php | {
"resource": ""
} |
q242181 | Token.override | validation | public function override($other)
{
@trigger_error(__METHOD__.' is deprecated and will be removed in 3.0.', E_USER_DEPRECATED);
Tokens::setLegacyMode(true);
$prototype = $other instanceof self ? $other->getPrototype() : $other;
if ($this->equals($prototype)) {
return;
}
$this->changed = true;
if (\is_array($prototype)) {
$this->isArray = true;
$this->id = $prototype[0];
$this->content = $prototype[1];
return;
}
$this->isArray = false;
$this->id = null;
$this->content = $prototype;
} | php | {
"resource": ""
} |
q242182 | ConfigurationResolver.getPath | validation | public function getPath()
{
if (null === $this->path) {
$filesystem = new Filesystem();
$cwd = $this->cwd;
if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) {
$this->path = $this->options['path'];
} else {
$this->path = array_map(
static function ($path) use ($cwd, $filesystem) {
$absolutePath = $filesystem->isAbsolutePath($path)
? $path
: $cwd.\DIRECTORY_SEPARATOR.$path;
if (!file_exists($absolutePath)) {
throw new InvalidConfigurationException(sprintf(
'The path "%s" is not readable.',
$path
));
}
return $absolutePath;
},
$this->options['path']
);
}
}
return $this->path;
} | php | {
"resource": ""
} |
q242183 | ConfigurationResolver.isDryRun | validation | public function isDryRun()
{
if (null === $this->isDryRun) {
if ($this->isStdIn()) {
// Can't write to STDIN
$this->isDryRun = true;
} else {
$this->isDryRun = $this->options['dry-run'];
}
}
return $this->isDryRun;
} | php | {
"resource": ""
} |
q242184 | ConfigurationResolver.computeConfigFiles | validation | private function computeConfigFiles()
{
$configFile = $this->options['config'];
if (null !== $configFile) {
if (false === file_exists($configFile) || false === is_readable($configFile)) {
throw new InvalidConfigurationException(sprintf('Cannot read config file "%s".', $configFile));
}
return [$configFile];
}
$path = $this->getPath();
if ($this->isStdIn() || 0 === \count($path)) {
$configDir = $this->cwd;
} elseif (1 < \count($path)) {
throw new InvalidConfigurationException('For multiple paths config parameter is required.');
} elseif (is_file($path[0]) && $dirName = pathinfo($path[0], PATHINFO_DIRNAME)) {
$configDir = $dirName;
} else {
$configDir = $path[0];
}
$candidates = [
$configDir.\DIRECTORY_SEPARATOR.'.php_cs',
$configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist',
];
if ($configDir !== $this->cwd) {
$candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs';
$candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs.dist';
}
return $candidates;
} | php | {
"resource": ""
} |
q242185 | ConfigurationResolver.parseRules | validation | private function parseRules()
{
if (null === $this->options['rules']) {
return $this->getConfig()->getRules();
}
$rules = trim($this->options['rules']);
if ('' === $rules) {
throw new InvalidConfigurationException('Empty rules value is not allowed.');
}
if ('{' === $rules[0]) {
$rules = json_decode($rules, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new InvalidConfigurationException(sprintf('Invalid JSON rules input: %s.', json_last_error_msg()));
}
return $rules;
}
$rules = [];
foreach (explode(',', $this->options['rules']) as $rule) {
$rule = trim($rule);
if ('' === $rule) {
throw new InvalidConfigurationException('Empty rule name is not allowed.');
}
if ('-' === $rule[0]) {
$rules[substr($rule, 1)] = false;
} else {
$rules[$rule] = true;
}
}
return $rules;
} | php | {
"resource": ""
} |
q242186 | ConfigurationResolver.setOption | validation | private function setOption($name, $value)
{
if (!\array_key_exists($name, $this->options)) {
throw new InvalidConfigurationException(sprintf('Unknown option name: "%s".', $name));
}
$this->options[$name] = $value;
} | php | {
"resource": ""
} |
q242187 | AuthProxy.handle | validation | public function handle(Request $request, Closure $next)
{
// Grab the query parameters we need, remove signature since its not part of the signature calculation
$query = $request->query->all();
$signature = $query['signature'];
unset($query['signature']);
// Build a local signature
$signatureLocal = ShopifyApp::createHmac(['data' => $query, 'buildQuery' => true]);
if ($signature !== $signatureLocal || !isset($query['shop'])) {
// Issue with HMAC or missing shop header
return Response::make('Invalid proxy signature.', 401);
}
// Save shop domain to session
Session::put('shopify_domain', ShopifyApp::sanitizeShopDomain($request->get('shop')));
// All good, process proxy request
return $next($request);
} | php | {
"resource": ""
} |
q242188 | ScripttagInstaller.scripttagExists | validation | protected function scripttagExists(array $shopScripttags, array $scripttag)
{
foreach ($shopScripttags as $shopScripttag) {
if ($shopScripttag->src === $scripttag['src']) {
// Found the scripttag in our list
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q242189 | ShopifyApp.api | validation | public function api()
{
$apiClass = Config::get('shopify-app.api_class');
$api = new $apiClass();
$api->setApiKey(Config::get('shopify-app.api_key'));
$api->setApiSecret(Config::get('shopify-app.api_secret'));
// Add versioning?
$version = Config::get('shopify-app.api_version');
if ($version !== null) {
$api->setVersion($version);
}
// Enable basic rate limiting?
if (Config::get('shopify-app.api_rate_limiting_enabled') === true) {
$api->enableRateLimiting(
Config::get('shopify-app.api_rate_limit_cycle'),
Config::get('shopify-app.api_rate_limit_cycle_buffer')
);
}
return $api;
} | php | {
"resource": ""
} |
q242190 | ShopifyApp.sanitizeShopDomain | validation | public function sanitizeShopDomain($domain)
{
if (empty($domain)) {
return;
}
$configEndDomain = Config::get('shopify-app.myshopify_domain');
$domain = strtolower(preg_replace('/https?:\/\//i', '', trim($domain)));
if (strpos($domain, $configEndDomain) === false && strpos($domain, '.') === false) {
// No myshopify.com ($configEndDomain) in shop's name
$domain .= ".{$configEndDomain}";
}
// Return the host after cleaned up
return parse_url("http://{$domain}", PHP_URL_HOST);
} | php | {
"resource": ""
} |
q242191 | ShopifyApp.createHmac | validation | public function createHmac(array $opts)
{
// Setup defaults
$data = $opts['data'];
$raw = $opts['raw'] ?? false;
$buildQuery = $opts['buildQuery'] ?? false;
$buildQueryWithJoin = $opts['buildQueryWithJoin'] ?? false;
$encode = $opts['encode'] ?? false;
$secret = $opts['secret'] ?? Config::get('shopify-app.api_secret');
if ($buildQuery) {
//Query params must be sorted and compiled
ksort($data);
$queryCompiled = [];
foreach ($data as $key => $value) {
$queryCompiled[] = "{$key}=".(is_array($value) ? implode($value, ',') : $value);
}
$data = implode($queryCompiled, ($buildQueryWithJoin ? '&' : ''));
}
// Create the hmac all based on the secret
$hmac = hash_hmac('sha256', $data, $secret, $raw);
// Return based on options
return $encode ? base64_encode($hmac) : $hmac;
} | php | {
"resource": ""
} |
q242192 | UsageCharge.activate | validation | public function activate()
{
// Ensure we have a recurring charge
$currentCharge = $this->shop->planCharge();
if (!$currentCharge->isType(Charge::CHARGE_RECURRING)) {
throw new Exception('Can only create usage charges for recurring charge.');
}
$this->response = $this->api->rest(
'POST',
"/admin/recurring_application_charges/{$currentCharge->charge_id}/usage_charges.json",
[
'usage_charge' => [
'price' => $this->data['price'],
'description' => $this->data['description'],
],
]
)->body->usage_charge;
return $this->response;
} | php | {
"resource": ""
} |
q242193 | UsageCharge.save | validation | public function save()
{
if (!$this->response) {
throw new Exception('No activation response was recieved.');
}
// Get the plan charge
$planCharge = $this->shop->planCharge();
// Create the charge
$charge = new Charge();
$charge->type = Charge::CHARGE_USAGE;
$charge->reference_charge = $planCharge->charge_id;
$charge->shop_id = $this->shop->id;
$charge->charge_id = $this->response->id;
$charge->price = $this->response->price;
$charge->description = $this->response->description;
$charge->billing_on = $this->response->billing_on;
return $charge->save();
} | php | {
"resource": ""
} |
q242194 | AuthControllerTrait.authenticate | validation | public function authenticate(AuthShop $request)
{
// Get the validated data
$validated = $request->validated();
$shopDomain = ShopifyApp::sanitizeShopDomain($validated['shop']);
$shop = ShopifyApp::shop($shopDomain);
// Start the process
$auth = new AuthShopHandler($shop);
$session = new ShopSession($shop);
// Check if we have a code
if (!$request->has('code')) {
// Handle a request without a code, do a fullpage redirect
// Check if they have offline access, if they do not, this is most likely an install
// If they do, fallback to using configured grant mode
$authUrl = $auth->buildAuthUrl(
$shop->hasOfflineAccess() ? Config::get('shopify-app.api_grant_mode') : ShopSession::GRANT_OFFLINE
);
return View::make('shopify-app::auth.fullpage_redirect', compact('authUrl', 'shopDomain'));
}
// We have a good code, get the access details
$access = $auth->getAccess($validated['code']);
// Save the session
$session->setDomain($shopDomain);
$session->setAccess($access);
// Do post processing and dispatch the jobs
$auth->postProcess();
$auth->dispatchJobs($session);
// Go to homepage of app or the return_to
return $this->returnTo();
} | php | {
"resource": ""
} |
q242195 | AuthControllerTrait.returnTo | validation | protected function returnTo()
{
// Set in AuthShop middleware
$return_to = Session::get('return_to');
if ($return_to) {
Session::forget('return_to');
return Redirect::to($return_to);
}
// No return_to, go to home route
return Redirect::route('home');
} | php | {
"resource": ""
} |
q242196 | Charge.retrieve | validation | public function retrieve()
{
$path = null;
switch ($this->type) {
case self::CHARGE_CREDIT:
$path = 'application_credits';
break;
case self::CHARGE_ONETIME:
$path = 'application_charges';
break;
default:
$path = 'recurring_application_charges';
break;
}
return $this
->shop
->api()
->rest('GET', "/admin/{$path}/{$this->charge_id}.json")->body->{substr($path, 0, -1)};
} | php | {
"resource": ""
} |
q242197 | Charge.isActiveTrial | validation | public function isActiveTrial()
{
return $this->isTrial() && Carbon::today()->lte(Carbon::parse($this->trial_ends_on));
} | php | {
"resource": ""
} |
q242198 | Charge.remainingTrialDays | validation | public function remainingTrialDays()
{
if (!$this->isTrial()) {
return;
}
return $this->isActiveTrial() ? Carbon::today()->diffInDays($this->trial_ends_on) : 0;
} | php | {
"resource": ""
} |
q242199 | Charge.remainingTrialDaysFromCancel | validation | public function remainingTrialDaysFromCancel()
{
if (!$this->isTrial()) {
return;
}
$cancelledDate = Carbon::parse($this->cancelled_on);
$trialEndsDate = Carbon::parse($this->trial_ends_on);
// Ensure cancelled date happened before the trial was supposed to end
if ($this->isCancelled() && $cancelledDate->lte($trialEndsDate)) {
// Diffeence the two dates and subtract from the total trial days to get whats remaining
return $this->trial_days - ($this->trial_days - $cancelledDate->diffInDays($trialEndsDate));
}
return 0;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.