diff --git a/README.md b/README.md index 5f74f30050..92933c9313 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Rules blink runs natively, per source. Regenerate with `blink/bin/rule-counts.sh |---|---:|---:|---:| | PHP-CS-Fixer | 282 | 282 | 100% | | Symplify | 34 | 34 | 100% | -| PHP_CodeSniffer | 101 | 114 | 88% | +| PHP_CodeSniffer | 114 | 114 | 100% | | slevomat | 37 | 132 | 28% | -| **total** | **454** | **562** | **80%** | +| **total** | **467** | **562** | **83%** | diff --git a/blink/README.md b/blink/README.md index b5934cca94..0b43c07088 100644 --- a/blink/README.md +++ b/blink/README.md @@ -24,10 +24,10 @@ those expectations can differ from upstream's `.inc.fixed`. Regenerate them with |---|---:|---:|---:| | PHP-CS-Fixer | 282 | 282 | 100% | | Symplify | 34 | 34 | 100% | -| PHP_CodeSniffer | 101 | 114 | 88% | -| **total** | **417** | **430** | **96%** | +| PHP_CodeSniffer | 114 | 114 | 100% | +| **total** | **430** | **430** | **100%** | -blink runs 460 rules in all, its own extras included. +blink runs 473 rules in all, its own extras included. ### slevomat sniffs diff --git a/blink/internal/fixer/rules/embedded_php.go b/blink/internal/fixer/rules/embedded_php.go new file mode 100644 index 0000000000..148e8fdf79 --- /dev/null +++ b/blink/internal/fixer/rules/embedded_php.go @@ -0,0 +1,312 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php +// +// EmbeddedPhp lays out PHP blocks embedded in HTML: a multi-line block gets +// its open and close tags on lines of their own, an inline one gets one space +// inside each tag and a closing semicolon, and an empty one is removed. +type EmbeddedPhp struct{} + +func (EmbeddedPhp) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\EmbeddedPhpSniff` +} + +func (EmbeddedPhp) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php" +} + +type embeddedPhp struct { + f *slvFile + sc *phpcsScope +} + +// phpcsOnePass: ECS stops on a fixer conflict between the open tag indent and +// the first content indent, which a second run would resolve differently. +func (EmbeddedPhp) phpcsOnePass() {} + +func (EmbeddedPhp) Fix(s *tokens.Stream) bool { + for i := range s.Len() { + // ECS runs PHP with short_open_tag off, so "= end; i-- { + if e.f.toks[i].kind != token.Whitespace { + return i + } + } + return 0 +} + +func (e embeddedPhp) multiline(ptr, closingTag int) { + f := e.f + prevTag := -1 + for i := ptr - 1; i >= 0; i-- { + if f.toks[i].kind == token.OpenTag { + prevTag = i + break + } + } + if prevTag < 0 { + return + } + firstContent := f.nextNonWhitespace(ptr+1, len(f.toks)) + if firstContent < 0 { + return + } + if closingTag >= 0 { + if f.nextNonWhitespace(closingTag+1, len(f.toks)) < 0 { + return + } + if firstContent == closingTag { + e.reportEmpty(ptr, closingTag) + return + } + } + + indent, indentSet := 0, false + if e.line(firstContent) == e.line(ptr) { + padding := e.lineIndent(ptr) + f.beginChangeset() + f.replaceToken(ptr, strings.TrimRight(f.toks[ptr].content, phpTrimChars)) + f.addContent(ptr, f.eol) + f.addContent(ptr, strings.Repeat(" ", padding)) + if f.toks[ptr+1].kind == token.Whitespace { + f.replaceToken(ptr+1, "") + } + f.endChangeset() + } else if !e.isCloser(firstContent) { + if e.line(firstContent) > e.line(ptr)+1 { + f.beginChangeset() + for i := ptr + 1; i < firstContent; i++ { + if e.line(i) == e.line(firstContent) || e.line(i) == e.line(ptr) { + continue + } + f.replaceToken(i, "") + } + f.endChangeset() + } + indent, indentSet = e.lineIndent(ptr), true + if contentColumn := f.toks[firstContent].column - 1; contentColumn != indent { + padding := strings.Repeat(" ", indent) + if contentColumn == 0 { + f.addContentBefore(firstContent, padding) + } else { + f.replaceToken(firstContent-1, padding) + } + } + } + + lastBefore := e.prevNonWhitespace(ptr-1, 0) + if e.line(lastBefore) == e.line(ptr) && + (f.toks[lastBefore].kind == token.InlineHTML && strings.Trim(f.toks[lastBefore].content, phpTrimChars) != "" || + lastBefore > 0 && f.toks[lastBefore-1].kind != token.InlineHTML && e.line(lastBefore-1) == e.line(ptr)) { + padding := e.lineIndent(lastBefore) + f.beginChangeset() + f.addContentBefore(ptr, f.eol+strings.Repeat(" ", padding)) + if f.toks[ptr-1].kind == token.InlineHTML && strings.Trim(f.toks[ptr-1].content, phpTrimChars) == "" { + f.replaceToken(ptr-1, "") + } + f.endChangeset() + } else { + first := lastBefore - 1 + for ; first > 0; first-- { + if e.line(first) == e.line(ptr) { + continue + } + if strings.Trim(f.toks[first].content, phpTrimChars) != "" { + first = f.firstOnLine(first) + break + } + } + expected := e.lineIndent(max(first, 0)) + 4 + if found := f.toks[ptr].column - 1; found > expected { + f.replaceToken(ptr-1, strings.Repeat(" ", expected)) + } + } + + if closingTag < 0 { + return + } + lastContent := e.prevNonWhitespace(closingTag-1, ptr+1) + firstAfter := f.nextNonWhitespace(closingTag+1, len(f.toks)) + if e.line(lastContent) == e.line(closingTag) { + closerIndent := 0 + if e.line(firstContent) == e.line(lastContent) && indentSet { + closerIndent = indent + } else { + closerIndent = e.lineIndent(closingTag) + } + f.beginChangeset() + if f.toks[closingTag-1].kind == token.Whitespace { + f.replaceToken(closingTag-1, "") + } + f.addContentBefore(closingTag, strings.Repeat(" ", closerIndent)) + f.addContentBefore(closingTag, f.eol) + f.endChangeset() + } else if firstAfter >= 0 && e.line(firstAfter) == e.line(closingTag) { + padding := e.lineIndent(closingTag) + f.beginChangeset() + f.addContent(closingTag, f.eol) + f.addContent(closingTag, strings.Repeat(" ", padding)) + switch f.toks[firstAfter].kind { + case token.InlineHTML: + f.replaceToken(firstAfter, strings.TrimLeft(f.toks[firstAfter].content, phpTrimChars)) + case token.OpenTag: + f.replaceToken(firstAfter, f.toks[firstAfter].content) + } + f.endChangeset() + } + + if e.next(token.OpenTag, closingTag+1) < 0 { + return + } + lastNonEmpty := 0 + for i := closingTag - 1; i >= ptr+1; i-- { + if !f.isEmpty(i) { + lastNonEmpty = i + break + } + } + if !e.isCloser(lastNonEmpty) && e.line(lastContent) < e.line(closingTag)-1 { + f.beginChangeset() + for i := lastContent + 1; i < closingTag; i++ { + if e.line(i) == e.line(lastContent) || e.line(i) == e.line(closingTag) { + continue + } + f.replaceToken(i, "") + } + f.endChangeset() + } +} + +func (e embeddedPhp) inline(ptr, closeTag int) { + f := e.f + if f.nextNonWhitespace(ptr+1, closeTag) < 0 { + e.reportEmpty(ptr, closeTag) + return + } + leadingSpace := 0 + if f.toks[ptr+1].kind == token.Whitespace { + leadingSpace = f.toks[ptr+1].length + } + if leadingSpace != 1 { + if f.toks[ptr+1].kind == token.Whitespace { + f.replaceToken(ptr+1, " ") + } else { + f.addContent(ptr, " ") + } + } + + prev := 0 + for i := closeTag - 1; i >= ptr; i-- { + if !f.isEmpty(i) { + prev = i + break + } + } + if prev != ptr && !e.isOpener(prev) && !e.isCloser(prev) && !f.is(prev, ";") { + f.addContent(prev, ";") + } + + before := f.toks[closeTag-1] + trailingSpace := 0 + isComment := before.kind == token.Comment + if before.kind == token.Whitespace { + trailingSpace = before.length + } else if isComment && strings.HasSuffix(before.content, " ") { + trailingSpace = len(before.content) - len(strings.TrimRight(before.content, phpTrimChars)) + } + if trailingSpace != 1 { + switch { + case trailingSpace == 0: + f.addContentBefore(closeTag, " ") + case isComment: + f.replaceToken(closeTag-1, strings.TrimRight(before.content, phpTrimChars)+" ") + default: + f.replaceToken(closeTag-1, " ") + } + } +} + +func (e embeddedPhp) reportEmpty(ptr, closeTag int) { + f := e.f + f.beginChangeset() + for i := ptr; i <= closeTag; i++ { + f.replaceToken(i, "") + } + if closeTag+1 < len(f.toks) && e.line(closeTag+1) != e.line(closeTag) && ptr > 0 { + if p := f.toks[ptr-1]; p.kind == token.InlineHTML && p.line == e.line(ptr) && p.column == 1 && + strings.Trim(p.content, phpTrimChars) == "" { + f.replaceToken(ptr-1, "") + } + } + f.endChangeset() +} + +// lineIndent is the sniff's calculateLineIndent. +func (e embeddedPhp) lineIndent(ptr int) int { + f := e.f + first := ptr + for first > 0 && f.toks[first].column != 1 { + first-- + } + for first > 0 && f.toks[first].kind == token.Comment && !phpcsIsAnnotation(f, first) && + f.toks[first].content != strings.TrimLeft(f.toks[first].content, phpTrimChars) { + for first--; first > 0 && f.toks[first].column != 1; first-- { + } + } + t := f.toks[first] + leading := len(t.content) - len(strings.TrimLeft(t.content, phpTrimChars)) + switch { + case t.kind == token.Whitespace: + return f.toks[first+1].column - 1 + case t.kind == token.InlineHTML, t.kind == token.String && t.heredoc && !strings.HasSuffix(t.orig, "\n"): + return leading + case t.doc == slvDocWhitespace: + return leading - 1 + } + return 0 +} diff --git a/blink/internal/fixer/rules/function_declaration_argument_spacing.go b/blink/internal/fixer/rules/function_declaration_argument_spacing.go new file mode 100644 index 0000000000..a2d3f257cd --- /dev/null +++ b/blink/internal/fixer/rules/function_declaration_argument_spacing.go @@ -0,0 +1,450 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php +// +// FunctionDeclarationArgumentSpacing fixes the spacing inside a function's +// parameter list: around "=", after "&", "..." and type hints, around commas +// and inside the parentheses. +type FunctionDeclarationArgumentSpacing struct { + EqualsSpacing int + RequiredSpacesAfterOpen int + RequiredSpacesBeforeClose int +} + +func (FunctionDeclarationArgumentSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationArgumentSpacingSniff` +} + +func (FunctionDeclarationArgumentSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php" +} + +func (r FunctionDeclarationArgumentSpacing) WithConfig(config map[string]any) fixer.Fixer { + r.EqualsSpacing = configInt(config, "equalsSpacing", r.EqualsSpacing) + r.RequiredSpacesAfterOpen = configInt(config, "requiredSpacesAfterOpen", r.RequiredSpacesAfterOpen) + r.RequiredSpacesBeforeClose = configInt(config, "requiredSpacesBeforeClose", r.RequiredSpacesBeforeClose) + return r +} + +func (r FunctionDeclarationArgumentSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if f.isKeyword(i, "function") { + p := f.prevEffective(i - 1) + if f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") { + continue + } + fn, ok := phpcsFunctionAt(f, i) + if !ok { + continue + } + r.processBracket(f, fn.openParen) + if fn.closure { + if open, _ := fn.useParens(f); open >= 0 { + r.processBracket(f, open) + } + } + continue + } + if open := phpcsFnParen(f, i); open >= 0 { + r.processBracket(f, open) + } + } + }) +} + +// phpcsFnParen returns the "(" of the arrow function whose "fn" is at i, or -1. +func phpcsFnParen(f *slvFile, i int) int { + if !f.isKeyword(i, "fn") { + return -1 + } + if p := f.prevEffective(i - 1); f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") || f.isKeyword(p, "function") { + return -1 + } + o := f.nextEffective(i+1, len(f.toks)) + if f.is(o, "&") { + o = f.nextEffective(o+1, len(f.toks)) + } + if !f.is(o, "(") || f.toks[o].closer < 0 { + return -1 + } + return o +} + +func (r FunctionDeclarationArgumentSpacing) gapTo(f *slvFile, from, to int, ws int) (int, bool) { + if f.toks[from].line != f.toks[to].line { + return 0, true + } + if f.isWS(ws) { + return f.toks[ws].length, false + } + return 0, false +} + +// clearAfter replaces the whitespace tokens after i with nothing. +func clearWhitespaceAfter(f *slvFile, i int) { + for j := i + 1; j < len(f.toks) && f.isWS(j); j++ { + f.replaceToken(j, "") + } +} + +func (r FunctionDeclarationArgumentSpacing) processBracket(f *slvFile, open int) { + closeIdx := f.toks[open].closer + multiLine := f.toks[open].line != f.toks[closeIdx].line + params := phpcsMethodParameters(f, open) + + if len(params) == 0 { + if f.nextNot(f.isWS, open+1, closeIdx) < 0 { + if closeIdx-open != 1 { + f.beginChangeset() + for j := open + 1; f.isWS(j); j++ { + f.replaceToken(j, "") + } + f.endChangeset() + } + return + } + } + + for n, p := range params { + if p.referenceToken >= 0 && f.isWS(p.referenceToken+1) { + f.beginChangeset() + clearWhitespaceAfter(f, p.referenceToken) + f.endChangeset() + } + if p.variadicToken >= 0 && f.isWS(p.variadicToken+1) { + f.beginChangeset() + clearWhitespaceAfter(f, p.variadicToken) + f.endChangeset() + } + if p.equalToken >= 0 { + r.equalsSide(f, p.token, p.equalToken, p.token+1, p.equalToken) + r.equalsSide(f, p.equalToken, p.defaultToken, p.equalToken+1, p.defaultToken) + } + if p.typeHintToken >= 0 { + end := p.typeHintEndToken + var gap strings.Builder + for j := end + 1; f.isWS(j); j++ { + gap.WriteString(f.toks[j].content) + } + if gap.String() != " " { + f.beginChangeset() + f.addContent(end, " ") + clearWhitespaceAfter(f, end) + f.endChangeset() + } + } + for _, mod := range []int{p.visibilityToken, p.setVisibilityToken, p.readonlyToken} { + if mod < 0 { + continue + } + after := f.nextNot(f.isWS, mod+1, p.token) + spaces := 0 + if after >= 0 && f.toks[mod].line != f.toks[after].line { + spaces = -1 + } else if f.isWS(mod + 1) { + spaces = f.toks[mod+1].length + } + if spaces != 1 { + f.beginChangeset() + f.addContent(mod, " ") + clearWhitespaceAfter(f, mod) + f.endChangeset() + } + } + + if n == 0 || params[n-1].commaToken < 0 { + continue + } + comma := params[n-1].commaToken + endOfPrev := f.prevEffective(comma - 1) + spaceBefore := 0 + if f.toks[endOfPrev].line != f.toks[comma].line { + spaceBefore = -1 + } else if f.isWS(comma - 1) { + spaceBefore = f.toks[comma-1].length + } + if spaceBefore != 0 { + startOfCurr := f.nextEffective(comma+1, len(f.toks)) + f.beginChangeset() + f.addContent(endOfPrev, ",") + f.replaceToken(comma, "") + if f.toks[comma].line == f.toks[startOfCurr].line { + clearWhitespaceAfter(f, comma) + } else { + for j := comma - 1; f.isWS(j) && f.toks[endOfPrev].line != f.toks[j].line; j-- { + f.replaceToken(j, "") + } + for j := comma + 1; f.isWS(j) && f.toks[comma].line == f.toks[j].line; j++ { + f.replaceToken(j, "") + } + } + f.endChangeset() + } + + if multiLine { + next := f.nextEffective(comma+1, closeIdx) + nextLine := f.toks[0].line + if next >= 0 { + nextLine = f.toks[next].line + } + if nextLine != f.toks[comma].line { + continue + } + } + spacesAfter := 0 + if f.isWS(comma + 1) { + spacesAfter = f.toks[comma+1].length + } + switch { + case spacesAfter == 0: + f.addContent(comma, " ") + case spacesAfter != 1: + f.replaceToken(comma+1, " ") + } + } + + if multiLine { + return + } + gap := 0 + if f.isWS(closeIdx - 1) { + gap = f.toks[closeIdx-1].length + } + if gap != r.RequiredSpacesBeforeClose { + padding := strings.Repeat(" ", r.RequiredSpacesBeforeClose) + if gap == 0 { + f.addContentBefore(closeIdx, padding) + } else { + f.replaceToken(closeIdx-1, padding) + } + } + gap = 0 + if f.isWS(open + 1) { + gap = f.toks[open+1].length + } + if gap != r.RequiredSpacesAfterOpen { + padding := strings.Repeat(" ", r.RequiredSpacesAfterOpen) + if gap == 0 { + f.addContent(open, padding) + } else { + f.replaceToken(open+1, padding) + } + } +} + +// equalsSide checks the spacing between from and to (the parameter and its +// "=", or the "=" and the default value), fixing it when only whitespace sits +// between them. +func (r FunctionDeclarationArgumentSpacing) equalsSide(f *slvFile, from, to, ws, searchEnd int) { + spaces, newline := r.gapTo(f, from, to, ws) + if !newline && spaces == r.EqualsSpacing { + return + } + if f.nextNot(f.isWS, from+1, searchEnd) >= 0 { + return + } + f.beginChangeset() + f.addContent(from, strings.Repeat(" ", r.EqualsSpacing)) + clearWhitespaceAfter(f, from) + f.endChangeset() +} + +// phpcsParam is one entry of File::getMethodParameters; token indexes are -1 +// when unset. +type phpcsParam struct { + token, defaultToken, equalToken, referenceToken, variadicToken int + typeHintToken, typeHintEndToken int + visibilityToken, setVisibilityToken, readonlyToken, commaToken int +} + +// phpcsTypeParen reports whether the "(" or ")" at i belongs to a DNF type in +// a parameter list rather than to an expression. +func phpcsTypeParen(f *slvFile, i, open int) bool { + if f.is(i, ")") { + i = f.toks[i].closer + if i < 0 { + return false + } + } + p := f.prevEffective(i - 1) + if p == open || f.is(p, ",") || f.is(p, "|") || p >= 0 && f.toks[p].kind == token.AttributeEnd { + return true + } + if p < 0 || f.toks[p].kind != token.Keyword { + return false + } + switch kw := strings.ToLower(f.toks[p].orig); { + case kw == "public" || kw == "protected" || kw == "private" || kw == "readonly" || kw == "final", + strings.HasSuffix(kw, "(set)"): + return true + } + return false +} + +// phpcsMethodParameters is File::getMethodParameters for the parameter list +// opening at open. +func phpcsMethodParameters(f *slvFile, open int) []phpcsParam { + closeIdx := f.toks[open].closer + if closeIdx < 0 { + return nil + } + var vars []phpcsParam + reset := func() phpcsParam { + return phpcsParam{token: -1, defaultToken: -1, equalToken: -1, referenceToken: -1, variadicToken: -1, + typeHintToken: -1, typeHintEndToken: -1, visibilityToken: -1, setVisibilityToken: -1, readonlyToken: -1, + commaToken: -1} + } + cur := reset() + defaultStart := -1 + typeTok := func(i int) { + if defaultStart >= 0 { + return + } + if cur.typeHintToken < 0 { + cur.typeHintToken = i + } + cur.typeHintEndToken = i + } + for i := open + 1; i <= closeIdx; i++ { + t := f.toks[i] + if (f.is(i, "(") || f.is(i, ")")) && t.closer >= 0 && i != closeIdx { + if defaultStart < 0 && phpcsTypeParen(f, i, open) { + typeTok(i) + continue + } + if f.is(i, "(") { + i = t.closer + } + continue + } + if (f.is(i, "[") || f.is(i, "{")) && t.closer > i { + i = t.closer + continue + } + if f.isParamName(i) { + continue + } + switch t.kind { + case token.AttributeStart: + if t.closer > i { + i = t.closer + } + case token.Variable: + cur.token = i + case token.Ident: + lower := strings.ToLower(t.orig) + switch lower { + case "self", "parent": + typeTok(i) + continue + case "true", "false", "null": + typeTok(i) + continue + } + prevComma := -1 + for k := i; k >= open; k-- { + if f.is(k, ",") { + prevComma = k + break + } + } + if prevComma >= 0 { + eq := false + for k := prevComma; k < i; k++ { + if f.is(k, "=") { + eq = true + break + } + } + if eq { + continue + } + } + typeTok(i) + case token.Keyword: + kw := strings.ToLower(t.orig) + switch { + case kw == "callable": + if cur.typeHintToken < 0 { + cur.typeHintToken = i + } + cur.typeHintEndToken = i + case kw == "static" || kw == "namespace": + typeTok(i) + case kw == "array" && !f.is(f.nextEffective(i+1, len(f.toks)), "("): + typeTok(i) + case kw == "public" || kw == "protected" || kw == "private": + if defaultStart < 0 { + cur.visibilityToken = i + } + case strings.HasSuffix(kw, "(set)"): + if defaultStart < 0 { + cur.setVisibilityToken = i + } + case kw == "readonly": + if defaultStart < 0 { + cur.readonlyToken = i + } + } + case token.Punct: + switch t.orig { + case "&": + if n := f.nextEffective(i+1, len(f.toks)); n >= 0 && f.toks[n].kind == token.Variable || f.is(n, "...") { + if defaultStart < 0 { + cur.referenceToken = i + } + } else { + typeTok(i) + } + case "|", "\\": + typeTok(i) + case "?": + if defaultStart < 0 { + cur.typeHintEndToken = i + } + case "...": + cur.variadicToken = i + case "=": + defaultStart = f.nextEffective(i+1, len(f.toks)) + cur.equalToken = i + case ")", ",": + if cur.token < 0 { + continue + } + if defaultStart >= 0 { + cur.defaultToken = defaultStart + } else { + cur.equalToken = -1 + } + if t.orig == "," { + cur.commaToken = i + } + vars = append(vars, cur) + cur = reset() + defaultStart = -1 + } + } + } + return vars +} + +// isParamName reports whether the word at i is a named-argument label, which +// PHP_CodeSniffer's tokenizer turns into T_PARAM_NAME: a name followed by ":" +// right after "(" or ",". +func (f *slvFile) isParamName(i int) bool { + k := f.toks[i].kind + if k != token.Ident && k != token.Keyword || strings.Contains(f.toks[i].orig, `\`) { + return false + } + p := f.prevEffective(i - 1) + return f.is(f.nextEffective(i+1, len(f.toks)), ":") && (f.is(p, "(") || f.is(p, ",")) +} diff --git a/blink/internal/fixer/rules/multi_line_function_declaration.go b/blink/internal/fixer/rules/multi_line_function_declaration.go new file mode 100644 index 0000000000..5ad262cc97 --- /dev/null +++ b/blink/internal/fixer/rules/multi_line_function_declaration.go @@ -0,0 +1,128 @@ +package rules + +import ( + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php +// +// MultiLineFunctionDeclaration is PEAR FunctionDeclaration that also calls a +// declaration multi-line when its parameters span lines, puts each parameter +// of such a declaration on its own line and keeps a single-line one's ")" on +// the last parameter's line. +type MultiLineFunctionDeclaration struct { + Indent int +} + +func (MultiLineFunctionDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff` +} + +func (MultiLineFunctionDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php" +} + +func (m MultiLineFunctionDeclaration) WithConfig(config map[string]any) fixer.Fixer { + m.Indent = configInt(config, "indent", m.Indent) + return m +} + +func (m MultiLineFunctionDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + var sc *phpcsScope + for i := range f.toks { + fn, ok := phpcsFunctionAt(f, i) + if !ok { + continue + } + if sc == nil { + sc = newPhpcsScope(f) + } + m.process(f, sc, fn) + } + }) +} + +func (m MultiLineFunctionDeclaration) process(f *slvFile, sc *phpcsScope, fn phpcsFn) { + pear := PEARFunctionDeclaration(m) + pear.processHead(f, fn) + if !m.isMultiLine(f, sc, fn) { + pearSingleLineBrace(f, fn) + m.closerOnParamLine(f, fn) + return + } + pear.processMultiLine(f, fn) + m.processBracket(f, fn.openParen) + if open, _ := fn.useParens(f); open >= 0 { + m.processBracket(f, open) + } +} + +func (MultiLineFunctionDeclaration) isMultiLine(f *slvFile, sc *phpcsScope, fn phpcsFn) bool { + type bracket struct{ ptr, open int } + check := []bracket{{fn.ptr, fn.openParen}} + if open, _ := fn.useParens(f); open >= 0 { + check = append(check, bracket{fn.use, open}) + } +next: + for _, b := range check { + if n := f.nextEffective(b.open+1, len(f.toks)); n < 0 || f.toks[n].line != f.toks[b.ptr].line { + return true + } + closeIdx := f.toks[b.open].closer + end := sc.endOfStatement(b.open + 1) + for f.is(end, ",") { + n := f.nextEffective(end+1, closeIdx) + if n < 0 { + continue next + } + if f.toks[n].line != f.toks[end].line { + return true + } + end = sc.endOfStatement(n) + } + if n := f.nextEffective(end+1, closeIdx); n >= 0 && f.toks[n].line != f.toks[end].line { + return true + } + } + return false +} + +// closerOnParamLine removes a newline before the ")" of a single-line +// declaration. +func (MultiLineFunctionDeclaration) closerOnParamLine(f *slvFile, fn phpcsFn) { + open, closeIdx := fn.openParen, fn.closeParen + prev := f.prevNot(f.isWS, closeIdx-1, open-1) + if prev < 0 || f.toks[prev].line == f.toks[closeIdx].line || f.isEmpty(prev) { + return + } + f.beginChangeset() + for i := closeIdx - 1; i > open && f.isWS(i); i-- { + f.replaceToken(i, "") + } + f.endChangeset() +} + +func (MultiLineFunctionDeclaration) processBracket(f *slvFile, open int) { + closeIdx := f.toks[open].closer + if f.toks[open].line != f.toks[closeIdx].line { + if n := f.nextEffective(open+1, len(f.toks)); n >= 0 && f.toks[n].line == f.toks[open].line { + f.addContent(open, f.eol) + } + } + for i := open + 1; i < closeIdx; i++ { + t := f.toks[i] + if (f.is(i, "(") || f.is(i, "[") || f.is(i, "{") || t.kind == token.AttributeStart) && t.closer > i { + i = t.closer + continue + } + if !f.is(i, ",") { + continue + } + if n := f.nextEffective(i+1, len(f.toks)); n >= 0 && f.toks[n].line == t.line { + f.addContent(i, f.eol) + } + } +} diff --git a/blink/internal/fixer/rules/operator_bracket.go b/blink/internal/fixer/rules/operator_bracket.go new file mode 100644 index 0000000000..66effee827 --- /dev/null +++ b/blink/internal/fixer/rules/operator_bracket.go @@ -0,0 +1,337 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/lexer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php +// +// OperatorBracket wraps arithmetic and bitwise operations in parentheses: +// "$a = $b + 1;" -> "$a = ($b + 1);". +type OperatorBracket struct{} + +func (OperatorBracket) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Formatting\OperatorBracketSniff` +} + +func (OperatorBracket) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php" +} + +// Tokens::OPERATORS. +var obOperators = phpcsSet("+", "-", "*", "/", "%", "**", "<=>", "??", "&", "|", "^", "<<", ">>") + +var obAssignment = phpcsSet("=", "&=", "|=", ".=", "/=", "-=", "**=", "%=", "*=", "+=", "^=", "double_arrow", + "<<=", ">>=", "??=") + +var obComparison = phpcsSet("==", "!=", "<>", "===", "!==", "<=", ">=", "<", ">", "<=>", "??") + +var obInvalidBefore = phpcsSet(",", "colon", "(", "[", "{", "open_short_array", "case", "exit", "match_arrow") + +// allowed inside a bracketed operation of a function call, besides operators and names +var obAllowedInside = phpcsSet("variable", "lnumber", "whitespace", "self", "static", "parent", "->", "?->", "::", + "[", "]", "~") + +// addMissingBracketsError's allowed tokens, besides empty, operator, cast and name tokens +var obAllowedExpr = phpcsSet("variable", "lnumber", "constant_encapsed_string", "double_quoted_string", "whitespace", + "self", "static", "->", "?->", "::", "isset", "array", "~") + +type obFile struct { + f *slvFile + sc *phpcsScope + code []string + notOpRef map[int]bool // "&" references and "|"/"&" type operators +} + +func (OperatorBracket) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + o := newObFile(f) + for i := range f.toks { + if o.isOperator(i) { + o.process(i) + } + } + }) +} + +func newObFile(f *slvFile) *obFile { + o := &obFile{f: f, sc: newPhpcsScope(f), code: make([]string, len(f.toks)), notOpRef: map[int]bool{}} + for i := range f.toks { + o.code[i] = o.classify(i) + } + o.markReferences() + return o +} + +// markReferences finds the "&" File::isReference accepts and the "|"/"&" the +// tokenizer turns into type operators, on a stream of the same source. +func (o *obFile) markReferences() { + f := o.f + var b strings.Builder + at := map[int]int{} + for i, t := range f.toks { + if t.kind == token.Punct && (t.orig == "&" || t.orig == "|") { + at[b.Len()] = i + } + b.WriteString(t.orig) + } + if len(at) == 0 { + return + } + s := tokens.New(lexer.Lex(b.String())) + ctx := newPhpcsOperatorContext(s) + off := 0 + for i := 0; i < s.Len(); i++ { + t := s.At(i) + if j, ok := at[off]; ok && t.Kind == token.Punct && (t.Value == "&" || t.Value == "|") { + if phpcsTypeOperator(s, i) || t.Value == "&" && ctx.isReference(s, i) { + o.notOpRef[j] = true + } + } + off += len(t.Value) + } +} + +func (o *obFile) classify(i int) string { + f := o.f + t := f.toks[i] + if f.isParamName(i) { + return "param_name" + } + switch t.kind { + case token.Variable: + if t.orig == "$" { + return "dollar_open_curly_braces" + } + case token.Number: + return "lnumber" + case token.String: + switch { + case t.heredoc: + return "heredoc" + case t.interp: + return "double_quoted_string" + } + return "constant_encapsed_string" + case token.Ident: + switch strings.ToLower(t.orig) { + case "true", "false", "null", "self", "parent": + if p := f.prevEffective(i - 1); !f.is(p, "->") && !f.is(p, "?->") && !f.is(p, "::") { + return strings.ToLower(t.orig) + } + } + case token.Keyword: + if p := f.prevEffective(i - 1); f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") { + return "string" + } + case token.Punct: + switch { + case len(t.orig) > 2 && t.orig[0] == '(': + if strings.EqualFold(strings.Trim(t.orig, "( \t)"), "void") { + return "void_cast" + } + return "cast" + case t.orig == "[" && f.isShortArrayOpen(i): + return "open_short_array" + case t.orig == "]" && t.closer >= 0 && f.isShortArrayOpen(t.closer): + return "close_short_array" + case t.orig == "=>": + if c := o.sc.code[i]; c == "match_arrow" || c == "fn_arrow" { + return c + } + return "double_arrow" + case t.orig == ":": + if o.sc.code[i] == "inline_else" { + return "inline_else" + } + return "colon" + } + } + return o.sc.code[i] +} + +func (o *obFile) isEmpty(i int) bool { return o.f.isEmpty(i) } + +func (o *obFile) isName(i int) bool { return o.code[i] == "string" } + +func (o *obFile) isOperator(i int) bool { + return o.f.toks[i].kind == token.Punct && obOperators[o.code[i]] && !o.notOpRef[i] +} + +func (o *obFile) isEquality(i int) bool { + switch o.code[i] { + case "==", "!=", "<>", "===", "!==", "<=", ">=": + return true + } + return false +} + +func (o *obFile) process(ptr int) { + f, code := o.f, o.code + if code[ptr] == "-" { + prev := f.prevEffective(ptr - 1) + if prev >= 0 && code[prev] == "return" { + return + } + number := f.nextNonWhitespace(ptr+1, len(f.toks)) + if number >= 0 && code[number] == "lnumber" { + if previous := f.prevNonWhitespace(ptr - 1); previous >= 0 { + if obAssignment[code[previous]] || o.isEquality(previous) || obComparison[code[previous]] || o.isOperator(previous) { + return + } + } + } + } + + if prevTok := f.prevNonWhitespace(ptr - 1); prevTok >= 0 && obInvalidBefore[code[prevTok]] { + return + } + + if code[ptr] == "|" { + if p := o.sc.nested[ptr]; p >= 0 && o.sc.pOwner[p] >= 0 && code[o.sc.pOwner[p]] == "catch" { + return + } + } + + allowed := func(i int) bool { + c := code[i] + return o.isName(i) || o.isOperator(i) || obAllowedInside[c] + } + + lastBracket := -1 + for bracket := o.sc.nested[ptr]; bracket >= 0; bracket = o.sc.nested[bracket] { + endBracket := f.toks[bracket].closer + prevToken := f.prevNonWhitespace(bracket - 1) + prevCode := "" + if prevToken >= 0 { + prevCode = code[prevToken] + } + if prevCode == "isset" { + break + } + if prevToken >= 0 && o.isName(prevToken) || prevCode == "switch" || prevCode == "match" { + prev := ptr - 1 + for ; prev > bracket; prev-- { + if allowed(prev) { + continue + } + if code[prev] == ")" && f.toks[prev].closer >= 0 { + prev = f.toks[prev].closer + } else { + break + } + } + if prev != bracket { + break + } + next := ptr + 1 + for ; next < endBracket; next++ { + if allowed(next) { + continue + } + if code[next] == "(" && f.toks[next].closer >= 0 { + next = f.toks[next].closer + } else { + break + } + } + if next != endBracket { + break + } + } + if phpcsScopeOpenerCodes[prevCode] && prevCode != "switch" && prevCode != "match" { + break + } + if prevCode == "(" && endBracket < ptr { + continue + } + lastBracket = bracket + break + } + + if lastBracket < 0 || f.toks[lastBracket].closer < ptr { + o.addMissingBrackets(ptr) + return + } + square := -1 + for j := ptr - 1; j >= lastBracket; j-- { + if code[j] == "[" || code[j] == "]" { + square = j + break + } + } + if square >= 0 && code[square] == "[" { + for j := ptr + 1; j < len(f.toks); j++ { + if code[j] == "[" || code[j] == "]" { + if code[j] == "]" { + o.addMissingBrackets(ptr) + } + break + } + } + } +} + +func (o *obFile) exprToken(i int, after bool) bool { + c := o.code[i] + return o.isEmpty(i) || o.isOperator(i) || c == "cast" || c == "void_cast" || o.isName(i) || obAllowedExpr[c] || + after && (c == "=" || c == "new") +} + +func (o *obFile) addMissingBrackets(ptr int) { + f, code := o.f, o.code + before := ptr - 1 + for ; before > 0; before-- { + if o.exprToken(before, false) { + continue + } + c := code[before] + if (c == ")" || c == "]" || c == "close_short_array") && f.toks[before].closer >= 0 { + before = f.toks[before].closer + continue + } + break + } + before = f.nextEffective(before+1, len(f.toks)) + if before < 0 || code[before] == "void_cast" || o.isVoidCastParen(before) { + return + } + + after := ptr + 1 + for ; after < len(f.toks); after++ { + if o.exprToken(after, true) { + continue + } + c := code[after] + if c == "(" || c == "[" || c == "open_short_array" { + if f.toks[after].closer < 0 { + return + } + after = f.toks[after].closer + continue + } + break + } + after = f.prevEffective(after - 1) + if before == after || before == ptr || after == ptr { + return + } + f.beginChangeset() + f.replaceToken(before, "("+f.toks[before].content) + f.replaceToken(after, f.toks[after].content+")") + f.endChangeset() +} + +// isVoidCastParen reports whether the "(" at i opens "(void)", a cast PHP +// 8.5 lexes as T_VOID_CAST. +func (o *obFile) isVoidCastParen(i int) bool { + f := o.f + if !f.is(i, "(") || f.toks[i].closer < 0 { + return false + } + return strings.EqualFold(strings.Trim(f.content(i+1, f.toks[i].closer-1), " \t"), "void") +} diff --git a/blink/internal/fixer/rules/pear_function_comment.go b/blink/internal/fixer/rules/pear_function_comment.go index 333785f05f..9bdf6aae01 100644 --- a/blink/internal/fixer/rules/pear_function_comment.go +++ b/blink/internal/fixer/rules/pear_function_comment.go @@ -56,8 +56,17 @@ func pearIsMethodModifier(f *slvFile, i int) bool { } func pearFunctionComment(f *slvFile, ptr int) { + if commentEnd, tags, ok := pearFunctionCommentPreamble(f, ptr); ok { + pearProcessParams(f, commentEnd, tags) + } +} + +// pearFunctionCommentPreamble is the part of PEAR's process() before the +// processReturn/processThrows/processParams calls: it finds the docblock and +// removes blank lines after it, returning its closer and tags. +func pearFunctionCommentPreamble(f *slvFile, ptr int) (commentEnd int, tags []int, ok bool) { ignored := func(i int) bool { return f.toks[i].kind == token.Whitespace || pearIsMethodModifier(f, i) } - commentEnd := ptr - 1 + commentEnd = ptr - 1 for ; commentEnd >= 0; commentEnd-- { if ignored(commentEnd) { continue @@ -69,7 +78,7 @@ func pearFunctionComment(f *slvFile, ptr int) { break } if commentEnd < 0 { - return + return 0, nil, false } isComment := func(i int) bool { return f.toks[i].kind == token.Comment && !phpcsIsAnnotation(f, i) } if isComment(commentEnd) { @@ -82,7 +91,7 @@ func pearFunctionComment(f *slvFile, ptr int) { } } if f.toks[commentEnd].doc != slvDocClose { - return + return 0, nil, false } if f.toks[commentEnd].line != f.toks[ptr].line-1 { @@ -112,13 +121,12 @@ func pearFunctionComment(f *slvFile, ptr int) { for commentStart > 0 && f.toks[commentStart].doc != slvDocOpen { commentStart-- } - var tags []int for i := commentStart + 1; i < commentEnd; i++ { if f.toks[i].doc == slvDocTag { tags = append(tags, i) } } - pearProcessParams(f, commentEnd, tags) + return commentEnd, tags, true } // phpcsAttributeCloser is the attribute_closer PHP_CodeSniffer gives every diff --git a/blink/internal/fixer/rules/pear_function_declaration.go b/blink/internal/fixer/rules/pear_function_declaration.go index e9cdacd8a3..cd6411d2ef 100644 --- a/blink/internal/fixer/rules/pear_function_declaration.go +++ b/blink/internal/fixer/rules/pear_function_declaration.go @@ -119,6 +119,29 @@ func phpcsSpacesAt(f *slvFile, i int) int { } func (d PEARFunctionDeclaration) process(f *slvFile, fn phpcsFn) { + d.processHead(f, fn) + if d.isMultiLine(f, fn) { + d.processMultiLine(f, fn) + return + } + pearSingleLineBrace(f, fn) +} + +// pearSingleLineBrace is processSingleLineDeclaration: K&R braces for a +// closure, BSD/Allman for a function. +func pearSingleLineBrace(f *slvFile, fn phpcsFn) { + if fn.scopeOpener < 0 { + return + } + if fn.closure { + openingFunctionBraceKernighanRitchie(f, fn.scopeOpener) + return + } + openingFunctionBraceBsdAllman(f, fn.ptr, fn.closeParen, fn.scopeOpener) +} + +// processHead is the part of process before the single/multi-line split. +func (d PEARFunctionDeclaration) processHead(f *slvFile, fn phpcsFn) { stackPtr := fn.ptr if strings.ToLower(f.toks[stackPtr].orig) == "function" { if spaces := phpcsSpacesAt(f, stackPtr+1); spaces != 1 { @@ -166,18 +189,6 @@ func (d PEARFunctionDeclaration) process(f *slvFile, fn phpcsFn) { } } - if d.isMultiLine(f, fn) { - d.processMultiLine(f, fn) - return - } - if fn.scopeOpener < 0 { - return - } - if fn.closure { - openingFunctionBraceKernighanRitchie(f, fn.scopeOpener) - return - } - openingFunctionBraceBsdAllman(f, stackPtr, fn.closeParen, fn.scopeOpener) } func phpcsUseGap(f *slvFile, i int) int { diff --git a/blink/internal/fixer/rules/phpcs_scope.go b/blink/internal/fixer/rules/phpcs_scope.go index 286278050f..faeb34b1f3 100644 --- a/blink/internal/fixer/rules/phpcs_scope.go +++ b/blink/internal/fixer/rules/phpcs_scope.go @@ -1,6 +1,7 @@ package rules import ( + "slices" "strings" "github.com/ecsphp/ecs-src/blink/internal/token" @@ -20,6 +21,10 @@ type phpcsScope struct { pOwner []int // parenthesis_owner of a "(" nested []int // the innermost "(" holding the token scopes []phpcsScopeRange + // the scope map as createLevelMap sees it, before processAdditional + preCond, preOpener, preCloser []int + // CASE/DEFAULT statements fixCases gave a braced body: case, new closer, old closer + caseFixes [][3]int } // phpcsScopeRange is a scope the level map counts: the tokens strictly @@ -94,6 +99,7 @@ func newPhpcsScope(f *slvFile) *phpcsScope { i = sc.recurse(i, 1, &ignore) } } + sc.preCond, sc.preOpener, sc.preCloser = slices.Clone(sc.cond), slices.Clone(sc.opener), slices.Clone(sc.closer) sc.fixCases() for i := range n { if sc.cond[i] == i && sc.opener[i] > i && sc.closer[i] > sc.opener[i] { @@ -163,7 +169,13 @@ func (sc *phpcsScope) isEnd(i int) bool { // startOfStatement is File::findStartOfStatement. func (sc *phpcsScope) startOfStatement(start int) int { + return sc.startOfStatementIgnoring(start) +} + +// startOfStatementIgnoring is File::findStartOfStatement with its $ignore codes. +func (sc *phpcsScope) startOfStatementIgnoring(start int, ignore ...string) int { f := sc.f + isEnd := func(i int) bool { return sc.isEnd(i) && !slices.Contains(ignore, sc.code[i]) } if conds := sc.conditions(start); len(conds) > 0 { match := conds[len(conds)-1] if sc.code[match] == "match" && sc.nested[match] == sc.nested[start] { @@ -172,7 +184,7 @@ func (sc *phpcsScope) startOfStatement(start int) int { } } } - for sc.isEnd(start) || sc.cond[start] >= 0 && start == sc.closer[start] { + for isEnd(start) || sc.cond[start] >= 0 && start == sc.closer[start] { if sc.cond[start] >= 0 { start = sc.cond[start] } else { @@ -183,9 +195,11 @@ func (sc *phpcsScope) startOfStatement(start int) int { for i := start; i >= 0; i-- { switch sc.code[i] { case "{", "[", "(", "open_tag": - return lastNotEmpty + if !slices.Contains(ignore, sc.code[i]) { + return lastNotEmpty + } } - if sc.isEnd(i) { + if isEnd(i) { return lastNotEmpty } if sc.opener[i] >= 0 && i == sc.closer[i] { @@ -667,6 +681,7 @@ func (sc *phpcsScope) fixCases() { continue } newCloser := f.toks[x].closer + sc.caseFixes = append(sc.caseFixes, [3]int{i, newCloser, scopeCloser}) for _, idx := range []int{i, x, newCloser} { sc.set(idx, i, x, newCloser) } @@ -684,3 +699,129 @@ func (sc *phpcsScope) fixCases() { } } } + +func phpcsFirstEnd(code string) string { + switch code { + case "case", "default": + return "break" + case "start_heredoc": + return "end_heredoc" + } + return "}" +} + +// phpcsCond is one entry of a token's conditions: the scope condition's +// token, or, with caseIndex, the entry PHP::processAdditional appends to the +// old closer of a CASE it gives a braced body, which holds the CASE's index +// instead of its code. +type phpcsCond struct { + key int + caseIndex bool +} + +// levelMap is Tokenizer::createLevelMap plus the condition fixes of +// PHP::processAdditional: each token's conditions, outermost first, and level, +// which a shared closer can leave apart from len(conditions). +func (sc *phpcsScope) levelMap() (conds [][]phpcsCond, levels []int) { + n := len(sc.code) + conds, levels = make([][]phpcsCond, n), make([]int, n) + nextFree := make([]int, n) + remove := func(list []phpcsCond, key int) []phpcsCond { + out := list[:0:0] + for _, c := range list { + if c.key != key || c.caseIndex { + out = append(out, c) + } + } + return out + } + level, free := 0, 0 + var conditions []phpcsCond + var openers []int + lastOpener := -1 + for i := range n { + levels[i], conds[i], nextFree[i] = level, conditions, free + if sc.preCond[i] < 0 { + continue + } + if sc.preOpener[i] == i { + stackPtr := sc.preCond[i] + if lastOpener >= 0 && sc.preCloser[lastOpener] == sc.preCloser[i] { + thisType := sc.code[sc.preCond[i]] + opener := sc.preCond[lastOpener] + isShared := phpcsScopeOpeners[thisType].with[sc.code[opener]] + if isShared && phpcsFirstEnd(thisType) == phpcsFirstEnd(sc.code[opener]) { + for x := sc.preCond[i]; x <= i; x++ { + levels[x]-- + conds[x] = remove(conds[x], opener) + } + conditions = remove(conditions, opener) + if k := slices.Index(openers, lastOpener); k >= 0 { + openers = slices.Delete(openers, k, k+1) + } + level-- + } + } + level++ + if !slices.Contains(conditions, phpcsCond{key: stackPtr}) { + conditions = append(slices.Clone(conditions), phpcsCond{key: stackPtr}) + free = max(free, stackPtr+1) + } + lastOpener = sc.preOpener[i] + if !slices.Contains(openers, lastOpener) { + openers = append(openers, lastOpener) + } + continue + } + if lastOpener < 0 || sc.preCloser[lastOpener] != i { + continue + } + reversed := slices.Clone(openers) + slices.Reverse(reversed) + for _, opener := range reversed { + if sc.preCloser[opener] != i { + continue + } + oldOpener := openers[len(openers)-1] + openers = openers[:len(openers)-1] + lastOpener = -1 + if len(openers) > 0 { + lastOpener = openers[len(openers)-1] + } + oldCondition := "" + if len(conditions) > 0 { + last := conditions[len(conditions)-1] + oldCondition = sc.code[last.key] + if last.key == free-1 { + free-- + } + conditions = slices.Clone(conditions[:len(conditions)-1]) + } + condition := sc.code[sc.preCond[i]] + if condition != oldCondition && !phpcsScopeOpeners[oldCondition].with[condition] { + badToken := sc.preCond[oldOpener] + for x := oldOpener + 1; x <= i; x++ { + levels[x]-- + conds[x] = remove(conds[x], badToken) + } + } + level-- + levels[i], conds[i], nextFree[i] = level, conditions, free + } + } + for _, fix := range sc.caseFixes { + i, newCloser, scopeCloser := fix[0], fix[1], fix[2] + conds[scopeCloser] = append(slices.Clone(conds[scopeCloser]), phpcsCond{key: nextFree[scopeCloser], caseIndex: true}) + nextFree[scopeCloser]++ + for x := newCloser; x < scopeCloser; x++ { + out := conds[x][:0:0] + for _, c := range conds[x] { + if c.caseIndex || sc.code[c.key] != sc.code[i] { + out = append(out, c) + } + } + conds[x] = out + } + } + return conds, levels +} diff --git a/blink/internal/fixer/rules/priorities.go b/blink/internal/fixer/rules/priorities.go index 3c3eb2776a..6f9bc9511a 100644 --- a/blink/internal/fixer/rules/priorities.go +++ b/blink/internal/fixer/rules/priorities.go @@ -75,6 +75,7 @@ var fixerPriority = map[string]int{ "FunctionSpacingSniff": 0, "MemberVarSpacingSniff": 0, "SelfMemberReferenceSniff": 0, + "ControlSignatureSniff": 0, "EmptyPHPStatementSniff": 0, "DisallowMultipleStatementsSniff": 0, "InlineControlStructureSniff": 0, @@ -138,6 +139,10 @@ var fixerPriority = map[string]int{ "ConcatenationSpacingSniff": 0, "InlineIfDeclarationSniff": 0, "IncrementDecrementSpacingSniff": 0, + "OperatorBracketSniff": 0, + "FunctionDeclarationArgumentSpacingSniff": 0, + "MultiLineFunctionDeclarationSniff": 0, + "ScopeIndentSniff": 0, "MethodDeclarationSniff": 0, "UseDeclarationSniff": 0, "PropertyDeclarationSniff": 0, @@ -160,6 +165,7 @@ var fixerPriority = map[string]int{ "DisallowSpaceIndentSniff": 0, "ArrayIndentSniff": 0, "ClassDeclarationSniff": 0, + "ArrayDeclarationSniff": 0, "AnonClassDeclarationSniff": 0, "ScopeClosingBraceSniff": 0, "SwitchDeclarationSniff": 0, @@ -186,9 +192,13 @@ var fixerPriority = map[string]int{ "FileCommentSniff": 0, "LongConditionClosingCommentSniff": 0, "VariableCommentSniff": 0, + "BlockCommentSniff": 0, "DocCommentAlignmentSniff": 0, + "EmbeddedPhpSniff": 0, "UselessParenthesesSniff": 0, - "UselessSemicolonSniff": 0, + // raised from 0 so an empty statement is gone before whitespace sniffs look + // past a closing brace, as NoEmptyStatementFixer (40) does + "UselessSemicolonSniff": 1, // getPriority() is 0 upstream; raised to run before blank_line_after_opening_tag // so blink reaches the same output in a single pass (PHP-CS-Fixer loops to fixpoint) "LinebreakAfterOpeningTagFixer": 2, diff --git a/blink/internal/fixer/rules/registry.go b/blink/internal/fixer/rules/registry.go index 4c67ccbb74..0b98e331f2 100644 --- a/blink/internal/fixer/rules/registry.go +++ b/blink/internal/fixer/rules/registry.go @@ -306,6 +306,8 @@ func ConstructFixers() []fixer.Fixer { EmptyPHPStatement{}, DisallowMultipleStatements{}, InlineControlStructure{}, + SquizControlSignature{RequiredSpacesBeforeColon: 1}, + SquizSwitchDeclaration{Indent: 4}, LowercaseDeclaration{}, EndFileNewline{}, EndFileNoNewline{}, @@ -341,6 +343,10 @@ func ConstructFixers() []fixer.Fixer { ConcatenationSpacing{}, InlineIfDeclaration{}, IncrementDecrementSpacing{}, + OperatorBracket{}, + FunctionDeclarationArgumentSpacing{}, + MultiLineFunctionDeclaration{Indent: 4}, + ScopeIndent{Indent: 4}, MethodDeclaration{}, TraitUseDeclaration{}, PropertyDeclaration{}, @@ -375,16 +381,23 @@ func ConstructFixers() []fixer.Fixer { LongConditionClosingComment{LineLimit: 20, CommentFormat: "//end %s"}, VariableComment{}, DocCommentAlignment{}, + SquizBlockComment{}, PEARClassDeclaration{}, PSR2ClassDeclaration{Indent: 4}, + SquizClassDeclaration{Indent: 4}, + SquizArrayDeclaration{}, PSR12AnonClassDeclaration{Indent: 4}, PSR2ControlStructureSpacing{}, PSR12ControlStructureSpacing{Indent: 4}, BooleanOperatorPlacement{}, MultiLineCondition{Indent: 4}, PearScopeClosingBrace{Indent: 4}, + SquizScopeClosingBrace{}, PSR2SwitchDeclaration{Indent: 4}, PearObjectOperatorIndent{Indent: 4}, + SquizFunctionComment{}, + EmbeddedPhp{}, + SquizControlStructureSpacing{}, SlevomatArrowFunctionDeclaration{}, SlevomatDisallowTrailingCommaInCall{}, SlevomatDisallowTrailingCommaInClosureUse{}, diff --git a/blink/internal/fixer/rules/scope_indent.go b/blink/internal/fixer/rules/scope_indent.go new file mode 100644 index 0000000000..15549fee9d --- /dev/null +++ b/blink/internal/fixer/rules/scope_indent.go @@ -0,0 +1,780 @@ +package rules + +import ( + "math" + "slices" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/WhiteSpace/ScopeIndentSniff.php +// +// ScopeIndent indents every line by Indent spaces per scope level, a line-by-line +// port of the sniff's single pass from the first open tag. +type ScopeIndent struct { + Indent int + Exact bool + TabIndent bool +} + +func (ScopeIndent) Name() string { + return `PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff` +} + +func (ScopeIndent) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/WhiteSpace/ScopeIndentSniff.php" +} + +func (r ScopeIndent) WithConfig(config map[string]any) fixer.Fixer { + r.Indent = configInt(config, "indent", r.Indent) + if v, ok := config["exact"].(bool); ok { + r.Exact = v + } + if v, ok := config["tabIndent"].(bool); ok { + r.TabIndent = v + } + return r +} + +func (ScopeIndent) phpcsOnePass() {} + +func (r ScopeIndent) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + m := newSiModel(f) + for i := range f.toks { + if m.code[i] == "open_tag" { + r.process(m, i) + return + } + } + }) +} + +// siModel is the PHP_CodeSniffer token data the sniff reads: refined token +// codes, conditions and parenthesis owners on top of the scope map. +type siModel struct { + f *slvFile + sc *phpcsScope + code []string + conds [][]phpcsCond + levels []int + pOwner []int + docEnd []int +} + +func newSiModel(f *slvFile) *siModel { + sc := newPhpcsScope(f) + n := len(f.toks) + m := &siModel{f: f, sc: sc, code: make([]string, n), pOwner: make([]int, n), docEnd: make([]int, n)} + for i := range n { + m.code[i] = m.classify(i) + m.pOwner[i] = -1 + m.docEnd[i] = -1 + } + m.conds, m.levels = sc.levelMap() + for i := range n { + if !f.is(i, "(") || f.toks[i].closer < 0 { + continue + } + owner := sc.pOwner[i] + if owner < 0 { + p := f.prevEffective(i - 1) + if f.is(p, "&") { + p = f.prevEffective(p - 1) + } + if p >= 0 && (sc.code[p] == "fn" || m.code[p] == "anon_class" || siCallOwners[strings.ToLower(f.toks[p].orig)] && !siIsMember(f, p)) { + owner = p + } + } + m.pOwner[i], m.pOwner[f.toks[i].closer] = owner, owner + } + open := -1 + for i := range n { + switch f.toks[i].doc { + case slvDocOpen: + open = i + case slvDocClose: + if open >= 0 { + m.docEnd[open] = i + open = -1 + } + } + } + return m +} + +func (m *siModel) classify(i int) string { + f := m.f + t := f.toks[i] + switch t.kind { + case token.String: + switch { + case t.heredoc && (i == 0 || !f.toks[i-1].heredoc): + return "start_heredoc" + case t.heredoc && (i+1 == len(f.toks) || !f.toks[i+1].heredoc): + return "end_heredoc" + case t.heredoc: + return "heredoc" + case t.interp: + return "double_quoted_string" + } + return "constant_encapsed_string" + case token.DocComment: + switch t.doc { + case slvDocOpen: + return "doc_open" + case slvDocWhitespace: + return "doc_whitespace" + } + return "doc" + case token.OpenTag: + if strings.HasPrefix(t.orig, "= 0 && f.isShortArrayOpen(t.closer): + return "close_short_array" + } + case token.Keyword: + switch strings.ToLower(t.orig) { + case "function": + if f.isClosure(i) { + return "closure" + } + case "class": + if phpcsIsAnonClassKeyword(f, i) { + return "anon_class" + } + } + } + return m.sc.code[i] +} + +// siCallOwners are the language constructs PHP_CodeSniffer gives the +// parentheses after them, whatever blink lexes them as. +var siCallOwners = phpcsSet("eval", "isset", "empty", "unset", "array", "list") + +func siIsMember(f *slvFile, i int) bool { + p := f.prevEffective(i - 1) + return f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") || f.isKeyword(p, "function") +} + +var siScopeOpeners = phpcsSet("class", "anon_class", "interface", "trait", "enum", "namespace", "function", "closure", + "if", "switch", "case", "declare", "default", "while", "else", "elseif", "for", "foreach", "do", "try", "catch", + "finally", "use", "match") + +var siMethodModifiers = phpcsSet("private", "public", "protected", "abstract", "static", "final") + +func (m *siModel) lastCond(i int) int { + if c := m.conds[i]; len(c) > 0 { + return c[len(c)-1].key + } + return -1 +} + +// firstOnLine is File::findFirstOnLine with exclude: the first token on the +// line of start whose code is not in skip, or -1. +func (m *siModel) firstOnLine(start int, skip ...string) int { + found := -1 + for i := start; i >= 0; i-- { + if m.f.toks[i].line < m.f.toks[start].line { + break + } + if !slices.Contains(skip, m.code[i]) { + found = i + } + } + return found +} + +// siAt maps PHP's $tokens[false] to the first token. +func siAt(i int) int { return max(i, 0) } + +func (m *siModel) nextNonEmpty(i int) int { + for ; i < len(m.f.toks); i++ { + if !m.f.isEmpty(i) { + return i + } + } + return -1 +} + +// prevLocal is File::findPrevious with local set. +func (m *siModel) prevLocal(start int, types ...string) int { + f, sc := m.f, m.sc + for i := start; i >= 0; i-- { + if slices.Contains(types, m.code[i]) { + return i + } + t := f.toks[i] + switch { + case sc.opener[i] >= 0 && i == sc.closer[i]: + i = sc.opener[i] + case (f.is(i, "]") || f.is(i, "}")) && t.closer >= 0 && t.closer < i: + i = t.closer + case f.is(i, ")") && t.closer >= 0 && t.closer < i: + i = t.closer + case m.code[i] == ";": + return -1 + } + } + return -1 +} + +func (r ScopeIndent) ceil(v int) int { + return int(math.Ceil(float64(v)/float64(r.Indent))) * r.Indent +} + +func (r ScopeIndent) floor(v int) int { + return int(math.Floor(float64(v)/float64(r.Indent))) * r.Indent +} + +// siOrdered is a PHP array keyed by scope closer, kept in insertion order. +type siOrdered struct { + keys []int + vals map[int]int +} + +func (o *siOrdered) set(k, v int) { + if _, ok := o.vals[k]; !ok { + o.keys = append(o.keys, k) + } + o.vals[k] = v +} + +func (o *siOrdered) has(k int) bool { + _, ok := o.vals[k] + return ok +} + +func (o *siOrdered) pop() int { + if len(o.keys) == 0 { + return -1 + } + k := o.keys[len(o.keys)-1] + o.keys = o.keys[:len(o.keys)-1] + v := o.vals[k] + delete(o.vals, k) + return v +} + +func (o *siOrdered) last() int { + if len(o.keys) == 0 { + return -1 + } + return o.vals[o.keys[len(o.keys)-1]] +} + +func (r ScopeIndent) process(m *siModel, stackPtr int) { + f, sc, code := m.f, m.sc, m.code + toks := f.toks + n := len(toks) + tabWidth := slvTabWidth + + lastOpenTag := stackPtr + lastCloseTag := -1 + openScopes := &siOrdered{vals: map[int]int{}} + adjustments := map[int]int{} + setIndents := map[int]int{} + disableExactStack := map[int]bool{} + disableExactEnd := 0 + + currentIndent := 0 + first := -1 + for i := stackPtr; i >= 0 && toks[i].line == toks[stackPtr].line; i-- { + if code[i] == "inline_html" { + first = i + } + } + first = siAt(first) + if trimmed := phpcsLtrim(toks[first].content); trimmed == "" { + currentIndent = toks[stackPtr].column - 1 + } else { + currentIndent = len(toks[first].content) - len(trimmed) + } + + tokenIndent := 0 + for i := stackPtr + 1; i < n; i++ { + checkToken := -1 + checkIndent := -1 + hasCheckIndent := false + exact := r.Exact + + if f.is(i, "(") && toks[i].closer >= 0 { + disableExactStack[toks[i].closer] = true + disableExactEnd = max(disableExactEnd, toks[i].closer) + } + if exact && i < disableExactEnd { + exact = false + } + + if toks[i].column == 1 { + trimmed := phpcsLtrim(toks[i].content) + if trimmed == "" { + if i+1 < n && toks[i].line == toks[i+1].line { + checkToken = i + 1 + tokenIndent = toks[i+1].column - 1 + } + } else { + checkToken = i + tokenIndent = len(toks[i].content) - len(trimmed) + } + } + + if checkToken >= 0 && f.is(checkToken, ")") && toks[checkToken].closer >= 0 || + f.is(i, ")") && toks[i].closer >= 0 { + parenCloser := i + if checkToken >= 0 { + parenCloser = checkToken + } + parenOpener := toks[parenCloser].closer + if toks[parenCloser].line != toks[parenOpener].line { + parens := 0 + if nested := sc.nested[parenCloser]; nested >= 0 { + parens = nested + } + condition := 0 + if lc := m.lastCond(parenCloser); lc >= 0 && (m.pOwner[parenCloser] < 0 || parens > 0) { + condition = lc + } + if parens > condition { + parenOpener = parens + condition = 0 + } else if condition > 0 { + parenOpener = condition + parens = 0 + } + exact = false + + lastOpenTagCondition := m.lastCond(lastOpenTag) + switch { + case condition > 0 && lastOpenTagCondition == condition: + first = siAt(m.firstOnLine(lastOpenTag, "whitespace", "inline_html")) + checkIndent, hasCheckIndent = toks[first].column-1, true + checkIndent += adjustments[condition] + currentIndent = checkIndent + case condition > 0 && sc.opener[condition] >= 0 && siHas(setIndents, sc.opener[condition]): + checkIndent, hasCheckIndent = setIndents[sc.opener[condition]], true + checkIndent += adjustments[condition] + currentIndent = checkIndent + default: + first = siAt(m.firstOnLine(parenOpener, "whitespace")) + checkIndent, hasCheckIndent = toks[first].column-1, true + checkIndent += adjustments[first] + if first == toks[parenCloser].closer && toks[siAt(first-1)].line == toks[first].line { + first-- + } + prev := sc.startOfStatementIgnoring(first, ",") + if prev != first { + first = m.firstOnLine(prev, "whitespace", "inline_html") + if first >= 0 { + prev = sc.startOfStatementIgnoring(first, ",") + first = siAt(m.firstOnLine(prev, "whitespace", "inline_html")) + } else { + first = prev + } + } + if sc.closer[first] >= 0 && sc.closer[first] == first { + if sc.cond[first] >= 0 { + scopeCloser := first + first = siAt(m.firstOnLine(sc.cond[scopeCloser], "whitespace")) + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + if code[sc.cond[scopeCloser]] != "closure" { + currentIndent = r.ceil(currentIndent) + } + setIndents[first] = currentIndent + } + } else { + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + setIndents[first] = currentIndent + } + } + } + } + + if code[i] == "close_short_array" || checkToken >= 0 && code[checkToken] == "close_short_array" { + arrayCloser := i + if checkToken >= 0 { + arrayCloser = checkToken + } + arrayOpener := toks[arrayCloser].closer + if toks[arrayCloser].line != toks[arrayOpener].line { + first = siAt(m.firstOnLine(arrayOpener, "whitespace")) + exact = false + if first == arrayOpener { + first-- + } + prev := sc.startOfStatementIgnoring(first, ",", "=>") + if prev != first { + first = siAt(m.firstOnLine(prev, "whitespace")) + prev = sc.startOfStatementIgnoring(first, ",", "=>") + first = siAt(m.firstOnLine(prev, "whitespace")) + } else if code[first] == "whitespace" { + first = siAt(m.nextNonWhitespace(first + 1)) + } + checkIndent, hasCheckIndent = toks[first].column-1, true + checkIndent += adjustments[first] + if sc.closer[first] >= 0 && sc.closer[first] == first { + if v, ok := setIndents[first]; ok { + currentIndent = v + } + } else { + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + setIndents[first] = currentIndent + } + } + } + + if checkToken >= 0 && !exact && (len(m.conds[checkToken]) > 0 || sc.opener[checkToken] >= 0 && sc.opener[checkToken] == checkToken) { + condition := sc.cond[checkToken] + if len(m.conds[checkToken]) > 0 { + condition = m.lastCond(checkToken) + } + first = siAt(m.firstOnLine(condition, "whitespace")) + // the sniff re-indents the line here only when $fixer->enabled, which + // ECS never sets + if adj, ok := adjustments[first]; ok && (adj < 0 && tokenIndent > currentIndent || adj > 0 && tokenIndent < currentIndent) { + adjustments[checkToken] = adj + } + } + + if checkToken >= 0 && (openScopes.has(checkToken) || + sc.cond[checkToken] >= 0 && sc.closer[checkToken] == checkToken && sc.opener[checkToken] >= 0 && + toks[checkToken].line != toks[sc.opener[checkToken]].line) || + checkToken < 0 && openScopes.has(i) { + scopeCloser := checkToken + if scopeCloser < 0 { + scopeCloser = i + } + openScopes.pop() + if sc.cond[scopeCloser] >= 0 { + first = siAt(m.firstOnLine(sc.cond[scopeCloser], "whitespace", "inline_html")) + for code[first] == "constant_encapsed_string" && first > 0 && code[first-1] == "constant_encapsed_string" { + first = siAt(m.firstOnLine(first-1, "whitespace")) + } + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + setIndents[scopeCloser] = currentIndent + if f.is(scopeCloser, "}") { + exact = true + } else { + checkToken = -1 + } + } + } + + if checkToken >= 0 && siScopeOpeners[code[checkToken]] && sc.opener[checkToken] >= 0 { + exact = true + if disableExactEnd > checkToken { + for end := range disableExactStack { + if end < checkToken { + continue + } + if slices.Equal(m.conds[checkToken], m.conds[end]) { + exact = false + break + } + } + } + lastOpener := openScopes.last() + if lastOpener >= 0 && sc.closer[lastOpener] >= 0 && + m.levels[lastOpener] == m.levels[checkToken] && + sc.closer[lastOpener] == sc.closer[checkToken] { + currentIndent -= r.Indent + setIndents[lastOpener] = currentIndent + } + if code[checkToken] == "closure" && tokenIndent > currentIndent { + checkIndent, hasCheckIndent = r.ceil(tokenIndent), true + exact = false + } + } + + if checkToken >= 0 && siMethodModifiers[code[checkToken]] && (checkToken+1 >= n || code[checkToken+1] != "::") { + next := m.nextNonEmpty(checkToken + 1) + if next < 0 || code[next] != "closure" && code[next] != "variable" && code[next] != "fn" { + isMethodPrefix := true + if deepest := sc.nested[checkToken]; deepest >= 0 { + if owner := m.pOwner[deepest]; owner >= 0 && code[owner] == "function" { + isMethodPrefix = false + } + } + if isMethodPrefix { + exact = true + } + } + } + + if checkToken >= 0 && (code[checkToken] == "open_tag" || code[checkToken] == "open_tag_with_echo") { + checkIndent, hasCheckIndent = toks[checkToken].column-1, true + if len(m.conds[checkToken]) > 0 { + closeTag := -1 + for j := checkToken - 1; j >= 0; j-- { + if code[j] == "close_tag" { + closeTag = j + break + } + } + if closeTag >= 0 && slices.Equal(m.conds[checkToken], m.conds[closeTag]) { + lastCondition := m.lastCond(checkToken) + lastOpener, lastCloser := sc.opener[lastCondition], sc.closer[lastCondition] + if v, ok := setIndents[lastOpener]; ok && toks[siAt(lastCloser)].line != toks[checkToken].line { + checkIndent = v + } + } + } + } + + if checkToken >= 0 && code[checkToken] == "close_tag" { + exact = true + checkIndent, hasCheckIndent = r.ceil(currentIndent), true + } + + if checkToken >= 0 && code[checkToken] == "else" { + exact = true + } + + if checkToken >= 0 && (code[checkToken] == "->" || code[checkToken] == "?->") && exact { + exact = false + } + + if !hasCheckIndent { + checkIndent = currentIndent + } + + if checkToken >= 0 && code[checkToken] != "inline_html" && + (tokenIndent != checkIndent && exact || tokenIndent < checkIndent && !exact) { + adjustments[checkToken] = checkIndent - tokenIndent + r.adjustIndent(m, checkToken, checkIndent, checkIndent-tokenIndent, tabWidth) + } + + if checkToken >= 0 { + i = checkToken + } + + if code[i] == "open_short_array" { + disableExactStack[toks[i].closer] = true + disableExactEnd = max(disableExactEnd, toks[i].closer) + } + + if code[i] == "start_heredoc" { + end := -1 + for j := i + 1; j < n; j++ { + if code[j] == "end_heredoc" { + end = j + break + } + } + if end < 0 { + return + } + i = end + if next := m.nextNonEmpty(i + 1); code[siAt(next)] == "," { + i = siAt(next) + } + continue + } + + if code[i] == "constant_encapsed_string" || code[i] == "double_quoted_string" { + for j := i + 1; j < n; j++ { + if code[j] != code[i] { + i = j - 1 + break + } + } + continue + } + + if code[i] == "doc_open" { + if m.docEnd[i] >= 0 { + i = m.docEnd[i] + } + continue + } + + if code[i] == "open_tag" || code[i] == "open_tag_with_echo" { + if checkToken < 0 { + first = siAt(m.firstOnLine(i, "whitespace")) + currentIndent = len(toks[first].content) - len(phpcsLtrim(toks[first].content)) + } else { + currentIndent = toks[i].column - 1 + } + lastOpenTag = i + currentIndent += adjustments[i] + currentIndent = r.ceil(currentIndent) + setIndents[i] = currentIndent + continue + } + + if code[i] == "close_tag" { + if toks[lastOpenTag].line != toks[i].line { + currentIndent = toks[i].column - 1 + lastCloseTag = i + } else if lastCloseTag < 0 { + currentIndent = 0 + } else { + currentIndent = toks[lastCloseTag].column - 1 + } + currentIndent += adjustments[i] + currentIndent = r.ceil(currentIndent) + setIndents[i] = currentIndent + continue + } + + if code[i] == "closure" || code[i] == "anon_class" { + closer := sc.closer[i] + if closer < 0 { + continue + } + if toks[i].line == toks[closer].line { + i = closer + continue + } + first = siAt(m.firstOnLine(i, "whitespace")) + for code[first] == "constant_encapsed_string" && first > 0 && code[first-1] == "constant_encapsed_string" { + first = siAt(m.firstOnLine(first-1, "whitespace")) + } + currentIndent = toks[first].column - 1 + r.Indent + openScopes.set(closer, sc.cond[i]) + currentIndent += adjustments[first] + currentIndent = r.floor(currentIndent) + i = sc.opener[i] + setIndents[i] = currentIndent + continue + } + + if sc.cond[i] >= 0 && sc.opener[i] >= 0 && sc.opener[i] == i { + closer := sc.closer[i] + if toks[i].line == toks[siAt(closer)].line { + i = closer + continue + } + if siScopeOpeners[code[sc.cond[i]]] { + currentIndent += r.Indent + setIndents[i] = currentIndent + openScopes.set(closer, sc.cond[i]) + continue + } + } + + if sc.cond[i] >= 0 && sc.closer[i] == i { + switch code[sc.cond[i]] { + case "closure", "anon_class", "match", "fn": + default: + continue + } + prev := -1 + parens := 0 + if nested := sc.nested[i]; nested >= 0 { + parens = nested + } + condition := 0 + if lc := m.lastCond(i); lc >= 0 { + condition = lc + } + if parens > condition { + prev = f.prevEffective(parens - 1) + condition = 0 + } else if condition > 0 { + prev = condition + parens = 0 + } + if prev < 0 { + prev = m.prevLocal(sc.cond[i]-1, "=", "return") + if prev < 0 { + prev = i + } + } + first = siAt(m.firstOnLine(prev, "whitespace")) + prev = sc.startOfStatementIgnoring(first) + if prev != first { + first = siAt(m.firstOnLine(prev, "whitespace")) + } + currentIndent = toks[first].column - 1 + if condition > 0 { + currentIndent += r.Indent + } + if sc.closer[first] >= 0 && sc.closer[first] == first { + if condition == 0 || sc.opener[condition] < first { + currentIndent = setIndents[first] + } + } + currentIndent = r.ceil(currentIndent) + setIndents[first] = currentIndent + } + } +} + +func siHas(m map[int]int, k int) bool { + _, ok := m[k] + return ok +} + +func (m *siModel) nextNonWhitespace(i int) int { + for ; i < len(m.code); i++ { + if m.code[i] != "whitespace" { + return i + } + } + return -1 +} + +func (r ScopeIndent) padding(length, tabWidth int) string { + if length <= 0 { + return "" + } + if !r.TabIndent { + return strings.Repeat(" ", length) + } + numTabs := length / tabWidth + if numTabs == 0 { + return "" + } + return strings.Repeat("\t", numTabs) + strings.Repeat(" ", length-numTabs*tabWidth) +} + +func (r ScopeIndent) adjustIndent(m *siModel, stackPtr, length, change, tabWidth int) { + f := m.f + toks := f.toks + if m.code[stackPtr] == "inline_html" { + return + } + padding := r.padding(length, tabWidth) + var accepted bool + if toks[stackPtr].column == 1 { + accepted = f.replaceToken(stackPtr, padding+phpcsLtrim(toks[stackPtr].content)) + } else { + accepted = f.replaceToken(stackPtr-1, padding) + } + if !accepted || m.code[stackPtr] != "doc_open" { + return + } + for x := stackPtr + 1; x < m.docEnd[stackPtr]; x++ { + if toks[x].column != 1 { + continue + } + l := 0 + if m.code[x] == "doc_whitespace" { + l = toks[x].length + } + pad := "" + if p := l + change; p > 0 { + if r.TabIndent { + numTabs := p / tabWidth + pad = strings.Repeat("\t", numTabs) + strings.Repeat(" ", p-numTabs*tabWidth) + } else { + pad = strings.Repeat(" ", p) + } + } + f.replaceToken(x, pad) + } +} diff --git a/blink/internal/fixer/rules/slevomat.go b/blink/internal/fixer/rules/slevomat.go index 9f392199a7..fa0b3ea478 100644 --- a/blink/internal/fixer/rules/slevomat.go +++ b/blink/internal/fixer/rules/slevomat.go @@ -114,6 +114,7 @@ func newSlvFile(toks []token.Token) *slvFile { func slvSplit(toks []token.Token) []slvTok { var out []slvTok eol := slvRawEOL(toks) + toks = slvSplitYieldFrom(toks) add := func(k token.Kind, v string, heredoc bool) { for v != "" { n := strings.IndexByte(v, '\n') @@ -187,6 +188,41 @@ func slvSplit(toks []token.Token) []slvTok { return out } +var slvYieldFromOneLine = regexp.MustCompile(`(?i)^yield[ \t]+from$`) + +// slvSplitYieldFrom splits a "yield from" holding a newline or a comment, which +// PHP lexes as one T_YIELD_FROM, into "yield", the tokens between and "from", +// like PHP_CodeSniffer's PHP tokenizer. +func slvSplitYieldFrom(toks []token.Token) []token.Token { + var out []token.Token + for n, t := range toks { + v := t.Value + if t.Kind != token.Keyword || len(v) <= 9 || !strings.EqualFold(v[:5], "yield") || slvYieldFromOneLine.MatchString(v) { + if out != nil { + out = append(out, t) + } + continue + } + if out == nil { + out = append(out, toks[:n]...) + } + out = append(out, token.Token{Kind: token.Keyword, Value: v[:5]}) + inner := lexer.Lex(" 0 { + inner[0].Value = strings.TrimPrefix(inner[0].Value, "\n") + if inner[0].Value == "" { + inner = inner[1:] + } + } + out = append(out, inner...) + out = append(out, token.Token{Kind: token.Keyword, Value: v[len(v)-4:]}) + } + if out == nil { + return toks + } + return out +} + // slvNameEnd returns the last token of a qualified name starting at i // ("Foo\Bar", "\Foo", "namespace\Foo"), which PHP lexes as one token, or -1. func slvNameEnd(toks []token.Token, i int) int { diff --git a/blink/internal/fixer/rules/squiz_array_declaration.go b/blink/internal/fixer/rules/squiz_array_declaration.go new file mode 100644 index 0000000000..38b61382fd --- /dev/null +++ b/blink/internal/fixer/rules/squiz_array_declaration.go @@ -0,0 +1,500 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php +// +// SquizArrayDeclaration lays out array declarations: a single-line array +// keeps one value, a multi-line one puts each value on its own line ending in +// a comma, with keys, double arrows and values aligned. +type SquizArrayDeclaration struct{} + +func (SquizArrayDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayDeclarationSniff` +} + +func (SquizArrayDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php" +} + +func (SquizArrayDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + a := &squizArrays{f: f, sc: newPhpcsScope(f)} + for i := range f.toks { + if a.isArray(i) || f.isShortArrayOpen(i) { + a.process(i) + } + } + }) +} + +type squizArrays struct { + f *slvFile + sc *phpcsScope +} + +type squizArrayEntry struct { + value, index, arrow int // -1 when unset + indexLength int +} + +// isArray tells T_ARRAY: the "array" keyword that owns parentheses. +func (a *squizArrays) isArray(i int) bool { + return a.f.isKeyword(i, "array") && a.sc.pCloser[i] >= 0 +} + +func (a *squizArrays) depth(i int) int { + n := 0 + for p := a.sc.nested[i]; p >= 0; p = a.sc.nested[p] { + n++ + } + return n +} + +// nextNot is File::findNext with exclude=true: the first token in +// [start, end) that skip rejects, or -1. +func (a *squizArrays) nextNot(skip func(int) bool, start, end int) int { + end = min(end, len(a.f.toks)) + for i := max(start, 0); i < end; i++ { + if !skip(i) { + return i + } + } + return -1 +} + +// prevNot is File::findPrevious with exclude=true: the first token in +// [end, start] going down that skip rejects, or -1. +func (a *squizArrays) prevNot(skip func(int) bool, start, end int) int { + for i := min(start, len(a.f.toks)-1); i >= max(end, 0); i-- { + if !skip(i) { + return i + } + } + return -1 +} + +func (a *squizArrays) isCast(i int) bool { + t := a.f.toks[i] + return t.kind == token.Punct && len(t.orig) > 1 && t.orig[0] == '(' +} + +func (a *squizArrays) isClosureOrFn(i int) bool { + return a.f.isKeyword(i, "function") && a.f.isClosure(i) || a.sc.code[i] == "fn" +} + +func (a *squizArrays) isEndHeredoc(i int) bool { return a.sc.code[i] == "end_heredoc" } + +func (a *squizArrays) process(stackPtr int) { + f, sc := a.f, a.sc + if f.is(stackPtr, "[") { + if p := sc.nested[stackPtr]; p >= 0 { + if owner := sc.pOwner[p]; owner >= 0 && sc.code[owner] == "foreach" { + closer := f.toks[p].closer + for j := p + 1; j < closer; j++ { + if f.isKeyword(j, "as") { + if j < stackPtr { + return + } + break + } + } + } + } + } + + var arrayStart, arrayEnd int + if !f.is(stackPtr, "[") { + if f.toks[stackPtr].orig != strings.ToLower(f.toks[stackPtr].orig) { + f.replaceToken(stackPtr, "array") + } + arrayEnd = sc.pCloser[stackPtr] + arrayStart = f.toks[arrayEnd].closer + if arrayStart != stackPtr+1 { + next := a.nextNot(f.isWS, stackPtr+1, arrayStart) + if next < 0 || !f.isCommentToken(next) { + f.beginChangeset() + for i := stackPtr + 1; i < arrayStart; i++ { + f.replaceToken(i, "") + } + f.endChangeset() + } + } + } else { + arrayStart, arrayEnd = stackPtr, f.toks[stackPtr].closer + } + + if a.nextNot(f.isWS, arrayStart+1, arrayEnd+1) == arrayEnd { + if arrayEnd-arrayStart != 1 { + f.beginChangeset() + for i := arrayStart + 1; i < arrayEnd; i++ { + f.replaceToken(i, "") + } + f.endChangeset() + } + return + } + + if f.toks[arrayStart].line == f.toks[arrayEnd].line { + a.singleLine(stackPtr, arrayStart, arrayEnd) + } else { + a.multiLine(stackPtr, arrayStart, arrayEnd) + } +} + +func (a *squizArrays) singleLine(stackPtr, arrayStart, arrayEnd int) { + f, sc := a.f, a.sc + valueCount := 0 + var commas []int + for i := arrayStart + 1; i < arrayEnd; i++ { + if f.is(i, "(") { + if f.toks[i].closer > i { + i = f.toks[i].closer + } + continue + } + if f.is(i, ",") { + if a.nextNot(f.isWS, i+1, arrayEnd) >= 0 { + valueCount++ + commas = append(commas, i) + } else { + f.replaceToken(i, "") + } + } + } + + for arrow := arrayStart + 1; arrow < arrayEnd; arrow++ { + if sc.code[arrow] != "=>" { + continue + } + if !f.isWS(arrow - 1) { + f.addContentBefore(arrow, " ") + } else if f.toks[arrow-1].length != 1 { + f.replaceToken(arrow-1, " ") + } + if !f.isWS(arrow + 1) { + f.addContent(arrow, " ") + } else if f.toks[arrow+1].length != 1 { + f.replaceToken(arrow+1, " ") + } + } + + if valueCount == 0 { + return + } + p := sc.nested[stackPtr] + if p < 0 || f.toks[f.toks[p].closer].line != f.toks[stackPtr].line { + f.beginChangeset() + f.addContent(arrayStart, f.eol) + if f.isWS(arrayEnd - 1) { + f.replaceToken(arrayEnd-1, f.eol) + } else { + f.addContentBefore(arrayEnd, f.eol) + } + f.endChangeset() + return + } + for _, comma := range commas { + if !f.isWS(comma + 1) { + f.addContent(comma, " ") + } else if f.toks[comma+1].length != 1 { + f.replaceToken(comma+1, " ") + } + if f.isWS(comma - 1) { + f.replaceToken(comma-1, "") + } + } +} + +func (a *squizArrays) multiLine(stackPtr, arrayStart, arrayEnd int) { + f, sc := a.f, a.sc + col := func(i int) int { return f.toks[i].column } + line := func(i int) int { return f.toks[i].line } + spaces := func(n int) string { return strings.Repeat(" ", max(n, 0)) } + keywordStart := col(stackPtr) + + lastContent := a.prevNot(f.isWS, arrayEnd-1, arrayStart) + if line(lastContent) == line(arrayEnd) { + f.addContentBefore(arrayEnd, f.eol) + } else if col(arrayEnd) != keywordStart { + expected, found := keywordStart-1, col(arrayEnd)-1 + if found == 0 { + f.addContent(arrayEnd-1, spaces(expected)) + } else { + f.replaceToken(arrayEnd-1, spaces(expected)) + } + } + + keyUsed, singleUsed := false, false + var indices []squizArrayEntry + maxLength := 0 + lastToken := stackPtr + if !f.is(stackPtr, "[") { + lastToken = arrayStart + } + + for next := stackPtr + 1; next < arrayEnd; next++ { + if f.is(next, "(") && sc.pOwner[next] != stackPtr { + if f.toks[next].closer > next { + next = f.toks[next].closer + } + continue + } + + if a.isArray(next) || f.isShortArrayOpen(next) || a.isClosureOrFn(next) || sc.code[next] == "match" { + if sc.code[lastToken] != "=>" { + indices = append(indices, squizArrayEntry{value: next, index: -1, arrow: -1}) + lastToken = next + } + switch { + case a.isArray(next): + next = sc.pCloser[next] + case f.is(next, "["): + next = f.toks[next].closer + default: + if sc.closer[next] < 0 { + continue + } + next = sc.closer[next] + } + next = a.nextNot(f.isWS, next+1, len(f.toks)) + if next < 0 { + break + } + if !f.is(next, ",") { + next-- + } else { + lastToken = next + } + continue + } + + if sc.code[next] != "=>" && !f.is(next, ",") { + continue + } + + if f.is(next, ",") { + stackPtrCount := a.depth(stackPtr) + commaCount := a.depth(next) + if commaCount > 0 && !f.is(stackPtr, "[") { + commaCount-- + } + if commaCount > stackPtrCount { + continue + } + if keyUsed && f.is(lastToken, ",") { + next = a.nextNot(f.isEmpty, lastToken+1, len(f.toks)) + if next < 0 || !f.is(next, "...") { + return + } + } + if !keyUsed { + if f.isWS(next - 1) { + prev := a.prevNot(f.isEmpty, next-1, 0) + if !a.isEndHeredoc(prev) || line(next-1) == line(next) { + if prev == a.prevNot(f.isWS, next-1, 0) { + f.replaceToken(next-1, "") + } + } + } + valueContent := a.nextNot(f.isEmpty, lastToken+1, next) + indices = append(indices, squizArrayEntry{value: valueContent, index: -1, arrow: -1}) + unpack := a.prevNot(f.isEmpty, next-2, 0) + if unpack < 0 || !f.is(unpack, "...") { + singleUsed = true + } + } + lastToken = next + continue + } + + if singleUsed { + return + } + keyUsed = true + indexEnd := a.prevNot(f.isWS, next-1, arrayStart) + indexStart := sc.startOfStatement(indexEnd) + entry := squizArrayEntry{arrow: next, index: indexEnd, indexLength: f.toks[indexEnd].length} + if indexStart != indexEnd { + entry.index, entry.indexLength = indexStart, 0 + for i := indexStart; i <= indexEnd; i++ { + entry.indexLength += f.toks[i].length + } + } + maxLength = max(maxLength, entry.indexLength) + entry.value = a.nextNot(f.isEmpty, next+1, arrayEnd) + indices = append(indices, entry) + lastToken = next + } + + singleValue := false + if len(indices) == 0 { + singleValue = true + } else if len(indices) == 1 && f.is(lastToken, ",") { + skip := func(i int) bool { return f.isEmpty(i) || f.is(i, ",") } + if a.nextNot(skip, max(indices[0].value, 0)+1, arrayEnd) < 0 { + singleValue = true + } + } + if singleValue && a.nextNot(func(i int) bool { return !f.toks[i].heredoc }, arrayStart+1, arrayEnd-1) < 0 { + notComment := func(i int) bool { return f.toks[i].kind != token.Comment && !phpcsIsAnnotation(f, i) } + if a.nextNot(notComment, arrayStart+1, arrayEnd) < 0 { + f.beginChangeset() + for i := arrayStart + 1; i < arrayEnd && f.isWS(i); i++ { + f.replaceToken(i, "") + } + for i := arrayEnd - 1; i > arrayStart && f.isWS(i); i-- { + f.replaceToken(i, "") + } + f.endChangeset() + } + return + } + + if !keyUsed && len(indices) > 0 { + lastIndex := max(indices[len(indices)-1].value, 0) + trailing := max(a.prevNot(f.isEmpty, arrayEnd-1, lastIndex), 0) + if !f.is(trailing, ",") { + f.addContent(trailing, ",") + } + ignore := func(i int) bool { return f.isWS(i) || f.is(i, ",") || a.isCast(i) } + for _, v := range indices { + valuePointer := v.value + if valuePointer <= 0 { + continue + } + if a.isClosureOrFn(valuePointer) { + if st := a.prevNot(ignore, valuePointer-1, arrayStart+1); st >= 0 && f.isKeyword(st, "static") { + valuePointer = st + } + } + previous := a.prevNot(ignore, valuePointer-1, arrayStart+1) + if previous < 0 { + previous = stackPtr + } + prevIsWS := f.isWS(valuePointer - 1) + if line(previous) == line(valuePointer) { + if prevIsWS { + f.replaceToken(valuePointer-1, f.eol) + } else { + f.addContentBefore(valuePointer, f.eol) + } + } else if prevIsWS { + first := f.firstNonWhitespaceOnLine(valuePointer) + if found := col(first) - 1; found != keywordStart { + if found == 0 { + f.addContent(first-1, spaces(keywordStart)) + } else { + f.replaceToken(first-1, spaces(keywordStart)) + } + } + } + } + } + + indicesStart := keywordStart + 1 + for _, index := range indices { + valuePointer := index.value + if valuePointer < 0 || index.index < 0 { + continue + } + indexPointer := index.index + indexLine := line(indexPointer) + previous := a.prevNot(func(i int) bool { return f.isWS(i) || f.is(i, ",") }, indexPointer-1, arrayStart+1) + if previous < 0 { + previous = stackPtr + } + if line(previous) == indexLine { + if f.isWS(indexPointer - 1) { + f.replaceToken(indexPointer-1, f.eol) + } else { + f.addContentBefore(indexPointer, f.eol) + } + continue + } + + if col(indexPointer) != indicesStart && indexPointer-1 != arrayStart { + expected, found := indicesStart-1, col(indexPointer)-1 + if found == 0 || !f.isWS(indexPointer-1) { + f.addContent(indexPointer-1, spaces(expected)) + } else { + f.replaceToken(indexPointer-1, spaces(expected)) + } + } + + arrowStart := col(indexPointer) + maxLength + 1 + if col(index.arrow) != arrowStart { + base := index.indexLength + col(indexPointer) + expected, found := arrowStart-base, col(index.arrow)-base + if found == 0 { + f.addContent(index.arrow-1, spaces(expected)) + } else { + f.replaceToken(index.arrow-1, spaces(expected)) + } + continue + } + + valueStart := arrowStart + 3 + if col(valuePointer) != valueStart { + base := f.toks[index.arrow].length + col(index.arrow) + expected, found := valueStart-base, col(valuePointer)-base + switch { + case found < 0: + prev := a.prevNot(f.isWS, valuePointer-1, 0) + f.beginChangeset() + for i := prev + 1; i < valuePointer; i++ { + f.replaceToken(i, "") + } + f.replaceToken(valuePointer-1, spaces(expected)) + f.endChangeset() + case found == 0: + f.addContent(valuePointer-1, spaces(expected)) + default: + f.replaceToken(valuePointer-1, spaces(expected)) + } + } + + nextComma := -1 + var valueEnd int + end := sc.endOfStatement(valuePointer) + if f.is(end, ",") { + valueEnd = a.prevNot(f.isEmpty, end-1, valuePointer) + nextComma = end + } else { + valueEnd = end + if n := a.nextNot(f.isEmpty, end+1, arrayEnd); n >= 0 && f.is(n, ",") { + nextComma = n + } + } + valueLine := line(valueEnd) + if a.isEndHeredoc(valueEnd) { + valueLine++ + } + + if nextComma < 0 || line(nextComma) != valueLine { + i := valuePointer + 1 + for ; i <= arrayEnd; i++ { + if line(i) > valueLine { + break + } + } + f.beginChangeset() + f.addContentBefore(i-1, ",") + if nextComma >= 0 { + f.replaceToken(nextComma, "") + } + f.endChangeset() + } + + if nextComma >= 0 && f.isWS(nextComma-1) { + if prev := a.prevNot(f.isEmpty, nextComma-1, 0); !a.isEndHeredoc(prev) { + f.replaceToken(nextComma-1, "") + } + } + } +} diff --git a/blink/internal/fixer/rules/squiz_block_comment.go b/blink/internal/fixer/rules/squiz_block_comment.go new file mode 100644 index 0000000000..dfdadbfc23 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_block_comment.go @@ -0,0 +1,196 @@ +package rules + +import ( + "regexp" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +const phpTrimChars = " \t\n\r\x00\x0B" + +// phpcsIsPlainComment reports whether i is a T_COMMENT: a comment that is +// neither a docblock piece nor a phpcs: annotation. +func phpcsIsPlainComment(f *slvFile, i int) bool { + return f.toks[i].kind == token.Comment && !phpcsIsAnnotation(f, i) +} + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php +// +// SquizBlockComment turns an inline "/** */" docblock into "/* */", a +// one-line "/* text */" ending its line into "// text", drops empty block +// comments and aligns the lines of a multi-line block comment to its star. +type SquizBlockComment struct{} + +func (SquizBlockComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\BlockCommentSniff` +} + +func (SquizBlockComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php" +} + +func (SquizBlockComment) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + switch { + case f.toks[i].doc == slvDocOpen: + squizBlockDocComment(f, i) + case phpcsIsPlainComment(f, i): + squizBlockComment(f, i) + } + } + }) +} + +// squizBlockCommentSkip lists the tokens a docblock may document; one before +// any other is an inline docblock. +var squizBlockCommentSkip = phpcsSet("public", "private", "protected", "public(set)", "protected(set)", "private(set)", + "class", "interface", "trait", "enum", "final", "static", "abstract", "const", "var", "readonly") + +func squizBlockDocComment(f *slvFile, ptr int) { + next := ptr + for { + next = f.nextEffective(next+1, len(f.toks)) + if next >= 0 && f.toks[next].kind == token.AttributeStart && f.toks[next].closer > next { + next = f.toks[next].closer + continue + } + break + } + if next >= 0 && f.toks[next].kind == token.Keyword { + if squizBlockCommentSkip[strings.ToLower(f.toks[next].orig)] || phpcsIsNamedFunction(f, next) { + return + } + } + if prev := max(f.prevEffective(ptr-1), 0); f.toks[prev].kind == token.OpenTag && !phpcsIsEchoTag(f, prev) { + return + } + f.replaceToken(ptr, "/*") + end := ptr + 1 + for end < len(f.toks) && f.toks[end].doc != slvDocClose { + end++ + } + if end < len(f.toks) && f.toks[end].content != "*/" { + f.replaceToken(end, "*/") + } +} + +func phpcsIsEchoTag(f *slvFile, i int) bool { + return strings.HasPrefix(f.toks[i].orig, " 0 && f.isWS(ptr-1) { + indent = f.toks[ptr-1].orig + } + comment := f.toks[ptr].content + if m := squizBlockCommentOpener.FindStringIndex(comment); m != nil { + comment = comment[:m[1]] + f.eol + indent + comment[m[1]:] + } + f.replaceToken(ptr, comment) + return + } + + starColumn := f.toks[ptr].column + hasStars := false + padding := func(line, expected int) string { + if strings.HasPrefix(f.toks[line].orig, "\t") { + return strings.Repeat("\t", expected/phpcsTabStop) + strings.Repeat(" ", expected%phpcsTabStop) + } + return strings.Repeat(" ", expected) + } + expectedFor := func(text string) int { + if text[0] == '*' { + hasStars = true + return starColumn + } + return starColumn + 3 + } + + first := commentLines[1] + if strings.Trim(f.toks[first].content, phpTrimChars) == "" { + f.replaceToken(first, "") + } else { + content := f.toks[first].content + text := strings.TrimLeft(content, phpTrimChars) + expected := expectedFor(text) + if len(content)-len(text) != expected { + f.replaceToken(first, padding(first, expected)+text) + } + } + + lastIndex := len(commentLines) - 1 + for n, line := range commentLines { + if n == 0 || n == 1 || n == lastIndex { + continue + } + content := f.toks[line].content + if strings.Trim(content, phpTrimChars) == "" { + continue + } + text := strings.TrimLeft(content, phpTrimChars) + expected := expectedFor(text) + if len(content)-len(text) < expected { + f.replaceToken(line, padding(line, expected)+text) + } + } + + last := commentLines[lastIndex] + content := f.toks[last].content + text := strings.TrimLeft(content, phpTrimChars) + if text != "*/" && text != "**/" { + return + } + expected := starColumn - 1 + if hasStars { + expected = starColumn + } + if len(content)-len(text) != expected { + f.replaceToken(last, padding(last, expected)+text) + } +} diff --git a/blink/internal/fixer/rules/squiz_class_declaration.go b/blink/internal/fixer/rules/squiz_class_declaration.go new file mode 100644 index 0000000000..a3d54f711a --- /dev/null +++ b/blink/internal/fixer/rules/squiz_class_declaration.go @@ -0,0 +1,134 @@ +package rules + +import ( + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php +// +// SquizClassDeclaration runs PSR2's opening checks, puts the keyword of an +// unmodified declaration at column 1, and wants the closing brace alone on its +// line, at column 1, followed by one blank line. +type SquizClassDeclaration struct { + Indent int +} + +func (SquizClassDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ClassDeclarationSniff` +} + +func (SquizClassDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php" +} + +func (r SquizClassDeclaration) WithConfig(config map[string]any) fixer.Fixer { + r.Indent = configInt(config, "indent", r.Indent) + return r +} + +func (r SquizClassDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if open := phpcsClassyOpener(f, i); open >= 0 { + pearClassDeclaration(f, i, open) + d := classDecl{keyword: i, open: open, parenOpen: -1, indent: r.Indent} + d.processOpen(f) + squizSpaceBeforeKeyword(f, i) + squizClassClose(f, open) + } + } + }) +} + +func squizSpaceBeforeKeyword(f *slvFile, stackPtr int) { + if stackPtr < 1 || !f.isWS(stackPtr-1) || f.toks[stackPtr-1].content == f.eol { + return + } + if f.isKeyword(stackPtr-2, "abstract") || f.isKeyword(stackPtr-2, "final") || f.isKeyword(stackPtr-2, "readonly") { + return + } + f.replaceToken(stackPtr-1, "") +} + +func squizClassClose(f *slvFile, open int) { + closeBrace := f.toks[open].closer + if closeBrace < 0 { + return + } + n := len(f.toks) + line := func(i int) int { return f.toks[i].line } + + nextContent := closeBrace + 1 + for ; nextContent < n; nextContent++ { + if line(nextContent) == line(closeBrace) && + (f.isWS(nextContent) || f.toks[nextContent].kind == token.Comment || phpcsIsAnnotation(f, nextContent)) { + continue + } + if !f.isWS(nextContent) { + break + } + } + + difference := 1 + if nextContent < n { + difference = line(nextContent) - line(closeBrace) - 1 + } + + lastContent := f.prevNonWhitespace(closeBrace - 1) + + if difference == -1 || line(lastContent) == line(closeBrace) { + if difference == -1 { + f.addContentBefore(nextContent, f.eol) + } + if line(lastContent) == line(closeBrace) { + f.addContentBefore(closeBrace, f.eol) + } + } else if f.isWS(closeBrace - 1) { + if f.toks[closeBrace-1].content != f.eol && line(closeBrace-1) == line(closeBrace) { + f.replaceToken(closeBrace-1, "") + } + } + + if difference == -1 || difference == 1 { + return + } + + next := nextContent + for ; next < n; next++ { + if f.isWS(next) { + continue + } + if f.toks[next].doc == slvDocOpen { + for next < n && f.toks[next].doc != slvDocClose { + next++ + } + continue + } + if f.toks[next].kind == token.AttributeStart && f.toks[next].closer >= 0 { + next = f.toks[next].closer + continue + } + break + } + if next < n && f.isKeyword(next, "function") { + return + } + + if difference == 0 { + f.addContentBefore(f.firstOnLine(nextContent), f.eol) + return + } + f.beginChangeset() + for i := closeBrace + 1; i < nextContent; i++ { + if line(i) <= line(closeBrace)+1 { + continue + } + if line(i) == line(nextContent) { + break + } + f.replaceToken(i, "") + } + f.endChangeset() +} diff --git a/blink/internal/fixer/rules/squiz_control_structure_spacing.go b/blink/internal/fixer/rules/squiz_control_structure_spacing.go new file mode 100644 index 0000000000..241d3d68aa --- /dev/null +++ b/blink/internal/fixer/rules/squiz_control_structure_spacing.go @@ -0,0 +1,209 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +// +// SquizControlStructureSpacing removes the spaces inside a control structure's +// parentheses and the blank lines at the start and end of its body, and wants +// one blank line after it. +type SquizControlStructureSpacing struct{} + +func (SquizControlStructureSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ControlStructureSpacingSniff` +} + +func (SquizControlStructureSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php" +} + +var squizControlStructures = phpcsSet("if", "while", "foreach", "for", "switch", "do", "else", "elseif", "try", + "catch", "finally", "match") + +func (SquizControlStructureSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if f.toks[i].kind == token.Keyword && squizControlStructures[sc.code[i]] { + squizControlStructureSpacing(sc, i) + } + } + }) +} + +// squizIgnoredStructure tells the structures whose spacing other sniffs check: +// named functions, classes, interfaces, traits, enums and docblocks. +func squizIgnoredStructure(sc *phpcsScope, i int) bool { + f := sc.f + switch sc.code[i] { + case "function": + return squizFunctionCode(sc, i) == "function" + case "class": + return !phpcsIsAnonClassKeyword(f, i) + case "interface", "trait", "enum": + return true + } + return f.toks[i].kind == token.DocComment && f.toks[i].doc == slvDocOpen +} + +// squizIsComment is T_COMMENT or a phpcs: annotation. +func squizIsComment(f *slvFile, i int) bool { + return f.toks[i].kind == token.Comment || phpcsIsAnnotation(f, i) +} + +func squizControlStructureSpacing(sc *phpcsScope, stackPtr int) { + f := sc.f + n := len(f.toks) + if pc := sc.pCloser[stackPtr]; pc >= 0 && f.toks[pc].closer >= 0 { + po := f.toks[pc].closer + if f.toks[po+1].kind == token.Whitespace { + f.replaceToken(po+1, "") + } + if f.toks[po].line == f.toks[pc].line && f.toks[pc-1].kind == token.Whitespace { + f.replaceToken(pc-1, "") + } + } + scopeCloser := squizScopeCloser(sc, stackPtr) + if scopeCloser < 0 { + return + } + scopeOpener := sc.opener[stackPtr] + firstContent := scopeOpener + 1 + for ; firstContent < n; firstContent++ { + t := f.toks[firstContent] + if t.kind == token.Whitespace || t.kind == token.InlineHTML && strings.TrimSpace(t.content) == "" { + continue + } + if t.line == f.toks[scopeOpener].line && (f.isEmpty(firstContent) || t.kind == token.CloseTag) { + continue + } + break + } + if firstContent >= n { + return + } + if !squizIgnoredStructure(sc, firstContent) && f.toks[firstContent].line >= f.toks[scopeOpener].line+2 { + f.beginChangeset() + for i := scopeOpener + 1; f.toks[i].line != f.toks[firstContent].line; i++ { + if f.toks[i].line != f.toks[scopeOpener].line { + f.replaceToken(i, "") + } + } + f.endChangeset() + } + if firstContent != scopeCloser { + lastContent := max(f.prevNonWhitespace(scopeCloser-1), 0) + lastNonEmpty := max(f.prevEffective(scopeCloser-1), 0) + checkToken := lastContent + if sc.cond[lastNonEmpty] >= 0 { + checkToken = sc.cond[lastNonEmpty] + } + if !squizIgnoredStructure(sc, checkToken) && f.toks[lastContent].line <= f.toks[scopeCloser].line-2 { + f.beginChangeset() + for i := scopeCloser - 1; i > lastContent; i-- { + if f.toks[i].line == f.toks[scopeCloser].line { + continue + } + if f.toks[i].line == f.toks[lastContent].line { + break + } + f.replaceToken(i, "") + } + f.endChangeset() + } + } + if sc.code[stackPtr] == "match" { + if next := f.nextEffective(scopeCloser+1, n); next >= 0 && (f.is(next, ";") || f.is(next, ",")) { + scopeCloser = next + } + } + trailing := max(f.nextNonWhitespace(scopeCloser+1, n), 0) + if squizIsComment(f, trailing) { + nextCode := max(f.nextEffective(scopeCloser+1, n), 0) + if f.isKeyword(nextCode, "else") || f.isKeyword(nextCode, "elseif") || + f.toks[trailing].line == f.toks[scopeCloser].line { + trailing = nextCode + } + } + code := sc.code[stackPtr] + switch { + case f.isKeyword(trailing, "else") && code == "if", + f.isKeyword(trailing, "while") && code == "do", + f.toks[trailing].kind == token.CloseTag: + return + } + if c := sc.cond[trailing]; c >= 0 && c != trailing && sc.opener[trailing] >= 0 && sc.opener[trailing] != trailing { + switch squizFunctionCode(sc, c) { + case "function": + return + case "closure": + if squizInFunction(sc, stackPtr) || sc.nested[stackPtr] >= 0 { + return + } + } + if f.toks[trailing].line != f.toks[scopeCloser].line+1 { + f.beginChangeset() + for i := scopeCloser + 1; f.toks[i].line != f.toks[trailing].line; i++ { + f.replaceToken(i, "") + } + f.addContent(scopeCloser, f.eol) + f.endChangeset() + } + return + } + switch sc.code[trailing] { + case "else", "elseif", "catch", "finally": + return + } + if f.toks[trailing].line != f.toks[scopeCloser].line+1 { + return + } + trailing = max(f.nextNonWhitespace(scopeCloser+1, n), 0) + if squizIsComment(f, trailing) && f.toks[trailing].line == f.toks[scopeCloser].line { + f.addContent(trailing, f.eol) + } else { + f.addContent(scopeCloser, f.eol) + } +} + +// squizFunctionCode is "function" for PHP_CodeSniffer's T_FUNCTION, "closure" +// for T_CLOSURE, else "": the tokenizer only retags a "function (" with a scope +// opener as T_CLOSURE. +func squizFunctionCode(sc *phpcsScope, i int) string { + f := sc.f + switch { + case !f.isKeyword(i, "function"): + return "" + case f.isClosure(i): + if squizScopeCloser(sc, i) >= 0 { + return "closure" + } + return "function" + case phpcsIsNamedFunction(f, i): + return "function" + } + return "" +} + +// squizScopeCloser is the scope_closer of the scope owner at i, or -1. +func squizScopeCloser(sc *phpcsScope, i int) int { + if sc.cond[i] != i || sc.opener[i] < 0 || sc.closer[i] < 0 { + return -1 + } + return sc.closer[i] +} + +// squizInFunction is File::hasCondition(i, [T_FUNCTION, T_CLOSURE]). +func squizInFunction(sc *phpcsScope, i int) bool { + for _, c := range sc.conditions(i) { + if sc.code[c] == "function" { + return true + } + } + return false +} diff --git a/blink/internal/fixer/rules/squiz_control_structures.go b/blink/internal/fixer/rules/squiz_control_structures.go new file mode 100644 index 0000000000..ac24ae4982 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_control_structures.go @@ -0,0 +1,412 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// phpcsNewline marks a PHP_CodeSniffer spacing count: a number of spaces, or -1 +// for "newline". +const phpcsNewline = -1 + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php +// +// SquizControlSignature puts one space after a control keyword and after its +// condition, the body on the line after the opening brace and one space +// between a closing brace and else, elseif, catch, finally or do-while. +type SquizControlSignature struct { + RequiredSpacesBeforeColon int +} + +func (SquizControlSignature) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ControlSignatureSniff` +} + +func (SquizControlSignature) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php" +} + +func (r SquizControlSignature) WithConfig(config map[string]any) fixer.Fixer { + r.RequiredSpacesBeforeColon = configInt(config, "requiredSpacesBeforeColon", r.RequiredSpacesBeforeColon) + return r +} + +var squizControlSignatureCodes = phpcsSet("try", "catch", "finally", "do", "while", "for", "if", "foreach", + "else", "elseif", "switch", "match") + +func (r SquizControlSignature) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if squizControlSignatureCodes[sc.code[i]] { + r.process(sc, i) + } + } + }) +} + +// phpcsWhitespaceFound counts the whitespace token at i the way the sniffs +// report it: 0 when it is not whitespace, -1 when it holds a newline. +func phpcsWhitespaceFound(f *slvFile, i int) int { + if i >= len(f.toks) || f.toks[i].kind != token.Whitespace { + return 0 + } + if strings.Contains(f.toks[i].content, f.eol) { + return phpcsNewline + } + return f.toks[i].length +} + +func (r SquizControlSignature) process(sc *phpcsScope, stackPtr int) { + f := sc.f + if f.nextEffective(stackPtr+1, len(f.toks)) < 0 { + return + } + opener := sc.opener[stackPtr] + isAlternative := opener >= 0 && sc.code[opener] == ":" + parenCloser := sc.pCloser[stackPtr] + + expected := 1 + if parenCloser < 0 && isAlternative { + expected = r.RequiredSpacesBeforeColon + } + found := 1 + if stackPtr+1 < len(f.toks) && (f.toks[stackPtr+1].kind != token.Whitespace || f.toks[stackPtr+1].content != " ") { + found = phpcsWhitespaceFound(f, stackPtr+1) + } + if found != expected { + if found == 0 { + f.addContent(stackPtr, strings.Repeat(" ", expected)) + } else { + f.replaceToken(stackPtr+1, strings.Repeat(" ", expected)) + } + } + + if parenCloser >= 0 && opener >= 0 { + r.afterCloseParenthesis(f, parenCloser, opener, isAlternative) + } + + if opener >= 0 { + squizNewlineAfterOpener(sc, opener) + } else if sc.code[stackPtr] == "while" && parenCloser >= 0 { + if next := f.nextEffective(parenCloser+1, len(f.toks)); next >= 0 && sc.code[next] == ";" { + if phpcsWhitespaceFound(f, parenCloser+1) != 0 { + f.replaceToken(parenCloser+1, "") + } + } + } + + var closer int + switch sc.code[stackPtr] { + case "while": + if sc.closer[stackPtr] >= 0 { + return + } + closer = f.prevEffective(stackPtr - 1) + if closer < 0 || sc.code[closer] != "}" || sc.cond[closer] < 0 || sc.code[sc.cond[closer]] != "do" { + return + } + case "else", "elseif", "catch", "finally": + if isAlternative { + return + } + closer = f.prevEffective(stackPtr - 1) + if closer < 0 || sc.code[closer] != "}" { + return + } + default: + return + } + + found = 1 + switch { + case f.toks[closer+1].kind != token.Whitespace: + found = 0 + case f.toks[closer].line != f.toks[stackPtr].line: + found = phpcsNewline + case f.toks[closer+1].content != " ": + found = f.toks[closer+1].length + } + if found == 1 { + return + } + for i := closer + 1; i < stackPtr; i++ { + if f.isPhpcsComment(i) { + return + } + } + if found == 0 { + f.addContent(closer, " ") + } else { + f.replaceToken(closer+1, " ") + } +} + +func (r SquizControlSignature) afterCloseParenthesis(f *slvFile, closer, opener int, isAlternative bool) { + expected := 1 + if isAlternative { + expected = r.RequiredSpacesBeforeColon + } + var b strings.Builder + for i := closer + 1; i < opener; i++ { + b.WriteString(f.toks[i].content) + } + content := b.String() + blank := strings.TrimSpace(content) == "" + found := -2 + if blank { + found = len(content) + if strings.Contains(content, f.eol) { + found = phpcsNewline + } + } + if found == expected { + return + } + padding := strings.Repeat(" ", expected) + if closer == opener-1 { + f.addContent(closer, padding) + return + } + f.beginChangeset() + if blank { + f.addContent(closer, padding) + if found != 0 { + for i := closer + 1; i < opener; i++ { + f.replaceToken(i, "") + } + } + } else { + f.addContent(closer, padding+f.toks[opener].content) + f.replaceToken(opener, "") + if f.toks[opener].line != f.toks[closer].line { + if next := f.nextNonWhitespace(opener+1, len(f.toks)); next >= 0 && f.toks[next].line != f.toks[opener].line { + for i := opener + 1; i < next; i++ { + f.replaceToken(i, "") + } + } + } + } + f.endChangeset() +} + +func squizNewlineAfterOpener(sc *phpcsScope, opener int) { + f := sc.f + next := opener + 1 + for ; next < len(f.toks); next++ { + t := f.toks[next] + if t.kind == token.Whitespace || t.kind == token.InlineHTML && strings.TrimSpace(t.content) == "" { + continue + } + if t.line == f.toks[opener].line && (f.isEmpty(next) || t.kind == token.CloseTag) { + continue + } + break + } + if next >= len(f.toks) { + next = len(f.toks) - 1 + } + if f.toks[next].line != f.toks[opener].line { + return + } + f.beginChangeset() + for i := opener + 1; i < next; i++ { + if strings.TrimSpace(f.toks[i].content) != "" { + break + } + f.replaceToken(i, "") + } + f.addContent(opener, f.eol) + f.endChangeset() +} + +// phpcsPrevNonWS is File::findPrevious(T_WHITESPACE, start, end, true), stopping +// above end. +func phpcsPrevNonWS(f *slvFile, start, end int) int { + for i := start; i > end; i-- { + if f.toks[i].kind != token.Whitespace { + return i + } + } + return 0 +} + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php +// +// SquizSwitchDeclaration lays out a switch: lowercase CASE and DEFAULT on +// their own lines Indent spaces in, no space before the colon, the breaking +// statement aligned with the CASE and followed by one blank line. +type SquizSwitchDeclaration struct { + Indent int +} + +func (SquizSwitchDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\SwitchDeclarationSniff` +} + +func (SquizSwitchDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php" +} + +func (r SquizSwitchDeclaration) WithConfig(config map[string]any) fixer.Fixer { + r.Indent = configInt(config, "indent", r.Indent) + return r +} + +func (r SquizSwitchDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if sc.code[i] == "switch" { + r.process(sc, i) + } + } + }) +} + +var squizCaseBreakers = phpcsSet("break", "return", "continue", "throw", "exit", "goto") + +// phpcsLineBreakAfter starts a new line at padding after prev, replacing the +// whitespace after it or appending to it. +func phpcsLineBreakAfter(f *slvFile, prev int, padding string) { + if f.toks[prev+1].kind == token.Whitespace { + f.replaceToken(prev+1, f.eol+padding) + } else { + f.addContent(prev, f.eol+padding) + } +} + +// phpcsAlign indents tok, the first on its line, to column-1 spaces. +func phpcsAlign(f *slvFile, tok int, padding string) { + if f.toks[tok].column == 1 || f.toks[tok-1].kind != token.Whitespace { + f.addContentBefore(tok, padding) + } else { + f.replaceToken(tok-1, padding) + } +} + +func (r SquizSwitchDeclaration) process(sc *phpcsScope, stackPtr int) { + f := sc.f + if sc.opener[stackPtr] < 0 || sc.closer[stackPtr] < 0 { + return + } + switchCloser := sc.closer[stackPtr] + caseAlignment := f.toks[stackPtr].column + r.Indent + padding := strings.Repeat(" ", caseAlignment-1) + for nextCase := phpcsNextCase(sc, stackPtr+1, switchCloser); nextCase >= 0; nextCase = phpcsNextCase(sc, nextCase+1, switchCloser) { + isCase := sc.code[nextCase] == "case" + if content := f.toks[nextCase].content; content != strings.ToLower(content) { + f.replaceToken(nextCase, strings.ToLower(content)) + } + if isCase && (f.toks[nextCase+1].kind != token.Whitespace || f.toks[nextCase+1].content != " ") { + if f.toks[nextCase+1].kind != token.Whitespace { + f.addContent(nextCase, " ") + } else { + f.replaceToken(nextCase+1, " ") + } + } + + beforeCase := phpcsPrevNonWS(f, nextCase-1, -1) + if f.toks[beforeCase].line == f.toks[nextCase].line { + phpcsLineBreakAfter(f, beforeCase, padding) + } else if f.toks[nextCase].column != caseAlignment { + phpcsAlign(f, nextCase, padding) + } + + opener := sc.opener[nextCase] + if opener < 0 { + continue + } + if sc.code[opener] == "close_tag" { + f.addContent(phpcsPrevNonWS(f, opener-1, -1), ":") + } + if f.toks[opener-1].kind == token.Whitespace { + f.replaceToken(opener-1, "") + } + + nextBreak := sc.closer[nextCase] + if nextBreak < 0 || !squizCaseBreakers[sc.code[nextBreak]] { + continue + } + if sc.cond[nextBreak] == nextCase { + r.breakLayout(sc, stackPtr, nextCase, opener, nextBreak, caseAlignment, isCase) + } + } +} + +func (r SquizSwitchDeclaration) breakLayout(sc *phpcsScope, stackPtr, nextCase, opener, nextBreak, caseAlignment int, isCase bool) { + f := sc.f + padding := strings.Repeat(" ", caseAlignment-1) + beforeBreak := phpcsPrevNonWS(f, nextBreak-1, -1) + if f.toks[beforeBreak].line == f.toks[nextBreak].line { + phpcsLineBreakAfter(f, beforeBreak, padding) + } else if f.toks[nextBreak].column != caseAlignment { + phpcsAlign(f, nextBreak, padding) + } + + switchCloser := sc.closer[stackPtr] + nextLine := f.toks[switchCloser].line + semicolon := sc.endOfStatement(nextBreak) + nextRelevant := semicolon + 1 + for ; nextRelevant < switchCloser; nextRelevant++ { + if !f.isEmpty(nextRelevant) { + nextLine = f.toks[nextRelevant].line + break + } + if f.toks[nextRelevant].kind != token.Whitespace && f.toks[nextBreak].line != f.toks[nextRelevant].line { + nextLine = f.toks[nextRelevant].line + break + } + } + + if isCase && nextLine != f.toks[semicolon].line+2 && nextRelevant != switchCloser { + f.beginChangeset() + if nextLine == f.toks[semicolon].line { + replacement := f.eol + f.eol + padding + if f.toks[nextRelevant-1].kind == token.Whitespace { + f.replaceToken(nextRelevant-1, replacement) + } else { + f.addContentBefore(nextRelevant, replacement) + } + } else { + for i := semicolon + 1; i < nextRelevant; i++ { + if f.toks[semicolon].line == f.toks[i].line { + if f.toks[i].line != f.toks[i+1].line { + f.addContent(i, f.eol) + } + continue + } + if f.toks[i].line == f.toks[nextRelevant].line { + break + } + f.replaceToken(i, "") + } + } + f.endChangeset() + } + + caseLine := f.toks[nextCase].line + nextLine = f.toks[nextBreak].line + i := opener + 1 + for ; i < nextBreak; i++ { + if !f.isEmpty(i) { + nextLine = f.toks[i].line + break + } + if f.toks[i].kind != token.Whitespace && f.toks[opener].line != f.toks[i].line { + nextLine = f.toks[i].line + break + } + } + if nextLine == caseLine { + pad := f.eol + strings.Repeat(" ", caseAlignment-1+r.Indent) + if f.toks[i-1].kind == token.Whitespace { + f.replaceToken(i-1, pad) + } else { + f.addContentBefore(i, pad) + } + } +} diff --git a/blink/internal/fixer/rules/squiz_function_comment.go b/blink/internal/fixer/rules/squiz_function_comment.go new file mode 100644 index 0000000000..cf8e2857a7 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_function_comment.go @@ -0,0 +1,191 @@ +package rules + +import ( + "regexp" + "slices" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php +// +// SquizFunctionComment is PEARFunctionComment's blank-line fix plus the Squiz +// type spellings of @param and @return ("int" -> "integer") and the alignment +// of @param types and names. +type SquizFunctionComment struct{} + +func (SquizFunctionComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff` +} + +func (SquizFunctionComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php" +} + +func (SquizFunctionComment) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if !phpcsIsNamedFunction(f, i) { + continue + } + if commentEnd, tags, ok := pearFunctionCommentPreamble(f, i); ok { + squizProcessReturn(f, tags) + squizProcessParams(f, commentEnd, tags) + } + } + }) +} + +var squizReturnParts = regexp.MustCompile(`(?i)^((?:\|?(?:array\([^\)]*\)|[\\a-z0-9_\[\]]+))*)( .*)?`) + +func squizSuggestTypes(typ string) string { + var names []string + for name := range strings.SplitSeq(typ, "|") { + if s := phpcsSuggestType(name); !slices.Contains(names, s) { + names = append(names, s) + } + } + return strings.Join(names, "|") +} + +func squizProcessReturn(f *slvFile, tags []int) { + ret := -1 + for _, tag := range tags { + if f.toks[tag].content == "@return" { + if ret >= 0 { + return + } + ret = tag + } + } + if ret < 0 || ret+2 >= len(f.toks) { + return + } + content := f.toks[ret+2].content + if content == "" || content == "0" || f.toks[ret+2].doc != slvDocString { + return + } + m := squizReturnParts.FindStringSubmatch(content) + if want := squizSuggestTypes(m[1]); want != m[1] { + f.replaceToken(ret+2, want+m[2]) + } +} + +type squizCommentLine struct { + comment string + token int + indent int +} + +type squizParam struct { + tag int + typ, varName string + comment string + lines []squizCommentLine + typeSpace, varSpace int +} + +func squizProcessParams(f *slvFile, commentCloser int, tags []int) { + var params []squizParam + maxType, maxVar := 0, 0 + for pos, tag := range tags { + if f.toks[tag].content != "@param" { + continue + } + p := squizParam{tag: tag} + if tag+2 < len(f.toks) && f.toks[tag+2].doc == slvDocString { + content := f.toks[tag+2].content + m := pearParseParam(content) + typeLen := len(m.typ) + p.typ = strings.Trim(m.typ, " \t\n\r\x00\x0B") + p.typeSpace = typeLen - len(p.typ) + maxType = max(maxType, len(p.typ)) + if content[0] != '$' && m.hasVar { + p.varName = m.varName + maxVar = max(maxVar, len(p.varName)) + if m.hasComment { + p.varSpace = len(m.space) + p.comment = m.comment + p.lines = append(p.lines, squizCommentLine{comment: m.comment, token: tag + 2, indent: p.varSpace}) + end := commentCloser + if pos+1 < len(tags) { + end = tags[pos+1] + } + for i := tag + 3; i < end; i++ { + if f.toks[i].doc != slvDocString { + continue + } + indent := 0 + if f.toks[i-1].doc == slvDocWhitespace { + indent = f.toks[i-1].length + } + p.comment += " " + f.toks[i].content + p.lines = append(p.lines, squizCommentLine{comment: f.toks[i].content, token: i, indent: indent}) + } + } else { + p.lines = append(p.lines, squizCommentLine{token: -1}) + } + } + } + params = append(params, p) + } + + for _, p := range params { + if p.typ == "" { + continue + } + var suggested []string + for name := range strings.SplitSeq(p.typ, "|") { + if name == "" { + continue + } + suggested = append(suggested, phpcsSuggestType(strings.TrimPrefix(name, "?"))) + } + if want := strings.Join(suggested, "|"); want != p.typ { + first := "" + if len(p.lines) > 0 { + first = p.lines[0].comment + } + diff := len(p.typ) - len(want) + f.beginChangeset() + f.replaceToken(p.tag+2, want+strings.Repeat(" ", p.typeSpace)+p.varName+strings.Repeat(" ", p.varSpace)+first) + squizReindentLines(f, p.lines, diff, false) + f.endChangeset() + } + if p.varName == "" { + continue + } + if spaces := maxType - len(p.typ) + 1; p.typeSpace != spaces { + f.beginChangeset() + f.replaceToken(p.tag+2, p.typ+strings.Repeat(" ", spaces)+p.varName+strings.Repeat(" ", p.varSpace)+p.lines[0].comment) + squizReindentLines(f, p.lines, p.typeSpace-spaces, true) + f.endChangeset() + } + if p.comment == "" { + continue + } + if spaces := maxVar - len(p.varName) + 1; p.varSpace != spaces { + f.beginChangeset() + f.replaceToken(p.tag+2, p.typ+strings.Repeat(" ", p.typeSpace)+p.varName+strings.Repeat(" ", spaces)+p.lines[0].comment) + squizReindentLines(f, p.lines, p.varSpace-spaces, true) + f.endChangeset() + } + } +} + +// squizReindentLines shifts the indent of a param comment's continuation +// lines by diff; skipNonPositive mirrors the checks that leave an indent +// that would drop to zero or below alone. +func squizReindentLines(f *slvFile, lines []squizCommentLine, diff int, skipNonPositive bool) { + for n, l := range lines { + if n == 0 || l.indent == 0 { + continue + } + indent := l.indent - diff + if indent <= 0 && skipNonPositive { + continue + } + f.replaceToken(l.token-1, strings.Repeat(" ", max(indent, 0))) + } +} diff --git a/blink/internal/fixer/rules/squiz_scope_closing_brace.go b/blink/internal/fixer/rules/squiz_scope_closing_brace.go new file mode 100644 index 0000000000..9b60f426f6 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_scope_closing_brace.go @@ -0,0 +1,103 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php +// +// SquizScopeClosingBrace puts a scope's closing brace on its own line, in the +// column of the first content on the line that opens the scope. +type SquizScopeClosingBrace struct{} + +func (SquizScopeClosingBrace) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeClosingBraceSniff` +} + +func (SquizScopeClosingBrace) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php" +} + +func (r SquizScopeClosingBrace) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if phpcsScopeOpenerCodes[sc.code[i]] { + r.process(sc, i) + } + } + }) +} + +func (SquizScopeClosingBrace) process(sc *phpcsScope, stackPtr int) { + f := sc.f + scopeEnd := sc.closer[stackPtr] + if scopeEnd < 0 { + return + } + scopeStart := sc.opener[stackPtr] + lineStart := squizFirstOnLine(sc, stackPtr) + for squizConstantString(f, lineStart) && squizConstantString(f, lineStart-1) { + lineStart = squizFirstOnLine(sc, lineStart-1) + } + startColumn := f.toks[lineStart].column + + lastContent := 0 + for i := scopeEnd - 1; i >= scopeStart && i >= 0; i-- { + if c := sc.code[i]; c != "inline_html" && c != "whitespace" && c != "open_tag" { + lastContent = i + break + } + } + lineStart = scopeEnd + for lineStart > 0 && f.toks[lineStart].column > 1 { + lineStart-- + } + if f.toks[lastContent].line == f.toks[scopeEnd].line || + sc.code[lineStart] == "inline_html" && strings.TrimSpace(f.toks[lineStart].content) != "" { + at := lineStart + 1 + if f.toks[lastContent].line == f.toks[scopeEnd].line { + at = scopeEnd + } + f.replaceToken(at, f.eol+f.tokenContent(at)) + return + } + + lineStart = squizFirstOnLine(sc, scopeEnd) + braceIndent := f.toks[lineStart].column + if c := sc.code[stackPtr]; c == "default" || c == "case" || braceIndent == startColumn { + return + } + if diff := startColumn - braceIndent; diff > 0 { + f.replaceToken(lineStart, strings.Repeat(" ", diff)+f.tokenContent(lineStart)) + } else if lineStart > 0 { + v := f.tokenContent(lineStart - 1) + f.replaceToken(lineStart-1, v[:max(0, len(v)+diff)]) + } +} + +// squizFirstOnLine is File::findFirstOnLine([T_WHITESPACE, T_INLINE_HTML], +// start, true): the first token on start's line that is neither, or 0 for +// none (PHP reads $tokens[false] as $tokens[0]). +func squizFirstOnLine(sc *phpcsScope, start int) int { + found := 0 + line := sc.f.toks[start].line + for i := start; i >= 0 && sc.f.toks[i].line == line; i-- { + if c := sc.code[i]; c != "whitespace" && c != "inline_html" { + found = i + } + } + return found +} + +// squizConstantString reports a T_CONSTANT_ENCAPSED_STRING token. +func squizConstantString(f *slvFile, i int) bool { + if i < 0 || i >= len(f.toks) { + return false + } + t := f.toks[i] + return t.kind == token.String && !t.heredoc && !t.interp +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc new file mode 100644 index 0000000000..eafa67896a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc @@ -0,0 +1,1687 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false + +hello(); + } + + function hello() + { + echo 'hello'; +}//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+    $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): +if ($bar) $foo = 1; +elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { +if (false) { +echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( +'some long description', function () { + }); +} + +switch ( $a ) { +case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'b': + $b = 3; +?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, +false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => +$value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +// Issue #110. +echo match (1) { + 0 => match (2) { + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, + 1 => match (2) { + 1 => match (3) { + 3 => 3, + default => -1, + }, + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, +}; + +// Issue #437. +match (true) { + default => [ + 'unrelated' => '', + 'example' => array_filter( + array_map( + function () { + return null; + }, + [] + ) + ) + ] +}; + +// Issue squizlabs/PHP_CodeSniffer#3808 +function test() { + yield + from [ 3, 4 ]; +} + +// Issue #968: Arrow function in function call argument +return json_encode( + array_filter( + [ + 'foo' => 42, + 'bar' => null, + ], + static fn(mixed $value) => $value !== null + ), + JSON_THROW_ON_ERROR +); + +// Issue #968: Arrow function with multiple arguments +$result = array_map( + static fn($a, $b) => $a + $b, + $array1, + $array2 +); + +// Issue #968: Nested arrow function +$result = array_map( + static fn($x) => array_filter( + $x, + static fn($y) => $y > 0 + ), + $data +); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc.fixed new file mode 100644 index 0000000000..6ea0da84bc --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc.fixed @@ -0,0 +1,1687 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false + +hello(); + } + + function hello() + { + echo 'hello'; + }//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+    $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): + if ($bar) $foo = 1; + elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { + if (false) { + echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( + 'some long description', function () { + }); +} + +switch ( $a ) { + case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'b': + $b = 3; + ?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => + $value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +// Issue #110. +echo match (1) { + 0 => match (2) { + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, + 1 => match (2) { + 1 => match (3) { + 3 => 3, + default => -1, + }, + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, +}; + +// Issue #437. +match (true) { + default => [ + 'unrelated' => '', + 'example' => array_filter( + array_map( + function () { + return null; + }, + [] + ) + ) + ] +}; + +// Issue squizlabs/PHP_CodeSniffer#3808 +function test() { + yield + from [ 3, 4 ]; +} + +// Issue #968: Arrow function in function call argument +return json_encode( + array_filter( + [ + 'foo' => 42, + 'bar' => null, + ], + static fn(mixed $value) => $value !== null + ), + JSON_THROW_ON_ERROR +); + +// Issue #968: Arrow function with multiple arguments +$result = array_map( + static fn($a, $b) => $a + $b, + $array1, + $array2 +); + +// Issue #968: Nested arrow function +$result = array_map( + static fn($x) => array_filter( + $x, + static fn($y) => $y > 0 + ), + $data +); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.2.inc new file mode 100644 index 0000000000..2bca107c35 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.2.inc @@ -0,0 +1,1687 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent true + +hello(); + } + + function hello() + { + echo 'hello'; +}//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+	$safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): +if ($bar) $foo = 1; +elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { +if (false) { +echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( +'some long description', function () { + }); +} + +switch ( $a ) { +case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'b': + $b = 3; +?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, +false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => +$value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +// Issue #110. +echo match (1) { + 0 => match (2) { + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, + 1 => match (2) { + 1 => match (3) { + 3 => 3, + default => -1, + }, + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, +}; + +// Issue #437. +match (true) { + default => [ + 'unrelated' => '', + 'example' => array_filter( + array_map( + function () { + return null; + }, + [] + ) + ) + ] +}; + +// Issue squizlabs/PHP_CodeSniffer#3808 +function test() { + yield + from [ 3, 4 ]; +} + +// Issue #968: Arrow function in function call argument +return json_encode( + array_filter( + [ + 'foo' => 42, + 'bar' => null, + ], + static fn(mixed $value) => $value !== null + ), + JSON_THROW_ON_ERROR +); + +// Issue #968: Arrow function with multiple arguments +$result = array_map( + static fn($a, $b) => $a + $b, + $array1, + $array2 +); + +// Issue #968: Nested arrow function +$result = array_map( + static fn($x) => array_filter( + $x, + static fn($y) => $y > 0 + ), + $data +); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.2.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.2.inc.fixed new file mode 100644 index 0000000000..a15054dad9 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.2.inc.fixed @@ -0,0 +1,1687 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent true + +hello(); + } + + function hello() + { + echo 'hello'; + }//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+	$safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): + if ($bar) $foo = 1; + elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { + if (false) { + echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( + 'some long description', function () { + }); +} + +switch ( $a ) { + case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'b': + $b = 3; + ?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => + $value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +// Issue #110. +echo match (1) { + 0 => match (2) { + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, + 1 => match (2) { + 1 => match (3) { + 3 => 3, + default => -1, + }, + 2 => match (3) { + 3 => 3, + default => -1, + }, + }, +}; + +// Issue #437. +match (true) { + default => [ + 'unrelated' => '', + 'example' => array_filter( + array_map( + function () { + return null; + }, + [] + ) + ) + ] +}; + +// Issue squizlabs/PHP_CodeSniffer#3808 +function test() { + yield + from [ 3, 4 ]; +} + +// Issue #968: Arrow function in function call argument +return json_encode( + array_filter( + [ + 'foo' => 42, + 'bar' => null, + ], + static fn(mixed $value) => $value !== null + ), + JSON_THROW_ON_ERROR +); + +// Issue #968: Arrow function with multiple arguments +$result = array_map( + static fn($a, $b) => $a + $b, + $array1, + $array2 +); + +// Issue #968: Nested arrow function +$result = array_map( + static fn($x) => array_filter( + $x, + static fn($y) => $y > 0 + ), + $data +); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.3.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.3.inc new file mode 100644 index 0000000000..dd095617c2 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.3.inc @@ -0,0 +1,34 @@ + $enabled, + 'compression' => $compression, + ] = $options; +} + +$this->foo() + ->bar() + ->baz(); + +// Issue squizlabs/PHP_CodeSniffer#3808 +function test() { + yield + from [ 3, 4 ]; +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.4.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.4.inc new file mode 100644 index 0000000000..e58dc4de70 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.4.inc @@ -0,0 +1,6 @@ + 1, + ); +} + +class TestClass +{ + public $good = array( + 'width' => '', + 'height' => '', + ); + + private $_bad = ARRAY( + 'width' => '', + 'height' => '' + ); + + + public function test() + { + $truck = array( + 'width' => '', + 'height' => '', + ); + + $plane = Array( + 'width' => '', + 'height' => '', + ); + + $car = array( + 'width' => '', + 'height' => '', + ); + + $bus = array( + 'width' => '', + 'height' => '' + ); + + $train = array ( + TRUE, + FALSE, + 'aaa' + ); + + $inline = array('aaa', 'bbb', 'ccc'); + $inline = array('aaa'); + $inline = Array('aaa'); + + $bigone = array( + 'name' => 'bigone', + 'children' => Array( + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => Array( + 'child' => 'aaa', + ), + ), + 'short_name' => 'big' + ); + } + +}//end class + +$value = array ( ); +$value = array( ); +$value = array('1'=>$one, '2' => $two, '3'=> $three, '4' =>$four); +$value = array('1'=>$one); + +if (in_array('1', array('1','2','3')) === TRUE) { + $value = in_array('1', array('1' , '2', '3','4')); +} + +$value = array( + '1'=> TRUE, + FALSE, + '3' => 'aaa',); + +$value = array( + '1'=> TRUE, + FALSE, + ); + +$value = array( + TRUE, + '1' => FALSE, + ); + +$value = array(1, + 2 , + 3 , + ); + +$value = array(1 => $one, + 2 => $two , + 3 => $three , + ); + +$value = array( + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2, + ), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2 + ) + ); + +// Space in second arg. +$args = array( + '"'.$this->id.'"', + (int) $hasSessions, + ); + +// No errors. +$paths = array( + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ); + +$x = array( + ); + +$x = array('test' + ); +$x = array('test', + ); +$x = array('name' => 'test', + ); + +$x = array( + $x, + ); + +$func = array( + $x, + 'get'.$x.'Replacement' + ); + +$array = array( + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ); + +$array = array( + 'input_one', + 'inputTwo', + 'input_3', + ); + +// Malformed +$foo = array(1 +, 2); + +$listItems[$aliasPath] = array('itemContent' => implode('
', $aliases)); + +$listItems[$aliasPath] = array( + 'itemContent' => implode('
', $aliases) + ); + +$x = array + ( + $x, + $y, + ); + +$x = array +( + $x, + $y, + ); + +$x = array( + + $x, + $y, + ); + +$test = array( + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ); + +$c = array('a' => 1,); + +function b() +{ + $a = array( + 'a' => a('a'), + + ); + +} + +$foo = Array('[',']',':',"\n","\r"); +$bar = Array('[',']',':',' ',' '); + +function foo() +{ + return array($a, $b->screen); +} + +$array = array( + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => array( + new \Zend\Validator\InArray(array('haystack' => array_keys($aSubjects))), + ), + ); + +$var = array( + 'ViewHelper', + array('Foo'), + 'Errors', + ); + +$data = array( + 'first', + 'second', + 'third', + // Add more here + ); + +$data = array( + 'first', + 'second', + //'third', + ); + +$data = array( + 'first', + 'second' + //'third', + ); + +$foo = array( + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ); + +$foo = array( + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ); + +$weightings = array( + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ); + +foreach (array( + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ) as $key => $value) { +} + +$ids = array( + '1', // Foo. + '13', // Bar. + ); + +array( + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + } +); + +array( + 'key1' => array( + '1', + '2', + ) +); + +$var = array( + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ); + +function test() : array +{ + return []; +} + +$fields = array( + 'id' => array('type' => 'INT'), + 'value' => array('type' => 'VARCHAR')); + +get_current_screen()->add_help_tab( array( + 'id' => << false); + +$x = array( + 'xxxx' => array('aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false), +); + +$foo = array + ('foo' => array + ('bar1' => 1 + ,'bar2' => 1 + ,'bar3' => 1 + ,'bar4' => 1 + ,'bar5' => 1 + ) + ); + +$foo = array( + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], array('notverified', 'unverified'), true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ); + +$foo = foo( + array( + // comment + ) +); + +$foo = array( + << lorem( + 1 + ), 2 => 2, +); + +$foo = array( + 'тип' => 'авто', + 'цвет' => 'синий', + ); + +$paths = array( + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ); + +$foo = array(<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ); + +$array = array( + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ); + +$foo = array( + $this->fn => 'value', + $foo->fn => 'value', + ); + +array($a, $b, +$c); + +array('a' => $a, 'b' => $b, +'c' => $c); + +array( + static function() { + return null; + }, + (array) array(), + (bool) array(), + (double) array(), + (int) array(), + (object) array(), + (string) array(), + (unset) array(), +); + +array( + 'foo', + 'bar' + // This is a non-fixable error. + , +); + +yield array( + static fn () : string => '', +); + +yield array( + static fn () : string => '', + ); + +$foo = array( + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ); + +// Intentional syntax error. +$a = array( + 'a' => + ); + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = array( + ...$a, + 'foo' => 'bar', + ); + +$x = array( + 'foo' => 'bar', + ...$a, + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ); + +$x = array( + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ); + +$x = array( + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ); + +$x = array( + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ); + + $x = + array( + 'a', + 'b', + ); + +$x = array( + 1, static fn (float $item): float => match ($item) { + 2.0 => 3.0, + default => $item + }, + ); + +$x = array( + 1, static::helloWorld(), $class instanceof static, + 2, + ); + +$noSpaceBeforeDoubleArrow = array( + 'width'=> '', + 'height' => '', + ); + +$newlineAfterDoubleArrow = array( + 'width' => + '', + 'height' => '', + ); diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.1.inc.fixed new file mode 100644 index 0000000000..048f898c8d --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.1.inc.fixed @@ -0,0 +1,598 @@ + 1); +} + +class TestClass +{ + public $good = array( + 'width' => '', + 'height' => '', + ); + + private $_bad = array( + 'width' => '', + 'height' => '', + ); + + + public function test() + { + $truck = array( + 'width' => '', + 'height' => '', + ); + + $plane = array( + 'width' => '', + 'height' => '', + ); + + $car = array( + 'width' => '', + 'height' => '', + ); + + $bus = array( + 'width' => '', + 'height' => '', + ); + + $train = array( + TRUE, + FALSE, + 'aaa', + ); + + $inline = array( + 'aaa', + 'bbb', + 'ccc', + ); + $inline = array('aaa'); + $inline = array('aaa'); + + $bigone = array( + 'name' => 'bigone', + 'children' => array( + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => array('child' => 'aaa'), + ), + 'short_name' => 'big', + ); + } + +}//end class + +$value = array(); +$value = array(); +$value = array( + '1' => $one, + '2' => $two, + '3' => $three, + '4' => $four, + ); +$value = array('1' => $one); + +if (in_array('1', array('1', '2', '3')) === TRUE) { + $value = in_array('1', array('1', '2', '3', '4')); +} + +$value = array( + '1'=> TRUE, + FALSE, + '3' => 'aaa', + ); + +$value = array( + '1'=> TRUE, + FALSE, + ); + +$value = array( + TRUE, + '1' => FALSE, + ); + +$value = array( + 1, + 2, + 3, + ); + +$value = array( + 1 => $one, + 2 => $two, + 3 => $three, + ); + +$value = array( + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2, + ), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2, + ), + ); + +// Space in second arg. +$args = array( + '"'.$this->id.'"', + (int) $hasSessions, + ); + +// No errors. +$paths = array( + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ); + +$x = array(); + +$x = array('test'); +$x = array('test'); +$x = array('name' => 'test'); + +$x = array($x); + +$func = array( + $x, + 'get'.$x.'Replacement', + ); + +$array = array( + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ); + +$array = array( + 'input_one', + 'inputTwo', + 'input_3', + ); + +// Malformed +$foo = array( + 1, + 2, + ); + +$listItems[$aliasPath] = array('itemContent' => implode('
    ', $aliases)); + +$listItems[$aliasPath] = array( + 'itemContent' => implode('
    ', $aliases), + ); + +$x = array( + $x, + $y, + ); + +$x = array( + $x, + $y, + ); + +$x = array( + + $x, + $y, + ); + +$test = array( + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ); + +$c = array('a' => 1); + +function b() +{ + $a = array( + 'a' => a('a'), + + ); + +} + +$foo = array( + '[', + ']', + ':', + "\n", + "\r", + ); +$bar = array( + '[', + ']', + ':', + ' ', + ' ', + ); + +function foo() +{ + return array( + $a, + $b->screen, + ); +} + +$array = array( + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => array( + new \Zend\Validator\InArray(array('haystack' => array_keys($aSubjects))), + ), + ); + +$var = array( + 'ViewHelper', + array('Foo'), + 'Errors', + ); + +$data = array( + 'first', + 'second', + 'third', + // Add more here + ); + +$data = array( + 'first', + 'second', + //'third', + ); + +$data = array( + 'first', + 'second', + //'third', + ); + +$foo = array( + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ); + +$foo = array( + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ); + +$weightings = array( + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ); + +foreach (array( + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ) as $key => $value) { +} + +$ids = array( + '1', // Foo. + '13', // Bar. + ); + +array( + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + }, +); + +array( + 'key1' => array( + '1', + '2', + ), +); + +$var = array( + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ); + +function test() : array +{ + return []; +} + +$fields = array( + 'id' => array('type' => 'INT'), + 'value' => array('type' => 'VARCHAR'), + ); + +get_current_screen()->add_help_tab( array( + 'id' => << false); + +$x = array( + 'xxxx' => array( + 'aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false, + ), + ); + +$foo = array( + 'foo' => array( + 'bar1' => 1, + 'bar2' => 1, + 'bar3' => 1, + 'bar4' => 1, + 'bar5' => 1, + ), + ); + +$foo = array( + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], array('notverified', 'unverified'), true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ); + +$foo = foo( + array( + // comment + ) +); + +$foo = array( + << lorem( + 1 + ), + 2 => 2, +); + +$foo = array( + 'тип' => 'авто', + 'цвет' => 'синий', + ); + +$paths = array( + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ); + +$foo = array(<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ); + +$array = array( + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ); + +$foo = array( + $this->fn => 'value', + $foo->fn => 'value', + ); + +array( + $a, + $b, + $c, +); + +array( + 'a' => $a, + 'b' => $b, + 'c' => $c, +); + +array( + static function() { + return null; + }, + (array) array(), + (bool) array(), + (double) array(), + (int) array(), + (object) array(), + (string) array(), + (unset) array(), +); + +array( + 'foo', + 'bar' + // This is a non-fixable error. + , +); + +yield array( + static fn () : string => '', + ); + +yield array( + static fn () : string => '', + ); + +$foo = array( + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ); + +// Intentional syntax error. +$a = array( + 'a' => + ); + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = array( + ...$a, + 'foo' => 'bar', + ); + +$x = array( + 'foo' => 'bar', + ...$a, + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ); + +$x = array( + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ); + +$x = array( + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ); + +$x = array( + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ); + + $x = + array( + 'a', + 'b', + ); + +$x = array( + 1, + static fn (float $item): float => match ($item) { + 2.0 => 3.0, + default => $item + }, + ); + +$x = array( + 1, + static::helloWorld(), + $class instanceof static, + 2, + ); + +$noSpaceBeforeDoubleArrow = array( + 'width' => '', + 'height' => '', + ); + +$newlineAfterDoubleArrow = array( + 'width' => '', + 'height' => '', + ); diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.2.inc new file mode 100644 index 0000000000..415042d89e --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.2.inc @@ -0,0 +1,555 @@ + 1, + ]; +} + +class TestClass +{ + public $good = [ + 'width' => '', + 'height' => '', + ]; + + private $_bad = [ + 'width' => '', + 'height' => '' + ]; + + + public function test() + { + $truck = [ + 'width' => '', + 'height' => '', + ]; + + $plane = [ + 'width' => '', + 'height' => '', + ]; + + $car = [ + 'width' => '', + 'height' => '', + ]; + + $bus = [ + 'width' => '', + 'height' => '' + ]; + + $train = [ + TRUE, + FALSE, + 'aaa' + ]; + + $inline = ['aaa', 'bbb', 'ccc']; + $inline = ['aaa']; + $inline = ['aaa']; + + $bigone = [ + 'name' => 'bigone', + 'children' => [ + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => [ + 'child' => 'aaa', + ], + ], + 'short_name' => 'big' + ]; + } + +}//end class + +$value = [ ]; +$value = [ ]; +$value = ['1'=>$one, '2' => $two, '3'=> $three, '4' =>$four]; +$value = ['1'=>$one]; + +if (in_array('1', ['1','2','3']) === TRUE) { + $value = in_array('1', ['1' , '2', '3','4']); +} + +$value = [ + '1'=> TRUE, + FALSE, + '3' => 'aaa',]; + +$value = [ + '1'=> TRUE, + FALSE, + ]; + +$value = [ + TRUE, + '1' => FALSE, + ]; + +$value = [1, + 2 , + 3 , + ]; + +$value = [1 => $one, + 2 => $two , + 3 => $three , + ]; + +$value = [ + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2, + ], + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2 + ] + ]; + +// Space in second arg. +$args = [ + '"'.$this->id.'"', + (int) $hasSessions, + ]; + +// No errors. +$paths = [ + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ]; + +$x = [ + ]; + +$x = ['test' + ]; +$x = ['test', + ]; +$x = ['name' => 'test', + ]; + +$x = [ + $x, + ]; + +$func = [ + $x, + 'get'.$x.'Replacement' + ]; + +$array = [ + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ]; + +$array = [ + 'input_one', + 'inputTwo', + 'input_3', + ]; + +// Malformed +$foo = [1 +, 2]; + +$listItems[$aliasPath] = ['itemContent' => implode('
    ', $aliases)]; + +$listItems[$aliasPath] = [ + 'itemContent' => implode('
    ', $aliases) + ]; + +$x = + [ + $x, + $y, + ]; + +$x = +[ + $x, + $y, + ]; + +$x = [ + + $x, + $y, + ]; + +$test = [ + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ]; + +$c = ['a' => 1,]; +$c->{$var}[ ] = 2; + +$foo = ['[',']',':',"\n","\r"]; +$bar = ['[',']',':',' ',' ']; + +function foo() +{ + return [$a, $b->screen]; +} + +$array = [ + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => [ + new \Zend\Validator\InArray(['haystack' => array_keys($aSubjects)]), + ], + ]; + +$var = [ + 'ViewHelper', + ['Foo'], + 'Errors', + ]; + +$data = [ + 'first', + 'second', + 'third', + // Add more here + ]; + +$data = [ + 'first', + 'second', + //'third', + ]; + +$data = [ + 'first', + 'second' + //'third', + ]; + +$foo = [ + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ]; + +$foo = [ + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ]; + +$weightings = [ + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ]; + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} + +$ids = [ + '1', // Foo. + '13', // Bar. + ]; + +[ + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + } +]; + +[ + 'key1' => [ + '1', + '2', + ] +]; + +$var = [ + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ]; + +function test() : array +{ + return []; +} + +$fields = [ + 'id' => ['type' => 'INT'], + 'value' => ['type' => 'VARCHAR']]; + +get_current_screen()->add_help_tab( [ + 'id' => << false]; + +$x = [ + 'xxxx' => ['aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false], +]; + +$foo = ['foo' => ['bar1' => 1 + ,'bar2' => 1 + ,'bar3' => 1 + ,'bar4' => 1 + ,'bar5' => 1 + ] + ]; + +$foo = [ + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], ['notverified', 'unverified'], true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ]; + + +$foo = foo( + [ + // comment + ] +); + +$foo = [ + << lorem( + 1 + ), 2 => 2, +]; + +$foo = [ + 'тип' => 'авто', + 'цвет' => 'синий', + ]; + +$paths = [ + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ]; + +$foo = [<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ]; + +$array = [ + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ]; + +$foo = [ + $this->fn => 'value', + $foo->fn => 'value', + ]; + +[$a, $b, +$c]; + +['a' => $a, 'b' => $b, +'c' => $c]; + +[ + static function() { + return null; + }, + (array) [], + (bool) [], + (double) [], + (int) [], + (object) [], + (string) [], + (unset) [], +]; + +[ + 'foo', + 'bar' + // This is a non-fixable error. + , +]; + +yield [ + static fn () : string => '', +]; + +yield [ + static fn () : string => '', + ]; + +$foo = [ + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ]; + +// Intentional syntax error. +$a = [ + 'a' => + ]; + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = [ + ...$a, + 'foo' => 'bar', + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ]; + +$x = [ + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ]; + +$x = [ + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ]; + +$x = [ + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ]; + + $x = + [ + 'a', + 'b', + ]; + +$x = [ + 1, static fn (float $item): float => match ($item) { + 2.0 => 3.0, + default => $item + }, + ]; + +$x = [ + 1, static::helloWorld(), $class instanceof static, + 2, + ]; + +$noSpaceBeforeDoubleArrow = [ + 'width'=> '', + 'height' => '', + ]; + +$newlineAfterDoubleArrow = [ + 'width' => + '', + 'height' => '', + ]; + +// Sniff should ignore short lists when inside a foreach. +// https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/527 +foreach ($data as [, , $value]) {} +foreach ($array as $k => [$v1, , $v3]) {} +foreach ([$a ,$b] as $c) {} // Not a short list. Sniff should handle it. diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.2.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.2.inc.fixed new file mode 100644 index 0000000000..d835064ba1 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.2.inc.fixed @@ -0,0 +1,591 @@ + 1]; +} + +class TestClass +{ + public $good = [ + 'width' => '', + 'height' => '', + ]; + + private $_bad = [ + 'width' => '', + 'height' => '', + ]; + + + public function test() + { + $truck = [ + 'width' => '', + 'height' => '', + ]; + + $plane = [ + 'width' => '', + 'height' => '', + ]; + + $car = [ + 'width' => '', + 'height' => '', + ]; + + $bus = [ + 'width' => '', + 'height' => '', + ]; + + $train = [ + TRUE, + FALSE, + 'aaa', + ]; + + $inline = [ + 'aaa', + 'bbb', + 'ccc', + ]; + $inline = ['aaa']; + $inline = ['aaa']; + + $bigone = [ + 'name' => 'bigone', + 'children' => [ + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => ['child' => 'aaa'], + ], + 'short_name' => 'big', + ]; + } + +}//end class + +$value = []; +$value = []; +$value = [ + '1' => $one, + '2' => $two, + '3' => $three, + '4' => $four, + ]; +$value = ['1' => $one]; + +if (in_array('1', ['1', '2', '3']) === TRUE) { + $value = in_array('1', ['1', '2', '3', '4']); +} + +$value = [ + '1'=> TRUE, + FALSE, + '3' => 'aaa', + ]; + +$value = [ + '1'=> TRUE, + FALSE, + ]; + +$value = [ + TRUE, + '1' => FALSE, + ]; + +$value = [ + 1, + 2, + 3, + ]; + +$value = [ + 1 => $one, + 2 => $two, + 3 => $three, + ]; + +$value = [ + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2, + ], + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2, + ], + ]; + +// Space in second arg. +$args = [ + '"'.$this->id.'"', + (int) $hasSessions, + ]; + +// No errors. +$paths = [ + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ]; + +$x = []; + +$x = ['test']; +$x = ['test']; +$x = ['name' => 'test']; + +$x = [$x]; + +$func = [ + $x, + 'get'.$x.'Replacement', + ]; + +$array = [ + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ]; + +$array = [ + 'input_one', + 'inputTwo', + 'input_3', + ]; + +// Malformed +$foo = [ + 1, + 2, + ]; + +$listItems[$aliasPath] = ['itemContent' => implode('
    ', $aliases)]; + +$listItems[$aliasPath] = [ + 'itemContent' => implode('
    ', $aliases), + ]; + +$x = + [ + $x, + $y, + ]; + +$x = +[ + $x, + $y, +]; + +$x = [ + + $x, + $y, + ]; + +$test = [ + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ]; + +$c = ['a' => 1]; +$c->{$var}[ ] = 2; + +$foo = [ + '[', + ']', + ':', + "\n", + "\r", + ]; +$bar = [ + '[', + ']', + ':', + ' ', + ' ', + ]; + +function foo() +{ + return [ + $a, + $b->screen, + ]; +} + +$array = [ + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => [ + new \Zend\Validator\InArray(['haystack' => array_keys($aSubjects)]), + ], + ]; + +$var = [ + 'ViewHelper', + ['Foo'], + 'Errors', + ]; + +$data = [ + 'first', + 'second', + 'third', + // Add more here + ]; + +$data = [ + 'first', + 'second', + //'third', + ]; + +$data = [ + 'first', + 'second', + //'third', + ]; + +$foo = [ + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ]; + +$foo = [ + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ]; + +$weightings = [ + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ]; + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} + +$ids = [ + '1', // Foo. + '13', // Bar. + ]; + +[ + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + }, +]; + +[ + 'key1' => [ + '1', + '2', + ], +]; + +$var = [ + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ]; + +function test() : array +{ + return []; +} + +$fields = [ + 'id' => ['type' => 'INT'], + 'value' => ['type' => 'VARCHAR'], + ]; + +get_current_screen()->add_help_tab( [ + 'id' => << false]; + +$x = [ + 'xxxx' => [ + 'aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false, + ], + ]; + +$foo = [ + 'foo' => [ + 'bar1' => 1, + 'bar2' => 1, + 'bar3' => 1, + 'bar4' => 1, + 'bar5' => 1, + ], + ]; + +$foo = [ + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], ['notverified', 'unverified'], true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ]; + + +$foo = foo( + [ + // comment + ] +); + +$foo = [ + << lorem( + 1 + ), + 2 => 2, +]; + +$foo = [ + 'тип' => 'авто', + 'цвет' => 'синий', + ]; + +$paths = [ + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ]; + +$foo = [<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ]; + +$array = [ + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ]; + +$foo = [ + $this->fn => 'value', + $foo->fn => 'value', + ]; + +[ + $a, + $b, + $c, +]; + +[ + 'a' => $a, + 'b' => $b, + 'c' => $c, +]; + +[ + static function() { + return null; + }, + (array) [], + (bool) [], + (double) [], + (int) [], + (object) [], + (string) [], + (unset) [], +]; + +[ + 'foo', + 'bar' + // This is a non-fixable error. + , +]; + +yield [ + static fn () : string => '', + ]; + +yield [ + static fn () : string => '', + ]; + +$foo = [ + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ]; + +// Intentional syntax error. +$a = [ + 'a' => + ]; + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = [ + ...$a, + 'foo' => 'bar', + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ]; + +$x = [ + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ]; + +$x = [ + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ]; + +$x = [ + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ]; + + $x = + [ + 'a', + 'b', + ]; + +$x = [ + 1, + static fn (float $item): float => match ($item) { + 2.0 => 3.0, + default => $item + }, + ]; + +$x = [ + 1, + static::helloWorld(), + $class instanceof static, + 2, + ]; + +$noSpaceBeforeDoubleArrow = [ + 'width' => '', + 'height' => '', + ]; + +$newlineAfterDoubleArrow = [ + 'width' => '', + 'height' => '', + ]; + +// Sniff should ignore short lists when inside a foreach. +// https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/527 +foreach ($data as [, , $value]) {} +foreach ($array as $k => [$v1, , $v3]) {} +foreach ([$a, $b] as $c) {} // Not a short list. Sniff should handle it. diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.3.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.3.inc new file mode 100644 index 0000000000..beb5ae1aec --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Arrays/ArrayDeclarationUnitTest.3.inc @@ -0,0 +1,7 @@ + + + + + + + + + + + + +MyClass) + */ +public function caseSensitive($a1, $a2, $a3, arRay $a4, $a5, $a6, myclas $a7) +{ + +}//end caseSensitive() + + +/** + * More type hint check for custom type and array. + * + * @param array $a1 Comment here. + * @param array $a2 Comment here. + * @param MyClass $a3 Comment here. + * @param MyClass $a4 Comment here. + * + * @return array(int => MyClass) + */ +public function typeHint(MyClass $a1, $a2, myclass $a3, $a4) +{ + return (3 => 'myclass obj'); + +}//end typeHint() + + +/** + * Mixed variable type separated by a '|'. + * + * @param array|string $a1 Comment here. + * @param mixed $a2 Comment here. + * @param string|array $a3 Comment here. + * @param MyClass|int $a4 Comment here. + * + * @return bool + */ +public function mixedType($a1, $a2, $a3, $a4) +{ + return true; + +}//end mixedType() + + +/** + * Array type. + * + * @param array(MyClass) $a1 OK. + * @param array() $a2 Invalid type. + * @param array( $a3 Typo. + * @param array(int) $a4 Use 'array(integer)' instead. + * @param array(int => integer) $a5 Use 'array(integer => integer)' instead. + * @param array(integer => bool) $a6 Use 'array(integer => boolean)' instead. + * @param aRRay $a7 Use 'array' instead. + * @param string $a8 String with unknown type hint. + * + * @return int + */ +public function mixedArrayType($a1, $a2, array $a3, $a4, $a5, $a6, $a7, unknownTypeHint $a8) +{ + return 1; + +}//end mixedArrayType() + + +/** + */ +function empty1() +{ +}//end empty1() + + +/** + * + */ +function empty2() +{ +}//end empty2() + + +/** + * + * + * + */ +function empty3() +{ +}//end empty3 + + +/** + * @return boolean + */ +public function missingShortDescriptionInFunctionComment() +{ + return true; + +}//end missingShortDescriptionInFunctionComment() + + +class Another_Class +{ + + /** + * Destructor should not include a return tag. + * + * @return void + */ + function __destruct() + { + return; + } + + /** + * Constructor should not include a return tag. + * + * @return void + */ + function __construct() + { + return; + } + +}//end class + + +/** + * Comment param alignment test. + * + * @param string $varrr1 Comment1.. + * @param string $vr2 Comment2. + * @param string $var3 Comment3.. + * + * @return void + */ +public static function paramAlign($varrr1, $vr2, $var3) +{ + +}//end paramAlign() + + +/** + * Comment. + * + * @param string $id Comment. + * @param array $design Comment. + * + * @return void + */ +public static function paint($id, array $design) +{ + +}//end paint() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @since 4.0.0 + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + return; + } + + return 'blah'; + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + + return 'blah'; + +}//end myFunction() + +/** + * Test function. + * + * @param string $arg1 An argument + * + * @access public + * @return bool + */ + +echo $blah; + +function myFunction($arg1) {} + +class MyClass() { + /** + * An abstract function. + * + * @return string[] + */ + abstract final protected function myFunction(); +} + +/** + * Comment. + * + * @param mixed $test An argument. + * + * @return mixed + */ +function test($test) +{ + if ($test === TRUE) { + return; + } + + return $test; + +}//end test() + + +/** Comment. + * + * @return mixed + * + */ +function test() +{ + +}//end test() + +/** + * Comment. + * + * @param \other\ns\item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\ns\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +// Closures should be ignored. +preg_replace_callback( + '~-([a-z])~', + function ($match) { + return strtoupper($match[1]); + }, + 'hello-world' +); + +$callback = function ($bar) use ($foo) + { + $bar += $foo; + }; + +/** + * Comment should end with '*', not '**' before the slash. + **/ +function test123() { + +} + +/** + * Cant use resource for type hint. + * + * @param resource $test An argument. + * + * @return mixed + */ +function test($test) +{ + return $test; + +}//end test() + +/** + * Variable number of args. + * + * @param string $a1 Comment here. + * @param string $a2 Comment here. + * @param string $a2,... Comment here. + * + * @return boolean + */ +public function variableArgs($a1, $a2) +{ + return true; + +}//end variableArgs() + +/** + * Contains closure. + * + * @return void + */ +public function containsClosure() +{ + function ($e) { + return new Event($e); + }, + +}//end containsClosure() + +/** + * 这是一条测试评论. + * + * @return void + */ +public function test() +{ + +}//end variableArgs() + +/** + * Uses callable. + * + * @param callable $cb Test parameter. + * + * @return void + */ +public function usesCallable(callable $cb) { + $cb(); +}//end usesCallable() + +/** + * Creates a map of tokens => line numbers for each token. + * + * @param array $tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to process this file. + * @param string $eolChar The EOL character + * to use for splitting strings. + * + * @return void + * @throws Exception If something really bad + * happens while doing foo. + */ +public function foo(array &$tokens, $tokenizer, $eolChar) +{ + +}//end foo() + +/** + * Some description. + * + * @param \Vendor\Package\SomeClass $someclass Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass2 Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass3 Some class. + * + * @return void + */ +public function foo(SomeClass $someclass, \OtherVendor\Package\SomeClass2 $someclass2, SomeClass3 $someclass3) +{ +} + +/** + * Gettext. + * + * @return string + */ +public function _() { + return $foo; +} + +class Baz { + /** + * The PHP5 constructor + * + * No return tag + */ + public function __construct() { + + } +} + +/** + * Test + * + * @return void + * @throws E + */ +function myFunction() {} + +/** + * Yield test + * + * @return integer + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Yield test + * + * @return void + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Using "array" as a type hint should satisfy a specified array parameter type. + * + * @param MyClass[] $values An array of MyClass objects. + * + * @return void + */ +public function specifiedArray(array $values) { + +}// end specifiedArray() + +/** + * Using "callable" as a type hint should satisfy a "callback" parameter type. + * + * @param callback $cb A callback. + * + * @return void + */ +public function callableCallback(callable $cb) { + +}// end callableCallback() + +/** + * PHP7 type hints. + * + * @param string $name1 Comment. + * @param integer $name2 Comment. + * @param float $name3 Comment. + * @param boolean $name4 Comment. + * + * @return void + */ +public function myFunction (string $name1, int $name2, float $name3, bool $name4) { +} + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string ...$name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string $name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + +/** + * Return description function + correct type. + * + * @return integer This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + incorrect type. + * + * @return int This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + no return. + * + * @return void This is a description. + */ +public function myFunction() { +} + +/** + * Return description function + mixed return. + * + * @return mixed This is a description. + */ +public function myFunction() { +} + +/** + * Function comment. + * + * @param $bar + * Comment here. + * @param ... + * Additional arguments here. + * + * @return + * Return value + * + */ +function foo($bar) { +} + +/** + * Do something. + * + * @return void + */ +public function someFunc(): void +{ + $class = new class + { + /** + * Do something. + * + * @return string + */ + public function getString(): string + { + return 'some string'; + } + }; +} + +/** + * Return description function + mixed return types. + * + * @return bool|int This is a description. + */ +function returnTypeWithDescriptionA() +{ + return 5; + +}//end returnTypeWithDescriptionA() + + +/** + * Return description function + mixed return types. + * + * @return real|bool This is a description. + */ +function returnTypeWithDescriptionB() +{ + return 5; + +}//end returnTypeWithDescriptionB() + + +/** + * Return description function + lots of different mixed return types. + * + * @return int|object|string[]|real|double|float|bool|array(int=>MyClass)|callable And here we have a description + */ +function returnTypeWithDescriptionC() +{ + return 5; + +}//end returnTypeWithDescriptionC() + + +/** + * Return description function + lots of different mixed return types. + * + * @return array(int=>bool)|\OtherVendor\Package\SomeClass2|MyClass[]|void And here we have a description + */ +function returnTypeWithDescriptionD() +{ + +}//end returnTypeWithDescriptionD() + +/** + * Yield from test + * + * @return int[] + */ +function yieldFromTest() +{ + yield from foo(); +} + +/** + * Audio + * + * Generates an audio element to embed sounds + * + * @param mixed $src Either a source string or + * an array of sources. + * @param mixed $unsupportedMessage The message to display + * if the media tag is not supported by the browser. + * @param mixed $attributes HTML attributes. + * @return string + */ +function audio( + $src, + $unsupportedMessage = '', + $attributes = '', +) +{ + return 'test'; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithClosure() +{ + function () { + return; + }; + + return []; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithAnonymousClass() +{ + new class { + /** + * @return void + */ + public function test() { + return; + } + }; + + return []; +} + +/** + * @return void + */ +function returnVoidWithClosure() +{ + function () { + return 1; + }; +} + +/** + * @return void + */ +function returnVoidWithAnonymousClass() +{ + new class { + /** + * @return integer + */ + public function test() + { + return 1; + } + }; +} + +class TestReturnVoid +{ + /** + * @return void + */ + public function test() + { + function () { + return 4; + }; + } +} + +/** + * Comment here. + * + * @param integer $a This is A. + * @param ?array $b This is B. + * + * @return void + */ +public static function foo(?int $a, ?array $b) {} + +/** + * Comment here. + * + * @param object $a This is A. + * @param object $b This is B. + * + * @return void + */ +public function foo(object $a, ?object $b) {} + +/** + * Prepares given PHP class method for later code building. + * + * @param integer $foo Comment. + * - Additional comment. + * + * @return void + */ +function foo($foo) {} + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +// phpcs:set Squiz.Commenting.FunctionComment skipIfInheritdoc true + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +/** + * Foo. + * + * @param mixed $a Comment. + * + * @return mixed + */ +public function foo(mixed $a): mixed {} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] +class Bar { + /** + * The PHP5 constructor + */ + public function __construct() { + + } +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] ignored +/** + * Should be ok + */ +public function ignored() { + +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] __construct,__destruct + +/** + * @return void + * @throws Exception If any other error occurs. */ +function throwCommentOneLine() {} + +/** + * When two adjacent pipe symbols are used (by mistake), the sniff should not throw a PHP Fatal error + * + * @param stdClass||null $object While invalid, this should not throw a PHP Fatal error. + * @return void + */ +function doublePipeFatalError(?stdClass $object) {} + +/** + * Test for passing variables by reference + * + * This sniff treats the '&' as optional for parameters passed by reference, but + * forbidden for parameters which are not passed by reference. + * + * Because mismatches may be in either direction, we cannot auto-fix these. + * + * @param string $foo A string passed in by reference. + * @param string &$bar A string passed in by reference. + * @param string $baz A string NOT passed in by reference. + * @param string &$qux A string NOT passed in by reference. + * @param string &$case1 A string passed in by reference with a case mismatch. + * @param string &$CASE2 A string NOT passed in by reference, also with a case mismatch. + * + * @return void + */ +public function variablesPassedByReference(&$foo, &$bar, $baz, $qux, &$CASE1, $case2) +{ + return; +} + +/** + * Test for param tag containing ref, but param in declaration not being by ref. + * + * @param string &$foo This should be flagged as (only) ParamNameUnexpectedAmpersandPrefix. + * @param string &$bar This should be flagged as (only) ParamNameNoMatch. + * @param string &$baz This should be flagged as (only) ParamNameNoCaseMatch. + * + * @return void + */ +function passedByRefMismatch($foo, $bra, $BAZ) { + return; +} + +/** + * Test variable case + * + * @param string $foo This parameter is lowercase. + * @param string $BAR This parameter is UPPERCASE. + * @param string $BazQux This parameter is TitleCase. + * @param string $corgeGrault This parameter is camelCase. + * @param string $GARPLY This parameter should be in lowercase. + * @param string $waldo This parameter should be in TitleCase. + * @param string $freD This parameter should be in UPPERCASE. + * @param string $PLUGH This parameter should be in TitleCase. + * + * @return void + */ +public function variableCaseTest( + $foo, + $BAR, + $BazQux, + $corgeGrault, + $garply, + $Waldo, + $FRED, + $PluGh +) { + return; +} + +/** + * Test variable order mismatch + * + * @param string $foo This is the third parameter. + * @param string $bar This is the first parameter. + * @param string $baz This is the second parameter. + * + * @return void + */ +public function variableOrderMismatch($bar, $baz, $foo) { + return; +} + +/** + * @return never + */ +function foo() {} + +/** + * @param $noTypeNoComment + * @return void + */ +function paramVariation1($noTypeNoComment): void {} + +/** + * @param $noTypeWithComment This parameter has no type specified. + * @return void + */ +function paramVariation2($noTypeWithComment): void {} + +/** + * @param integer $hasTypeNoComment + * @return void + */ +function paramVariation3($hasTypeNoComment): void {} + +/** + * @param integer $hasTypehasComment This parameter has type. + * @return void + */ +function paramVariation4($hasTypehasComment): void {} + +/** + * @param (Foo&Bar)|null $a Comment. + * @return void + */ +public function setTranslator($a): void +{ + $this->translator = $translator; +} + +/** + * Issue PHPCSStandards/PHP_CodeSniffer#1197. + * + * @return int|WP_Error + */ +function doNotTruncateClassNamesContainingUnderscoresAtEndOfType() { + return 0; +} + +/** + * Issue PHPCSStandards/PHP_CodeSniffer#1197. + * + * @return WP_Error|int + */ +function doNotTruncateClassNamesContainingUnderscoresAtStartOfType() { + return 0; +} + +/** + * Issue PHPCSStandards/PHP_CodeSniffer#1197. + * + * @return int|WP_Error|false + */ +function doNotTruncateClassNamesContainingUnderscoresInTheMiddelOfType() { + return 0; +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FunctionCommentUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FunctionCommentUnitTest.1.inc.fixed new file mode 100644 index 0000000000..b0d9fa0e7b --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FunctionCommentUnitTest.1.inc.fixed @@ -0,0 +1,1196 @@ + MyClass) + */ +public function caseSensitive($a1, $a2, $a3, arRay $a4, $a5, $a6, myclas $a7) +{ + +}//end caseSensitive() + + +/** + * More type hint check for custom type and array. + * + * @param array $a1 Comment here. + * @param array $a2 Comment here. + * @param MyClass $a3 Comment here. + * @param MyClass $a4 Comment here. + * + * @return array(integer => MyClass) + */ +public function typeHint(MyClass $a1, $a2, myclass $a3, $a4) +{ + return (3 => 'myclass obj'); + +}//end typeHint() + + +/** + * Mixed variable type separated by a '|'. + * + * @param array|string $a1 Comment here. + * @param mixed $a2 Comment here. + * @param string|array $a3 Comment here. + * @param MyClass|integer $a4 Comment here. + * + * @return boolean + */ +public function mixedType($a1, $a2, $a3, $a4) +{ + return true; + +}//end mixedType() + + +/** + * Array type. + * + * @param array(MyClass) $a1 OK. + * @param array $a2 Invalid type. + * @param array $a3 Typo. + * @param array(integer) $a4 Use 'array(integer)' instead. + * @param array(integer => integer) $a5 Use 'array(integer => integer)' instead. + * @param array(integer => boolean) $a6 Use 'array(integer => boolean)' instead. + * @param array $a7 Use 'array' instead. + * @param string $a8 String with unknown type hint. + * + * @return integer + */ +public function mixedArrayType($a1, $a2, array $a3, $a4, $a5, $a6, $a7, unknownTypeHint $a8) +{ + return 1; + +}//end mixedArrayType() + + +/** + */ +function empty1() +{ +}//end empty1() + + +/** + * + */ +function empty2() +{ +}//end empty2() + + +/** + * + * + * + */ +function empty3() +{ +}//end empty3 + + +/** + * @return boolean + */ +public function missingShortDescriptionInFunctionComment() +{ + return true; + +}//end missingShortDescriptionInFunctionComment() + + +class Another_Class +{ + + /** + * Destructor should not include a return tag. + * + * @return void + */ + function __destruct() + { + return; + } + + /** + * Constructor should not include a return tag. + * + * @return void + */ + function __construct() + { + return; + } + +}//end class + + +/** + * Comment param alignment test. + * + * @param string $varrr1 Comment1.. + * @param string $vr2 Comment2. + * @param string $var3 Comment3.. + * + * @return void + */ +public static function paramAlign($varrr1, $vr2, $var3) +{ + +}//end paramAlign() + + +/** + * Comment. + * + * @param string $id Comment. + * @param array $design Comment. + * + * @return void + */ +public static function paint($id, array $design) +{ + +}//end paint() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @since 4.0.0 + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + return; + } + + return 'blah'; + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + + return 'blah'; + +}//end myFunction() + +/** + * Test function. + * + * @param string $arg1 An argument + * + * @access public + * @return bool + */ + +echo $blah; + +function myFunction($arg1) {} + +class MyClass() { + /** + * An abstract function. + * + * @return string[] + */ + abstract final protected function myFunction(); +} + +/** + * Comment. + * + * @param mixed $test An argument. + * + * @return mixed + */ +function test($test) +{ + if ($test === TRUE) { + return; + } + + return $test; + +}//end test() + + +/** Comment. + * + * @return mixed + * + */ +function test() +{ + +}//end test() + +/** + * Comment. + * + * @param \other\ns\item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\ns\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +// Closures should be ignored. +preg_replace_callback( + '~-([a-z])~', + function ($match) { + return strtoupper($match[1]); + }, + 'hello-world' +); + +$callback = function ($bar) use ($foo) + { + $bar += $foo; + }; + +/** + * Comment should end with '*', not '**' before the slash. + **/ +function test123() { + +} + +/** + * Cant use resource for type hint. + * + * @param resource $test An argument. + * + * @return mixed + */ +function test($test) +{ + return $test; + +}//end test() + +/** + * Variable number of args. + * + * @param string $a1 Comment here. + * @param string $a2 Comment here. + * @param string $a2,... Comment here. + * + * @return boolean + */ +public function variableArgs($a1, $a2) +{ + return true; + +}//end variableArgs() + +/** + * Contains closure. + * + * @return void + */ +public function containsClosure() +{ + function ($e) { + return new Event($e); + }, + +}//end containsClosure() + +/** + * 这是一条测试评论. + * + * @return void + */ +public function test() +{ + +}//end variableArgs() + +/** + * Uses callable. + * + * @param callable $cb Test parameter. + * + * @return void + */ +public function usesCallable(callable $cb) { + $cb(); +}//end usesCallable() + +/** + * Creates a map of tokens => line numbers for each token. + * + * @param array $tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to process this file. + * @param string $eolChar The EOL character + * to use for splitting strings. + * + * @return void + * @throws Exception If something really bad + * happens while doing foo. + */ +public function foo(array &$tokens, $tokenizer, $eolChar) +{ + +}//end foo() + +/** + * Some description. + * + * @param \Vendor\Package\SomeClass $someclass Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass2 Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass3 Some class. + * + * @return void + */ +public function foo(SomeClass $someclass, \OtherVendor\Package\SomeClass2 $someclass2, SomeClass3 $someclass3) +{ +} + +/** + * Gettext. + * + * @return string + */ +public function _() { + return $foo; +} + +class Baz { + /** + * The PHP5 constructor + * + * No return tag + */ + public function __construct() { + + } +} + +/** + * Test + * + * @return void + * @throws E + */ +function myFunction() {} + +/** + * Yield test + * + * @return integer + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Yield test + * + * @return void + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Using "array" as a type hint should satisfy a specified array parameter type. + * + * @param MyClass[] $values An array of MyClass objects. + * + * @return void + */ +public function specifiedArray(array $values) { + +}// end specifiedArray() + +/** + * Using "callable" as a type hint should satisfy a "callback" parameter type. + * + * @param callback $cb A callback. + * + * @return void + */ +public function callableCallback(callable $cb) { + +}// end callableCallback() + +/** + * PHP7 type hints. + * + * @param string $name1 Comment. + * @param integer $name2 Comment. + * @param float $name3 Comment. + * @param boolean $name4 Comment. + * + * @return void + */ +public function myFunction (string $name1, int $name2, float $name3, bool $name4) { +} + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string ...$name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string $name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + +/** + * Return description function + correct type. + * + * @return integer This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + incorrect type. + * + * @return integer This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + no return. + * + * @return void This is a description. + */ +public function myFunction() { +} + +/** + * Return description function + mixed return. + * + * @return mixed This is a description. + */ +public function myFunction() { +} + +/** + * Function comment. + * + * @param $bar + * Comment here. + * @param ... + * Additional arguments here. + * + * @return + * Return value + * + */ +function foo($bar) { +} + +/** + * Do something. + * + * @return void + */ +public function someFunc(): void +{ + $class = new class + { + /** + * Do something. + * + * @return string + */ + public function getString(): string + { + return 'some string'; + } + }; +} + +/** + * Return description function + mixed return types. + * + * @return boolean|integer This is a description. + */ +function returnTypeWithDescriptionA() +{ + return 5; + +}//end returnTypeWithDescriptionA() + + +/** + * Return description function + mixed return types. + * + * @return float|boolean This is a description. + */ +function returnTypeWithDescriptionB() +{ + return 5; + +}//end returnTypeWithDescriptionB() + + +/** + * Return description function + lots of different mixed return types. + * + * @return integer|object|string[]|float|boolean|array(integer => MyClass)|callable And here we have a description + */ +function returnTypeWithDescriptionC() +{ + return 5; + +}//end returnTypeWithDescriptionC() + + +/** + * Return description function + lots of different mixed return types. + * + * @return array(integer => boolean)|\OtherVendor\Package\SomeClass2|MyClass[]|void And here we have a description + */ +function returnTypeWithDescriptionD() +{ + +}//end returnTypeWithDescriptionD() + +/** + * Yield from test + * + * @return int[] + */ +function yieldFromTest() +{ + yield from foo(); +} + +/** + * Audio + * + * Generates an audio element to embed sounds + * + * @param mixed $src Either a source string or + * an array of sources. + * @param mixed $unsupportedMessage The message to display + * if the media tag is not supported by the browser. + * @param mixed $attributes HTML attributes. + * @return string + */ +function audio( + $src, + $unsupportedMessage = '', + $attributes = '', +) +{ + return 'test'; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithClosure() +{ + function () { + return; + }; + + return []; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithAnonymousClass() +{ + new class { + /** + * @return void + */ + public function test() { + return; + } + }; + + return []; +} + +/** + * @return void + */ +function returnVoidWithClosure() +{ + function () { + return 1; + }; +} + +/** + * @return void + */ +function returnVoidWithAnonymousClass() +{ + new class { + /** + * @return integer + */ + public function test() + { + return 1; + } + }; +} + +class TestReturnVoid +{ + /** + * @return void + */ + public function test() + { + function () { + return 4; + }; + } +} + +/** + * Comment here. + * + * @param integer $a This is A. + * @param array $b This is B. + * + * @return void + */ +public static function foo(?int $a, ?array $b) {} + +/** + * Comment here. + * + * @param object $a This is A. + * @param object $b This is B. + * + * @return void + */ +public function foo(object $a, ?object $b) {} + +/** + * Prepares given PHP class method for later code building. + * + * @param integer $foo Comment. + * - Additional comment. + * + * @return void + */ +function foo($foo) {} + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +// phpcs:set Squiz.Commenting.FunctionComment skipIfInheritdoc true + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +/** + * Foo. + * + * @param mixed $a Comment. + * + * @return mixed + */ +public function foo(mixed $a): mixed {} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] +class Bar { + /** + * The PHP5 constructor + */ + public function __construct() { + + } +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] ignored +/** + * Should be ok + */ +public function ignored() { + +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] __construct,__destruct + +/** + * @return void + * @throws Exception If any other error occurs. */ +function throwCommentOneLine() {} + +/** + * When two adjacent pipe symbols are used (by mistake), the sniff should not throw a PHP Fatal error + * + * @param stdClass|null $object While invalid, this should not throw a PHP Fatal error. + * @return void + */ +function doublePipeFatalError(?stdClass $object) {} + +/** + * Test for passing variables by reference + * + * This sniff treats the '&' as optional for parameters passed by reference, but + * forbidden for parameters which are not passed by reference. + * + * Because mismatches may be in either direction, we cannot auto-fix these. + * + * @param string $foo A string passed in by reference. + * @param string &$bar A string passed in by reference. + * @param string $baz A string NOT passed in by reference. + * @param string &$qux A string NOT passed in by reference. + * @param string &$case1 A string passed in by reference with a case mismatch. + * @param string &$CASE2 A string NOT passed in by reference, also with a case mismatch. + * + * @return void + */ +public function variablesPassedByReference(&$foo, &$bar, $baz, $qux, &$CASE1, $case2) +{ + return; +} + +/** + * Test for param tag containing ref, but param in declaration not being by ref. + * + * @param string &$foo This should be flagged as (only) ParamNameUnexpectedAmpersandPrefix. + * @param string &$bar This should be flagged as (only) ParamNameNoMatch. + * @param string &$baz This should be flagged as (only) ParamNameNoCaseMatch. + * + * @return void + */ +function passedByRefMismatch($foo, $bra, $BAZ) { + return; +} + +/** + * Test variable case + * + * @param string $foo This parameter is lowercase. + * @param string $BAR This parameter is UPPERCASE. + * @param string $BazQux This parameter is TitleCase. + * @param string $corgeGrault This parameter is camelCase. + * @param string $GARPLY This parameter should be in lowercase. + * @param string $waldo This parameter should be in TitleCase. + * @param string $freD This parameter should be in UPPERCASE. + * @param string $PLUGH This parameter should be in TitleCase. + * + * @return void + */ +public function variableCaseTest( + $foo, + $BAR, + $BazQux, + $corgeGrault, + $garply, + $Waldo, + $FRED, + $PluGh +) { + return; +} + +/** + * Test variable order mismatch + * + * @param string $foo This is the third parameter. + * @param string $bar This is the first parameter. + * @param string $baz This is the second parameter. + * + * @return void + */ +public function variableOrderMismatch($bar, $baz, $foo) { + return; +} + +/** + * @return never + */ +function foo() {} + +/** + * @param $noTypeNoComment + * @return void + */ +function paramVariation1($noTypeNoComment): void {} + +/** + * @param $noTypeWithComment This parameter has no type specified. + * @return void + */ +function paramVariation2($noTypeWithComment): void {} + +/** + * @param integer $hasTypeNoComment + * @return void + */ +function paramVariation3($hasTypeNoComment): void {} + +/** + * @param integer $hasTypehasComment This parameter has type. + * @return void + */ +function paramVariation4($hasTypehasComment): void {} + +/** + * @param (Foo&Bar)|null $a Comment. + * @return void + */ +public function setTranslator($a): void +{ + $this->translator = $translator; +} + +/** + * Issue PHPCSStandards/PHP_CodeSniffer#1197. + * + * @return integer|WP_Error + */ +function doNotTruncateClassNamesContainingUnderscoresAtEndOfType() { + return 0; +} + +/** + * Issue PHPCSStandards/PHP_CodeSniffer#1197. + * + * @return WP_Error|integer + */ +function doNotTruncateClassNamesContainingUnderscoresAtStartOfType() { + return 0; +} + +/** + * Issue PHPCSStandards/PHP_CodeSniffer#1197. + * + * @return integer|WP_Error|false + */ +function doNotTruncateClassNamesContainingUnderscoresInTheMiddelOfType() { + return 0; +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FunctionCommentUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FunctionCommentUnitTest.2.inc new file mode 100644 index 0000000000..cc91650d12 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FunctionCommentUnitTest.2.inc @@ -0,0 +1,12 @@ + 0); + +do +{ + echo $i; +} while ($i > 0); + +do +{ + echo $i; +} +while ($i > 0); + +do { echo $i; } while ($i > 0); + +do{ + echo $i; +}while($i > 0); + +while ($i < 1) { + echo $i; +} + +while($i < 1){ + echo $i; +} + +while ($i < 1) { echo $i; } + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for($i = 1; $i < 1; $i++){ + echo $i; +} + +for ($i = 1; $i < 1; $i++) { echo $i; } + +if ($i == 0) { + $i = 1; +} + +if($i == 0){ + $i = 1; +} + +if ($i == 0) { $i = 1; } + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else{ + $i = 0; +} + +if ($i == 0) { $i = 1; } else { $i = 0; } + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else if($i == 2){ + $i = 0; +} + +if ($i == 0) { $i = 1; } else if ($i == 2) { $i = 0; } + +if ($i == 0) { // comments are allowed + $i = 1; +} + +if ($i == 0) {// comments are allowed + $i = 1; +} + +if ($i == 0) { /* comments are allowed*/ + $i = 1; +} + +if ($i == 0) +{ // this is ok + $i = 1; +} + +if ($i == 0) /* this is ok */ { +} + +try { + $code = 'this'; +} catch (Exception $e) { + // Caught! +} + +try { $code = 'this'; } catch (Exception $e) { + // Caught! +} + +do { echo $i; +} while ($i > 0); + +if ($i === 0) { + + $i = 1 +} + +if ($a) { + +} +elseif ($b) { +} + +foreach ($items as $item) { + echo $item; +} + +foreach($items as $item){ + echo $item; +} + +if ($a && $b) // && $c) +{ +} + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +try { + // try body +} +catch (FirstExceptionType $e) { + // catch body +} +catch (OtherExceptionType $e) { + // catch body +} + +switch($foo) { + + case 'bar': + break; + +} + +if ($foo) : +endif; + +?> + +getRow()): ?> +

    + + + +
    + +
    + + + + + + + hello + + + + hello + + + + +getRow()) : ?> +

    + + + + + + + + hello + + + + hello + + 1, +}; + +$r = match($x){1 => 1}; + +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 2 +if ($a == 5): + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +// Reset property. +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 1 diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.1.inc.fixed new file mode 100644 index 0000000000..bc37e70bca --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.1.inc.fixed @@ -0,0 +1,324 @@ + 0); + +do { + echo $i; +} while ($i > 0); + +do { + echo $i; +} while ($i > 0); + +do { +echo $i; } while ($i > 0); + +do { + echo $i; +} while ($i > 0); + +while ($i < 1) { + echo $i; +} + +while ($i < 1) { + echo $i; +} + +while ($i < 1) { +echo $i; } + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for ($i = 1; $i < 1; $i++) { +echo $i; } + +if ($i == 0) { + $i = 1; +} + +if ($i == 0) { + $i = 1; +} + +if ($i == 0) { +$i = 1; } + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { +$i = 1; } else { +$i = 0; } + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { +$i = 1; } else if ($i == 2) { +$i = 0; } + +if ($i == 0) { // comments are allowed + $i = 1; +} + +if ($i == 0) {// comments are allowed + $i = 1; +} + +if ($i == 0) { /* comments are allowed*/ + $i = 1; +} + +if ($i == 0) { // this is ok + $i = 1; +} + +if ($i == 0) { /* this is ok */ +} + +try { + $code = 'this'; +} catch (Exception $e) { + // Caught! +} + +try { +$code = 'this'; } catch (Exception $e) { + // Caught! +} + +do { +echo $i; +} while ($i > 0); + +if ($i === 0) { + + $i = 1 +} + +if ($a) { + +} elseif ($b) { +} + +foreach ($items as $item) { + echo $item; +} + +foreach ($items as $item) { + echo $item; +} + +if ($a && $b) { // && $c) +} + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +try { + // try body +} catch (FirstExceptionType $e) { + // catch body +} catch (OtherExceptionType $e) { + // catch body +} + +switch ($foo) { + + case 'bar': + break; + +} + +if ($foo) : +endif; + +?> + +getRow()) : ?> +

    + + + +
    + +
    + + + + + + + hello + + + + hello + + + + +getRow()) : ?> +

    + + + + + + + + hello + + + + hello + + 1, +}; + +$r = match ($x) { +1 => 1}; + +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 2 +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +// Reset property. +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 1 diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.2.inc new file mode 100644 index 0000000000..ef99b1a223 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.2.inc @@ -0,0 +1,5 @@ + +
    Some html
    + + +
    Some html
    + + +
    Some html
    + +
    Some html
    + +
    Some html
    + + +
    Some html
    + + +
    Some html
    + +
    Some html
    + words[$wordPos-1]) || $this->words[$wordPos-1] !== ' ') { +} else if ($this->tokens[$pos + 1] === "\n") { +} + +if ($pos === count($this->tokens) - 1) { + $file = '...'.substr($file, (($padding * -1) + 3)); +} + +if (substr($basename, -5) !== 'Sniff') { + $i = ($this->_tokens[$i]['parenthesis_closer'] + 1); +} + +$pos = $this->_getShortCommentEndPos(); +if ($pos === -1) { + $stackPtr = ($tokens[$next][$to] - 1); + $stackPtr = ($tokens[$next][$pattern[$i]['to']] + 1); + $var = (($var1 + $var2) + $var3 + $var4) +} + +$commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1); +$commentEnd = ($this->_phpcsFile->findNext(T_DOC_COMMENT, ($commentStart + 1), null, true) - 1); +$expected .= '...'.substr($tokens[($stackPtr - 2)]['content'], -5).$tokens[$stackPtr]['content']; + +if (($tokens[$nextToken - 1]['code']) !== T_WHITESPACE) { + $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart); +} + +while (($nextSpace = $phpcsFile->findNext(T_WHITESPACE, $nextSpace + 1, $nextBreak)) !== false) { +} + +foreach ($attributes as $id => &$attribute) { +} + +class MyClass +{ + + + public function &myFunction(array &$one, array &$two) + { + + }//end myFunction() + + +}//end class + +if ($index < -1) $index = 0; +if ($index < - 1) $index = 0; + +$three = ceil($one / $two); +$three = ceil(($one / $two) / $four); +$three = ceil($one / ($two / $four)); + +$four = -0.25; + +$three = ceil($one[1] / $two); + +switch ($number % 10) { + case -1: + $suffix = 'st'; + break; +} + +$expectedPermission = array( + 'granted' => 4, + 'denied' => 1, + 'cascade' => TRUE, + 'blockergranted' => 2, + 'blockerdenied' => - 3, + 'effective' => TRUE, + ); + +$value = (int) isset($blah) + 2; +$value = (int) isset($blah) + (int) isset($foo) + (int) isset($bar); + +doSomething(getValue($var, 2)) - $y; + +$codeFiles = array($global => $codeFiles[$global]) + $codeFiles; + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$cntPages = ceil(count($items) / self::ON_PAGE); + +error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); +error_reporting(E_ALL & ~E_NOTICE | ~E_WARNING); +$results = $stmt->fetchAll(\PDO::FETCH_ASSOC | Relative\PDO::FETCH_GROUP | namespace\PDO::FETCH_UNIQUE); +$di = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS); +foo(1 + 2 + 3); + +if (empty($foo[-1]) === true) { + $foo[-1] = 'foo'; +} + +try { +} catch (AException | BException $e) { +} + +$var = $foo['blah'] + []; + +$a = 2 * ${x} - ${minus}; + +$foo = $bar ?? $baz ?? ''; + +$foo = $myString{-1}; + +$value = (binary) $blah + b"binary $foo"; + +$test = (1 * static::TEST); +$test = myfunc(1 * static::TEST); + +$errorPos = $params[$x]?->getLine() + $commentStart; + +$foo = $this->gmail ?? $this->gmail = new Google_Service_Gmail($this->google); + +exit -1; + +$expr = match ($number - 10) { + -1 => 0, +}; + +$expr = match ($number % 10) { + 1 => 2 * $num, +}; + +$expr = match (true) { + $num * 100 > 500 => 'expression in key', +}; + +// PHP 8.0 named parameters. +if ($pos === count(value: $this->tokens) - 1) { + $file = '...'.substr(string: $file, offset: $padding * -1 + 3); +} + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +$cntPages = ceil(count($items) / parent::ON_PAGE); + +$nsRelative = namespace\doSomething($items + 10); +$partiallyQualified = Partially\qualified($items + 10); +$fullyQualified = \Fully\qualified($items + 10); + +// The below should be ignored as adding parentheses will turn this into a parse error. +(void) CallMeOnce() + (bool) CallMeTwice(); diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Formatting/OperatorBracketUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Formatting/OperatorBracketUnitTest.1.inc.fixed new file mode 100644 index 0000000000..26915609b1 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Formatting/OperatorBracketUnitTest.1.inc.fixed @@ -0,0 +1,210 @@ +words[($wordPos-1)]) || $this->words[($wordPos-1)] !== ' ') { +} else if ($this->tokens[($pos + 1)] === "\n") { +} + +if ($pos === (count($this->tokens) - 1)) { + $file = '...'.substr($file, (($padding * -1) + 3)); +} + +if (substr($basename, -5) !== 'Sniff') { + $i = ($this->_tokens[$i]['parenthesis_closer'] + 1); +} + +$pos = $this->_getShortCommentEndPos(); +if ($pos === -1) { + $stackPtr = ($tokens[$next][$to] - 1); + $stackPtr = ($tokens[$next][$pattern[$i]['to']] + 1); + $var = (($var1 + $var2) + $var3 + $var4) +} + +$commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1); +$commentEnd = ($this->_phpcsFile->findNext(T_DOC_COMMENT, ($commentStart + 1), null, true) - 1); +$expected .= '...'.substr($tokens[($stackPtr - 2)]['content'], -5).$tokens[$stackPtr]['content']; + +if (($tokens[($nextToken - 1)]['code']) !== T_WHITESPACE) { + $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart); +} + +while (($nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), $nextBreak)) !== false) { +} + +foreach ($attributes as $id => &$attribute) { +} + +class MyClass +{ + + + public function &myFunction(array &$one, array &$two) + { + + }//end myFunction() + + +}//end class + +if ($index < -1) $index = 0; +if ($index < - 1) $index = 0; + +$three = ceil($one / $two); +$three = ceil(($one / $two) / $four); +$three = ceil($one / ($two / $four)); + +$four = -0.25; + +$three = ceil($one[1] / $two); + +switch ($number % 10) { + case -1: + $suffix = 'st'; + break; +} + +$expectedPermission = array( + 'granted' => 4, + 'denied' => 1, + 'cascade' => TRUE, + 'blockergranted' => 2, + 'blockerdenied' => - 3, + 'effective' => TRUE, + ); + +$value = ((int) isset($blah) + 2); +$value = ((int) isset($blah) + (int) isset($foo) + (int) isset($bar)); + +(doSomething(getValue($var, 2)) - $y); + +$codeFiles = (array($global => $codeFiles[$global]) + $codeFiles); + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$cntPages = ceil(count($items) / self::ON_PAGE); + +error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); +error_reporting(E_ALL & ~E_NOTICE | ~E_WARNING); +$results = $stmt->fetchAll(\PDO::FETCH_ASSOC | Relative\PDO::FETCH_GROUP | namespace\PDO::FETCH_UNIQUE); +$di = new \RecursiveDirectoryIterator($path, (\RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS)); +foo(1 + 2 + 3); + +if (empty($foo[-1]) === true) { + $foo[-1] = 'foo'; +} + +try { +} catch (AException | BException $e) { +} + +$var = ($foo['blah'] + []); + +$a = 2 * ${x} - ${minus}; + +$foo = ($bar ?? $baz ?? ''); + +$foo = $myString{-1}; + +$value = ((binary) $blah + b"binary $foo"); + +$test = (1 * static::TEST); +$test = myfunc(1 * static::TEST); + +$errorPos = ($params[$x]?->getLine() + $commentStart); + +$foo = ($this->gmail ?? $this->gmail = new Google_Service_Gmail($this->google)); + +exit -1; + +$expr = match ($number - 10) { + -1 => 0, +}; + +$expr = match ($number % 10) { + 1 => (2 * $num), +}; + +$expr = match (true) { + ($num * 100) > 500 => 'expression in key', +}; + +// PHP 8.0 named parameters. +if ($pos === (count(value: $this->tokens) - 1)) { + $file = '...'.substr(string: $file, offset: ($padding * -1 + 3)); +} + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +$cntPages = ceil(count($items) / parent::ON_PAGE); + +$nsRelative = namespace\doSomething($items + 10); +$partiallyQualified = Partially\qualified($items + 10); +$fullyQualified = \Fully\qualified($items + 10); + +// The below should be ignored as adding parentheses will turn this into a parse error. +(void) CallMeOnce() + (bool) CallMeTwice(); diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Formatting/OperatorBracketUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Formatting/OperatorBracketUnitTest.2.inc new file mode 100644 index 0000000000..1284f121fc --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Formatting/OperatorBracketUnitTest.2.inc @@ -0,0 +1,7 @@ + $a($b); + +function multipleWhitespaceTokensAfterType(int + + $number) {} + +function spacingBetweenParenthesesShouldBeFixedInOneGo( + + + ) {} + +function newlineAfterReferenceShouldBeFlaggedAndFixed( + & + + $param +) {} + +function newlineAfterReferenceFixerRespectsComment( + & + // comment + $param +) {} + +function newlineAfterVariadicShouldBeFlaggedAndFixed( + ... + + $param +) {} + +function newlineAfterVariadicFixerRespectsComment( + ... + //comment + $param +) {} + +function newlineBeforeAndAfterEqualsSignShouldBeFixedForSpacing0( + $param + + = + + true +) {} + +function commentBeforeOrAfterEqualsSignShouldBeFlaggedNotFixed( + $param /*comment*/ = /*comment*/ true +) {} + +function newlineAndCommentBeforeAndAfterEqualsSignShouldBeFlaggedNotFixed( + $param + + //comment + + = + + //comment + + true +) {} + +// phpcs:set Squiz.Functions.FunctionDeclarationArgumentSpacing equalsSpacing 1 +function newlineBeforeAndAfterEqualsSignShouldBeFixedForSpacing1( + $param + + = + + true +) {} +// phpcs:set Squiz.Functions.FunctionDeclarationArgumentSpacing equalsSpacing 0 + +function newlineBeforeCommaShouldBeFixedInOneGo( + $paramA +, + $paramB + + , + $paramC +) {} + +function newlineBeforeCommaFixerRespectsComments( + $paramA // comment + , + $paramB=10 /* comment */ +, + $paramC=20 # comment + , $paramC=30 + , string $paramC='foo' +) {} + +class PropertyPromotionSpacingAfterComma { + public function __construct(private string|int $propA, protected bool $correctSpace, public MyClass $tooMuchSpace,readonly string $noSpace) {} +} + +class PropertyPromotionSpacingAfterModifier { + public function __construct( + private$noSpace, + public MyClass $tooMuchSpace, + protected readonly string $tooMuchSpaceX2, + readonly + public + string $tooMuchSpaceNewLines, + ) {} +} + +class AsymVisibilityPropertyPromotionSpacingAfterComma { + public function __construct(private(set) string|int $propA, protected(set) bool $correctSpace, public(set) MyClass $tooMuchSpace,public(set) string $noSpace) {} +} + +class AsymVisibilityPropertyPromotionSpacingAfterModifier { + public function __construct( + private(set)$noSpace, + public(set) MyClass $tooMuchSpace, + protected(set) public string $tooMuchSpaceX2, + private + public(set) + string $tooMuchSpaceNewLines, + ) {} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Functions/FunctionDeclarationArgumentSpacingUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Functions/FunctionDeclarationArgumentSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000000..894668cd89 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Functions/FunctionDeclarationArgumentSpacingUnitTest.1.inc.fixed @@ -0,0 +1,199 @@ + $a($b); + +function multipleWhitespaceTokensAfterType(int $number) {} + +function spacingBetweenParenthesesShouldBeFixedInOneGo() {} + +function newlineAfterReferenceShouldBeFlaggedAndFixed( + &$param +) {} + +function newlineAfterReferenceFixerRespectsComment( + &// comment + $param +) {} + +function newlineAfterVariadicShouldBeFlaggedAndFixed( + ...$param +) {} + +function newlineAfterVariadicFixerRespectsComment( + ...//comment + $param +) {} + +function newlineBeforeAndAfterEqualsSignShouldBeFixedForSpacing0( + $param=true +) {} + +function commentBeforeOrAfterEqualsSignShouldBeFlaggedNotFixed( + $param /*comment*/ = /*comment*/ true +) {} + +function newlineAndCommentBeforeAndAfterEqualsSignShouldBeFlaggedNotFixed( + $param + + //comment + + = + + //comment + + true +) {} + +// phpcs:set Squiz.Functions.FunctionDeclarationArgumentSpacing equalsSpacing 1 +function newlineBeforeAndAfterEqualsSignShouldBeFixedForSpacing1( + $param=true +) {} +// phpcs:set Squiz.Functions.FunctionDeclarationArgumentSpacing equalsSpacing 0 + +function newlineBeforeCommaShouldBeFixedInOneGo( + $paramA, + $paramB, + $paramC +) {} + +function newlineBeforeCommaFixerRespectsComments( + $paramA, // comment + $paramB=10, /* comment */ + $paramC=20, # comment + $paramC=30, + string $paramC='foo' +) {} + +class PropertyPromotionSpacingAfterComma { + public function __construct(private string|int $propA, protected bool $correctSpace, public MyClass $tooMuchSpace, readonly string $noSpace) {} +} + +class PropertyPromotionSpacingAfterModifier { + public function __construct( + private $noSpace, + public MyClass $tooMuchSpace, + protected readonly string $tooMuchSpaceX2, + readonly public string $tooMuchSpaceNewLines, + ) {} +} + +class AsymVisibilityPropertyPromotionSpacingAfterComma { + public function __construct(private(set) string|int $propA, protected(set) bool $correctSpace, public(set) MyClass $tooMuchSpace, public(set) string $noSpace) {} +} + +class AsymVisibilityPropertyPromotionSpacingAfterModifier { + public function __construct( + private(set) $noSpace, + public(set) MyClass $tooMuchSpace, + protected(set) public string $tooMuchSpaceX2, + private public(set) string $tooMuchSpaceNewLines, + ) {} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Functions/FunctionDeclarationArgumentSpacingUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Functions/FunctionDeclarationArgumentSpacingUnitTest.2.inc new file mode 100644 index 0000000000..1b572336b2 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Functions/FunctionDeclarationArgumentSpacingUnitTest.2.inc @@ -0,0 +1,6 @@ + + + +<?php echo $title ?> + + + + + hello + + + + + + + + + + + + + + + + + + + + + +section as $section) { + ?> + + + + + + section as $section) { + ?> +
    + + + + + + + + +?> + + + + + + + + + + + + + + + + + + + +
    + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + +
    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +<?php echo $title; ?> + + + + + hello + + + + + + + + + + + + + + + + + + + +section as $section) { + ?> +
    + + + + + section as $section) { + ?> +
    + + + + + + + + + + + + +?> + + + + + + + + + + + + + + + + + + + +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.15.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.15.inc new file mode 100644 index 0000000000..d8f0512773 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.15.inc @@ -0,0 +1,9 @@ + + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.16.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.16.inc new file mode 100644 index 0000000000..754c241b8e --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.16.inc @@ -0,0 +1,8 @@ + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.17.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.17.inc new file mode 100644 index 0000000000..71de17bfb4 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.17.inc @@ -0,0 +1,8 @@ + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.18.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.18.inc new file mode 100644 index 0000000000..3d61d4859d --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.18.inc @@ -0,0 +1,15 @@ + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.18.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.18.inc.fixed new file mode 100644 index 0000000000..8c906d40c7 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.18.inc.fixed @@ -0,0 +1,13 @@ + + +
    + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.19.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.19.inc new file mode 100644 index 0000000000..34db64d605 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.19.inc @@ -0,0 +1,17 @@ + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.19.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.19.inc.fixed new file mode 100644 index 0000000000..b1738db57f --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.19.inc.fixed @@ -0,0 +1,15 @@ + + +
    + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.2.inc new file mode 100644 index 0000000000..755fd355b5 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.2.inc @@ -0,0 +1,7 @@ + + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.2.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.2.inc.fixed new file mode 100644 index 0000000000..e9073da915 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.2.inc.fixed @@ -0,0 +1,7 @@ + + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.20.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.20.inc new file mode 100644 index 0000000000..28cdbdaf7a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.20.inc @@ -0,0 +1,15 @@ + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.20.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.20.inc.fixed new file mode 100644 index 0000000000..fcc24a278e --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.20.inc.fixed @@ -0,0 +1,16 @@ + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.21.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.21.inc new file mode 100644 index 0000000000..1da67a2ea7 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.21.inc @@ -0,0 +1,15 @@ + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.21.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.21.inc.fixed new file mode 100644 index 0000000000..d7487b507d --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.21.inc.fixed @@ -0,0 +1,16 @@ + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.22.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.22.inc new file mode 100644 index 0000000000..5196a3b45b --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.22.inc @@ -0,0 +1,30 @@ +
    Inline HTML with indent to demonstrate the bug in the indent calculation.
    + + + + + + + + +Inline HTML with indent to demonstrate the bug in the indent calculation.
    + + + + + + + + + + + +
    + + +
    +

    Some more content after the last PHP tag block.

    diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.24.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.24.inc new file mode 100644 index 0000000000..dc1749c330 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.24.inc @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + +<?= $title ?> + + + + + hello + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + +// Safeguard fixing when there is no whitespace between the close tag and the contents. + + + + + + + + + +<?= $title; ?> + + + + + hello + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// Safeguard fixing when there is no whitespace between the close tag and the contents. + + + + + + + + + + + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.4.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.4.inc.fixed new file mode 100644 index 0000000000..b7985cc508 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.4.inc.fixed @@ -0,0 +1,7 @@ + + + + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.5.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.5.inc new file mode 100644 index 0000000000..f4d8d8a0c0 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/EmbeddedPhpUnitTest.5.inc @@ -0,0 +1,48 @@ + + + + + + + +
    + + + + + + + +
    + + + + + + + + + + + + +
    + + + + + + +
    + + + + + + + + + + + + + + + +
    + + + +
    + children as $child) { + // There should be no error after this + // foreach, because it is followed by a + // close PHP tag. + } + ?> +
    +children as $child) { + echo $child; + +} + +if ($defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +foreach ( $blah as $var ) { + if ( $blah ) { + } +} + +if ( + $defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +$moo = 'blar'; +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + return $moo; + + default: + $moo = 'moo'; + break; +} + +do { +} +while (true); + +try { + // Something +} catch (Exception $e) { + // Something +} + +try { + + // Something + +} catch (Exception $e) { + + // Something + +} + +if ($one) { +} +elseif ($two) { +} +// else if something +else if ($three) { +} // else do something +else { +} + +if ($one) { + +} + +do { + echo 'hi'; +} while ( $blah ); + +if ($one) { +} +// No blank line here. +if ($two) { +} + +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + + return $moo; +} + +try { + // Something +} +catch (Exception $e) { + // Something +} +finally { + // Something +} + +if ($foo) { + + + /** + * Comment + */ + function foo() { + // Code here + } + + + /** + * Comment + */ + class bar() { + + }//end class + + +} + +if (true) { // some comment goes here + + echo 'foo'; +} + +if (true) { echo 'foo'; + + echo 'foo'; +} + +if ($true) { + echo 'hi 2'; +}//end if +echo 'hi'; + +if ($true) { + echo 'hi 2'; +} // phpcs:enable Standard.Category.Sniff -- for reasons. +echo 'hi'; + +?> + + + + + + + 1, + 2 => 2, + +}; +echo $expr; + +if($true) { + + enum SomeEnum {} + +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed new file mode 100644 index 0000000000..c64de25e16 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed @@ -0,0 +1,261 @@ + + + + + +
    + children as $child) { + // There should be no error after this + // foreach, because it is followed by a + // close PHP tag. + } + ?> +
    +children as $child) { + echo $child; +} + +if ($defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +foreach ($blah as $var) { + if ($blah) { + } +} + +if ($defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +$moo = 'blar'; +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + return $moo; + + default: + $moo = 'moo'; + break; +} + +do { +} +while (true); + +try { + // Something +} catch (Exception $e) { + // Something +} + +try { + // Something +} catch (Exception $e) { + // Something +} + +if ($one) { +} +elseif ($two) { +} +// else if something +else if ($three) { +} // else do something +else { +} + +if ($one) { +} + +do { + echo 'hi'; +} while ($blah); + +if ($one) { +} + +// No blank line here. +if ($two) { +} + +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + return $moo; +} + +try { + // Something +} +catch (Exception $e) { + // Something +} +finally { + // Something +} + +if ($foo) { + + + /** + * Comment + */ + function foo() { + // Code here + } + + + /** + * Comment + */ + class bar() { + + }//end class + + +} + +if (true) { // some comment goes here + echo 'foo'; +} + +if (true) { echo 'foo'; + + echo 'foo'; +} + +if ($true) { + echo 'hi 2'; +}//end if + +echo 'hi'; + +if ($true) { + echo 'hi 2'; +} // phpcs:enable Standard.Category.Sniff -- for reasons. + +echo 'hi'; + +?> + + + + + + 1, + 2 => 2, +}; + +echo $expr; + +if($true) { + + enum SomeEnum {} + +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeClosingBraceUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeClosingBraceUnitTest.inc new file mode 100644 index 0000000000..526edbbfaa --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeClosingBraceUnitTest.inc @@ -0,0 +1,174 @@ +{$property} =& new $class_name($this->db_index); + $this->modules[$module] =& $this->{$property}; +} + +foreach ($elements as $element) { + if ($something) { + // Do IF. + } else if ($somethingElse) { + // Do ELSE. + } +} + +if ($token['code'] === T_COMMENT + && $multiLineComment === false + && (substr($token['content'], 0, 2) === '//' + || $token['content']{0} === '#') +) { +} + +switch ($blah) { + case 'one': + echo 'one'; + break; + default: + echo 'another'; +} + +?> + +getRow()): ?> +

    + + + +
    + +

    o hai!

    + +
    + + + + + + + + + + + + $x + $y; + +$match = match ($test) { 1 => 'a', 2 => 'b' }; + +$match = match ($test) { + 1 => 'a', + 2 => 'b' + }; + +?> + +
    + +
    + + + + + + + + + + + + + + + + {$property} =& new $class_name($this->db_index); + $this->modules[$module] =& $this->{$property}; +} + +foreach ($elements as $element) { + if ($something) { + // Do IF. + } else if ($somethingElse) { + // Do ELSE. + } +} + +if ($token['code'] === T_COMMENT + && $multiLineComment === false + && (substr($token['content'], 0, 2) === '//' + || $token['content']{0} === '#') +) { +} + +switch ($blah) { + case 'one': + echo 'one'; + break; + default: + echo 'another'; +} + +?> + +getRow()): ?> +

    + + + +
    + +

    o hai!

    + +
    + + + + + + + + + + + + $x + $y; + +$match = match ($test) { 1 => 'a', 2 => 'b' +}; + +$match = match ($test) { + 1 => 'a', + 2 => 'b' +}; + +?> + +
    + +
    + + + + + + + + + + + + + + + + +