diff --git a/README.md b/README.md index 819a134141..5f74f30050 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 | 86 | 114 | 75% | +| PHP_CodeSniffer | 101 | 114 | 88% | | slevomat | 37 | 132 | 28% | -| **total** | **439** | **562** | **78%** | +| **total** | **454** | **562** | **80%** | diff --git a/blink/README.md b/blink/README.md index e4df029333..b5934cca94 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 | 86 | 114 | 75% | -| **total** | **402** | **430** | **93%** | +| PHP_CodeSniffer | 101 | 114 | 88% | +| **total** | **417** | **430** | **96%** | -blink runs 445 rules in all, its own extras included. +blink runs 460 rules in all, its own extras included. ### slevomat sniffs diff --git a/blink/bin/php-builtin-functions.sh b/blink/bin/php-builtin-functions.sh new file mode 100755 index 0000000000..7532401c04 --- /dev/null +++ b/blink/bin/php-builtin-functions.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Regenerates internal/fixer/rules/php_builtin_functions.txt: the lowercased +# names of PHP's built-in functions, which LowercasePHPFunctionsSniff reads from +# get_defined_functions() at runtime. Lists every loaded extension except the +# non-bundled PECL ones, so the result does not depend on a developer's setup. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +php -r ' +$skip = ["xdebug", "mongodb", "rdkafka", "mailparse", "pcov", "imap", "apcu", "redis", "memcached", "imagick", "swoole", "grpc", "protobuf", "yaml", "igbinary", "msgpack", "amqp", "xhprof", "ast", "uopz"]; +$names = []; +foreach (get_loaded_extensions() as $ext) { + if (in_array(strtolower($ext), $skip, true)) { + continue; + } + foreach (get_extension_funcs($ext) ?: [] as $fn) { + $names[strtolower($fn)] = true; + } +} +ksort($names, SORT_STRING); +echo implode("\n", array_keys($names)), "\n"; +' > "$ROOT/internal/fixer/rules/php_builtin_functions.txt" +echo "Wrote $(wc -l < "$ROOT/internal/fixer/rules/php_builtin_functions.txt") functions" diff --git a/blink/bin/phpcs-fixtures.sh b/blink/bin/phpcs-fixtures.sh index 27f7562896..999b516de4 100755 --- a/blink/bin/phpcs-fixtures.sh +++ b/blink/bin/phpcs-fixtures.sh @@ -8,6 +8,8 @@ # # Covers only the sniffs blink implements; rerun after porting a sniff. # An input whose ECS output equals it gets no .fixed file. +# Squiz FileComment fills a missing copyright year from the clock: after +# regenerating in a new year, bump the year pinned in file_comment_clock_test.go. set -euo pipefail UPSTREAM="${1:?usage: bin/phpcs-fixtures.sh }/src/Standards" diff --git a/blink/internal/fixer/rules/concatenation_spacing.go b/blink/internal/fixer/rules/concatenation_spacing.go new file mode 100644 index 0000000000..4a1775ca1d --- /dev/null +++ b/blink/internal/fixer/rules/concatenation_spacing.go @@ -0,0 +1,150 @@ +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/Strings/ConcatenationSpacingSniff.php +// +// ConcatenationSpacing puts exactly Spacing spaces (default 0) on both sides of +// the concat operator: "'a' . $b" -> "'a'.$b". With Spacing 0 a number next to +// the removed space is wrapped, "1 . 'x'" -> "(1).'x'", so it cannot read as a +// float. The space after a heredoc closer is kept; with IgnoreNewlines a line +// break around the operator is too. +type ConcatenationSpacing struct { + Spacing int + IgnoreNewlines bool +} + +func (ConcatenationSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\ConcatenationSpacingSniff` +} + +func (ConcatenationSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Strings/ConcatenationSpacingSniff.php" +} + +func (f ConcatenationSpacing) WithConfig(config map[string]any) fixer.Fixer { + f.Spacing = configInt(config, "spacing", f.Spacing) + if v, ok := config["ignoreNewlines"].(bool); ok { + f.IgnoreNewlines = v + } + return f +} + +// concatNewline is the spacing measured on a side of a concat that crosses a line. +const concatNewline = -1 + +func (f ConcatenationSpacing) Fix(s *tokens.Stream) bool { + return phpcsRunUntilStable(s, f.pass) +} + +func (f ConcatenationSpacing) pass(s *tokens.Stream) bool { + changed := false + for i := 0; i < s.Len(); i++ { + if t := s.At(i); t.Kind != token.Punct || t.Value != "." { + continue + } + // live coding: PHP_CodeSniffer needs two tokens after the operator + if i+2 >= s.Len() { + continue + } + prev := phpcsPrevNonEmpty(s, i-1) + ignoreBefore := prev >= 0 && isHeredocEnd(s, prev) + + before := f.concatSideSpace(s, i-1) + after := f.concatSideSpace(s, i+1) + if (ignoreBefore || f.concatSpaceOK(before)) && f.concatSpaceOK(after) { + continue + } + padding := strings.Repeat(" ", f.Spacing) + // after first, so i stays valid + if after != concatNewline || !f.IgnoreNewlines { + if f.setConcatSpace(s, i+1, i+2, padding) { + changed = true + } + } + if !ignoreBefore && (before != concatNewline || !f.IgnoreNewlines) { + if removed, did := f.setConcatSpaceBefore(s, i, padding); did { + changed = true + i -= removed + } + } + } + return changed +} + +func (f ConcatenationSpacing) concatSpaceOK(n int) bool { + return n == f.Spacing || (n == concatNewline && f.IgnoreNewlines) +} + +// concatSideSpace measures the whitespace at w the way PHP_CodeSniffer does: +// 0 when there is none, concatNewline when it crosses a line, else its width. +func (ConcatenationSpacing) concatSideSpace(s *tokens.Stream, w int) int { + if !phpcsWhitespaceAt(s, w) { + return 0 + } + if strings.ContainsAny(s.At(w).Value, "\r\n") { + return concatNewline + } + return phpcsTabWidth(s, w) +} + +// setConcatSpace makes the whitespace at w (after the operator) padding, and +// wraps a number right after it when the space goes. +func (f ConcatenationSpacing) setConcatSpace(s *tokens.Stream, w, operand int, padding string) bool { + if !phpcsWhitespaceAt(s, w) { + if f.Spacing > 0 { + s.InsertAt(w, token.Token{Kind: token.Whitespace, Value: padding}) + return true + } + return false + } + if padding != "" { + s.SetValue(w, padding) + } else { + s.RemoveAt(w) + operand-- + } + if f.Spacing == 0 && operand < s.Len() { + wrapConcatNumber(s, operand) + } + return true +} + +// setConcatSpaceBefore makes the whitespace before the operator at op padding, +// keeping a line comment's newline. It returns how many tokens were removed. +func (f ConcatenationSpacing) setConcatSpaceBefore(s *tokens.Stream, op int, padding string) (int, bool) { + w := op - 1 + if !phpcsWhitespaceAt(s, w) { + if f.Spacing > 0 { + s.InsertAt(op, token.Token{Kind: token.Whitespace, Value: padding}) + return -1, true + } + return 0, false + } + removed := 0 + switch { + case padding != "": + keep := phpcsCommentNewline(s, w) + s.SetValue(w, s.At(w).Value[:keep]+padding) + case dropPhpcsWhitespace(s, w): + removed = 1 + } + if f.Spacing == 0 && removed == 1 && w-1 >= 0 { + wrapConcatNumber(s, w-1) + } + return removed, true +} + +// wrapConcatNumber parenthesizes the number at i once; a number between two +// concats is wrapped by the first, like PHP_CodeSniffer's conflicting changesets. +func wrapConcatNumber(s *tokens.Stream, i int) { + if t := s.At(i); t.Kind == token.Number && !strings.HasPrefix(t.Value, "(") { + s.SetValue(i, "("+t.Value+")") + } +} diff --git a/blink/internal/fixer/rules/file_comment.go b/blink/internal/fixer/rules/file_comment.go new file mode 100644 index 0000000000..cb24ad310e --- /dev/null +++ b/blink/internal/fixer/rules/file_comment.go @@ -0,0 +1,107 @@ +package rules + +import ( + "regexp" + "strconv" + "strings" + "time" + + "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/Commenting/FileCommentSniff.php +// +// SquizFileComment rewrites the @author and @copyright tags of the file +// docblock to Squiz's own; a copyright keeps its leading year range, or gets +// the current year. +type SquizFileComment struct{} + +func (SquizFileComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FileCommentSniff` +} + +func (SquizFileComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/FileCommentSniff.php" +} + +const ( + squizAuthor = "Squiz Pty Ltd " + squizCopyright = "Squiz Pty Ltd (ABN 77 084 670 600)" +) + +var ( + squizCopyrightOK = regexp.MustCompile(`^([0-9]{4})(-[0-9]{4})? (Squiz Pty Ltd \(ABN 77 084 670 600\))$`) + squizCopyrightYear = regexp.MustCompile(`^([0-9]{4}(-[0-9]{4})?)`) +) + +// fileCommentNow is the clock the sniff fills a missing copyright year from; tests pin it. +var fileCommentNow = time.Now + +var fileCommentIgnore = map[string]bool{ + "class": true, "interface": true, "trait": true, "enum": true, "function": true, + "public": true, "private": true, "protected": true, "final": true, "static": true, + "abstract": true, "readonly": true, "const": true, "include": true, + "include_once": true, "require": true, "require_once": true, +} + +func (SquizFileComment) Fix(s *tokens.Stream) bool { + open := -1 + for i := range s.Len() { + if t := s.At(i); t.Kind == token.OpenTag && !strings.HasPrefix(t.Value, "= s.Len() || s.At(c).Kind != token.DocComment || !strings.HasSuffix(s.At(c).Value, "*/") { + return false + } + next := c + 1 + for next < s.Len() { + if s.At(next).Kind == token.Whitespace { + next++ + continue + } + if e := s.AttributeEnd(next); s.At(next).Kind == token.AttributeStart && e >= 0 { + next = e + 1 + continue + } + break + } + if next < s.Len() && s.At(next).Kind == token.Keyword && fileCommentIgnore[strings.ToLower(s.At(next).Value)] { + return false + } + doc := s.At(c).Value + repl := map[int][2]string{} + for _, tag := range phpcsDocTags(doc, phpcsEolChar(s)) { + if tag.StrPos < 0 { + continue + } + switch tag.Name { + case "@author": + if tag.Str != squizAuthor { + repl[tag.StrPos] = [2]string{tag.Str, squizAuthor} + } + case "@copyright": + if !squizCopyrightOK.MatchString(tag.Str) { + year := squizCopyrightYear.FindString(tag.Str) + if year == "" { + year = strconv.Itoa(fileCommentNow().Year()) + } + repl[tag.StrPos] = [2]string{tag.Str, year + " " + squizCopyright} + } + } + } + if len(repl) == 0 { + return false + } + s.SetValue(c, replaceDocStrings(doc, repl)) + return true +} diff --git a/blink/internal/fixer/rules/file_comment_clock_test.go b/blink/internal/fixer/rules/file_comment_clock_test.go new file mode 100644 index 0000000000..a98db49a99 --- /dev/null +++ b/blink/internal/fixer/rules/file_comment_clock_test.go @@ -0,0 +1,9 @@ +package rules + +import "time" + +// the FileComment fixtures embed the year ECS generated them in; regenerating +// them with bin/phpcs-fixtures.sh in a later year means bumping this one too +func init() { + fileCommentNow = func() time.Time { return time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) } +} diff --git a/blink/internal/fixer/rules/for_each_loop_declaration.go b/blink/internal/fixer/rules/for_each_loop_declaration.go new file mode 100644 index 0000000000..1608172d32 --- /dev/null +++ b/blink/internal/fixer/rules/for_each_loop_declaration.go @@ -0,0 +1,115 @@ +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/ControlStructures/ForEachLoopDeclarationSniff.php +// +// ForEachLoopDeclaration normalizes the spacing of a foreach header and +// lowercases "as": "foreach ( $a AS $k=>$v )" -> "foreach ($a as $k => $v)". +type ForEachLoopDeclaration struct { + RequiredSpacesAfterOpen int + RequiredSpacesBeforeClose int +} + +func (ForEachLoopDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForEachLoopDeclarationSniff` +} + +func (ForEachLoopDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/ForEachLoopDeclarationSniff.php" +} + +func (r ForEachLoopDeclaration) WithConfig(config map[string]any) fixer.Fixer { + r.RequiredSpacesAfterOpen = configInt(config, "requiredSpacesAfterOpen", r.RequiredSpacesAfterOpen) + r.RequiredSpacesBeforeClose = configInt(config, "requiredSpacesBeforeClose", r.RequiredSpacesBeforeClose) + return r +} + +func (r ForEachLoopDeclaration) Fix(s *tokens.Stream) bool { + if !s.Index().HasAnyWord("foreach") { + return false + } + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if f.isKeyword(i, "foreach") { + r.process(f, i) + } + } + }) +} + +func (r ForEachLoopDeclaration) process(f *slvFile, i int) { + open := slvFindNext(f, i, len(f.toks), func(j int) bool { return f.is(j, "(") }) + if open < 0 || f.toks[open].closer < 0 { + return + } + closeIdx := f.toks[open].closer + slvRequiredSpaces(f, open+1, r.RequiredSpacesAfterOpen, func(pad string) { f.add(open, pad) }) + slvRequiredSpaces(f, closeIdx-1, r.RequiredSpacesBeforeClose, func(pad string) { f.addBefore(closeIdx, pad) }) + + as := slvFindNext(f, open, len(f.toks), func(j int) bool { return f.isKeyword(j, "as") }) + if as < 0 { + return + } + if v := f.toks[as].orig; v != strings.ToLower(v) { + f.replaceToken(as, strings.ToLower(v)) + } + if arrow := slvFindNext(f, as, closeIdx, func(j int) bool { return f.is(j, "=>") }); arrow >= 0 { + slvOneSpace(f, arrow-1, func() { f.addBefore(arrow, " ") }) + slvOneSpace(f, arrow+1, func() { f.add(arrow, " ") }) + } + slvOneSpace(f, as-1, func() { f.addBefore(as, " ") }) + slvOneSpace(f, as+1, func() { f.add(as, " ") }) +} + +// slvFindNext is File::findNext for the first token in [from, end) match accepts, or -1. +func slvFindNext(f *slvFile, from, end int, match func(int) bool) int { + for j := from; j < end && j < len(f.toks); j++ { + if match(j) { + return j + } + } + return -1 +} + +// slvRequiredSpaces wants exactly n spaces in the whitespace token at w (just +// inside a bracket); pad adds them when there is none. +func slvRequiredSpaces(f *slvFile, w, n int, pad func(string)) { + isWs := f.toks[w].kind == token.Whitespace + if n == 0 { + if isWs { + f.replaceToken(w, "") + } + return + } + found := 0 + if isWs { + found = f.toks[w].length + } + if found == n { + return + } + if found == 0 { + pad(strings.Repeat(" ", n)) + return + } + f.replaceToken(w, strings.Repeat(" ", n)) +} + +// slvOneSpace wants a single space in the whitespace token at w; add inserts +// one when there is none. +func slvOneSpace(f *slvFile, w int, add func()) { + if f.toks[w].kind != token.Whitespace { + add() + return + } + if f.toks[w].length != 1 { + f.replaceToken(w, " ") + } +} diff --git a/blink/internal/fixer/rules/for_loop_declaration.go b/blink/internal/fixer/rules/for_loop_declaration.go new file mode 100644 index 0000000000..8fccd2150b --- /dev/null +++ b/blink/internal/fixer/rules/for_loop_declaration.go @@ -0,0 +1,165 @@ +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/ControlStructures/ForLoopDeclarationSniff.php +// +// ForLoopDeclaration normalizes the spacing of a for header: no space inside +// the parentheses or before a semicolon, one after it: +// "for ( $i = 0 ;$i < 3 ; $i++ )" -> "for ($i = 0; $i < 3; $i++)". +type ForLoopDeclaration struct { + RequiredSpacesAfterOpen int + RequiredSpacesBeforeClose int + IgnoreNewlines bool +} + +func (ForLoopDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForLoopDeclarationSniff` +} + +func (ForLoopDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/ForLoopDeclarationSniff.php" +} + +func (r ForLoopDeclaration) WithConfig(config map[string]any) fixer.Fixer { + r.RequiredSpacesAfterOpen = configInt(config, "requiredSpacesAfterOpen", r.RequiredSpacesAfterOpen) + r.RequiredSpacesBeforeClose = configInt(config, "requiredSpacesBeforeClose", r.RequiredSpacesBeforeClose) + if v, ok := config["ignoreNewlines"].(bool); ok { + r.IgnoreNewlines = v + } + return r +} + +func (r ForLoopDeclaration) Fix(s *tokens.Stream) bool { + if !s.Index().HasAnyWord("for") { + return false + } + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if f.isKeyword(i, "for") { + r.process(f, i) + } + } + }) +} + +func (r ForLoopDeclaration) process(f *slvFile, i int) { + open := slvFindNext(f, i, len(f.toks), func(j int) bool { return f.is(j, "(") }) + if open < 0 || f.toks[open].closer < 0 { + return + } + closeIdx := f.toks[open].closer + isWs := func(j int) bool { return f.toks[j].kind == token.Whitespace } + // findNext/findPrevious(T_WHITESPACE, ..., true) give false, read as token 0 + nonWsAfter := func(from, end int) int { + return max(slvFindNext(f, from, end, func(j int) bool { return !isWs(j) }), 0) + } + nonWsBefore := func(from, end int) int { // end is inclusive, as in findPrevious + for j := from; j >= end; j-- { + if !isWs(j) { + return j + } + } + return 0 + } + line := func(j int) int { return f.toks[j].line } + clear := func(from, to int) { // [from, to) + for j := from; j < to; j++ { + f.replaceToken(j, "") + } + } + + if r.RequiredSpacesAfterOpen == 0 && isWs(open+1) { + next := nonWsAfter(open+1, closeIdx) + if !r.IgnoreNewlines || line(next) == line(open) { + f.beginChangeset() + for j := open + 1; j < closeIdx && isWs(j); j++ { + f.replaceToken(j, "") + } + f.endChangeset() + } + } else if r.RequiredSpacesAfterOpen > 0 { + next := nonWsAfter(open+1, closeIdx) + found, newline := 0, line(open) != line(next) + if !newline && isWs(open+1) { + found = f.toks[open+1].length + } + if (newline || found != r.RequiredSpacesAfterOpen) && (!newline || !r.IgnoreNewlines) { + pad := strings.Repeat(" ", r.RequiredSpacesAfterOpen) + if !newline && found == 0 { + f.add(open, pad) + } else { + f.beginChangeset() + f.replaceToken(open+1, pad) + clear(open+2, next) + f.endChangeset() + } + } + } + + prev := nonWsBefore(closeIdx-1, open) + fixable := line(prev) == line(closeIdx) || !f.isEmpty(prev) + if r.RequiredSpacesBeforeClose == 0 && isWs(closeIdx-1) && (!r.IgnoreNewlines || line(prev) == line(closeIdx)) { + if fixable { + f.beginChangeset() + for j := closeIdx - 1; j > open && isWs(j); j-- { + f.replaceToken(j, "") + } + f.endChangeset() + } + } else if r.RequiredSpacesBeforeClose > 0 { + found, newline := 0, line(closeIdx) != line(prev) + if !newline && isWs(closeIdx-1) { + found = f.toks[closeIdx-1].length + } + if (newline || found != r.RequiredSpacesBeforeClose) && (!newline || !r.IgnoreNewlines) && fixable { + pad := strings.Repeat(" ", r.RequiredSpacesBeforeClose) + if !newline && found == 0 { + f.addBefore(closeIdx, pad) + } else { + f.beginChangeset() + f.replaceToken(closeIdx-1, pad) + clear(prev+1, closeIdx-1) + f.endChangeset() + } + } + } + + count := 0 + for semi := open; count < 2; { + semi = slvFindNext(f, semi+1, closeIdx, func(j int) bool { return f.is(j, ";") }) + if semi < 0 { + return + } + if f.enclosingScope(semi) > open { + continue + } + count++ + if p := nonWsBefore(semi-1, open); (count != 1 || p != open) && isWs(semi-1) { + f.beginChangeset() + clear(p+1, semi) + f.endChangeset() + } + next := nonWsAfter(semi+1, closeIdx+1) + if count == 2 && next == closeIdx { + continue + } + if !isWs(semi+1) && !f.is(semi+1, ";") { + f.add(semi, " ") + } else if isWs(semi+1) && !f.is(next, ";") { + newline := line(semi) != line(next) + if (newline || f.toks[semi+1].length != 1) && (!newline || !r.IgnoreNewlines) { + f.beginChangeset() + f.replaceToken(semi+1, " ") + clear(semi+2, next) + f.endChangeset() + } + } + } +} diff --git a/blink/internal/fixer/rules/function_closing_brace_space.go b/blink/internal/fixer/rules/function_closing_brace_space.go new file mode 100644 index 0000000000..fecafbb29e --- /dev/null +++ b/blink/internal/fixer/rules/function_closing_brace_space.go @@ -0,0 +1,141 @@ +package rules + +import ( + "slices" + "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/FunctionClosingBraceSpaceSniff.php +// +// FunctionClosingBraceSpace puts exactly one blank line before the closing +// brace of a function, and none before the brace of a nested function or a +// closure passed as an argument. +type FunctionClosingBraceSpace struct{} + +func (FunctionClosingBraceSpace) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionClosingBraceSpaceSniff` +} + +func (FunctionClosingBraceSpace) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionClosingBraceSpaceSniff.php" +} + +func (FunctionClosingBraceSpace) Fix(s *tokens.Stream) bool { + return phpcsRunUntilStable(s, functionClosingBraceSpacePass) +} + +func functionClosingBraceSpacePass(s *tokens.Stream) bool { + type body struct{ keyword, open, close int } + var bodies []body + for i := range s.Len() { + if open, closeIdx, ok := phpcsFunctionBody(s, i); ok { + bodies = append(bodies, body{i, open, closeIdx}) + } + } + nested := map[int]bool{} + for _, b := range bodies { + if phpcsInnermostParen(s, b.keyword) >= 0 { + nested[b.keyword] = true + continue + } + for _, o := range bodies { + if o.open < b.keyword && b.keyword < o.close { + nested[b.keyword] = true + break + } + } + } + eol := phpcsEolChar(s) + changed := false + // last to first, so the keywords still to visit keep their indices + for _, b := range slices.Backward(bodies) { + _, closeIdx, ok := phpcsFunctionBody(s, b.keyword) + if ok && functionClosingBraceFix(s, closeIdx, nested[b.keyword], eol) { + changed = true + } + } + return changed +} + +func functionClosingBraceFix(s *tokens.Stream, closeIdx int, nested bool, eol string) bool { + prev := closeIdx - 1 + for prev >= 0 && s.At(prev).Kind == token.Whitespace { + prev-- + } + if prev < 0 { + return false + } + lines := phpcsTokenLines(s) + found := lines[closeIdx] - lines[prev] - 1 + w := -1 + if prev+1 < closeIdx { + w = prev + 1 + } + if nested { + switch { + case found < 0: + functionClosingBraceNewlineBefore(s, closeIdx, w, eol) + return true + case found > 0 && w >= 0: + keep := phpcsCommentNewline(s, w) + v := s.At(w).Value + pieces := phpcsWhitespacePieces(v[keep:]) + line := lines[prev] + phpcsLineBreaks(s.At(prev).Value+v[:keep]) + drop := 0 + for _, p := range pieces { + if line == lines[closeIdx]-1 { + break + } + drop++ + line += phpcsLineBreaks(p) + } + if drop == 0 { + drop = 1 + } + s.SetValue(w, v[:keep]+strings.Join(pieces[drop:], "")) + return true + } + return false + } + if found == 1 { + return false + } + if found > 1 { + if w < 0 { + return false + } + s.SetValue(w, s.At(w).Value[:phpcsCommentNewline(s, w)]+eol) + return true + } + if phpcsWhitespaceAt(s, w) { + v := s.At(w).Value + p := phpcsLastPieceStart(v) + s.SetValue(w, v[:p]+eol+v[p:]) + return true + } + functionClosingBraceNewlineBefore(s, closeIdx, w, eol) + return true +} + +// functionClosingBraceNewlineBefore adds a newline right before the brace. +func functionClosingBraceNewlineBefore(s *tokens.Stream, closeIdx, w int, eol string) { + if w >= 0 { + s.SetValue(w, s.At(w).Value+eol) + return + } + s.InsertAt(closeIdx, token.Token{Kind: token.Whitespace, Value: eol}) +} + +// phpcsWhitespacePieces splits whitespace into PHP_CodeSniffer's per-line tokens. +func phpcsWhitespacePieces(v string) []string { + var pieces []string + for v != "" { + p := phpcsThroughFirstBreak(v) + pieces = append(pieces, p) + v = v[len(p):] + } + return pieces +} diff --git a/blink/internal/fixer/rules/function_spacing.go b/blink/internal/fixer/rules/function_spacing.go new file mode 100644 index 0000000000..57e3869faf --- /dev/null +++ b/blink/internal/fixer/rules/function_spacing.go @@ -0,0 +1,248 @@ +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/WhiteSpace/FunctionSpacingSniff.php +// +// FunctionSpacing puts Spacing blank lines before and after a function, with +// SpacingBeforeFirst and SpacingAfterLast at the edges of its scope. +type FunctionSpacing struct { + Spacing int + SpacingBeforeFirst int + SpacingAfterLast int +} + +func (FunctionSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionSpacingSniff` +} + +func (FunctionSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionSpacingSniff.php" +} + +func (fs FunctionSpacing) WithConfig(config map[string]any) fixer.Fixer { + fs.Spacing = configInt(config, "spacing", fs.Spacing) + fs.SpacingBeforeFirst = configInt(config, "spacingBeforeFirst", fs.SpacingBeforeFirst) + fs.SpacingAfterLast = configInt(config, "spacingAfterLast", fs.SpacingAfterLast) + return fs +} + +func (fs FunctionSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(f.isNamedFunction, func(i int) int { + fs.process(f, i) + return 0 + }) + }) +} + +// isFunctionSpacingIgnored is the sniff's $ignore: whitespace and Tokens::METHOD_MODIFIERS. +func (f *slvFile) isFunctionSpacingIgnored(i int) bool { + if f.toks[i].kind == token.Whitespace { + return true + } + if f.toks[i].kind != token.Keyword { + return false + } + switch strings.ToLower(f.toks[i].orig) { + case "public", "protected", "private", "static", "abstract", "final": + return true + } + return false +} + +// isNamedFunction tells PHP_CodeSniffer's T_FUNCTION: not a closure, and not +// the "function" of "use function", which it retokenizes to T_STRING. +func (f *slvFile) isNamedFunction(i int) bool { + if !f.isKeyword(i, "function") || f.isClosure(i) || f.isKeyword(f.prevEffective(i-1), "use") { + return false + } + e := f.enclosing(i) + return !f.is(e, "{") || !f.is(f.prevEffective(e-1), "\\") +} + +// phpIndex mirrors PHP reading $tokens[false]: a missing token is token 0. +func phpIndex(i int) int { + return max(i, 0) +} + +func (fs FunctionSpacing) process(f *slvFile, fn int) { + toks := f.toks + n := len(toks) + eol := func(times int) string { return strings.Repeat(f.eol, max(times, 0)) } + + if p := f.prevEffective(fn - 1); p >= 0 && toks[p].kind == token.OpenTag && toks[p].line != 1 { + return + } + closer := f.scopeCloser(fn) + if closer < 0 { + closer = -1 + for j := fn; j < n; j++ { + if f.is(j, ";") { + closer = j + break + } + } + } + closer = phpIndex(closer) + + prev := fn - 1 + for prev >= 0 && f.isFunctionSpacingIgnored(prev) { + prev-- + } + startOfDeclarationLine := phpIndex(f.nextOfKind(prev+1, token.Whitespace)) + for i := startOfDeclarationLine; i >= 0 && toks[i].line == toks[startOfDeclarationLine].line; i-- { + startOfDeclarationLine = i + } + + prev = startOfDeclarationLine + if startOfDeclarationLine > 0 { + seenDocblock := false + for prev = startOfDeclarationLine - 1; prev > 0; prev-- { + if toks[prev].kind == token.Whitespace { + continue + } + if !seenDocblock && f.isDocClose(prev) { + prev = f.docBlockOpener(prev) + seenDocblock = true + continue + } + if toks[prev].kind == token.AttributeEnd && toks[prev].closer >= 0 { + prev = toks[prev].closer + continue + } + break + } + } + isFirst := f.is(prev, "{") + + nextNotIgnored := func(from int) int { + for j := from; j < n; j++ { + if !f.isFunctionSpacingIgnored(j) { + return j + } + } + return 0 + } + next := nextNotIgnored(closer + 1) + if f.isEmpty(next) && toks[next].line == toks[closer].line { + next = nextNotIgnored(next + 1) + } + isLast := f.is(next, "}") + + nextLineToken := closer + 1 + for ; nextLineToken < n; nextLineToken++ { + if toks[nextLineToken].doc == slvDocOpen || toks[nextLineToken].line != toks[closer].line { + break + } + } + required := fs.Spacing + if isLast { + required = fs.SpacingAfterLast + } + foundLines := required + nextContent := -1 + if nextLineToken != n-1 && nextLineToken < n { + if nextContent = f.nextOfKind(nextLineToken, token.Whitespace); nextContent >= 0 { + foundLines = toks[nextContent].line - toks[nextLineToken].line + } + } + if foundLines != required { + f.beginChangeset() + for i := nextLineToken; i <= nextContent; i++ { + if toks[i].line == toks[nextContent].line { + f.replaceToken(i, eol(required)+f.tokenContent(i)) + break + } + f.replaceToken(i, "") + } + f.endChangeset() + } + + startOfPreamble := phpIndex(f.nextOfKind(prev+1, token.Whitespace)) + prevLineToken := -1 + for i := startOfPreamble; i >= 0; i-- { + if toks[i].line != toks[startOfPreamble].line { + prevLineToken = i + break + } + } + var prevContent int + if prevLineToken < 0 { + foundLines, prevContent, prevLineToken = 0, 0, 0 + } else { + firstBefore := phpIndex(f.prevNonWhitespace(startOfDeclarationLine - 1)) + if toks[firstBefore].kind == token.Comment { + return + } + stopAt := 0 + if owner := f.conditionOwner(prevLineToken); owner >= 0 { + stopAt = owner + } + prevContent = prev + prevLine := toks[prevContent].line - 1 + foundLines = toks[startOfPreamble].line - toks[prevContent].line - 1 + for i := prevContent; i > stopAt; i-- { + if f.is(i, "}") { + if owner := f.scopeCondition(i); owner >= 0 && f.isNamedFunction(owner) { + return + } + break + } + if f.isNamedFunction(i) { + return + } + if toks[i].line == prevLine { + break + } + } + } + required = fs.Spacing + if isFirst { + required = fs.SpacingBeforeFirst + } + if foundLines == required { + return + } + nextSpace := fn - 1 + for j := prevContent + 1; j < fn; j++ { + if toks[j].kind == token.Whitespace { + nextSpace = j + break + } + } + if foundLines < required { + f.replaceToken(prevLineToken, f.tokenContent(prevLineToken)+eol(required-foundLines)) + return + } + nextContent = phpIndex(f.nextOfKind(nextSpace+1, token.Whitespace)) + f.beginChangeset() + for i := nextSpace; i < nextContent; i++ { + if toks[i].line == toks[prevContent].line { + continue + } + if toks[i].line == toks[nextContent].line { + f.replaceToken(i, eol(required)+f.tokenContent(i)) + break + } + f.replaceToken(i, "") + } + f.endChangeset() +} + +// conditionOwner is the innermost scope condition holding i (the last key of +// its conditions), -1 when it sits in no scope. +func (f *slvFile) conditionOwner(i int) int { + for open := f.enclosingScope(i); open >= 0; open = f.enclosingScope(open) { + if owner := f.scopeCondition(open); owner >= 0 { + return owner + } + } + return -1 +} diff --git a/blink/internal/fixer/rules/inline_if_declaration.go b/blink/internal/fixer/rules/inline_if_declaration.go new file mode 100644 index 0000000000..d978138c99 --- /dev/null +++ b/blink/internal/fixer/rules/inline_if_declaration.go @@ -0,0 +1,211 @@ +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/ControlStructures/InlineIfDeclarationSniff.php +// +// InlineIfDeclaration puts one space around the "?" and ":" of a single-line +// ternary ("($a)?'x':'y'" -> "($a) ? 'x' : 'y'"), and none between them in a +// short ternary ("? :" -> "?:"). A ternary spanning lines is left alone. +type InlineIfDeclaration struct{} + +func (InlineIfDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\InlineIfDeclarationSniff` +} + +func (InlineIfDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/InlineIfDeclarationSniff.php" +} + +func (InlineIfDeclaration) Fix(s *tokens.Stream) bool { + return phpcsRunUntilStable(s, inlineIfDeclarationPass) +} + +func inlineIfDeclarationPass(s *tokens.Stream) bool { + changed := false + ctx := newPhpcsOperatorContext(s) + lines := phpcsTokenLines(s) + for i := 0; i < s.Len(); i++ { + if t := s.At(i); t.Kind != token.Punct || t.Value != "?" || phpcsIsNullable(s, i) { + continue + } + if inlineIfFix(s, i, ctx, lines) { + changed = true + ctx = newPhpcsOperatorContext(s) + lines = phpcsTokenLines(s) + } + } + return changed +} + +// inlineIfFix applies the sniff's fixes to the ternary whose "?" is at q, right +// to left so the indices it computed stay valid. +func inlineIfFix(s *tokens.Stream, q int, ctx phpcsOperatorContext, lines []int) bool { + closeBracket := -1 + if open := phpcsInnermostParen(s, q); open >= 0 { + closeBracket = s.MatchForward(open) + } + firstElse := -1 + for j := q + 1; j < s.Len(); j++ { + if ctx.inlineElse[j] { + firstElse = j + break + } + } + if firstElse < 0 { + return false + } + end := s.Len() + if closeBracket >= 0 { + end = closeBracket + } + statementEnd := -1 + for j := firstElse + 1; j < end; j++ { + if v := s.At(j); v.Kind == token.Punct && (v.Value == ";" || v.Value == ",") { + statementEnd = j + break + } + } + if statementEnd < 0 { + if closeBracket < 0 { + return false + } + statementEnd = closeBracket - 1 + for statementEnd >= 0 && s.At(statementEnd).Kind == token.Whitespace { + statementEnd-- + } + } + if statementEnd < 0 || lines[statementEnd] != lines[q] { + return false + } + + var elseIdx int + elvis := false + if next := inlineIfNextNonWhitespace(s, q+1); next < s.Len() && ctx.inlineElse[next] { + elseIdx, elvis = next, true + } else { + elseIdx = -1 + for j := q + 1; j < statementEnd; j++ { + if ctx.inlineElse[j] { + elseIdx = j + break + } + } + if elseIdx < 0 { + return false + } + } + + // after the ":" first, so the earlier indices stay valid + changed := inlineIfSetSpaceAfter(s, elseIdx) + if elvis { + if elseIdx != q+1 { + s.RemoveAt(q + 1) + changed = true + } + } else { + if inlineIfSetSpaceBefore(s, elseIdx) { + changed = true + } + if inlineIfSetSpaceAfter(s, q) { + changed = true + } + } + if inlineIfSetSpaceBefore(s, q) { + changed = true + } + return changed +} + +// inlineIfSetSpaceAfter makes the space after the operator at i one column +// wide, measured to the next non-whitespace token as PHP_CodeSniffer does. +func inlineIfSetSpaceAfter(s *tokens.Stream, i int) bool { + w := i + 1 + if w >= s.Len() { + return false + } + if s.At(w).Kind != token.Whitespace { + s.InsertAt(w, token.Token{Kind: token.Whitespace, Value: " "}) + return true + } + if strings.ContainsAny(s.At(w).Value, "\r\n") { + s.SetValue(w, " "+s.At(w).Value[phpcsFirstPieceEnd(s.At(w).Value):]) + return true + } + if phpcsTabWidth(s, w) == 1 { + return false + } + s.SetValue(w, " ") + return true +} + +// inlineIfSetSpaceBefore makes the space before the operator at i one column +// wide; across a line break only the last line's piece of the whitespace is +// replaced, PHP_CodeSniffer's whitespace token directly before the operator. +func inlineIfSetSpaceBefore(s *tokens.Stream, i int) bool { + w := i - 1 + if w < 0 { + return false + } + if s.At(w).Kind != token.Whitespace { + s.InsertAt(i, token.Token{Kind: token.Whitespace, Value: " "}) + return true + } + v := s.At(w).Value + if !strings.ContainsAny(v, "\r\n") { + if phpcsTabWidth(s, w) == 1 { + return false + } + s.SetValue(w, " ") + return true + } + fixed := v[:phpcsLastPieceStart(v)] + " " + if fixed == v { + return false + } + s.SetValue(w, fixed) + return true +} + +func inlineIfNextNonWhitespace(s *tokens.Stream, i int) int { + for i < s.Len() && s.At(i).Kind == token.Whitespace { + i++ + } + return i +} + +// phpcsFirstPieceEnd is where PHP_CodeSniffer's first whitespace token of v +// ends: just after its first line break. +func phpcsFirstPieceEnd(v string) int { + return len(phpcsThroughFirstBreak(v)) +} + +// phpcsLastPieceStart is where PHP_CodeSniffer's last whitespace token of v +// starts: after the last line break, or at the start of the last line when v +// ends with a break. +func phpcsLastPieceStart(v string) int { + if tail := phpcsAfterLastBreak(v); tail != "" { + return len(v) - len(tail) + } + body := strings.TrimSuffix(strings.TrimSuffix(v, "\n"), "\r") + if strings.HasSuffix(v, "\r\n") { + body = v[:len(v)-2] + } + return len(body) - len(phpcsAfterLastBreak(body)) +} + +// phpcsTokenLines is the 1-based line each token starts on. +func phpcsTokenLines(s *tokens.Stream) []int { + lines := make([]int, s.Len()) + line := 1 + for i := range s.Len() { + lines[i] = line + line += phpcsLineBreaks(s.At(i).Value) + } + return lines +} diff --git a/blink/internal/fixer/rules/long_condition_closing_comment.go b/blink/internal/fixer/rules/long_condition_closing_comment.go new file mode 100644 index 0000000000..2d5af0bcb8 --- /dev/null +++ b/blink/internal/fixer/rules/long_condition_closing_comment.go @@ -0,0 +1,235 @@ +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/Commenting/LongConditionClosingCommentSniff.php +// +// LongConditionClosingComment puts "//end if", "//end foreach" and the like +// after the closing brace of a long control structure, and corrects a wrong +// comment there. +type LongConditionClosingComment struct { + LineLimit int + CommentFormat string +} + +func (LongConditionClosingComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\LongConditionClosingCommentSniff` +} + +func (LongConditionClosingComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/LongConditionClosingCommentSniff.php" +} + +func (f LongConditionClosingComment) WithConfig(config map[string]any) fixer.Fixer { + f.LineLimit = configInt(config, "lineLimit", f.LineLimit) + if v, ok := config["commentFormat"].(string); ok { + f.CommentFormat = v + } + return f +} + +func (f LongConditionClosingComment) Fix(s *tokens.Stream) bool { + return phpcsFixLoop(s, f.pass) +} + +func (f LongConditionClosingComment) pass(s *tokens.Stream) bool { + eol := phpcsEolChar(s) + lines := phpcsLines(s, eol) + var edits []phpcsDocEdit + for i := range s.Len() { + open, closeIdx := longConditionBody(s, i) + if closeIdx < 0 { + continue + } + kw := strings.ToLower(s.At(i).Value) + end, ok := longConditionEnd(s, kw, closeIdx) + if !ok { + continue + } + at := end + if kw == "match" { + if n := nextNonWhitespaceIndex(s, end); n >= 0 && (isPunctVal(s, n, ";") || isPunctVal(s, n, ",")) { + at = n + } + } + expected := strings.Replace(f.CommentFormat, "%s", s.At(i).Value, 1) + comment := at + for comment < s.Len() && !isPhpcsComment(s.At(comment)) { + comment++ + } + if comment == s.Len() || lines[comment] != lines[end] { + if lines[end]-lines[open] < f.LineLimit { + continue + } + content := expected + if n := nextNonWhitespaceIndex(s, at); n >= 0 && lines[n] == lines[at] { + content += eol + } + edits = append(edits, phpcsDocEdit{at, func(s *tokens.Stream) { + s.InsertAt(at+1, token.Token{Kind: token.Comment, Value: content}) + }}) + continue + } + if phpTrim(s.At(comment).Value) == expected { + continue + } + keepsBreak := isLineComment(s.At(comment)) && comment+1 < s.Len() && + s.At(comment+1).Kind == token.Whitespace && strings.ContainsAny(s.At(comment + 1).Value[:1], "\r\n") + edits = append(edits, phpcsDocEdit{comment, func(s *tokens.Stream) { + if keepsBreak { + s.SetValue(comment, expected) + return + } + s.SetValue(comment, expected+eol) + }}) + } + return applyPhpcsEdits(s, edits) +} + +// longConditionBody returns the braces of the switch, if, for, foreach, while, +// try, case or match whose keyword is at i, closeIdx -1 for anything else. +func longConditionBody(s *tokens.Stream, i int) (open, closeIdx int) { + t := s.At(i) + if t.Kind != token.Keyword { + return -1, -1 + } + switch strings.ToLower(t.Value) { + case "if": + if p := prevNonWhitespaceIdx(s, i); p >= 0 && s.At(p).Kind == token.Keyword && strings.EqualFold(s.At(p).Value, "else") { + return -1, -1 + } + return scopeBraces(s, i, true) + case "switch", "for", "foreach", "while", "match": + return scopeBraces(s, i, true) + case "try": + return scopeBraces(s, i, false) + case "case": + return caseBraces(s, i) + } + return -1, -1 +} + +// scopeBraces returns the "{...}" body right after the keyword at i, past its +// parenthesized condition when withParens. +func scopeBraces(s *tokens.Stream, i int, withParens bool) (open, closeIdx int) { + o := phpcsNextNonEmpty(s, i+1) + if withParens { + if !isPunctVal(s, o, "(") { + return -1, -1 + } + c := s.MatchForward(o) + if c < 0 { + return -1, -1 + } + o = phpcsNextNonEmpty(s, c+1) + } + if !isPunctVal(s, o, "{") { + return -1, -1 + } + if c := s.MatchForward(o); c >= 0 { + return o, c + } + return -1, -1 +} + +// caseBraces returns the braces right after a case's ":" or ";", which +// PHP_CodeSniffer makes the case's own scope. +func caseBraces(s *tokens.Stream, i int) (open, closeIdx int) { + depth := 0 + for j := i + 1; j < s.Len(); j++ { + t := s.At(j) + if t.Kind == token.CloseTag { + return -1, -1 + } + if t.Kind != token.Punct { + continue + } + switch t.Value { + case "(", "[", "{": + depth++ + case ")", "]", "}": + depth-- + if depth < 0 { + return -1, -1 + } + case ":", ";": + if depth > 0 { + continue + } + o := phpcsNextNonEmpty(s, j+1) + if !isPunctVal(s, o, "{") { + return -1, -1 + } + if c := s.MatchForward(o); c >= 0 { + return o, c + } + return -1, -1 + } + } + return -1, -1 +} + +// longConditionEnd follows an if through its elseif and else blocks, and a try +// through its catch and finally blocks, to the last closing brace; ok is false +// when an elseif has no braces. +func longConditionEnd(s *tokens.Stream, kw string, closeIdx int) (end int, ok bool) { + end = closeIdx + switch kw { + case "if": + for { + n := nextNonWhitespaceIndex(s, end) + if n < 0 || s.At(n).Kind != token.Keyword { + return end, true + } + switch strings.ToLower(s.At(n).Value) { + case "elseif": + _, c := scopeBraces(s, n, true) + if c < 0 { + return end, false + } + end = c + case "else": + _, c := scopeBraces(s, n, false) + if c < 0 { + m := nextNonWhitespaceIndex(s, n) + if m < 0 || s.At(m).Kind != token.Keyword || !strings.EqualFold(s.At(m).Value, "if") { + return end, true + } + if _, c = scopeBraces(s, m, true); c < 0 { + return end, true + } + } + end = c + default: + return end, true + } + } + case "try": + for { + n := nextNonWhitespaceIndex(s, end) + if n < 0 || s.At(n).Kind != token.Keyword { + return end, true + } + var c int + switch strings.ToLower(s.At(n).Value) { + case "catch": + _, c = scopeBraces(s, n, true) + case "finally": + _, c = scopeBraces(s, n, false) + default: + return end, true + } + if c < 0 { + return end, true + } + end = c + } + } + return end, true +} diff --git a/blink/internal/fixer/rules/lowercase_php_functions.go b/blink/internal/fixer/rules/lowercase_php_functions.go new file mode 100644 index 0000000000..b75e632dab --- /dev/null +++ b/blink/internal/fixer/rules/lowercase_php_functions.go @@ -0,0 +1,118 @@ +package rules + +import ( + _ "embed" + "strings" + "sync" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// phpBuiltinFunctionsList is PHP's get_defined_functions()['internal'], +// regenerated with bin/php-builtin-functions.sh. +// +//go:embed php_builtin_functions.txt +var phpBuiltinFunctionsList string + +var phpBuiltinFunctions = sync.OnceValue(func() map[string]bool { + m := map[string]bool{} + for name := range strings.SplitSeq(phpBuiltinFunctionsList, "\n") { + if name = strings.TrimSpace(name); name != "" { + m[name] = true + } + } + return m +}) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/PHP/LowercasePHPFunctionsSniff.php +// +// LowercasePHPFunctions lowercases calls to PHP's built-in functions +// ("Array_Keys($a)" -> "array_keys($a)") and their "use function" imports. +// Methods, declarations, instantiations and attribute arguments are left alone. +type LowercasePHPFunctions struct{} + +func (LowercasePHPFunctions) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\LowercasePHPFunctionsSniff` +} + +func (LowercasePHPFunctions) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/PHP/LowercasePHPFunctionsSniff.php" +} + +func (LowercasePHPFunctions) Fix(s *tokens.Stream) bool { + changed := false + inAttribute := false + for i := range s.Len() { + t := s.At(i) + switch t.Kind { + case token.AttributeStart: + inAttribute = true + continue + case token.AttributeEnd: + inAttribute = false + continue + } + if t.Kind != token.Ident || inAttribute { + continue + } + lower := strings.ToLower(t.Value) + if lower == t.Value || !phpBuiltinFunctions()[lower] { + continue + } + start, ok := lowercasePHPFunctionNameStart(s, i) + if !ok || (i+1 < s.Len() && s.At(i+1).Value == `\`) { + continue + } + next := phpcsNextNonEmpty(s, i+1) + if next >= s.Len() { + continue + } + prev := lowercasePHPFunctionPrev(s, start-1) + if s.At(next).Value != "(" { + // "use function StrLen;" imports a native function + if start != i || prev < 0 || s.At(prev).Value != "function" { + continue + } + if pp := phpcsPrevNonEmpty(s, prev-1); pp < 0 || !strings.EqualFold(s.At(pp).Value, "use") { + continue + } + } else if prev >= 0 { + switch strings.ToLower(s.At(prev).Value) { + case "function", "new", "->", "?->", "::": + continue + } + } + s.SetValue(i, lower) + changed = true + } + return changed +} + +// lowercasePHPFunctionNameStart is where the name at i begins: i itself, or the +// leading "\" of a fully qualified "\strlen". A name inside a qualified or +// relative name ("Foo\strlen", "namespace\strlen", "strlen\Foo") is not a candidate. +func lowercasePHPFunctionNameStart(s *tokens.Stream, i int) (int, bool) { + if i == 0 || s.At(i-1).Kind != token.Punct || s.At(i-1).Value != `\` { + return i, true + } + if i >= 2 { + if k := s.At(i - 2).Kind; k == token.Ident || k == token.Keyword { + return 0, false + } + } + return i - 1, true +} + +// lowercasePHPFunctionPrev is the previous token before i skipping comments, +// whitespace and "&" (a by-reference function declaration). +func lowercasePHPFunctionPrev(s *tokens.Stream, i int) int { + for j := i; j >= 0; j-- { + t := s.At(j) + if isPhpcsEmpty(t) || (t.Kind == token.Punct && t.Value == "&") { + continue + } + return j + } + return -1 +} diff --git a/blink/internal/fixer/rules/member_var_spacing.go b/blink/internal/fixer/rules/member_var_spacing.go new file mode 100644 index 0000000000..91d7a20b55 --- /dev/null +++ b/blink/internal/fixer/rules/member_var_spacing.go @@ -0,0 +1,293 @@ +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/WhiteSpace/MemberVarSpacingSniff.php +// +// MemberVarSpacing puts Spacing blank lines before a property (SpacingBeforeFirst +// before the first one in a class) and none between its comment and itself. +type MemberVarSpacing struct { + Spacing int + SpacingBeforeFirst int +} + +func (MemberVarSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\MemberVarSpacingSniff` +} + +func (MemberVarSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/MemberVarSpacingSniff.php" +} + +func (m MemberVarSpacing) WithConfig(config map[string]any) fixer.Fixer { + m.Spacing = configInt(config, "spacing", m.Spacing) + m.SpacingBeforeFirst = configInt(config, "spacingBeforeFirst", m.SpacingBeforeFirst) + return m +} + +func (m MemberVarSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { return f.toks[i].kind == token.Variable }, func(i int) int { + scopes, inFunction := f.ooConditions(i) + if scopes == 0 { + return 0 + } + if !inFunction && f.inFunctionParens(i) { + inFunction = true + } + if inFunction { + return 0 + } + end := m.process(f, i) + if scopes > 1 { + // AbstractScopeSniff returns min() of every OO scope's result, + // and the outer ones return null + return 0 + } + return end + }) + }) +} + +// ooConditions counts the class-like scopes holding i and reports whether a +// function or closure sits between the innermost of them and i. +func (f *slvFile) ooConditions(i int) (int, bool) { + scopes, inFunction, seenOO := 0, false, false + for open := f.enclosingScope(i); open >= 0; open = f.enclosingScope(open) { + owner := f.braceOwner(open) + if owner < 0 { + continue + } + switch strings.ToLower(f.toks[owner].orig) { + case "class", "interface", "trait", "enum": + scopes++ + seenOO = true + case "function": + if !seenOO { + inFunction = true + } + } + } + return scopes, inFunction +} + +// inFunctionParens reports whether any parentheses holding i belong to a +// function, closure or closure use. +func (f *slvFile) inFunctionParens(i int) bool { + for open := f.enclosing(i); open >= 0; open = f.enclosing(open) { + if !f.is(open, "(") { + continue + } + p := f.prevEffective(open - 1) + if f.isKeyword(p, "use") || f.isKeyword(p, "function") { + return true + } + if p >= 0 && (f.toks[p].kind == token.Ident || f.toks[p].kind == token.Keyword) { + q := f.prevEffective(p - 1) + if f.is(q, "&") { + q = f.prevEffective(q - 1) + } + if f.isKeyword(q, "function") { + return true + } + } + } + return false +} + +func (f *slvFile) isMemberVarPrefix(i int) bool { + if f.toks[i].kind != token.Keyword { + return false + } + switch v := strings.ToLower(f.toks[i].orig); v { + case "public", "protected", "private", "static", "final", "var", "readonly", "abstract": + return true + default: + return strings.HasSuffix(v, "(set)") + } +} + +// attributeCloser is the "]" of the attribute holding i, -1 when none does. +func (f *slvFile) attributeCloser(i int) int { + if f.toks[i].kind == token.AttributeEnd { + return i + } + for j := i; j >= 0; j = f.enclosing(j) { + if f.toks[j].kind == token.AttributeStart && f.toks[j].closer >= i { + return f.toks[j].closer + } + } + return -1 +} + +// docBlockOpener is the comment_opener of the docblock closer at i. +func (f *slvFile) docBlockOpener(i int) int { + for j := i; j >= 0; j-- { + if f.toks[j].doc == slvDocOpen { + return j + } + } + return i +} + +func (f *slvFile) isDocClose(i int) bool { + return i >= 0 && f.toks[i].doc == slvDocClose +} + +func (f *slvFile) isPhpcsAnnotation(i int) bool { + return i >= 0 && f.toks[i].kind == token.Comment && isPhpcsAnnotationComment(f.toks[i].orig) +} + +func (f *slvFile) nextOfKind(i int, k token.Kind) int { + for ; i < len(f.toks); i++ { + if f.toks[i].kind != k { + return i + } + } + return -1 +} + +func (m MemberVarSpacing) process(f *slvFile, v int) int { + toks := f.toks + eops := -1 + for j := v - 1; j >= 0; j-- { + if f.is(j, ";") || f.is(j, "{") || f.is(j, "}") { + eops = j + break + } + if (f.is(j, ")") || f.is(j, "]")) && toks[j].closer >= 0 { + j = toks[j].closer + } + } + startOfStatement := -1 + for j := eops + 1; j < v; j++ { + if f.isMemberVarPrefix(j) { + startOfStatement = j + break + } + if f.is(j, ";") { + break + } + } + if startOfStatement < 0 { + return 0 + } + endOfStatement := 0 + for j := v + 1; j < len(toks); j++ { + if f.is(j, ";") { + endOfStatement = j + break + } + } + + start := startOfStatement + prev := startOfStatement - 1 + for ; prev >= 0; prev-- { + if toks[prev].kind == token.Whitespace { + continue + } + if toks[prev].kind == token.AttributeEnd && toks[prev].closer >= 0 { + prev = toks[prev].closer + start = prev + continue + } + break + } + if f.isDocClose(prev) { + start = prev + } else if prev >= 0 && (toks[prev].kind == token.Comment || toks[prev].kind == token.DocComment) { + prevContent := f.prevEffective(prev - 1) + if prevContent < 0 || toks[prevContent].line != toks[prev].line { + start = prev + } + } + + for i := start + 1; i < startOfStatement; i++ { + if c := f.attributeCloser(i); c >= 0 { + i = c + continue + } + if toks[i].column != 1 || toks[i].kind != token.Whitespace || toks[i].line == toks[i+1].line || f.isPhpcsAnnotation(i-1) { + continue + } + next := f.nextOfKind(i+1, token.Whitespace) + if next < 0 { + break + } + f.beginChangeset() + for j := i; j < next; j++ { + if toks[j].line == toks[next].line { + break + } + f.replaceToken(j, "") + } + f.endChangeset() + i = next + } + + var first int + switch { + case start == startOfStatement: + first = start + for j := start; j >= 0 && toks[j].line == toks[start].line; j-- { + if !f.isEmpty(j) { + first = j + } + } + case f.isDocClose(start): + first = f.docBlockOpener(start) + default: + first = f.prevEffective(start-1) + 1 + for ; first < len(toks); first++ { + if toks[first].kind == token.Comment || toks[first].kind == token.DocComment || toks[first].kind == token.AttributeStart { + break + } + } + } + + prev = first - 1 + for prev >= 0 && toks[prev].kind == token.Whitespace { + prev-- + } + if prev < 0 { + return endOfStatement + } + if f.is(prev, "}") { + if owner := f.scopeCondition(prev); owner >= 0 && f.isKeyword(owner, "function") && !f.isClosure(owner) { + return 0 + } + } + spacing := m.Spacing + if f.is(prev, "{") { + if owner := f.scopeCondition(prev); owner >= 0 { + switch strings.ToLower(toks[owner].orig) { + case "class", "interface", "trait", "enum": + spacing = m.SpacingBeforeFirst + } + } + } + if toks[first].line-toks[prev].line-1 == spacing { + return endOfStatement + } + f.beginChangeset() + for i := prev + 1; i < first; i++ { + if toks[i].line == toks[prev].line { + continue + } + if toks[i].line == toks[first].line { + for range spacing { + f.replaceToken(i, f.eol+f.tokenContent(i)) + } + break + } + f.replaceToken(i, "") + } + f.endChangeset() + return endOfStatement +} diff --git a/blink/internal/fixer/rules/php_builtin_functions.txt b/blink/internal/fixer/rules/php_builtin_functions.txt new file mode 100644 index 0000000000..0fe812bb94 --- /dev/null +++ b/blink/internal/fixer/rules/php_builtin_functions.txt @@ -0,0 +1,1784 @@ +_ +abs +acos +acosh +addcslashes +addslashes +array_all +array_any +array_change_key_case +array_chunk +array_column +array_combine +array_count_values +array_diff +array_diff_assoc +array_diff_key +array_diff_uassoc +array_diff_ukey +array_fill +array_fill_keys +array_filter +array_find +array_find_key +array_flip +array_intersect +array_intersect_assoc +array_intersect_key +array_intersect_uassoc +array_intersect_ukey +array_is_list +array_key_exists +array_key_first +array_key_last +array_keys +array_map +array_merge +array_merge_recursive +array_multisort +array_pad +array_pop +array_product +array_push +array_rand +array_reduce +array_replace +array_replace_recursive +array_reverse +array_search +array_shift +array_slice +array_splice +array_sum +array_udiff +array_udiff_assoc +array_udiff_uassoc +array_uintersect +array_uintersect_assoc +array_uintersect_uassoc +array_unique +array_unshift +array_values +array_walk +array_walk_recursive +arsort +asin +asinh +asort +assert +assert_options +atan +atan2 +atanh +base64_decode +base64_encode +base_convert +basename +bcadd +bcceil +bccomp +bcdiv +bcdivmod +bcfloor +bcmod +bcmul +bcpow +bcpowmod +bcround +bcscale +bcsqrt +bcsub +bin2hex +bind_textdomain_codeset +bindec +bindtextdomain +boolval +cal_days_in_month +cal_from_jd +cal_info +cal_to_jd +call_user_func +call_user_func_array +ceil +chdir +checkdate +checkdnsrr +chgrp +chmod +chop +chown +chr +chroot +chunk_split +class_alias +class_exists +class_implements +class_parents +class_uses +clearstatcache +cli_get_process_title +cli_set_process_title +closedir +closelog +collator_asort +collator_compare +collator_create +collator_get_attribute +collator_get_error_code +collator_get_error_message +collator_get_locale +collator_get_sort_key +collator_get_strength +collator_set_attribute +collator_set_strength +collator_sort +collator_sort_with_sort_keys +compact +connection_aborted +connection_status +constant +convert_uudecode +convert_uuencode +copy +cos +cosh +count +count_chars +crc32 +crypt +ctype_alnum +ctype_alpha +ctype_cntrl +ctype_digit +ctype_graph +ctype_lower +ctype_print +ctype_punct +ctype_space +ctype_upper +ctype_xdigit +curl_close +curl_copy_handle +curl_errno +curl_error +curl_escape +curl_exec +curl_file_create +curl_getinfo +curl_init +curl_multi_add_handle +curl_multi_close +curl_multi_errno +curl_multi_exec +curl_multi_getcontent +curl_multi_info_read +curl_multi_init +curl_multi_remove_handle +curl_multi_select +curl_multi_setopt +curl_multi_strerror +curl_pause +curl_reset +curl_setopt +curl_setopt_array +curl_share_close +curl_share_errno +curl_share_init +curl_share_setopt +curl_share_strerror +curl_strerror +curl_unescape +curl_upkeep +curl_version +current +date +date_add +date_create +date_create_from_format +date_create_immutable +date_create_immutable_from_format +date_date_set +date_default_timezone_get +date_default_timezone_set +date_diff +date_format +date_get_last_errors +date_interval_create_from_date_string +date_interval_format +date_isodate_set +date_modify +date_offset_get +date_parse +date_parse_from_format +date_sub +date_sun_info +date_sunrise +date_sunset +date_time_set +date_timestamp_get +date_timestamp_set +date_timezone_get +date_timezone_set +datefmt_create +datefmt_format +datefmt_format_object +datefmt_get_calendar +datefmt_get_calendar_object +datefmt_get_datetype +datefmt_get_error_code +datefmt_get_error_message +datefmt_get_locale +datefmt_get_pattern +datefmt_get_timetype +datefmt_get_timezone +datefmt_get_timezone_id +datefmt_is_lenient +datefmt_localtime +datefmt_parse +datefmt_set_calendar +datefmt_set_lenient +datefmt_set_pattern +datefmt_set_timezone +dcgettext +dcngettext +debug_backtrace +debug_print_backtrace +debug_zval_dump +decbin +dechex +decoct +define +defined +deflate_add +deflate_init +deg2rad +dgettext +die +dir +dirname +disk_free_space +disk_total_space +diskfreespace +dl +dngettext +dns_check_record +dns_get_mx +dns_get_record +dom\import_simplexml +dom_import_simplexml +doubleval +easter_date +easter_days +end +enum_exists +error_clear_last +error_get_last +error_log +error_reporting +escapeshellarg +escapeshellcmd +exec +exif_imagetype +exif_read_data +exif_tagname +exif_thumbnail +exit +exp +explode +expm1 +extension_loaded +extract +fclose +fdatasync +fdiv +feof +fflush +fgetc +fgetcsv +fgets +file +file_exists +file_get_contents +file_put_contents +fileatime +filectime +filegroup +fileinode +filemtime +fileowner +fileperms +filesize +filetype +filter_has_var +filter_id +filter_input +filter_input_array +filter_list +filter_var +filter_var_array +finfo_buffer +finfo_close +finfo_file +finfo_open +finfo_set_flags +floatval +flock +floor +flush +fmod +fnmatch +fopen +forward_static_call +forward_static_call_array +fpassthru +fpow +fprintf +fputcsv +fputs +fread +frenchtojd +fscanf +fseek +fsockopen +fstat +fsync +ftell +ftok +ftp_alloc +ftp_append +ftp_cdup +ftp_chdir +ftp_chmod +ftp_close +ftp_connect +ftp_delete +ftp_exec +ftp_fget +ftp_fput +ftp_get +ftp_get_option +ftp_login +ftp_mdtm +ftp_mkdir +ftp_mlsd +ftp_nb_continue +ftp_nb_fget +ftp_nb_fput +ftp_nb_get +ftp_nb_put +ftp_nlist +ftp_pasv +ftp_put +ftp_pwd +ftp_quit +ftp_raw +ftp_rawlist +ftp_rename +ftp_rmdir +ftp_set_option +ftp_site +ftp_size +ftp_ssl_connect +ftp_systype +ftruncate +func_get_arg +func_get_args +func_num_args +function_exists +fwrite +gc_collect_cycles +gc_disable +gc_enable +gc_enabled +gc_mem_caches +gc_status +gd_info +get_browser +get_called_class +get_cfg_var +get_class +get_class_methods +get_class_vars +get_current_user +get_debug_type +get_declared_classes +get_declared_interfaces +get_declared_traits +get_defined_constants +get_defined_functions +get_defined_vars +get_extension_funcs +get_headers +get_html_translation_table +get_include_path +get_included_files +get_loaded_extensions +get_mangled_object_vars +get_meta_tags +get_object_vars +get_parent_class +get_required_files +get_resource_id +get_resource_type +get_resources +getcwd +getdate +getenv +gethostbyaddr +gethostbyname +gethostbynamel +gethostname +getimagesize +getimagesizefromstring +getlastmod +getmxrr +getmygid +getmyinode +getmypid +getmyuid +getopt +getprotobyname +getprotobynumber +getrandmax +getrusage +getservbyname +getservbyport +gettext +gettimeofday +gettype +glob +gmdate +gmmktime +gmstrftime +grapheme_extract +grapheme_str_split +grapheme_stripos +grapheme_stristr +grapheme_strlen +grapheme_strpos +grapheme_strripos +grapheme_strrpos +grapheme_strstr +grapheme_substr +gregoriantojd +gzclose +gzcompress +gzdecode +gzdeflate +gzencode +gzeof +gzfile +gzgetc +gzgets +gzinflate +gzopen +gzpassthru +gzputs +gzread +gzrewind +gzseek +gztell +gzuncompress +gzwrite +hash +hash_algos +hash_copy +hash_equals +hash_file +hash_final +hash_hkdf +hash_hmac +hash_hmac_algos +hash_hmac_file +hash_init +hash_pbkdf2 +hash_update +hash_update_file +hash_update_stream +header +header_register_callback +header_remove +headers_list +headers_sent +hebrev +hex2bin +hexdec +highlight_file +highlight_string +hrtime +html_entity_decode +htmlentities +htmlspecialchars +htmlspecialchars_decode +http_build_query +http_clear_last_response_headers +http_get_last_response_headers +http_response_code +hypot +iconv +iconv_get_encoding +iconv_mime_decode +iconv_mime_decode_headers +iconv_mime_encode +iconv_set_encoding +iconv_strlen +iconv_strpos +iconv_strrpos +iconv_substr +idate +idn_to_ascii +idn_to_utf8 +ignore_user_abort +image_type_to_extension +image_type_to_mime_type +imageaffine +imageaffinematrixconcat +imageaffinematrixget +imagealphablending +imageantialias +imagearc +imageavif +imagebmp +imagechar +imagecharup +imagecolorallocate +imagecolorallocatealpha +imagecolorat +imagecolorclosest +imagecolorclosestalpha +imagecolorclosesthwb +imagecolordeallocate +imagecolorexact +imagecolorexactalpha +imagecolormatch +imagecolorresolve +imagecolorresolvealpha +imagecolorset +imagecolorsforindex +imagecolorstotal +imagecolortransparent +imageconvolution +imagecopy +imagecopymerge +imagecopymergegray +imagecopyresampled +imagecopyresized +imagecreate +imagecreatefromavif +imagecreatefrombmp +imagecreatefromgd +imagecreatefromgd2 +imagecreatefromgd2part +imagecreatefromgif +imagecreatefromjpeg +imagecreatefrompng +imagecreatefromstring +imagecreatefromtga +imagecreatefromwbmp +imagecreatefromwebp +imagecreatefromxbm +imagecreatefromxpm +imagecreatetruecolor +imagecrop +imagecropauto +imagedashedline +imagedestroy +imageellipse +imagefill +imagefilledarc +imagefilledellipse +imagefilledpolygon +imagefilledrectangle +imagefilltoborder +imagefilter +imageflip +imagefontheight +imagefontwidth +imageftbbox +imagefttext +imagegammacorrect +imagegd +imagegd2 +imagegetclip +imagegetinterpolation +imagegif +imageinterlace +imageistruecolor +imagejpeg +imagelayereffect +imageline +imageloadfont +imageopenpolygon +imagepalettecopy +imagepalettetotruecolor +imagepng +imagepolygon +imagerectangle +imageresolution +imagerotate +imagesavealpha +imagescale +imagesetbrush +imagesetclip +imagesetinterpolation +imagesetpixel +imagesetstyle +imagesetthickness +imagesettile +imagestring +imagestringup +imagesx +imagesy +imagetruecolortopalette +imagettfbbox +imagettftext +imagetypes +imagewbmp +imagewebp +imagexbm +implode +in_array +inet_ntop +inet_pton +inflate_add +inflate_get_read_len +inflate_get_status +inflate_init +ini_alter +ini_get +ini_get_all +ini_parse_quantity +ini_restore +ini_set +intdiv +interface_exists +intl_error_name +intl_get_error_code +intl_get_error_message +intl_is_failure +intlcal_add +intlcal_after +intlcal_before +intlcal_clear +intlcal_create_instance +intlcal_equals +intlcal_field_difference +intlcal_from_date_time +intlcal_get +intlcal_get_actual_maximum +intlcal_get_actual_minimum +intlcal_get_available_locales +intlcal_get_day_of_week_type +intlcal_get_error_code +intlcal_get_error_message +intlcal_get_first_day_of_week +intlcal_get_greatest_minimum +intlcal_get_keyword_values_for_locale +intlcal_get_least_maximum +intlcal_get_locale +intlcal_get_maximum +intlcal_get_minimal_days_in_first_week +intlcal_get_minimum +intlcal_get_now +intlcal_get_repeated_wall_time_option +intlcal_get_skipped_wall_time_option +intlcal_get_time +intlcal_get_time_zone +intlcal_get_type +intlcal_get_weekend_transition +intlcal_in_daylight_time +intlcal_is_equivalent_to +intlcal_is_lenient +intlcal_is_set +intlcal_is_weekend +intlcal_roll +intlcal_set +intlcal_set_first_day_of_week +intlcal_set_lenient +intlcal_set_minimal_days_in_first_week +intlcal_set_repeated_wall_time_option +intlcal_set_skipped_wall_time_option +intlcal_set_time +intlcal_set_time_zone +intlcal_to_date_time +intlgregcal_create_instance +intlgregcal_get_gregorian_change +intlgregcal_is_leap_year +intlgregcal_set_gregorian_change +intltz_count_equivalent_ids +intltz_create_default +intltz_create_enumeration +intltz_create_time_zone +intltz_create_time_zone_id_enumeration +intltz_from_date_time_zone +intltz_get_canonical_id +intltz_get_display_name +intltz_get_dst_savings +intltz_get_equivalent_id +intltz_get_error_code +intltz_get_error_message +intltz_get_gmt +intltz_get_iana_id +intltz_get_id +intltz_get_id_for_windows_id +intltz_get_offset +intltz_get_raw_offset +intltz_get_region +intltz_get_tz_data_version +intltz_get_unknown +intltz_get_windows_id +intltz_has_same_rules +intltz_to_date_time_zone +intltz_use_daylight_time +intval +ip2long +iptcembed +iptcparse +is_a +is_array +is_bool +is_callable +is_countable +is_dir +is_double +is_executable +is_file +is_finite +is_float +is_infinite +is_int +is_integer +is_iterable +is_link +is_long +is_nan +is_null +is_numeric +is_object +is_readable +is_resource +is_scalar +is_soap_fault +is_string +is_subclass_of +is_uploaded_file +is_writable +is_writeable +iterator_apply +iterator_count +iterator_to_array +jddayofweek +jdmonthname +jdtofrench +jdtogregorian +jdtojewish +jdtojulian +jdtounix +jewishtojd +join +json_decode +json_encode +json_last_error +json_last_error_msg +json_validate +juliantojd +key +key_exists +krsort +ksort +lcfirst +lcg_value +lchgrp +lchown +levenshtein +libxml_clear_errors +libxml_disable_entity_loader +libxml_get_errors +libxml_get_external_entity_loader +libxml_get_last_error +libxml_set_external_entity_loader +libxml_set_streams_context +libxml_use_internal_errors +link +linkinfo +locale_accept_from_http +locale_canonicalize +locale_compose +locale_filter_matches +locale_get_all_variants +locale_get_default +locale_get_display_language +locale_get_display_name +locale_get_display_region +locale_get_display_script +locale_get_display_variant +locale_get_keywords +locale_get_primary_language +locale_get_region +locale_get_script +locale_lookup +locale_parse +locale_set_default +localeconv +localtime +log +log10 +log1p +long2ip +lstat +ltrim +mail +max +mb_check_encoding +mb_chr +mb_convert_case +mb_convert_encoding +mb_convert_kana +mb_convert_variables +mb_decode_mimeheader +mb_decode_numericentity +mb_detect_encoding +mb_detect_order +mb_encode_mimeheader +mb_encode_numericentity +mb_encoding_aliases +mb_ereg +mb_ereg_match +mb_ereg_replace +mb_ereg_replace_callback +mb_ereg_search +mb_ereg_search_getpos +mb_ereg_search_getregs +mb_ereg_search_init +mb_ereg_search_pos +mb_ereg_search_regs +mb_ereg_search_setpos +mb_eregi +mb_eregi_replace +mb_get_info +mb_http_input +mb_http_output +mb_internal_encoding +mb_language +mb_lcfirst +mb_list_encodings +mb_ltrim +mb_ord +mb_output_handler +mb_parse_str +mb_preferred_mime_name +mb_regex_encoding +mb_regex_set_options +mb_rtrim +mb_scrub +mb_send_mail +mb_split +mb_str_pad +mb_str_split +mb_strcut +mb_strimwidth +mb_stripos +mb_stristr +mb_strlen +mb_strpos +mb_strrchr +mb_strrichr +mb_strripos +mb_strrpos +mb_strstr +mb_strtolower +mb_strtoupper +mb_strwidth +mb_substitute_character +mb_substr +mb_substr_count +mb_trim +mb_ucfirst +md5 +md5_file +memory_get_peak_usage +memory_get_usage +memory_reset_peak_usage +metaphone +method_exists +mhash +mhash_count +mhash_get_block_size +mhash_get_hash_name +mhash_keygen_s2k +microtime +mime_content_type +min +mkdir +mktime +move_uploaded_file +msg_get_queue +msg_queue_exists +msg_receive +msg_remove_queue +msg_send +msg_set_queue +msg_stat_queue +msgfmt_create +msgfmt_format +msgfmt_format_message +msgfmt_get_error_code +msgfmt_get_error_message +msgfmt_get_locale +msgfmt_get_pattern +msgfmt_parse +msgfmt_parse_message +msgfmt_set_pattern +mt_getrandmax +mt_rand +mt_srand +mysqli_affected_rows +mysqli_autocommit +mysqli_begin_transaction +mysqli_change_user +mysqli_character_set_name +mysqli_close +mysqli_commit +mysqli_connect +mysqli_connect_errno +mysqli_connect_error +mysqli_data_seek +mysqli_debug +mysqli_dump_debug_info +mysqli_errno +mysqli_error +mysqli_error_list +mysqli_escape_string +mysqli_execute +mysqli_execute_query +mysqli_fetch_all +mysqli_fetch_array +mysqli_fetch_assoc +mysqli_fetch_column +mysqli_fetch_field +mysqli_fetch_field_direct +mysqli_fetch_fields +mysqli_fetch_lengths +mysqli_fetch_object +mysqli_fetch_row +mysqli_field_count +mysqli_field_seek +mysqli_field_tell +mysqli_free_result +mysqli_get_charset +mysqli_get_client_info +mysqli_get_client_stats +mysqli_get_client_version +mysqli_get_connection_stats +mysqli_get_host_info +mysqli_get_links_stats +mysqli_get_proto_info +mysqli_get_server_info +mysqli_get_server_version +mysqli_get_warnings +mysqli_info +mysqli_init +mysqli_insert_id +mysqli_kill +mysqli_more_results +mysqli_multi_query +mysqli_next_result +mysqli_num_fields +mysqli_num_rows +mysqli_options +mysqli_ping +mysqli_poll +mysqli_prepare +mysqli_query +mysqli_real_connect +mysqli_real_escape_string +mysqli_real_query +mysqli_reap_async_query +mysqli_refresh +mysqli_release_savepoint +mysqli_report +mysqli_rollback +mysqli_savepoint +mysqli_select_db +mysqli_set_charset +mysqli_set_opt +mysqli_sqlstate +mysqli_ssl_set +mysqli_stat +mysqli_stmt_affected_rows +mysqli_stmt_attr_get +mysqli_stmt_attr_set +mysqli_stmt_bind_param +mysqli_stmt_bind_result +mysqli_stmt_close +mysqli_stmt_data_seek +mysqli_stmt_errno +mysqli_stmt_error +mysqli_stmt_error_list +mysqli_stmt_execute +mysqli_stmt_fetch +mysqli_stmt_field_count +mysqli_stmt_free_result +mysqli_stmt_get_result +mysqli_stmt_get_warnings +mysqli_stmt_init +mysqli_stmt_insert_id +mysqli_stmt_more_results +mysqli_stmt_next_result +mysqli_stmt_num_rows +mysqli_stmt_param_count +mysqli_stmt_prepare +mysqli_stmt_reset +mysqli_stmt_result_metadata +mysqli_stmt_send_long_data +mysqli_stmt_sqlstate +mysqli_stmt_store_result +mysqli_store_result +mysqli_thread_id +mysqli_thread_safe +mysqli_use_result +mysqli_warning_count +natcasesort +natsort +net_get_interfaces +next +ngettext +nl2br +nl_langinfo +normalizer_get_raw_decomposition +normalizer_is_normalized +normalizer_normalize +number_format +numfmt_create +numfmt_format +numfmt_format_currency +numfmt_get_attribute +numfmt_get_error_code +numfmt_get_error_message +numfmt_get_locale +numfmt_get_pattern +numfmt_get_symbol +numfmt_get_text_attribute +numfmt_parse +numfmt_parse_currency +numfmt_set_attribute +numfmt_set_pattern +numfmt_set_symbol +numfmt_set_text_attribute +ob_clean +ob_end_clean +ob_end_flush +ob_flush +ob_get_clean +ob_get_contents +ob_get_flush +ob_get_length +ob_get_level +ob_get_status +ob_gzhandler +ob_implicit_flush +ob_list_handlers +ob_start +octdec +opcache_compile_file +opcache_get_configuration +opcache_get_status +opcache_invalidate +opcache_is_script_cached +opcache_jit_blacklist +opcache_reset +opendir +openlog +openssl_cipher_iv_length +openssl_cipher_key_length +openssl_cms_decrypt +openssl_cms_encrypt +openssl_cms_read +openssl_cms_sign +openssl_cms_verify +openssl_csr_export +openssl_csr_export_to_file +openssl_csr_get_public_key +openssl_csr_get_subject +openssl_csr_new +openssl_csr_sign +openssl_decrypt +openssl_dh_compute_key +openssl_digest +openssl_encrypt +openssl_error_string +openssl_free_key +openssl_get_cert_locations +openssl_get_cipher_methods +openssl_get_curve_names +openssl_get_md_methods +openssl_get_privatekey +openssl_get_publickey +openssl_open +openssl_pbkdf2 +openssl_pkcs12_export +openssl_pkcs12_export_to_file +openssl_pkcs12_read +openssl_pkcs7_decrypt +openssl_pkcs7_encrypt +openssl_pkcs7_read +openssl_pkcs7_sign +openssl_pkcs7_verify +openssl_pkey_derive +openssl_pkey_export +openssl_pkey_export_to_file +openssl_pkey_free +openssl_pkey_get_details +openssl_pkey_get_private +openssl_pkey_get_public +openssl_pkey_new +openssl_private_decrypt +openssl_private_encrypt +openssl_public_decrypt +openssl_public_encrypt +openssl_random_pseudo_bytes +openssl_seal +openssl_sign +openssl_spki_export +openssl_spki_export_challenge +openssl_spki_new +openssl_spki_verify +openssl_verify +openssl_x509_check_private_key +openssl_x509_checkpurpose +openssl_x509_export +openssl_x509_export_to_file +openssl_x509_fingerprint +openssl_x509_free +openssl_x509_parse +openssl_x509_read +openssl_x509_verify +ord +output_add_rewrite_var +output_reset_rewrite_vars +pack +parse_ini_file +parse_ini_string +parse_str +parse_url +passthru +password_algos +password_get_info +password_hash +password_needs_rehash +password_verify +pathinfo +pclose +pcntl_alarm +pcntl_async_signals +pcntl_errno +pcntl_exec +pcntl_fork +pcntl_get_last_error +pcntl_getcpu +pcntl_getcpuaffinity +pcntl_getpriority +pcntl_setcpuaffinity +pcntl_setns +pcntl_setpriority +pcntl_signal +pcntl_signal_dispatch +pcntl_signal_get_handler +pcntl_sigprocmask +pcntl_sigtimedwait +pcntl_sigwaitinfo +pcntl_strerror +pcntl_unshare +pcntl_wait +pcntl_waitid +pcntl_waitpid +pcntl_wexitstatus +pcntl_wifcontinued +pcntl_wifexited +pcntl_wifsignaled +pcntl_wifstopped +pcntl_wstopsig +pcntl_wtermsig +pdo_drivers +pfsockopen +php_ini_loaded_file +php_ini_scanned_files +php_sapi_name +php_strip_whitespace +php_uname +phpcredits +phpinfo +phpversion +pi +popen +pos +posix_access +posix_ctermid +posix_eaccess +posix_errno +posix_fpathconf +posix_get_last_error +posix_getcwd +posix_getegid +posix_geteuid +posix_getgid +posix_getgrgid +posix_getgrnam +posix_getgroups +posix_getlogin +posix_getpgid +posix_getpgrp +posix_getpid +posix_getppid +posix_getpwnam +posix_getpwuid +posix_getrlimit +posix_getsid +posix_getuid +posix_initgroups +posix_isatty +posix_kill +posix_mkfifo +posix_mknod +posix_pathconf +posix_setegid +posix_seteuid +posix_setgid +posix_setpgid +posix_setrlimit +posix_setsid +posix_setuid +posix_strerror +posix_sysconf +posix_times +posix_ttyname +posix_uname +pow +preg_filter +preg_grep +preg_last_error +preg_last_error_msg +preg_match +preg_match_all +preg_quote +preg_replace +preg_replace_callback +preg_replace_callback_array +preg_split +prev +print_r +printf +proc_close +proc_get_status +proc_nice +proc_open +proc_terminate +property_exists +putenv +quoted_printable_decode +quoted_printable_encode +quotemeta +rad2deg +rand +random_bytes +random_int +range +rawurldecode +rawurlencode +readdir +readfile +readgzfile +readline +readline_add_history +readline_callback_handler_install +readline_callback_handler_remove +readline_callback_read_char +readline_clear_history +readline_completion_function +readline_info +readline_list_history +readline_on_new_line +readline_read_history +readline_redisplay +readline_write_history +readlink +realpath +realpath_cache_get +realpath_cache_size +register_shutdown_function +register_tick_function +rename +request_parse_body +reset +resourcebundle_count +resourcebundle_create +resourcebundle_get +resourcebundle_get_error_code +resourcebundle_get_error_message +resourcebundle_locales +restore_error_handler +restore_exception_handler +rewind +rewinddir +rmdir +round +rsort +rtrim +scandir +sem_acquire +sem_get +sem_release +sem_remove +serialize +session_abort +session_cache_expire +session_cache_limiter +session_commit +session_create_id +session_decode +session_destroy +session_encode +session_gc +session_get_cookie_params +session_id +session_module_name +session_name +session_regenerate_id +session_register_shutdown +session_reset +session_save_path +session_set_cookie_params +session_set_save_handler +session_start +session_status +session_unset +session_write_close +set_error_handler +set_exception_handler +set_file_buffer +set_include_path +set_time_limit +setcookie +setlocale +setrawcookie +settype +sha1 +sha1_file +shell_exec +shm_attach +shm_detach +shm_get_var +shm_has_var +shm_put_var +shm_remove +shm_remove_var +shmop_close +shmop_delete +shmop_open +shmop_read +shmop_size +shmop_write +show_source +shuffle +similar_text +simplexml_import_dom +simplexml_load_file +simplexml_load_string +sin +sinh +sizeof +sleep +socket_accept +socket_addrinfo_bind +socket_addrinfo_connect +socket_addrinfo_explain +socket_addrinfo_lookup +socket_atmark +socket_bind +socket_clear_error +socket_close +socket_cmsg_space +socket_connect +socket_create +socket_create_listen +socket_create_pair +socket_export_stream +socket_get_option +socket_get_status +socket_getopt +socket_getpeername +socket_getsockname +socket_import_stream +socket_last_error +socket_listen +socket_read +socket_recv +socket_recvfrom +socket_recvmsg +socket_select +socket_send +socket_sendmsg +socket_sendto +socket_set_block +socket_set_blocking +socket_set_nonblock +socket_set_option +socket_set_timeout +socket_setopt +socket_shutdown +socket_strerror +socket_write +sodium_add +sodium_base642bin +sodium_bin2base64 +sodium_bin2hex +sodium_compare +sodium_crypto_aead_aes256gcm_decrypt +sodium_crypto_aead_aes256gcm_encrypt +sodium_crypto_aead_aes256gcm_is_available +sodium_crypto_aead_aes256gcm_keygen +sodium_crypto_aead_chacha20poly1305_decrypt +sodium_crypto_aead_chacha20poly1305_encrypt +sodium_crypto_aead_chacha20poly1305_ietf_decrypt +sodium_crypto_aead_chacha20poly1305_ietf_encrypt +sodium_crypto_aead_chacha20poly1305_ietf_keygen +sodium_crypto_aead_chacha20poly1305_keygen +sodium_crypto_aead_xchacha20poly1305_ietf_decrypt +sodium_crypto_aead_xchacha20poly1305_ietf_encrypt +sodium_crypto_aead_xchacha20poly1305_ietf_keygen +sodium_crypto_auth +sodium_crypto_auth_keygen +sodium_crypto_auth_verify +sodium_crypto_box +sodium_crypto_box_keypair +sodium_crypto_box_keypair_from_secretkey_and_publickey +sodium_crypto_box_open +sodium_crypto_box_publickey +sodium_crypto_box_publickey_from_secretkey +sodium_crypto_box_seal +sodium_crypto_box_seal_open +sodium_crypto_box_secretkey +sodium_crypto_box_seed_keypair +sodium_crypto_core_ristretto255_add +sodium_crypto_core_ristretto255_from_hash +sodium_crypto_core_ristretto255_is_valid_point +sodium_crypto_core_ristretto255_random +sodium_crypto_core_ristretto255_scalar_add +sodium_crypto_core_ristretto255_scalar_complement +sodium_crypto_core_ristretto255_scalar_invert +sodium_crypto_core_ristretto255_scalar_mul +sodium_crypto_core_ristretto255_scalar_negate +sodium_crypto_core_ristretto255_scalar_random +sodium_crypto_core_ristretto255_scalar_reduce +sodium_crypto_core_ristretto255_scalar_sub +sodium_crypto_core_ristretto255_sub +sodium_crypto_generichash +sodium_crypto_generichash_final +sodium_crypto_generichash_init +sodium_crypto_generichash_keygen +sodium_crypto_generichash_update +sodium_crypto_kdf_derive_from_key +sodium_crypto_kdf_keygen +sodium_crypto_kx_client_session_keys +sodium_crypto_kx_keypair +sodium_crypto_kx_publickey +sodium_crypto_kx_secretkey +sodium_crypto_kx_seed_keypair +sodium_crypto_kx_server_session_keys +sodium_crypto_pwhash +sodium_crypto_pwhash_scryptsalsa208sha256 +sodium_crypto_pwhash_scryptsalsa208sha256_str +sodium_crypto_pwhash_scryptsalsa208sha256_str_verify +sodium_crypto_pwhash_str +sodium_crypto_pwhash_str_needs_rehash +sodium_crypto_pwhash_str_verify +sodium_crypto_scalarmult +sodium_crypto_scalarmult_base +sodium_crypto_scalarmult_ristretto255 +sodium_crypto_scalarmult_ristretto255_base +sodium_crypto_secretbox +sodium_crypto_secretbox_keygen +sodium_crypto_secretbox_open +sodium_crypto_secretstream_xchacha20poly1305_init_pull +sodium_crypto_secretstream_xchacha20poly1305_init_push +sodium_crypto_secretstream_xchacha20poly1305_keygen +sodium_crypto_secretstream_xchacha20poly1305_pull +sodium_crypto_secretstream_xchacha20poly1305_push +sodium_crypto_secretstream_xchacha20poly1305_rekey +sodium_crypto_shorthash +sodium_crypto_shorthash_keygen +sodium_crypto_sign +sodium_crypto_sign_detached +sodium_crypto_sign_ed25519_pk_to_curve25519 +sodium_crypto_sign_ed25519_sk_to_curve25519 +sodium_crypto_sign_keypair +sodium_crypto_sign_keypair_from_secretkey_and_publickey +sodium_crypto_sign_open +sodium_crypto_sign_publickey +sodium_crypto_sign_publickey_from_secretkey +sodium_crypto_sign_secretkey +sodium_crypto_sign_seed_keypair +sodium_crypto_sign_verify_detached +sodium_crypto_stream +sodium_crypto_stream_keygen +sodium_crypto_stream_xchacha20 +sodium_crypto_stream_xchacha20_keygen +sodium_crypto_stream_xchacha20_xor +sodium_crypto_stream_xchacha20_xor_ic +sodium_crypto_stream_xor +sodium_hex2bin +sodium_increment +sodium_memcmp +sodium_memzero +sodium_pad +sodium_unpad +sort +soundex +spl_autoload +spl_autoload_call +spl_autoload_extensions +spl_autoload_functions +spl_autoload_register +spl_autoload_unregister +spl_classes +spl_object_hash +spl_object_id +sprintf +sqrt +srand +sscanf +stat +str_contains +str_decrement +str_ends_with +str_getcsv +str_increment +str_ireplace +str_pad +str_repeat +str_replace +str_rot13 +str_shuffle +str_split +str_starts_with +str_word_count +strcasecmp +strchr +strcmp +strcoll +strcspn +stream_bucket_append +stream_bucket_make_writeable +stream_bucket_new +stream_bucket_prepend +stream_context_create +stream_context_get_default +stream_context_get_options +stream_context_get_params +stream_context_set_default +stream_context_set_option +stream_context_set_options +stream_context_set_params +stream_copy_to_stream +stream_filter_append +stream_filter_prepend +stream_filter_register +stream_filter_remove +stream_get_contents +stream_get_filters +stream_get_line +stream_get_meta_data +stream_get_transports +stream_get_wrappers +stream_is_local +stream_isatty +stream_register_wrapper +stream_resolve_include_path +stream_select +stream_set_blocking +stream_set_chunk_size +stream_set_read_buffer +stream_set_timeout +stream_set_write_buffer +stream_socket_accept +stream_socket_client +stream_socket_enable_crypto +stream_socket_get_name +stream_socket_pair +stream_socket_recvfrom +stream_socket_sendto +stream_socket_server +stream_socket_shutdown +stream_supports_lock +stream_wrapper_register +stream_wrapper_restore +stream_wrapper_unregister +strftime +strip_tags +stripcslashes +stripos +stripslashes +stristr +strlen +strnatcasecmp +strnatcmp +strncasecmp +strncmp +strpbrk +strpos +strptime +strrchr +strrev +strripos +strrpos +strspn +strstr +strtok +strtolower +strtotime +strtoupper +strtr +strval +substr +substr_compare +substr_count +substr_replace +symlink +sys_get_temp_dir +sys_getloadavg +syslog +system +tan +tanh +tempnam +textdomain +time +time_nanosleep +time_sleep_until +timezone_abbreviations_list +timezone_identifiers_list +timezone_location_get +timezone_name_from_abbr +timezone_name_get +timezone_offset_get +timezone_open +timezone_transitions_get +timezone_version_get +tmpfile +token_get_all +token_name +touch +trait_exists +transliterator_create +transliterator_create_from_rules +transliterator_create_inverse +transliterator_get_error_code +transliterator_get_error_message +transliterator_list_ids +transliterator_transliterate +trigger_error +trim +uasort +ucfirst +ucwords +uksort +umask +uniqid +unixtojd +unlink +unpack +unregister_tick_function +unserialize +urldecode +urlencode +use_soap_error_handler +user_error +usleep +usort +utf8_decode +utf8_encode +var_dump +var_export +version_compare +vfprintf +vprintf +vsprintf +wordwrap +xml_error_string +xml_get_current_byte_index +xml_get_current_column_number +xml_get_current_line_number +xml_get_error_code +xml_parse +xml_parse_into_struct +xml_parser_create +xml_parser_create_ns +xml_parser_free +xml_parser_get_option +xml_parser_set_option +xml_set_character_data_handler +xml_set_default_handler +xml_set_element_handler +xml_set_end_namespace_decl_handler +xml_set_external_entity_ref_handler +xml_set_notation_decl_handler +xml_set_object +xml_set_processing_instruction_handler +xml_set_start_namespace_decl_handler +xml_set_unparsed_entity_decl_handler +xmlwriter_end_attribute +xmlwriter_end_cdata +xmlwriter_end_comment +xmlwriter_end_document +xmlwriter_end_dtd +xmlwriter_end_dtd_attlist +xmlwriter_end_dtd_element +xmlwriter_end_dtd_entity +xmlwriter_end_element +xmlwriter_end_pi +xmlwriter_flush +xmlwriter_full_end_element +xmlwriter_open_memory +xmlwriter_open_uri +xmlwriter_output_memory +xmlwriter_set_indent +xmlwriter_set_indent_string +xmlwriter_start_attribute +xmlwriter_start_attribute_ns +xmlwriter_start_cdata +xmlwriter_start_comment +xmlwriter_start_document +xmlwriter_start_dtd +xmlwriter_start_dtd_attlist +xmlwriter_start_dtd_element +xmlwriter_start_dtd_entity +xmlwriter_start_element +xmlwriter_start_element_ns +xmlwriter_start_pi +xmlwriter_text +xmlwriter_write_attribute +xmlwriter_write_attribute_ns +xmlwriter_write_cdata +xmlwriter_write_comment +xmlwriter_write_dtd +xmlwriter_write_dtd_attlist +xmlwriter_write_dtd_element +xmlwriter_write_dtd_entity +xmlwriter_write_element +xmlwriter_write_element_ns +xmlwriter_write_pi +xmlwriter_write_raw +zend_version +zip_close +zip_entry_close +zip_entry_compressedsize +zip_entry_compressionmethod +zip_entry_filesize +zip_entry_name +zip_entry_open +zip_entry_read +zip_open +zip_read +zlib_decode +zlib_encode +zlib_get_coding_type diff --git a/blink/internal/fixer/rules/phpcs_doc.go b/blink/internal/fixer/rules/phpcs_doc.go new file mode 100644 index 0000000000..c2280591b6 --- /dev/null +++ b/blink/internal/fixer/rules/phpcs_doc.go @@ -0,0 +1,158 @@ +package rules + +import ( + "sort" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// phpcsDocTag is a docblock tag as PHP_CodeSniffer's comment tokenizer splits +// it, with the T_DOC_COMMENT_STRING that follows it on the same line. +type phpcsDocTag struct { + Name string + Str string + StrPos int // byte offset of Str in the docblock, -1 when the line has none +} + +// phpcsDocTags tokenizes doc like PHP_CodeSniffer's Comment tokenizer: the open +// tag is the leading "/*" run, the close tag the trailing one, and each line is +// padding, an optional "*" (not on the first line), padding, an optional tag +// with its padding, then the rest of the line as the string. +func phpcsDocTags(doc, eol string) []phpcsDocTag { + open := len(doc) - len(strings.TrimLeft(doc, "/*")) + if open == len(doc) { + return nil + } + body := strings.TrimRight(doc[open:], "/*") + lines := strings.Split(body, eol) + var tags []phpcsDocTag + pos := open + for n, line := range lines { + str := line + if n < len(lines)-1 { + str += eol + } + base := pos + pos += len(str) + c := skipDocPadding(str, 0) + if c > 0 && c == len(str) { + break + } + if str == "" { + continue + } + if n > 0 && str[c] == '*' { + c++ + } + c = skipDocPadding(str, c) + if c >= len(str) { + continue + } + tag := phpcsDocTag{StrPos: -1} + if str[c] == '@' { + if name := phpcsDocTagName(str[c:]); name != "" && !strings.HasPrefix(strings.ToLower(name), "@phpcs:") { + tag.Name = name + c = skipDocPadding(str, c+len(name)) + } + } + end := len(str) + if k := strings.Index(str[c:], eol); k >= 0 { + end = c + k + } + if end > c { + tag.Str = str[c:end] + tag.StrPos = base + c + } + if tag.Name != "" { + tags = append(tags, tag) + } + } + return tags +} + +func skipDocPadding(str string, c int) int { + for c < len(str) && (str[c] == ' ' || str[c] == '\t') { + c++ + } + return c +} + +// phpcsDocTagName is the first "@" plus non-space run in v, as PHP_CodeSniffer's +// unanchored "/@[^\s]+/" finds it. +func phpcsDocTagName(v string) string { + for k := 0; k < len(v); k++ { + if v[k] != '@' { + continue + } + end := k + 1 + for end < len(v) && !strings.ContainsRune(" \t\n\r\v\f", rune(v[end])) { + end++ + } + if end > k+1 { + return v[k:end] + } + } + return "" +} + +// replaceDocStrings swaps the strings of tags for their replacements (keyed by +// StrPos) and returns the new docblock. +func replaceDocStrings(doc string, repl map[int][2]string) string { + positions := make([]int, 0, len(repl)) + for p := range repl { + positions = append(positions, p) + } + sort.Sort(sort.Reverse(sort.IntSlice(positions))) + for _, p := range positions { + r := repl[p] + doc = doc[:p] + r[1] + doc[p+len(r[0]):] + } + return doc +} + +// phpcsLines is the 1-based line PHP_CodeSniffer gives each token: the count +// of eol in everything before it. +func phpcsLines(s *tokens.Stream, eol string) []int { + lines := make([]int, s.Len()) + line := 1 + for i := range s.Len() { + lines[i] = line + line += strings.Count(s.At(i).Value, eol) + } + return lines +} + +// phpcsDocEdit is one fix decided on an unchanged stream; edits run from the +// highest index down so earlier indices stay valid, as PHP_CodeSniffer applies +// every fix of a pass against the tokens it was decided on. +type phpcsDocEdit struct { + at int + apply func(s *tokens.Stream) +} + +func applyPhpcsEdits(s *tokens.Stream, edits []phpcsDocEdit) bool { + sort.SliceStable(edits, func(a, b int) bool { return edits[a].at > edits[b].at }) + for _, e := range edits { + e.apply(s) + } + return len(edits) > 0 +} + +// phpcsFixLoop re-runs pass until it changes nothing, at most 50 times like +// PHP_CodeSniffer's fixer. +func phpcsFixLoop(s *tokens.Stream, pass func(s *tokens.Stream) bool) bool { + changed := false + for range 50 { + if !pass(s) { + break + } + changed = true + } + return changed +} + +// phpTrim is PHP's trim() with its default character list. +func phpTrim(v string) string { + return strings.Trim(v, " \t\n\r\x00\x0B") +} diff --git a/blink/internal/fixer/rules/phpcs_operator.go b/blink/internal/fixer/rules/phpcs_operator.go index 874f3c188b..12a487bf82 100644 --- a/blink/internal/fixer/rules/phpcs_operator.go +++ b/blink/internal/fixer/rules/phpcs_operator.go @@ -70,6 +70,9 @@ func newPhpcsOperatorContext(s *tokens.Stream) phpcsOperatorContext { ternaries = append(ternaries, pending{depth}) } case ":": + if o.returnTypeColon(s, i) { + continue + } if n := len(ternaries); n > 0 && ternaries[n-1].depth == depth { o.inlineElse[i] = true ternaries = ternaries[:n-1] @@ -132,6 +135,17 @@ func (o phpcsOperatorContext) markFunction(s *tokens.Stream, i int) { } } +// returnTypeColon reports whether the ":" at i starts the return type of a +// function, closure or arrow function (after its parameters or use list). +func (o phpcsOperatorContext) returnTypeColon(s *tokens.Stream, i int) bool { + p := phpcsPrevNonEmpty(s, i-1) + if p < 0 || s.At(p).Value != ")" { + return false + } + open := s.MatchBackward(p) + return open >= 0 && (o.paramParens[open] || o.useParens[open]) +} + // markMatch records the arm arrows of the match expression at i. func (o phpcsOperatorContext) markMatch(s *tokens.Stream, i int) { open := phpcsNextNonEmpty(s, i+1) diff --git a/blink/internal/fixer/rules/priorities.go b/blink/internal/fixer/rules/priorities.go index 5636ccacf5..3c3eb2776a 100644 --- a/blink/internal/fixer/rules/priorities.go +++ b/blink/internal/fixer/rules/priorities.go @@ -71,6 +71,10 @@ var fixerPriority = map[string]int{ "FunctionOpeningBraceSpaceSniff": 0, "FunctionClosingBraceSniff": 0, "ElseIfDeclarationSniff": 0, + "ScopeKeywordSpacingSniff": 0, + "FunctionSpacingSniff": 0, + "MemberVarSpacingSniff": 0, + "SelfMemberReferenceSniff": 0, "EmptyPHPStatementSniff": 0, "DisallowMultipleStatementsSniff": 0, "InlineControlStructureSniff": 0, @@ -127,6 +131,12 @@ var fixerPriority = map[string]int{ "SingleLineArrayWhitespaceSniff": 0, "SpaceAfterNotSniff": 0, "ClassInstantiationSniff": 0, + "ForEachLoopDeclarationSniff": 0, + "ForLoopDeclarationSniff": 0, + "FunctionClosingBraceSpaceSniff": 0, + "LowercasePHPFunctionsSniff": 0, + "ConcatenationSpacingSniff": 0, + "InlineIfDeclarationSniff": 0, "IncrementDecrementSpacingSniff": 0, "MethodDeclarationSniff": 0, "UseDeclarationSniff": 0, @@ -173,6 +183,9 @@ var fixerPriority = map[string]int{ "OperatorSpacingSniff": 0, "PostStatementCommentSniff": 0, "ClosingDeclarationCommentSniff": 0, + "FileCommentSniff": 0, + "LongConditionClosingCommentSniff": 0, + "VariableCommentSniff": 0, "DocCommentAlignmentSniff": 0, "UselessParenthesesSniff": 0, "UselessSemicolonSniff": 0, diff --git a/blink/internal/fixer/rules/registry.go b/blink/internal/fixer/rules/registry.go index 614da1498a..4c67ccbb74 100644 --- a/blink/internal/fixer/rules/registry.go +++ b/blink/internal/fixer/rules/registry.go @@ -298,6 +298,10 @@ func ConstructFixers() []fixer.Fixer { SlevomatSingleLineArrayWhitespace{}, SlevomatTrailingArrayComma{}, SquizElseIfDeclaration{}, + ScopeKeywordSpacing{}, + SelfMemberReference{}, + FunctionSpacing{Spacing: 2, SpacingBeforeFirst: 2, SpacingAfterLast: 2}, + MemberVarSpacing{Spacing: 1, SpacingBeforeFirst: 1}, PSR2ElseIfDeclaration{}, EmptyPHPStatement{}, DisallowMultipleStatements{}, @@ -329,6 +333,13 @@ func ConstructFixers() []fixer.Fixer { SemicolonSpacing{}, SpaceAfterNot{Spacing: 1}, ClassInstantiation{}, + SquizOperatorSpacing{IgnoreSpacingBeforeAssignments: true}, + ForEachLoopDeclaration{}, + ForLoopDeclaration{}, + FunctionClosingBraceSpace{}, + LowercasePHPFunctions{}, + ConcatenationSpacing{}, + InlineIfDeclaration{}, IncrementDecrementSpacing{}, MethodDeclaration{}, TraitUseDeclaration{}, @@ -359,6 +370,10 @@ func ConstructFixers() []fixer.Fixer { PSR12OperatorSpacing{}, PostStatementComment{}, ClosingDeclarationComment{}, + SquizFileComment{}, + SquizInlineComment{}, + LongConditionClosingComment{LineLimit: 20, CommentFormat: "//end %s"}, + VariableComment{}, DocCommentAlignment{}, PEARClassDeclaration{}, PSR2ClassDeclaration{Indent: 4}, diff --git a/blink/internal/fixer/rules/regression_test.go b/blink/internal/fixer/rules/regression_test.go index 3a60806bd7..6c0967bdc4 100644 --- a/blink/internal/fixer/rules/regression_test.go +++ b/blink/internal/fixer/rules/regression_test.go @@ -57,7 +57,7 @@ func TestTernaryLeavesNullableTypes(t *testing.T) { func TestOperatorLinebreakKeepsNullFirstParenAssignment(t *testing.T) { t.Parallel() src := "getPolicyFor($arguments[0])) &&\n $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)) {\n return $callback;\n }\n }\n}\n" - want := "getPolicyFor($arguments[0]))\n && $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)\n ) {\n return $callback;\n }\n }//end resolve()\n}\n" + want := "getPolicyFor($arguments[0]))\n && $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)\n ) {\n return $callback;\n }\n\n }//end resolve()\n\n}\n" if got := runAll(src); got != want { t.Fatalf("parenthesized assignment must stay null-first\n got: %q\nwant: %q", got, want) } diff --git a/blink/internal/fixer/rules/scope_keyword_spacing.go b/blink/internal/fixer/rules/scope_keyword_spacing.go new file mode 100644 index 0000000000..535b09a1e0 --- /dev/null +++ b/blink/internal/fixer/rules/scope_keyword_spacing.go @@ -0,0 +1,153 @@ +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/ScopeKeywordSpacingSniff.php +// +// ScopeKeywordSpacing puts exactly one space after a scope or method modifier: +// "public static\nfunction" -> "public static function". +type ScopeKeywordSpacing struct{} + +func (ScopeKeywordSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeKeywordSpacingSniff` +} + +func (ScopeKeywordSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeKeywordSpacingSniff.php" +} + +func (ScopeKeywordSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(f.isScopeOrMethodModifier, func(i int) int { + f.scopeKeywordSpacing(i) + return 0 + }) + }) +} + +// isScopeOrMethodModifier matches Tokens::METHOD_MODIFIERS + SCOPE_MODIFIERS + T_READONLY. +func (f *slvFile) isScopeOrMethodModifier(i int) bool { + t := f.toks[i] + if t.kind != token.Keyword { + return false + } + switch v := strings.ToLower(t.orig); v { + case "public", "protected", "private", "static", "abstract", "final", "readonly": + return true + default: + return strings.HasSuffix(v, "(set)") + } +} + +func (f *slvFile) scopeKeywordSpacing(i int) { + n := len(f.toks) + if f.nextNonWhitespace(i+1, n) < 0 { + return + } + prev := f.prevEffective(i - 1) + next := f.nextEffective(i+1, n) + if f.isKeyword(i, "static") { + if next < 0 || f.is(next, "::") || f.isKeyword(prev, "new") || f.isKeyword(prev, "instanceof") { + return + } + if f.is(prev, "|") || f.is(prev, "?") { + return + } + if f.is(prev, ":") && f.isReturnColon(prev) { + return + } + } + if f.isKeyword(prev, "as") { + return + } + if next >= 0 && f.toks[next].kind == token.Variable && !f.inFunctionDeclarationParens(i) { + end := -1 + for j := next + 1; j < n; j++ { + if f.is(j, ";") { + end = j + break + } + } + if end < 0 { + return + } + multi := false + for j := next + 1; j < end; j++ { + if f.toks[j].kind == token.Variable { + multi = true + break + } + } + if multi && f.toks[i].line != f.toks[next].line && f.toks[next].line != f.toks[end].line { + return + } + } + spacing := 0 + newline := false + if i+1 < n && f.toks[i+1].kind == token.Whitespace { + if i+2 < n && f.toks[i+2].line != f.toks[i].line { + newline = true + } else { + spacing = f.toks[i+1].length + } + } + if !newline && spacing == 1 { + return + } + if !newline && spacing == 0 { + f.replaceToken(i, f.tokenContent(i)+" ") + return + } + f.beginChangeset() + for j := i + 2; j < n && f.toks[j].kind == token.Whitespace; j++ { + f.replaceToken(j, "") + } + f.replaceToken(i+1, " ") + f.endChangeset() +} + +// inFunctionDeclarationParens reports whether the innermost parentheses holding +// i are a named function's parameter list (constructor property promotion). +func (f *slvFile) inFunctionDeclarationParens(i int) bool { + open := -1 + for j := i - 1; j >= 0; j-- { + if f.is(j, "(") && f.toks[j].closer > i { + open = j + break + } + } + if open < 0 { + return false + } + name := f.prevEffective(open - 1) + if name < 0 || f.toks[name].kind != token.Ident && f.toks[name].kind != token.Keyword { + return false + } + fn := f.prevEffective(name - 1) + if f.is(fn, "&") { + fn = f.prevEffective(fn - 1) + } + return f.isKeyword(fn, "function") +} + +// isReturnColon tells a return type's ":" (T_COLON after a function's, closure's +// or arrow function's parameters or closure use) from a ternary's. +func (f *slvFile) isReturnColon(colon int) bool { + closeIdx := f.prevEffective(colon - 1) + if !f.is(closeIdx, ")") || f.toks[closeIdx].closer < 0 { + return false + } + p := f.prevEffective(f.toks[closeIdx].closer - 1) + if p >= 0 && f.toks[p].kind == token.Ident { + p = f.prevEffective(p - 1) + } + if f.is(p, "&") { + p = f.prevEffective(p - 1) + } + return f.isKeyword(p, "function") || f.isKeyword(p, "fn") || f.isKeyword(p, "use") +} diff --git a/blink/internal/fixer/rules/self_member_reference.go b/blink/internal/fixer/rules/self_member_reference.go new file mode 100644 index 0000000000..103feb40a6 --- /dev/null +++ b/blink/internal/fixer/rules/self_member_reference.go @@ -0,0 +1,131 @@ +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/Classes/SelfMemberReferenceSniff.php +// +// SelfMemberReference rewrites a static reference to the enclosing class by name +// to "self::" ("Foo::bar()" in class Foo -> "self::bar()"), lowercases "Self::" +// and removes whitespace around "::" inside a class. +type SelfMemberReference struct{} + +func (SelfMemberReference) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\SelfMemberReferenceSniff` +} + +func (SelfMemberReference) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Classes/SelfMemberReferenceSniff.php" +} + +func (SelfMemberReference) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { return f.is(i, "::") }, func(i int) int { + if class := f.innermostClassScope(i); class >= 0 { + f.selfMemberReference(i, class) + } + return 0 + }) + }) +} + +// innermostClassScope returns the "class" keyword of the named class whose body +// is the innermost class, anonymous class or closure scope holding i, or -1. +func (f *slvFile) innermostClassScope(i int) int { + for open := f.enclosingScope(i); open >= 0; open = f.enclosingScope(open) { + owner := f.braceOwner(open) + if owner < 0 { + continue + } + switch { + case f.isKeyword(owner, "class"): + if f.isAnonClassKeyword(owner) { + return -1 + } + return owner + case f.isKeyword(owner, "function") && f.isClosure(owner): + return -1 + } + } + return -1 +} + +// isAnonClassKeyword tells "new class" from a class declaration. +func (f *slvFile) isAnonClassKeyword(class int) bool { + n := f.nextEffective(class+1, len(f.toks)) + return n < 0 || f.toks[n].kind != token.Ident +} + +func (f *slvFile) selfMemberReference(i, class int) { + called := f.prevEffective(i - 1) + if called < 0 { + return + } + t := f.toks[called] + lower := strings.ToLower(t.orig) + switch { + case t.kind == token.Ident && lower == "self": + if t.orig != "self" { + f.replaceToken(called, "self") + return + } + case t.kind == token.Ident && lower != "parent": + ns := f.namespaceBefore(class) + if ns == `\` { + ns = "" + } + name := "" + if n := f.nextEffective(class+1, len(f.toks)); n >= 0 { + name = f.toks[n].orig + } + var inline string + switch { + case strings.HasPrefix(t.orig, `\`): + inline = t.orig + case strings.HasPrefix(lower, `namespace\`): + inline = ns + t.orig[len("namespace"):] + default: + inline = ns + `\` + t.orig + } + if ns+`\`+name == inline { + f.beginChangeset() + f.replaceToken(called, "") + f.replaceToken(i, "self::") + f.endChangeset() + return + } + } + if i > 0 && f.toks[i-1].kind == token.Whitespace { + f.beginChangeset() + for j := i - 1; j >= 0 && f.toks[j].kind == token.Whitespace; j-- { + f.replaceToken(j, "") + } + f.endChangeset() + } + if i+1 < len(f.toks) && f.toks[i+1].kind == token.Whitespace { + f.beginChangeset() + for j := i + 1; j < len(f.toks) && f.toks[j].kind == token.Whitespace; j++ { + f.replaceToken(j, "") + } + f.endChangeset() + } +} + +// namespaceBefore is the sniff's getNamespaceName: "\" plus the name of the +// last namespace declaration before i, or "\" for none. +func (f *slvFile) namespaceBefore(i int) string { + for j := i - 1; j >= 0; j-- { + if !f.isKeyword(j, "namespace") { + continue + } + if n := f.nextEffective(j+1, len(f.toks)); n >= 0 && f.toks[n].kind == token.Ident && !strings.HasPrefix(f.toks[n].orig, `\`) { + return `\` + f.toks[n].orig + } + return `\` + } + return `\` +} diff --git a/blink/internal/fixer/rules/squiz_inline_comment.go b/blink/internal/fixer/rules/squiz_inline_comment.go new file mode 100644 index 0000000000..064ffdb748 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_inline_comment.go @@ -0,0 +1,117 @@ +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/Commenting/InlineCommentSniff.php +// +// SquizInlineComment rewrites "#" comments to "//", puts exactly one space +// after "//", drops a blank "//" comment and the blank lines after a comment +// on its own line. +type SquizInlineComment struct{} + +func (SquizInlineComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\InlineCommentSniff` +} + +func (SquizInlineComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/InlineCommentSniff.php" +} + +func (f SquizInlineComment) Fix(s *tokens.Stream) bool { + return phpcsFixLoop(s, squizInlineCommentPass) +} + +func squizInlineCommentPass(s *tokens.Stream) bool { + eol := phpcsEolChar(s) + lines := phpcsLines(s, eol) + endLine := func(i int) int { + return lines[i] + strings.Count(strings.TrimSuffix(s.At(i).Value, eol), eol) + } + var edits []phpcsDocEdit + for i := 0; i < s.Len(); i++ { + t := s.At(i) + if !isPhpcsComment(t) { + continue + } + if strings.HasPrefix(t.Value, "#") { + at, v := i, "// "+strings.TrimLeft(t.Value, "# \t") + edits = append(edits, phpcsDocEdit{at, func(s *tokens.Stream) { s.SetValue(at, v) }}) + } + prev := prevNonWhitespaceIdx(s, i) + if prev >= 0 && endLine(prev) == lines[i] && isPunctVal(s, prev, "}") { + continue + } + if !strings.HasPrefix(t.Value, "//") { + continue + } + block := []int{i} + for n := i + 1; n < s.Len(); n++ { + last := block[len(block)-1] + if lines[n] > lines[last]+1 { + break + } + if !isPhpcsComment(s.At(n)) { + continue + } + if lines[n] != lines[last]+1 || !strings.HasPrefix(s.At(n).Value, "//") || prevNonWhitespaceIdx(s, n) != last { + break + } + block = append(block, n) + } + last := block[len(block)-1] + blank := true + for _, c := range block { + v := phpRtrim(s.At(c).Value) + if phpTrim(v[2:]) == "" { + continue + } + if spacing := v[2:]; strings.HasPrefix(strings.TrimLeft(spacing, " "), "\t") || !strings.HasPrefix(spacing, " ") || strings.HasPrefix(spacing, " ") { + at, nv := c, "// "+strings.TrimLeft(s.At(c).Value, "/\t ") + edits = append(edits, phpcsDocEdit{at, func(s *tokens.Stream) { s.SetValue(at, nv) }}) + } + blank = false + } + i = last + if blank { + at := block[0] + edits = append(edits, phpcsDocEdit{at, func(s *tokens.Stream) { removeLineComment(s, at) }}) + continue + } + if prev >= 0 && endLine(prev) >= lines[block[0]] { + continue + } + next := nextNonWhitespaceIndex(s, last) + if next < 0 || s.At(next).Kind == token.DocComment || lines[next] <= lines[last]+1 { + continue + } + if w := last + 1; w < next { + edits = append(edits, phpcsDocEdit{w, func(s *tokens.Stream) { + v := s.At(w).Value + s.SetValue(w, v[:phpcsCommentNewline(s, w)]+phpcsAfterLastBreak(v)) + }}) + } + } + return applyPhpcsEdits(s, edits) +} + +// removeLineComment drops the comment at i with the line break PHP_CodeSniffer +// counts as part of it, merging the whitespace around it. +func removeLineComment(s *tokens.Stream, i int) { + if n := i + 1; n < s.Len() && s.At(n).Kind == token.Whitespace { + if k := phpcsCommentNewline(s, n); k > 0 { + s.SetValue(n, s.At(n).Value[k:]) + } + } + s.RemoveAt(i) + if i > 0 && i < s.Len() && s.At(i-1).Kind == token.Whitespace && s.At(i).Kind == token.Whitespace { + s.SetValue(i-1, s.At(i-1).Value+s.At(i).Value) + s.RemoveAt(i) + } else if i < s.Len() && s.At(i).Kind == token.Whitespace && s.At(i).Value == "" { + s.RemoveAt(i) + } +} diff --git a/blink/internal/fixer/rules/squiz_operator_spacing.go b/blink/internal/fixer/rules/squiz_operator_spacing.go new file mode 100644 index 0000000000..72ff5575a2 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_operator_spacing.go @@ -0,0 +1,240 @@ +package rules + +import ( + "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/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php +// +// SquizOperatorSpacing requires exactly one space around arithmetic, bitwise, +// comparison, assignment and ternary operators: "$a +$b" -> "$a + $b". The +// space before an assignment is left alone (IgnoreSpacingBeforeAssignments), +// and a comment on the neighbouring line keeps its operator where it is. +type SquizOperatorSpacing struct { + IgnoreNewlines bool + IgnoreSpacingBeforeAssignments bool +} + +func (SquizOperatorSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff` +} + +func (SquizOperatorSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php" +} + +func (f SquizOperatorSpacing) WithConfig(config map[string]any) fixer.Fixer { + if v, ok := config["ignoreNewlines"].(bool); ok { + f.IgnoreNewlines = v + } + if v, ok := config["ignoreSpacingBeforeAssignments"].(bool); ok { + f.IgnoreSpacingBeforeAssignments = v + } + return f +} + +func (f SquizOperatorSpacing) Fix(s *tokens.Stream) bool { + // a newline is fixed one PHP_CodeSniffer whitespace token per pass, so + // repeat like ECS does until a pass changes nothing + changed := false + history := map[int]*phpcsHistory{} + for loop := range phpcsFixerLoops { + if !f.pass(s, loop, history) { + break + } + changed = true + } + return changed +} + +func (f SquizOperatorSpacing) pass(s *tokens.Stream, loop int, history map[int]*phpcsHistory) bool { + ops := newPhpcsOperatorContext(s) + // edits are collected on the original indices ops was built on, then applied + var e phpcsEdits + for i := 0; i < s.Len(); i++ { + if end, ok := ops.declare[i]; ok { + if end < 0 { + break + } + i = end + continue + } + if !ops.isOperatorToken(s, i, false) || !ops.isOperator(s, i) { + continue + } + f.fixBefore(s, i, &e) + f.fixAfter(s, i, &e) + } + return e.apply(s, loop, history) +} + +// fixBefore fixes the whitespace before the operator at i. +func (f SquizOperatorSpacing) fixBefore(s *tokens.Stream, i int, e *phpcsEdits) { + if i == 0 { + return + } + v := s.At(i).Value + if s.At(i-1).Kind != token.Whitespace || !phpcsWhitespaceAt(s, i-1) { + if v != ":" || s.At(i-1).Value != "?" { + e.insert(i) + } + return + } + ws := i - 1 + commentNL := phpcsCommentNewline(s, ws) + own := s.At(ws).Value[commentNL:] + newline := commentNL > 0 || phpcsLineBreaks(own) > 0 + if v == "&" { + if !f.spacingOK(s, ws, newline) { + // only PHP_CodeSniffer's last whitespace token, the current line's, becomes " " + e.replace(ws, s.At(ws).Value[:commentNL]+phpcsBeforeLastPiece(own)+" ", phpcsAfterLastPieceOf(own)) + } + return + } + if (phpcsAssignment[v] || v == "=>") && f.IgnoreSpacingBeforeAssignments { + return + } + if f.spacingOK(s, ws, newline) { + return + } + if p := ws - 1; p >= 0 && isPhpcsCommentToken(s.At(p)) { + return + } + e.replace(ws, " ", phpcsAfterLastPieceOf(own)) +} + +func (f SquizOperatorSpacing) fixAfter(s *tokens.Stream, i int, e *phpcsEdits) { + next := i + 1 + if next >= s.Len() { + return + } + if s.At(next).Kind != token.Whitespace { + if s.At(i).Value != "?" || s.At(next).Value != ":" { + e.insert(next) + } + return + } + if next+1 >= s.Len() { + return + } + ws := s.At(next).Value + newline := phpcsLineBreaks(ws) > 0 + if f.spacingOK(s, next, newline) { + return + } + if newline && s.At(i).Value != "&" && isPhpcsCommentToken(s.At(next+1)) { + return + } + // only PHP_CodeSniffer's first whitespace token, through the first line break, becomes " " + e.replace(next, " "+ws[len(phpcsThroughFirstBreak(ws)):], phpcsThroughFirstBreak(ws)) +} + +// phpcsFixerLoops is PHP_CodeSniffer's cap on fixer passes per file. +const phpcsFixerLoops = 50 + +// phpcsEdits is one fixer pass's edits in the order the sniff made them, on +// the token indices it read, applied at once like PHP_CodeSniffer's fixer. +type phpcsEdits struct { + list []phpcsEdit +} + +type phpcsEdit struct { + i int + insert bool // a " " whitespace token goes in before i + value string // the new value of token i + piece string // the PHP_CodeSniffer whitespace token replaced, for conflicts +} + +// phpcsHistory is PHP_CodeSniffer Fixer::$oldTokenValues for one token. +type phpcsHistory struct { + curr, prev string + loop int +} + +func (e *phpcsEdits) insert(i int) { + e.list = append(e.list, phpcsEdit{i: i, insert: true}) +} + +func (e *phpcsEdits) replace(i int, value, piece string) { + e.list = append(e.list, phpcsEdit{i: i, value: value, piece: piece}) +} + +// apply makes the pass's edits: a token is changed once per pass, and an edit +// that turns a token back into what the previous pass changed it from is a +// conflict that drops it and every later edit of the pass. +func (e *phpcsEdits) apply(s *tokens.Stream, loop int, history map[int]*phpcsHistory) bool { + set := map[int]string{} + var inserts []int + for _, ed := range e.list { + if ed.insert { + inserts = append(inserts, ed.i) + continue + } + // a no-op replacement still counts for PHP_CodeSniffer's conflict check + if _, done := set[ed.i]; done { + continue + } + h := history[ed.i] + if h != nil && h.prev == " " && h.loop == loop-1 { + break + } + if h == nil { + history[ed.i] = &phpcsHistory{curr: " ", prev: ed.piece, loop: loop} + } else { + h.prev, h.curr, h.loop = h.curr, " ", loop + } + set[ed.i] = ed.value + } + changed := false + for i, v := range set { + if s.At(i).Value != v { + s.SetValue(i, v) + changed = true + } + } + slices.Sort(inserts) + for _, at := range slices.Backward(slices.Compact(inserts)) { + s.InsertAt(at, token.Token{Kind: token.Whitespace, Value: " "}) + changed = true + } + return changed +} + +// spacingOK reports whether the whitespace at ws is the single space the sniff +// wants, or a line break it is told to ignore. +func (f SquizOperatorSpacing) spacingOK(s *tokens.Stream, ws int, newline bool) bool { + if newline { + return f.IgnoreNewlines + } + return phpcsTabWidth(s, ws) == 1 +} + +// phpcsBeforeLastPiece is v without PHP_CodeSniffer's last whitespace token: +// the text after the last line break, or else the last line including its break. +func phpcsBeforeLastPiece(v string) string { + end := len(v) - len(phpcsAfterLastBreak(v)) + if end < len(v) { + return v[:end] + } + rest := strings.TrimSuffix(v, "\n") + if len(rest) == len(v) || strings.HasSuffix(rest, "\r") { + rest = strings.TrimSuffix(rest, "\r") + } + return rest[:len(rest)-len(phpcsAfterLastBreak(rest))] +} + +// isPhpcsCommentToken reports whether t is one of PHP_CodeSniffer's +// COMMENT_TOKENS: a comment, a docblock or a phpcs: annotation. +func isPhpcsCommentToken(t token.Token) bool { + return (t.Kind == token.Comment && !strings.HasPrefix(t.Value, "#[")) || t.Kind == token.DocComment +} + +// phpcsAfterLastPieceOf is PHP_CodeSniffer's last whitespace token of v. +func phpcsAfterLastPieceOf(v string) string { + return v[len(phpcsBeforeLastPiece(v)):] +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Classes/SelfMemberReferenceUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Classes/SelfMemberReferenceUnitTest.inc new file mode 100644 index 0000000000..00aa5922e0 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Classes/SelfMemberReferenceUnitTest.inc @@ -0,0 +1,199 @@ +testResults; + + + // Correct call to self. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = parent::selfMemberReferenceUnitTestFunction(); + + // Incorrect case. + $testResults[] = Self::selfMemberReferenceUnitTestFunction(); + $testResults[] = SELF::selfMemberReferenceUnitTestFunction(); + $testResults[] = SelfMemberReferenceUnitTestExample::selfMemberReferenceUnitTestFunction(); + + + // Incorrect spacing. + $testResults[] = self ::selfMemberReferenceUnitTestFunction(); + $testResults[] = self:: selfMemberReferenceUnitTestFunction(); + $testResults[] = self :: selfMemberReferenceUnitTestFunction(); + + // Remove ALL the newlines + $testResults[] = self + + + + + :: + + + + + selfMemberReferenceUnitTestFunction(); + + } + + + function selfMemberReferenceUnitTestFunction() + { + $this->testCount = $this->testCount + 1; + return $this->testCount; + + } + + +} + + +class MyClass { + + public static function test($value) { + echo "$value\n"; + } + + public static function walk() { + $callback = function($value, $key) { + // This is valid because you can't use self:: in a closure. + MyClass::test($value); + }; + + $array = array(1,2,3); + array_walk($array, $callback); + } +} + +MyClass::walk(); + +class Controller +{ + public function Action() + { + Doctrine\Common\Util\Debug::dump(); + } +} + +class Foo +{ + public static function bar() + { + \Foo::baz(); + } +} + +namespace TYPO3\CMS\Reports; + +class Status { + const NOTICE = -2; + const INFO = -1; + const OK = 0; + const WARNING = 1; + const ERROR = 2; +} + +namespace TYPO3\CMS\Reports\Report\Status; + +class Status implements \TYPO3\CMS\Reports\ReportInterface { + public function getHighestSeverity(array $statusCollection) { + $highestSeverity = \TYPO3\CMS\Reports\Status::NOTICE; + } +} + +namespace Foo; + +class Bar { + + function myFunction() + { + \Foo\Whatever::something(); + \Foo\Bar::something(); + } +} + +namespace Foo\Bar; + +class Baz { + + function myFunction() + { + \Foo\Bar\Whatever::something(); + \Foo\Bar\Baz::something(); + } +} + +class Nested_Anon_Class { + public function getAnonymousClass() { + // Spacing/comments should not cause false negatives for the NotUsed error. + Nested_Anon_Class :: $prop; + Nested_Anon_Class + /* some comment */ + + :: + + // phpcs:ignore Standard.Category.SniffName -- for reasons. + Bar(); + + // Anonymous class is a different scope. + return new class() { + public function nested_function() { + Nested_Anon_Class::$prop; + Nested_Anon_Class::BAR; + } + }; + } +} + +// Test dealing with scoped namespaces. +namespace Foo\Baz { + class BarFoo { + public function foo() { + echo \Foo\Baz\BarFoo::$prop; + } + } +} + +// Prevent false negative when namespace has whitespace/comments - no longer supported as of PHPCS 4.x. +namespace Foo /*comment*/ \ Bah { + class BarFoo { + public function foo() { + echo \Foo \ /*comment*/ Bah\BarFoo::$prop; + } + } +} + +namespace EndsIn\CloseTag ?> +testResults; + + + // Correct call to self. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = parent::selfMemberReferenceUnitTestFunction(); + + // Incorrect case. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + + + // Incorrect spacing. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + + // Remove ALL the newlines + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + + } + + + function selfMemberReferenceUnitTestFunction() + { + $this->testCount = $this->testCount + 1; + return $this->testCount; + + } + + +} + + +class MyClass { + + public static function test($value) { + echo "$value\n"; + } + + public static function walk() { + $callback = function($value, $key) { + // This is valid because you can't use self:: in a closure. + MyClass::test($value); + }; + + $array = array(1,2,3); + array_walk($array, $callback); + } +} + +MyClass::walk(); + +class Controller +{ + public function Action() + { + Doctrine\Common\Util\Debug::dump(); + } +} + +class Foo +{ + public static function bar() + { + self::baz(); + } +} + +namespace TYPO3\CMS\Reports; + +class Status { + const NOTICE = -2; + const INFO = -1; + const OK = 0; + const WARNING = 1; + const ERROR = 2; +} + +namespace TYPO3\CMS\Reports\Report\Status; + +class Status implements \TYPO3\CMS\Reports\ReportInterface { + public function getHighestSeverity(array $statusCollection) { + $highestSeverity = \TYPO3\CMS\Reports\Status::NOTICE; + } +} + +namespace Foo; + +class Bar { + + function myFunction() + { + \Foo\Whatever::something(); + self::something(); + } +} + +namespace Foo\Bar; + +class Baz { + + function myFunction() + { + \Foo\Bar\Whatever::something(); + self::something(); + } +} + +class Nested_Anon_Class { + public function getAnonymousClass() { + // Spacing/comments should not cause false negatives for the NotUsed error. + self::$prop; + + /* some comment */ + + self::// phpcs:ignore Standard.Category.SniffName -- for reasons. + Bar(); + + // Anonymous class is a different scope. + return new class() { + public function nested_function() { + Nested_Anon_Class::$prop; + Nested_Anon_Class::BAR; + } + }; + } +} + +// Test dealing with scoped namespaces. +namespace Foo\Baz { + class BarFoo { + public function foo() { + echo self::$prop; + } + } +} + +// Prevent false negative when namespace has whitespace/comments - no longer supported as of PHPCS 4.x. +namespace Foo /*comment*/ \ Bah { + class BarFoo { + public function foo() { + echo \Foo \ /*comment*/ Bah\BarFoo::$prop; + } + } +} + +namespace EndsIn\CloseTag ?> + +* @author +* @copyright 1997~1994 The PHP Group +* @copyright 1994-1997 The PHP Group +* @copyright The PHP Group +* @license http://www.php.net/license/3_0.txt +* @summary An unknown summary tag +* +*/ + + +?> + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.1.inc.fixed new file mode 100644 index 0000000000..435e11e9f3 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.1.inc.fixed @@ -0,0 +1,43 @@ + +* @author +* @copyright 1997 Squiz Pty Ltd (ABN 77 084 670 600) +* @copyright 1994-1997 Squiz Pty Ltd (ABN 77 084 670 600) +* @copyright 2026 Squiz Pty Ltd (ABN 77 084 670 600) +* @license http://www.php.net/license/3_0.txt +* @summary An unknown summary tag +* +*/ + + +?> + diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.10.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.10.inc new file mode 100644 index 0000000000..1f82abfeaf --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.10.inc @@ -0,0 +1,12 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +readonly class Foo { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.2.inc new file mode 100644 index 0000000000..520d349752 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.2.inc @@ -0,0 +1,11 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +echo 'hi'; \ No newline at end of file diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.3.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.3.inc new file mode 100644 index 0000000000..b47603f20c --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.3.inc @@ -0,0 +1,9 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.4.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.4.inc new file mode 100644 index 0000000000..2fdeeba1fe --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.4.inc @@ -0,0 +1,3 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +class Foo { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.7.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.7.inc new file mode 100644 index 0000000000..7074dac234 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.7.inc @@ -0,0 +1,12 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ +#[Attribute] +class Foo { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.8.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.8.inc new file mode 100644 index 0000000000..5ef90f2ad1 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.8.inc @@ -0,0 +1,9 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.9.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.9.inc new file mode 100644 index 0000000000..f6c9d99682 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/FileCommentUnitTest.9.inc @@ -0,0 +1,12 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +enum Foo { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/InlineCommentUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/InlineCommentUnitTest.inc new file mode 100644 index 0000000000..220b916e40 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/InlineCommentUnitTest.inc @@ -0,0 +1,199 @@ + One +// -> One.One +// -> Two + +/* + Here is some inline example code: + -> One + -> One.One + -> Two +*/ + +/** + * Comment should be ignored in PHP 5.4. + * + */ +trait MyTrait { + +} + +$foo = 'foo'; // Var set to foo. + +echo $foo; + +// Comment here. +echo $foo; + +/** + * Comments about the include + */ +include_once($blah); + +// some comment without capital or full stop +echo $foo; // An unrelated comment. + +// An unrelated comment. +echo $foo; // some comment without capital or full stop + +class Foo +{ + // This is fine. + + /** + * Spacing is ignored above. + */ + function bar(){} +} + +if ($foo) { +}//end if +// Another comment here. +$foo++; + +if ($foo) { +}//end if +// another comment here. +$foo++; + +/** + * Comment should be ignored, even though there is an attribute between the docblock and the class declaration. + */ + +#[AttributeA] + +final class MyClass +{ + /** + * Comment should be ignored, even though there is an attribute between the docblock and the function declaration + */ + #[AttributeA] + #[AttributeB] + final public function test() {} +} + +/** + * Comment should be ignored. + * + */ +enum MyEnum { + +} + +/** + * Comment should be ignored. + * + */ +readonly class MyClass +{ + /** + * Comment should be ignored. + * + */ + readonly $property = 10; +} + +#️⃣ Apparently the emoji keycap number sign (hash) also works and turns this into a comment. +echo 'hello!'; + +/* + * N.B.: The below test line must be the last test in the file. + * Testing that a new line after an inline comment when it's the last non-whitespace + * token in a file, does *not* throw an error as this would conflict with the common + * "new line required at end of file" rule. + */ + +// For this test line having an empty line below it, is fine. diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/InlineCommentUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/InlineCommentUnitTest.inc.fixed new file mode 100644 index 0000000000..2cc700c6bf --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/InlineCommentUnitTest.inc.fixed @@ -0,0 +1,192 @@ + One +// -> One.One +// -> Two +/* + Here is some inline example code: + -> One + -> One.One + -> Two +*/ + +/** + * Comment should be ignored in PHP 5.4. + * + */ +trait MyTrait { + +} + +$foo = 'foo'; // Var set to foo. + +echo $foo; + +// Comment here. +echo $foo; + +/** + * Comments about the include + */ +include_once($blah); + +// some comment without capital or full stop +echo $foo; // An unrelated comment. + +// An unrelated comment. +echo $foo; // some comment without capital or full stop + +class Foo +{ + // This is fine. + + /** + * Spacing is ignored above. + */ + function bar(){} +} + +if ($foo) { +}//end if +// Another comment here. +$foo++; + +if ($foo) { +}//end if +// another comment here. +$foo++; + +/** + * Comment should be ignored, even though there is an attribute between the docblock and the class declaration. + */ + +#[AttributeA] + +final class MyClass +{ + /** + * Comment should be ignored, even though there is an attribute between the docblock and the function declaration + */ + #[AttributeA] + #[AttributeB] + final public function test() {} +} + +/** + * Comment should be ignored. + * + */ +enum MyEnum { + +} + +/** + * Comment should be ignored. + * + */ +readonly class MyClass +{ + /** + * Comment should be ignored. + * + */ + readonly $property = 10; +} + +// ️⃣ Apparently the emoji keycap number sign (hash) also works and turns this into a comment. +echo 'hello!'; + +/* + * N.B.: The below test line must be the last test in the file. + * Testing that a new line after an inline comment when it's the last non-whitespace + * token in a file, does *not* throw an error as this would conflict with the common + * "new line required at end of file" rule. + */ + +// For this test line having an empty line below it, is fine. diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/LongConditionClosingCommentUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/LongConditionClosingCommentUnitTest.inc new file mode 100644 index 0000000000..9e84133dda --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/LongConditionClosingCommentUnitTest.inc @@ -0,0 +1,1033 @@ + + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + match ($foo) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 + }, +]; diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/LongConditionClosingCommentUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/LongConditionClosingCommentUnitTest.inc.fixed new file mode 100644 index 0000000000..be681cf4b9 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/LongConditionClosingCommentUnitTest.inc.fixed @@ -0,0 +1,1033 @@ + + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + // some code here. + match ($foo) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 + },//end match +]; diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/VariableCommentUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/VariableCommentUnitTest.inc new file mode 100644 index 0000000000..1a1b233d04 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/VariableCommentUnitTest.inc @@ -0,0 +1,543 @@ + $content) { + echo $content; + } + + return $var1; + + }//end checkVariable() + + + /** + * + * + */ + $emptyVarDoc = ''; + + /** + * Var type checking (int v.s. integer). + * + * @var int + */ + private $_varSimpleTypeCheck; + + + /** + * Var type checking (array(int => string) v.s. array(int => string)). + * + * @var array(int => string) + */ + private $_varArrayTypeCheck; + + + /** + * Boolean @var tag Capitalized + * + * @var Boolean + */ + public $CapBoolTag = true; + + + /** + * Boolean @var tag Capitalized + * + * @var BOOLEAN + */ + public $CapBoolTag2 = true; + + + /** + * Double @var tag Capitalized + * + * @var Double + */ + public $CapDoubleTag = 1; + + + /** + * Double @var tag Capitalized + * + * @var DOUBLE + */ + public $CapDoubleTag2 = 1; + + + /** + * Real @var tag Capitalized + * + * @var Real + */ + public $CapRealTag = 1; + + + /** + * Real @var tag Capitalized + * + * @var REAL + */ + public $CapRealTag2 = 1; + + + /** + * Float @var tag Capitalized + * + * @var Float + */ + public $CapFloatTag = 1; + + + /** + * Float @var tag Capitalized + * + * @var FLOAT + */ + public $CapFloatTag2 = 1; + + + /** + * Int @var tag Capitalized + * + * @var Int + */ + public $CapIntTag = 1; + + + /** + * Int @var tag Capitalized + * + * @var INT + */ + public $CapIntTag2 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var Integer + */ + public $CapIntTag3 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var INTEGER + */ + public $CapIntTag4 = 1; + + + /** + * Array @var tag Capitalized + * + * @var Array + */ + public $CapVarTag = []; + + + /** + * Array @var tag All Caps + * + * @var ARRAY + */ + public $CapVarTag2 = []; + + + /** + * Array @var tag Capitalized + * + * @var Array() + */ + public $CapVarTag3 = []; + + + /** + * Array @var tag All Caps + * + * @var ARRAY() + */ + public $CapVarTag4 = []; + + + /** + * Var type checking (STRING v.s. string). + * + * @var STRING + */ + private $_varCaseTypeCheck; + + + /** + * @var integer + */ + private $_varWithNoShortComment; + + protected $noComment2 = ''; + + + /** + * @var int Var type checking (int v.s. integer) with single-line comment. + */ + private $_varSimpleTypeCheckSingleLine; + + +}//end class + + +/** + * VariableCommentUnitTest2. + * + * Long description goes here. + * + */ +class VariableCommentUnitTest2 +{ + + public $hello; + + /** Comment starts here. + * + * @var string + * + */ + private $_varCaseTypeCheck; + + /** + * 这是一条测试评论. + * + * @var string + */ + public $foo; + +}//end class + + +/* + * Class comment + */ +class Foo +{ + + protected $bar; + + /** + * Short description of the member variable. + * + * @var array + */ + public static array $variableName = array(); + +} + +class Foo +{ + + /** + * Short description of the member variable. + * + * @var array + */ + public array $variableName = array(); + + + // Not "/**" style comment. + // + // @var string + private ?Folder\ClassName $_incorrectCommentStyle = null; + + + var int $noComment = 1; + } + +class HasAttributes +{ + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\Id]#[ORM\Column("integer")] + private $id; + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; +} + +class ReadOnlyProps +{ + /** + * Short description of the member variable. + * + * @var array + */ + public readonly array $variableName = array(); + + /** + * Short description of the member variable. + * + * @var + */ + readonly protected ?int $variableName = 10; + + private readonly string $variable; +} + +class UnionTypes +{ + /** + * @var array|boolean + */ + private array|bool $variableName = array(); +} + +class IntersectionTypes +{ + /** + * @var \Iterator|\Countable + */ + private \Iterator&\Countable $variableName; +} + +class StandaloneNullTrueFalseTypes +{ + /** + * @var null + */ + public null $variableName = null; + + /** + * @var true + */ + protected true $variableName = true; + + /** + * @var false + */ + private false $variableName = false; +} + +class MoreMissingButSupportedTypes +{ + /** + * @var parent + */ + public parent $variableName; + + /** + * @var self + */ + protected self $variableName; + + /** + * @var SomeClass + */ + private namespace\SomeClass $variableName; + + public static ?\Folder\ClassName $FQNTypeDecl_noComment = null; + + /** + * @var \Folder\ClassName|null + */ + public ?\Folder\ClassName $FQNTypeDecl_withComment = null; +} + +class DNFTypes +{ + /** + * @var mixed + */ + private (\Iterator&namespace\Countable)|false|null $variableName; +} + +class PHP84FinalProperties { + /** + * @var integer + */ + final int $hasDocblock; +} + +// phpcs:disable Squiz.Commenting.VariableComment.SinceTagNotAllowed +// phpcs:disable Squiz.Commenting.VariableComment.DeprecatedTagNotAllowed +class AllowMoreForSelectivelyIgnoringDisallowedTags { + /** + * @var string + * + * @since 3.1 + * @deprecated 10.5 + */ + public string $propertyWithExtraTags; + + /** + * @var string + * + * @link https://example.org/some-link + * @api + * @param string This tag is not allowed. + */ + public $theAboveExtraTagsAreStillNotAllowed; +} + +// phpcs:enable Squiz.Commenting.VariableComment + +class StandaloneFQNNullTrueFalseTypes +{ + /** + * @var null + */ + public \Null $variableName = null; + + /** + * @var true + */ + protected \true $variableName = true; + + /** + * @var false + */ + private \FALSE $variableName = false; +} + +class AsymVisibility { + /** + * @var integer + */ + public(set) int $hasDocblockA; + + /** + * @var integer + */ + public protected(set) int $hasDocblockB; + + /** + * @var integer + */ + private(set) protected int $hasDocblockC; +} + +abstract class PHP84AbstractProperties { + /** + * @var Type + */ + abstract Type $hasDocblock {get;} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/VariableCommentUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/VariableCommentUnitTest.inc.fixed new file mode 100644 index 0000000000..ceece0f223 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/VariableCommentUnitTest.inc.fixed @@ -0,0 +1,543 @@ + $content) { + echo $content; + } + + return $var1; + + }//end checkVariable() + + + /** + * + * + */ + $emptyVarDoc = ''; + + /** + * Var type checking (int v.s. integer). + * + * @var integer + */ + private $_varSimpleTypeCheck; + + + /** + * Var type checking (array(int => string) v.s. array(int => string)). + * + * @var array(integer => string) + */ + private $_varArrayTypeCheck; + + + /** + * Boolean @var tag Capitalized + * + * @var boolean + */ + public $CapBoolTag = true; + + + /** + * Boolean @var tag Capitalized + * + * @var boolean + */ + public $CapBoolTag2 = true; + + + /** + * Double @var tag Capitalized + * + * @var float + */ + public $CapDoubleTag = 1; + + + /** + * Double @var tag Capitalized + * + * @var float + */ + public $CapDoubleTag2 = 1; + + + /** + * Real @var tag Capitalized + * + * @var float + */ + public $CapRealTag = 1; + + + /** + * Real @var tag Capitalized + * + * @var float + */ + public $CapRealTag2 = 1; + + + /** + * Float @var tag Capitalized + * + * @var float + */ + public $CapFloatTag = 1; + + + /** + * Float @var tag Capitalized + * + * @var float + */ + public $CapFloatTag2 = 1; + + + /** + * Int @var tag Capitalized + * + * @var integer + */ + public $CapIntTag = 1; + + + /** + * Int @var tag Capitalized + * + * @var integer + */ + public $CapIntTag2 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var integer + */ + public $CapIntTag3 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var integer + */ + public $CapIntTag4 = 1; + + + /** + * Array @var tag Capitalized + * + * @var array + */ + public $CapVarTag = []; + + + /** + * Array @var tag All Caps + * + * @var array + */ + public $CapVarTag2 = []; + + + /** + * Array @var tag Capitalized + * + * @var array + */ + public $CapVarTag3 = []; + + + /** + * Array @var tag All Caps + * + * @var array + */ + public $CapVarTag4 = []; + + + /** + * Var type checking (STRING v.s. string). + * + * @var string + */ + private $_varCaseTypeCheck; + + + /** + * @var integer + */ + private $_varWithNoShortComment; + + protected $noComment2 = ''; + + + /** + * @var integer Var type checking (int v.s. integer) with single-line comment. + */ + private $_varSimpleTypeCheckSingleLine; + + +}//end class + + +/** + * VariableCommentUnitTest2. + * + * Long description goes here. + * + */ +class VariableCommentUnitTest2 +{ + + public $hello; + + /** Comment starts here. + * + * @var string + * + */ + private $_varCaseTypeCheck; + + /** + * 这是一条测试评论. + * + * @var string + */ + public $foo; + +}//end class + + +/* + * Class comment + */ +class Foo +{ + + protected $bar; + + /** + * Short description of the member variable. + * + * @var array + */ + public static array $variableName = array(); + +} + +class Foo +{ + + /** + * Short description of the member variable. + * + * @var array + */ + public array $variableName = array(); + + + // Not "/**" style comment. + // + // @var string + private ?Folder\ClassName $_incorrectCommentStyle = null; + + + var int $noComment = 1; + } + +class HasAttributes +{ + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\Id]#[ORM\Column("integer")] + private $id; + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; +} + +class ReadOnlyProps +{ + /** + * Short description of the member variable. + * + * @var array + */ + public readonly array $variableName = array(); + + /** + * Short description of the member variable. + * + * @var + */ + readonly protected ?int $variableName = 10; + + private readonly string $variable; +} + +class UnionTypes +{ + /** + * @var array|boolean + */ + private array|bool $variableName = array(); +} + +class IntersectionTypes +{ + /** + * @var \Iterator|\Countable + */ + private \Iterator&\Countable $variableName; +} + +class StandaloneNullTrueFalseTypes +{ + /** + * @var null + */ + public null $variableName = null; + + /** + * @var true + */ + protected true $variableName = true; + + /** + * @var false + */ + private false $variableName = false; +} + +class MoreMissingButSupportedTypes +{ + /** + * @var parent + */ + public parent $variableName; + + /** + * @var self + */ + protected self $variableName; + + /** + * @var SomeClass + */ + private namespace\SomeClass $variableName; + + public static ?\Folder\ClassName $FQNTypeDecl_noComment = null; + + /** + * @var \Folder\ClassName|null + */ + public ?\Folder\ClassName $FQNTypeDecl_withComment = null; +} + +class DNFTypes +{ + /** + * @var mixed + */ + private (\Iterator&namespace\Countable)|false|null $variableName; +} + +class PHP84FinalProperties { + /** + * @var integer + */ + final int $hasDocblock; +} + +// phpcs:disable Squiz.Commenting.VariableComment.SinceTagNotAllowed +// phpcs:disable Squiz.Commenting.VariableComment.DeprecatedTagNotAllowed +class AllowMoreForSelectivelyIgnoringDisallowedTags { + /** + * @var string + * + * @since 3.1 + * @deprecated 10.5 + */ + public string $propertyWithExtraTags; + + /** + * @var string + * + * @link https://example.org/some-link + * @api + * @param string This tag is not allowed. + */ + public $theAboveExtraTagsAreStillNotAllowed; +} + +// phpcs:enable Squiz.Commenting.VariableComment + +class StandaloneFQNNullTrueFalseTypes +{ + /** + * @var null + */ + public \Null $variableName = null; + + /** + * @var true + */ + protected \true $variableName = true; + + /** + * @var false + */ + private \FALSE $variableName = false; +} + +class AsymVisibility { + /** + * @var integer + */ + public(set) int $hasDocblockA; + + /** + * @var integer + */ + public protected(set) int $hasDocblockB; + + /** + * @var integer + */ + private(set) protected int $hasDocblockC; +} + +abstract class PHP84AbstractProperties { + /** + * @var Type + */ + abstract Type $hasDocblock {get;} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForEachLoopDeclarationUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForEachLoopDeclarationUnitTest.inc new file mode 100644 index 0000000000..4709923ee9 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForEachLoopDeclarationUnitTest.inc @@ -0,0 +1,36 @@ + $that) { +} + +// Invalid. +foreach ( $something as $blah => $that ) { +} + +foreach ($something as $blah => $that) { +} + +foreach ($something as $blah => $that) { +} + +foreach (${something}AS$blah=>$that) { +} + +// The works. +foreach ( $something aS $blah => $that ) { +} + +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 1 +foreach ($something as $blah => $that) {} +foreach ( $something as $blah => $that ) {} +foreach ( $something as $blah => $that ) {} +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 0 + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForEachLoopDeclarationUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForEachLoopDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000000..c07d06f31f --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForEachLoopDeclarationUnitTest.inc.fixed @@ -0,0 +1,36 @@ + $that) { +} + +// Invalid. +foreach ($something as $blah => $that) { +} + +foreach ($something as $blah => $that) { +} + +foreach ($something as $blah => $that) { +} + +foreach (${something} as $blah => $that) { +} + +// The works. +foreach ($something as $blah => $that) { +} + +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 1 +foreach ($something as $blah => $that) {} +foreach ($something as $blah => $that) {} +foreach ($something as $blah => $that) {} +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 0 + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.1.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.1.inc new file mode 100644 index 0000000000..d10bd98008 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.1.inc @@ -0,0 +1,126 @@ +i ; }; $i < function() { return $this->max; }; $i++) {} +for ($i = function() { return $this->i; }; $i < function() { return $this->max; } ; $i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines true +for ( + $i = 0; + $i < 5; + $i++ +) { + // body here +} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines false diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.1.inc.fixed new file mode 100644 index 0000000000..60f4d092bc --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.1.inc.fixed @@ -0,0 +1,88 @@ +i ; }; $i < function() { return $this->max; }; $i++) {} +for ($i = function() { return $this->i; }; $i < function() { return $this->max; }; $i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines true +for ($i = 0; $i < 5; $i++) { + // body here +} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines false diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.2.inc new file mode 100644 index 0000000000..d7a783853f --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ForLoopDeclarationUnitTest.2.inc @@ -0,0 +1,6 @@ +id.'"', + '"'.$this->stepInfo['title'].'"', + '"'.((isset($this->stepInfo['description']) === TRUE) ? $this->stepInfo['description'] : '').'"', + '"'.(isset($this->stepInfo['description']) === TRUE ? $this->stepInfo['description'] : '').'"', + '"'.$this->stepInfo['title'].'"', + ); + +echo (TRUE)?'Hello':'Bye'; + +$array = array( + 'one' => ($test == 1) ? true : false, + 'two' => (($test == 1) ? true : false), + 'three' => (($test == 1) ? true : false) +); +$var = ($test == 1) ? true : false; +$var = (myFunc(1,2,3) == 1) ? true : false; + +set('config', function() { + $foo = ($bar === "on") ? "1" : "2"; +}); + +$config = function() { + $foo = ($bar === "on") ? "1" : "2"; +}; + +rand(0, 1) ? 'ěščřžýáí' : NULL; + +$c = ($argv[1]) ? : ""; +$filepath = realpath($argv[1]) ?: $argv[1]; +$c = ($argv[1]) ? /* comment */ : ""; +$c = ($argv[1]) ? +: ""; diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/InlineIfDeclarationUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/InlineIfDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000000..f7aa1d67cc --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/InlineIfDeclarationUnitTest.inc.fixed @@ -0,0 +1,48 @@ +id.'"', + '"'.$this->stepInfo['title'].'"', + '"'.((isset($this->stepInfo['description']) === TRUE) ? $this->stepInfo['description'] : '').'"', + '"'.(isset($this->stepInfo['description']) === TRUE ? $this->stepInfo['description'] : '').'"', + '"'.$this->stepInfo['title'].'"', + ); + +echo (TRUE) ? 'Hello' : 'Bye'; + +$array = array( + 'one' => ($test == 1) ? true : false, + 'two' => (($test == 1) ? true : false), + 'three' => (($test == 1) ? true : false) +); +$var = ($test == 1) ? true : false; +$var = (myFunc(1,2,3) == 1) ? true : false; + +set('config', function() { + $foo = ($bar === "on") ? "1" : "2"; +}); + +$config = function() { + $foo = ($bar === "on") ? "1" : "2"; +}; + +rand(0, 1) ? 'ěščřžýáí' : NULL; + +$c = ($argv[1]) ?: ""; +$filepath = realpath($argv[1]) ?: $argv[1]; +$c = ($argv[1]) ? /* comment */ : ""; +$c = ($argv[1]) ? +: ""; diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/LowercasePHPFunctionsUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/LowercasePHPFunctionsUnitTest.inc new file mode 100644 index 0000000000..99b6246ba9 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/LowercasePHPFunctionsUnitTest.inc @@ -0,0 +1,50 @@ +Count(); +$count = $object::Count(); +$count = $object->count(); +$count = $object::count(); +class MyClass { + public function Count() {} +} + +function &Sort() { + +} + +$connection = new Db\Adapter\Pdo\Mysql($config); + +namespace Strtolower\Silly; + +use function strToUpper as somethingElse; +use function MyClass\WordsToUpper as UCWords; // Intentional redeclared function error. +use function strToUpper\NotTheFunction; + +class ArrayUnique {} + +$sillyComments = strToLower /*comment*/ ($string); + +$callToGlobalFunction = \STR_REPEAT($a, 2); +$callToGlobalFunction = \str_Repeat($a, 2); + +$callToNamespacedFunction = MyNamespace\STR_REPEAT($a, 2); +$callToNamespacedFunction = namespace\STR_REPEAT($a, 2); // Could potentially be false negative. + +$filePath = new \File($path); + +$count = $object?->Count(); + +class AttributesShouldBeIgnored +{ + #[Putenv('FOO', 'foo')] + public function foo(): void + {} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/LowercasePHPFunctionsUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/LowercasePHPFunctionsUnitTest.inc.fixed new file mode 100644 index 0000000000..67aa475930 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/PHP/LowercasePHPFunctionsUnitTest.inc.fixed @@ -0,0 +1,50 @@ +Count(); +$count = $object::Count(); +$count = $object->count(); +$count = $object::count(); +class MyClass { + public function Count() {} +} + +function &Sort() { + +} + +$connection = new Db\Adapter\Pdo\Mysql($config); + +namespace Strtolower\Silly; + +use function strtoupper as somethingElse; +use function MyClass\WordsToUpper as UCWords; // Intentional redeclared function error. +use function strToUpper\NotTheFunction; + +class ArrayUnique {} + +$sillyComments = strtolower /*comment*/ ($string); + +$callToGlobalFunction = \str_repeat($a, 2); +$callToGlobalFunction = \str_repeat($a, 2); + +$callToNamespacedFunction = MyNamespace\STR_REPEAT($a, 2); +$callToNamespacedFunction = namespace\STR_REPEAT($a, 2); // Could potentially be false negative. + +$filePath = new \File($path); + +$count = $object?->Count(); + +class AttributesShouldBeIgnored +{ + #[Putenv('FOO', 'foo')] + public function foo(): void + {} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/ConcatenationSpacingUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/ConcatenationSpacingUnitTest.inc new file mode 100644 index 0000000000..3bf4186e0a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/ConcatenationSpacingUnitTest.inc @@ -0,0 +1,49 @@ +add_help_tab( array( +'id' => <<', +) ); + +// phpcs:set Squiz.Strings.ConcatenationSpacing spacing 1 + +$string = 'Hello'.$there.'. How are'.$you.$going. "today $okay"; +$string = 'Hello' . $there . '. How are' . $you . $going . "today $okay"; +$string = 'Hello'.$there; +$string = 'Hello'. $there; +$string = 'Hello' .$there; + +// phpcs:set Squiz.Strings.ConcatenationSpacing ignoreNewlines true +$y = '1' + . '2' + . '3'; + +$y = '1' . + '2' . + '3'; + +$y = '1' +. '2' +. '3'; + +$y = '1' + .'2'. + '3' + . '4'; diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/ConcatenationSpacingUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/ConcatenationSpacingUnitTest.inc.fixed new file mode 100644 index 0000000000..bdae01fa11 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/ConcatenationSpacingUnitTest.inc.fixed @@ -0,0 +1,38 @@ +add_help_tab( array( +'id' => <<', +) ); + +// phpcs:set Squiz.Strings.ConcatenationSpacing spacing 1 + +$string = 'Hello'.$there.'. How are'.$you.$going."today $okay"; +$string = 'Hello'.$there.'. How are'.$you.$going."today $okay"; +$string = 'Hello'.$there; +$string = 'Hello'.$there; +$string = 'Hello'.$there; + +// phpcs:set Squiz.Strings.ConcatenationSpacing ignoreNewlines true +$y = '1'.'2'.'3'; + +$y = '1'.'2'.'3'; + +$y = '1'.'2'.'3'; + +$y = '1'.'2'.'3'.'4'; diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/FunctionClosingBraceSpaceUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/FunctionClosingBraceSpaceUnitTest.inc new file mode 100644 index 0000000000..8c8daf1f49 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/FunctionClosingBraceSpaceUnitTest.inc @@ -0,0 +1,90 @@ +setLogger(new class { + public function a(){} + private function b(){} + protected function c(){} +}); + +?> + +setLogger(new class { + + + public function a(){} + + + private function b(){} + + + protected function c(){} + + +}); + +?> + + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; +} + +// Make sure the determination of whether a property is the first property or not is done correctly. +class ClassUsingSimpleTraits +{ + use HelloWorld; + + + /* comment */ + public $firstVar = array( 'a', 'b' ); + protected $secondVar = true; +} + +class ClassUsingComplexTraits +{ + use A, B { + B::smallTalk insteadof A; + A::bigTalk insteadof B; + } + + + + public $firstVar = array( 'a', 'b' ); + + + /* comment */ + protected $secondVar = true; +} + +class Foo +{ + + + private function foo() + { + } + + + /* no error here because after function */ + private $bar = false; +} + +class CommentedOutCodeAtStartOfClass { + + /** + * Description. + * + * @var bool + */ + //public $commented_out_property = true; + + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class CommentedOutCodeAtStartOfClassNoBlankLine { + + // phpcs:disable Stnd.Cat.Sniff -- For reasons. + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class HasAttributes +{ + /** + * Short description of the member variable. + * + * @var array + */ + + #[ORM\Id]#[ORM\Column("integer")] + + private $id; + + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; + + #[SingleAttribute] + protected $propertySingle; + + #[FirstAttribute] + #[SecondAttribute] + protected $propertyDouble; + #[ThirdAttribute] + protected $propertyWithoutSpacing; +} + +enum SomeEnum +{ + // Enum cannot have properties + + case ONE = 'one'; +} + +class SupportReadonlyProperties { + readonly int $readonlyA; + public readonly string $publicReadonly; + readonly bool $readonlyB; + readonly private bool $readonlyPrivate; +} + +class NoPreambleMultilineDeclaration { + public + static + int $prop = 1; +} + +class MultipleBlankLinesInPreAmble { + + /** + * Docblock. + */ + + #[MyAttribute] + + + #[ + + BlankLinesWithinAnAttributeShouldBeLeftAlone + + ] + + public $prop; +} + +final class BlankLinesBetweenVsAttributesWithoutCommentIssueSquiz3594 +{ + + // PHPCS can fix blank lines for the first property, but not for the second. (fixed now) + #[SingleAttribute] + + public $property1; + #[SingleAttribute] + + public $property2; +} + +class PHP84FinalProperties { + final int $finalA; + + /** + * Docblock + */ + public final string $publicfinal; + #[AnAttribute] + final bool $finalB; + + final private bool $finalPrivate; +} + +class MultilineCommentShouldNotBeSplitUp { + // This is the first line + // of a multi-line comment + // which should be recognized as belonging + // with the property. + public $prop; + + + /* This is the first line + of a multi-line comment + which should be recognized as belonging + with the property. + */ + public $prop; +} + +class AsymVisibility { + protected private(set) int $asymProtectedPrivate; + + /** + * Docblock + */ + protected(set) final string $asymProtected; + #[AnAttribute] + + public(set) string|bool $asymPublic; + + + private(set) private bool $asymPrivate; +} + +abstract class PHP84AbstractProperties { + abstract int $abstractA {get;} + + /** + * Docblock + */ + public abstract string $publicAbstract { set; } + #[AnAttribute] + abstract bool $abstractB {get;} + + abstract protected bool $abstractProtected { set; } +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/MemberVarSpacingUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/MemberVarSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000000..1ea0f9e82a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/MemberVarSpacingUnitTest.1.inc.fixed @@ -0,0 +1,471 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; +} + +// Make sure the determination of whether a property is the first property or not is done correctly. +class ClassUsingSimpleTraits +{ + use HelloWorld; + + /* comment */ + public $firstVar = array( 'a', 'b' ); + + protected $secondVar = true; +} + +class ClassUsingComplexTraits +{ + use A, B { + B::smallTalk insteadof A; + A::bigTalk insteadof B; + } + + public $firstVar = array( 'a', 'b' ); + + /* comment */ + protected $secondVar = true; +} + +class Foo +{ + + + private function foo() + { + } + + + /* no error here because after function */ + private $bar = false; +} + +class CommentedOutCodeAtStartOfClass { + + /** + * Description. + * + * @var bool + */ + //public $commented_out_property = true; + + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class CommentedOutCodeAtStartOfClassNoBlankLine { + + // phpcs:disable Stnd.Cat.Sniff -- For reasons. + + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class HasAttributes +{ + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\Id]#[ORM\Column("integer")] + private $id; + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; + + #[SingleAttribute] + protected $propertySingle; + + #[FirstAttribute] + #[SecondAttribute] + protected $propertyDouble; + + #[ThirdAttribute] + protected $propertyWithoutSpacing; +} + +enum SomeEnum +{ + // Enum cannot have properties + + case ONE = 'one'; +} + +class SupportReadonlyProperties { + + readonly int $readonlyA; + + public readonly string $publicReadonly; + + readonly bool $readonlyB; + + readonly private bool $readonlyPrivate; +} + +class NoPreambleMultilineDeclaration { + + public + static + int $prop = 1; +} + +class MultipleBlankLinesInPreAmble { + + /** + * Docblock. + */ + #[MyAttribute] + #[ + + BlankLinesWithinAnAttributeShouldBeLeftAlone + + ] + public $prop; +} + +final class BlankLinesBetweenVsAttributesWithoutCommentIssueSquiz3594 +{ + + // PHPCS can fix blank lines for the first property, but not for the second. (fixed now) + #[SingleAttribute] + public $property1; + + #[SingleAttribute] + public $property2; +} + +class PHP84FinalProperties { + + final int $finalA; + + /** + * Docblock + */ + public final string $publicfinal; + + #[AnAttribute] + final bool $finalB; + + final private bool $finalPrivate; +} + +class MultilineCommentShouldNotBeSplitUp { + + // This is the first line + // of a multi-line comment + // which should be recognized as belonging + // with the property. + public $prop; + + /* This is the first line + of a multi-line comment + which should be recognized as belonging + with the property. + */ + public $prop; +} + +class AsymVisibility { + + protected private(set) int $asymProtectedPrivate; + + /** + * Docblock + */ + protected(set) final string $asymProtected; + + #[AnAttribute] + public(set) string|bool $asymPublic; + + private(set) private bool $asymPrivate; +} + +abstract class PHP84AbstractProperties { + + abstract int $abstractA {get;} + + /** + * Docblock + */ + public abstract string $publicAbstract { set; } + + #[AnAttribute] + abstract bool $abstractB {get;} + + abstract protected bool $abstractProtected { set; } +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/MemberVarSpacingUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/MemberVarSpacingUnitTest.2.inc new file mode 100644 index 0000000000..2aab7c0591 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/MemberVarSpacingUnitTest.2.inc @@ -0,0 +1,10 @@ + $j && $k< $l && $m>= $n && $o<= $p && $q<> $r; + +$a ==$b && $c !=$d && $e ===$f && $g !==$h; +$i >$j && $k <$l && $m >=$n && $o <=$p && $q <>$r; + +function myFunction($variable=0, $var2='string') {} + +if (index > -1) { +} + +array_walk_recursive($array, function(&$item) use (&$something) { +}); + +$var = saveFile(&$model, &$foo); + +// This is all valid. +$boo = -$foo; +function foo($boo = -1) {} +$foo = array('boo' => -1); +$x = $test ? -1 : 1; +$y = $test ? 1 : -1; +$z = $test ?: false; + +$closureWithDefaultParameter = function (array $testArray=array()) {}; + +switch ($foo) { + case -1: + break; +} + +$y = 1 * -1; +$y = -1 * 1; +$y = -1 * $var; +$y = 10 / -2; +$y = -10 / 2; +$y = (-10 / 2); +$y = (-10 / $var); +$y = 10 + -2; +$y = -10 + 2; + +$a = $x?$y:$z; +$a = $x ? $y : $z; + +$y = 1 + + 2 + - 3; + +$y = 1 + + 2 - + 3; + +$y = 1 ++ 2 +- 3; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +$y = 1 + + 2 + - 3; + +$y = 1 + + 2 - + 3; + +$y = 1 ++ 2 +- 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false + +if (true || -1 == $b) { +} + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$y = array(&$x); +$y = [&$x]; +$y = array(&$a, &$b, &$c); +$y = [&$a, &$b, &$c]; +$y = array(&$a => 1, 2 => &$b, &$c); +$y = [&$a => 1, 2 => &$b, &$c]; + +if ($a <=> $b) { +} + +if ($a <=>$b) { +} + +$a |= $b; +$a **= $b; +$a ??= $b; + +$a = +1; + +function bar($boo = +1) {} + +$username = $_GET['user']??'nobody'; + +function foo(string $bar, array $baz, ?MyClass $object) : MyClass {} + +declare(strict_types=1); + +function foo($c = ((BAR)?10:100)) {} + +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; + +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; + +function foo(string $a = '', ?string $b = ''): ?string {} + +// Issue #1605. +$text = preg_replace_callback( + self::CHAR_REFS_REGEX, + [ 'Sanitizer', 'decodeCharReferencesCallback' ], + $text, /* limit */ -1, $count ); + +if (true || /* test */ -1 == $b) {} +$y = 10 + /* test */ -2; + +// Issue #1604. +Hooks::run( 'ParserOptionsRegister', [ + &self::$defaults, + &self::$inCacheKey, + &self::$lazyOptions, +] ); + +$x = $foo ? function (): int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) + // comment + : int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) use /* comment */ ($bar): int { + return 1; +} : $bar; + +$x = !$foo ? $bar : function (): int { + return 1; +}; + +$a = + // Comment. + [ + 'a', + 'b', + ]; + +$a = +// phpcs:ignore Standard.Category.Sniff -- for reasons. +[ + 'a', + 'b', +]; + +$foo = is_array($bar) ? array_map( + function () {}, + $bar + ) : $bar; + +function bar(): array {} + +if ($line{-1} === ':') { + $line = substr($line, 0, -1); +} + +$a = $a instanceof $b; +$a = $a instanceof static; +$a = ($a)instanceof$b; + +fn&($x) => $x; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments false +$a = 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments true +yield -1; +echo -1; +$a = -1; +func(-1); +$a = [-1]; +return -1; +print -1; +$a &= -1; +switch ($a) { + case -1: +} +$a = $a ?? -1; +$a .= -1; +$a /= -1; +$a = [1 => -1]; +$a = $a == -1; +$a = $a >= -1; +$a = $a === -1; +$a = $a != -1; +$a = $a !== -1; +$a = $a <= -1; +$a = $a <=> -1; +$a = $a and -1; +$a = $a or -1; +$a = $a xor -1; +$a -= -1; +$a %= -1; +$a *= -1; +$a |= -1; +$a += -1; +$a = $a ** -1; +$a **= -1; +$a = $a << -1; +$a <<= -1; +$a = $a >> -1; +$a >>= -1; +$a = (string) -1; +$a = (array) -1; +$a = (bool) -1; +$a = (object) -1; +$a = (unset) -1; +$a = (float) -1; +$a = (int) -1; +$a ^= -1; +$a = [$a, -1]; +$a = $a[-1]; +$a = $a ? -1 : -1; + +yield - 1; +echo - 1; +$a = - 1; +func(- 1); +$a = [- 1]; +return - 1; +print - 1; +$a &= - 1; +switch ($a) { + case - 1: +} +$a = $a ?? - 1; +$a .= - 1; +$a /= - 1; +$a = [1 => - 1]; +$a = $a == - 1; +$a = $a >= - 1; +$a = $a === - 1; +$a = $a != - 1; +$a = $a !== - 1; +$a = $a <= - 1; +$a = $a <=> - 1; +$a = $a and - 1; +$a = $a or - 1; +$a = $a xor - 1; +$a -= - 1; +$a %= - 1; +$a *= - 1; +$a |= - 1; +$a += - 1; +$a = $a ** - 1; +$a **= - 1; +$a = $a << - 1; +$a <<= - 1; +$a = $a >> - 1; +$a >>= - 1; +$a = (string) - 1; +$a = (array) - 1; +$a = (bool) - 1; +$a = (object) - 1; +$a = (unset) - 1; +$a = (float) - 1; +$a = (int) - 1; +$a ^= - 1; +$a = [$a, - 1]; +$a = $a[- 1]; +$a = $a ? - 1 : - 1; + + +yield -$b; +echo -$b; +$a = -$b; +func(-$b); +$a = [-$b]; +return -$b; +print -$b; +$a &= -$b; +switch ($a) { + case -$b: +} +$a = $a ?? -$b; +$a .= -$b; +$a /= -$b; +$a = [1 => -$b]; +$a = $a == -$b; +$a = $a >= -$b; +$a = $a === -$b; +$a = $a != -$b; +$a = $a !== -$b; +$a = $a <= -$b; +$a = $a <=> -$b; +$a = $a and -$b; +$a = $a or -$b; +$a = $a xor -$b; +$a -= -$b; +$a %= -$b; +$a *= -$b; +$a |= -$b; +$a += -$b; +$a = $a ** -$b; +$a **= -$b; +$a = $a << -$b; +$a <<= -$b; +$a = $a >> -$b; +$a >>= -$b; +$a = (string) -$b; +$a = (array) -$b; +$a = (bool) -$b; +$a = (object) -$b; +$a = (unset) -$b; +$a = (float) -$b; +$a = (int) -$b; +$a ^= -$b; +$a = [$a, -$b]; +$a = $a[-$b]; +$a = $a ? -$b : -$b; + +yield - $b; +echo - $b; +$a = - $b; +func(- $b); +$a = [- $b]; +return - $b; +print - $b; +$a &= - $b; +switch ($a) { + case - $b: +} +$a = $a ?? - $b; +$a .= - $b; +$a /= - $b; +$a = [1 => - $b]; +$a = $a == - $b; +$a = $a >= - $b; +$a = $a === - $b; +$a = $a != - $b; +$a = $a !== - $b; +$a = $a <= - $b; +$a = $a <=> - $b; +$a = $a and - $b; +$a = $a or - $b; +$a = $a xor - $b; +$a -= - $b; +$a %= - $b; +$a *= - $b; +$a |= - $b; +$a += - $b; +$a = $a ** - $b; +$a **= - $b; +$a = $a << - $b; +$a <<= - $b; +$a = $a >> - $b; +$a >>= - $b; +$a = (string) - $b; +$a = (array) - $b; +$a = (bool) - $b; +$a = (object) - $b; +$a = (unset) - $b; +$a = (float) - $b; +$a = (int) - $b; +$a ^= - $b; +$a = [$a, - $b]; +$a = $a[- $b]; +$a = $a ? - $b : - $b; + +exit -1; + +$cl = function ($boo =-1) {}; +$cl = function ($boo =+1) {}; +$fn = fn ($boo =-1) => $boo; +$fn = fn ($boo =+1) => $boo; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +$a = 'a '.-MY_CONSTANT; +$a = 'a '.-$b; +$a = 'a '.- MY_CONSTANT; +$a = 'a '.- $b; + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +$foo = $var + ? 10 + : true; + +// Safeguard that a non-fixable error is thrown when there is a new line before the operator, +// but the last non-whitespace token before the operator is a comment token. +$foo = $var // Comment + ? false /* Comment */ + : true; + +$foo = $var // phpcs: ignore Stnd.Cat.Sniff -- for reasons. + + + ? $something /** + * Don't ask, but someone might have a docblock between the lines. It's valid PHP after all. + */ + + + : true; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +$foo = $var // Comment + ? false // Comment + : true; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/OperatorSpacingUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/OperatorSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000000..6e70fe75bb --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/OperatorSpacingUnitTest.1.inc.fixed @@ -0,0 +1,496 @@ + $j && $k < $l && $m >= $n && $o <= $p && $q <> $r; + +$a == $b && $c != $d && $e === $f && $g !== $h; +$i > $j && $k < $l && $m >= $n && $o <= $p && $q <> $r; + +function myFunction($variable=0, $var2='string') {} + +if (index > -1) { +} + +array_walk_recursive($array, function(&$item) use (&$something) { +}); + +$var = saveFile(&$model, &$foo); + +// This is all valid. +$boo = -$foo; +function foo($boo = -1) {} +$foo = array('boo' => -1); +$x = $test ? -1 : 1; +$y = $test ? 1 : -1; +$z = $test ?: false; + +$closureWithDefaultParameter = function (array $testArray=array()) {}; + +switch ($foo) { + case -1: + break; +} + +$y = 1 * -1; +$y = -1 * 1; +$y = -1 * $var; +$y = 10 / -2; +$y = -10 / 2; +$y = (-10 / 2); +$y = (-10 / $var); +$y = 10 + -2; +$y = -10 + 2; + +$a = $x ? $y : $z; +$a = $x ? $y : $z; + +$y = 1 + 2 - 3; + +$y = 1 + 2 - 3; + +$y = 1 + 2 - 3; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +$y = 1 + 2 - 3; + +$y = 1 + 2 - 3; + +$y = 1 + 2 - 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false + +if (true || -1 == $b) { +} + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$y = array(&$x); +$y = [&$x]; +$y = array(&$a, &$b, &$c); +$y = [&$a, &$b, &$c]; +$y = array(&$a => 1, 2 => &$b, &$c); +$y = [&$a => 1, 2 => &$b, &$c]; + +if ($a <=> $b) { +} + +if ($a <=> $b) { +} + +$a |= $b; +$a **= $b; +$a ??= $b; + +$a = +1; + +function bar($boo = +1) {} + +$username = $_GET['user'] ?? 'nobody'; + +function foo(string $bar, array $baz, ?MyClass $object) : MyClass {} + +declare(strict_types=1); + +function foo($c = ((BAR) ? 10 : 100)) {} + +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; + +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; + +function foo(string $a = '', ?string $b = ''): ?string {} + +// Issue #1605. +$text = preg_replace_callback( + self::CHAR_REFS_REGEX, + [ 'Sanitizer', 'decodeCharReferencesCallback' ], + $text, /* limit */ -1, $count ); + +if (true || /* test */ -1 == $b) {} +$y = 10 + /* test */ -2; + +// Issue #1604. +Hooks::run( 'ParserOptionsRegister', [ + &self::$defaults, + &self::$inCacheKey, + &self::$lazyOptions, +] ); + +$x = $foo ? function (): int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) + // comment + : int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) use /* comment */ ($bar): int { + return 1; +} : $bar; + +$x = !$foo ? $bar : function (): int { + return 1; +}; + +$a = + // Comment. + [ + 'a', + 'b', + ]; + +$a = +// phpcs:ignore Standard.Category.Sniff -- for reasons. +[ + 'a', + 'b', +]; + +$foo = is_array($bar) ? array_map( + function () {}, + $bar + ) : $bar; + +function bar(): array {} + +if ($line{-1} === ':') { + $line = substr($line, 0, -1); +} + +$a = $a instanceof $b; +$a = $a instanceof static; +$a = ($a) instanceof $b; + +fn&($x) => $x; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments false +$a = 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments true +yield -1; +echo -1; +$a = -1; +func(-1); +$a = [-1]; +return -1; +print -1; +$a &= -1; +switch ($a) { + case -1: +} +$a = $a ?? -1; +$a .= -1; +$a /= -1; +$a = [1 => -1]; +$a = $a == -1; +$a = $a >= -1; +$a = $a === -1; +$a = $a != -1; +$a = $a !== -1; +$a = $a <= -1; +$a = $a <=> -1; +$a = $a and -1; +$a = $a or -1; +$a = $a xor -1; +$a -= -1; +$a %= -1; +$a *= -1; +$a |= -1; +$a += -1; +$a = $a ** -1; +$a **= -1; +$a = $a << -1; +$a <<= -1; +$a = $a >> -1; +$a >>= -1; +$a = (string) -1; +$a = (array) -1; +$a = (bool) -1; +$a = (object) -1; +$a = (unset) -1; +$a = (float) -1; +$a = (int) -1; +$a ^= -1; +$a = [$a, -1]; +$a = $a[-1]; +$a = $a ? -1 : -1; + +yield - 1; +echo - 1; +$a = - 1; +func(- 1); +$a = [- 1]; +return - 1; +print - 1; +$a &= - 1; +switch ($a) { + case - 1: +} +$a = $a ?? - 1; +$a .= - 1; +$a /= - 1; +$a = [1 => - 1]; +$a = $a == - 1; +$a = $a >= - 1; +$a = $a === - 1; +$a = $a != - 1; +$a = $a !== - 1; +$a = $a <= - 1; +$a = $a <=> - 1; +$a = $a and - 1; +$a = $a or - 1; +$a = $a xor - 1; +$a -= - 1; +$a %= - 1; +$a *= - 1; +$a |= - 1; +$a += - 1; +$a = $a ** - 1; +$a **= - 1; +$a = $a << - 1; +$a <<= - 1; +$a = $a >> - 1; +$a >>= - 1; +$a = (string) - 1; +$a = (array) - 1; +$a = (bool) - 1; +$a = (object) - 1; +$a = (unset) - 1; +$a = (float) - 1; +$a = (int) - 1; +$a ^= - 1; +$a = [$a, - 1]; +$a = $a[- 1]; +$a = $a ? - 1 : - 1; + + +yield -$b; +echo -$b; +$a = -$b; +func(-$b); +$a = [-$b]; +return -$b; +print -$b; +$a &= -$b; +switch ($a) { + case -$b: +} +$a = $a ?? -$b; +$a .= -$b; +$a /= -$b; +$a = [1 => -$b]; +$a = $a == -$b; +$a = $a >= -$b; +$a = $a === -$b; +$a = $a != -$b; +$a = $a !== -$b; +$a = $a <= -$b; +$a = $a <=> -$b; +$a = $a and -$b; +$a = $a or -$b; +$a = $a xor -$b; +$a -= -$b; +$a %= -$b; +$a *= -$b; +$a |= -$b; +$a += -$b; +$a = $a ** -$b; +$a **= -$b; +$a = $a << -$b; +$a <<= -$b; +$a = $a >> -$b; +$a >>= -$b; +$a = (string) -$b; +$a = (array) -$b; +$a = (bool) -$b; +$a = (object) -$b; +$a = (unset) -$b; +$a = (float) -$b; +$a = (int) -$b; +$a ^= -$b; +$a = [$a, -$b]; +$a = $a[-$b]; +$a = $a ? -$b : -$b; + +yield - $b; +echo - $b; +$a = - $b; +func(- $b); +$a = [- $b]; +return - $b; +print - $b; +$a &= - $b; +switch ($a) { + case - $b: +} +$a = $a ?? - $b; +$a .= - $b; +$a /= - $b; +$a = [1 => - $b]; +$a = $a == - $b; +$a = $a >= - $b; +$a = $a === - $b; +$a = $a != - $b; +$a = $a !== - $b; +$a = $a <= - $b; +$a = $a <=> - $b; +$a = $a and - $b; +$a = $a or - $b; +$a = $a xor - $b; +$a -= - $b; +$a %= - $b; +$a *= - $b; +$a |= - $b; +$a += - $b; +$a = $a ** - $b; +$a **= - $b; +$a = $a << - $b; +$a <<= - $b; +$a = $a >> - $b; +$a >>= - $b; +$a = (string) - $b; +$a = (array) - $b; +$a = (bool) - $b; +$a = (object) - $b; +$a = (unset) - $b; +$a = (float) - $b; +$a = (int) - $b; +$a ^= - $b; +$a = [$a, - $b]; +$a = $a[- $b]; +$a = $a ? - $b : - $b; + +exit -1; + +$cl = function ($boo =-1) {}; +$cl = function ($boo =+1) {}; +$fn = fn ($boo =-1) => $boo; +$fn = fn ($boo =+1) => $boo; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +$a = 'a '.-MY_CONSTANT; +$a = 'a '.-$b; +$a = 'a '.- MY_CONSTANT; +$a = 'a '.- $b; + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +$foo = $var ? 10 : true; + +// Safeguard that a non-fixable error is thrown when there is a new line before the operator, +// but the last non-whitespace token before the operator is a comment token. +$foo = $var // Comment + ? false /* Comment */ + : true; + +$foo = $var // phpcs: ignore Stnd.Cat.Sniff -- for reasons. + + + ? $something /** + * Don't ask, but someone might have a docblock between the lines. It's valid PHP after all. + */ + + + : true; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +$foo = $var // Comment + ? false // Comment + : true; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/OperatorSpacingUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/OperatorSpacingUnitTest.2.inc new file mode 100644 index 0000000000..3a0dbac3e9 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/OperatorSpacingUnitTest.2.inc @@ -0,0 +1,3 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; + + public + $varS, + $varT, + $varU; + + // Issue #3188 - static as return type. + public static function staticAsReturnType($attributes = []): static + { + return static::factory()->create($attributes); + } + + public static function nullableStaticReturnType($attributes = []): ?static + { + return static::factory()->create($attributes); + } + + // Also account for static used within union types. + public function staticLast($attributes = []): object|static {} + public function staticMiddle(): string|static|object {} + public function staticFirst(): static|object {} +} + +// Ensure that static as a scope keyword when preceeded by a colon which is not for a type declaration is still handled. +$callback = $cond ? get_fn_name() : static function ($a) { return $a * 10; }; + +class TypedProperties { + public + int $var; + + protected string $stringA, $stringB; + + private bool + $boolA, + $boolB; +} + +// PHP 8.0 constructor property promotion. +class ConstructorPropertyPromotionTest { + public function __construct( + public $x = 0.0, + protected $y = '', + private $z = null, + $normalParam, + ) {} +} + +class ConstructorPropertyPromotionWithTypesTest { + public function __construct(protected float|int $x, public?string &$y = 'test', private mixed $z) {} +} + +// PHP 8.1 readonly keywords. +class ReadonlyTest { + public readonly int $publicReadonlyProperty; + + protected readonly int $protectedReadonlyProperty; + + readonly protected int $protectedReadonlyProperty; + + readonly private int $privateReadonlyProperty; + + public function __construct(readonly protected float|int $x, public readonly?string &$y = 'test') {} +} + +// PHP 8.2 readonly classes. +readonly class ReadonlyClassTest {} +readonly class ReadonlyClassTest {} + +// PHP 8.3 readonly anonymous classes. +$anon = new readonly class {}; +$anon = new readonly class {}; + +class FinalTest { + final public static function create(ContainerInterface $container) {} +} + +final class FinalTest2 { +} + +final + readonly class FinalTest3 {} + +class FinalTest4 { + final const X = "foo"; + final public const Y = "bar"; +} + +abstract class AbstractTest { + abstract public function foo(); +} + +final class FinalSpacingCorrect { + public final const SPACING_CORRECT = true; +} + +abstract class AbstractSpacingCorrect { + public abstract function spacingCorrect() {} +} + +$closure = static function() { return 'spacing correct'; }; +$closure = static function() { return 'spacing incorrect'; }; + +class ConstantVisibility { + public const PUBLIC_SPACING_CORRECT = true; + protected const PROTECTED_SPACING_CORRECT = true; + private const PRIVATE_SPACING_CORRECT = true; + + public const PUBLIC_SPACING_INCORRECT = true; + protected const PROTECTED_SPACING_INCORRECT = true; + private const PRIVATE_SPACING_INCORRECT = true; +} + +class FinalProperties { + final readonly public ?MyType $spacing_correct; + protected final $spacing_incorrect = 'foo'; +} + +class AsymVisibility { + public(set) string $asymPublic = 'hello'; + public protected(set) final $asymProtected = 'hello'; + private(set) public string|false $asymPrivate = 'hello'; + + public public(set) $asymPublicPublic = 'hello'; + protected(set) public $asymPublicProtected = 'hello'; + protected private(set) $asymProtectedPrivate = 'hello'; +} + +abstract class AbstractProperties { + abstract public ?MyType $spacing_correct {get;} + protected abstract $spacing_incorrect { set; } +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000000..c0ee0c0066 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc.fixed @@ -0,0 +1,202 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; + + public + $varS, + $varT, + $varU; + + // Issue #3188 - static as return type. + public static function staticAsReturnType($attributes = []): static + { + return static::factory()->create($attributes); + } + + public static function nullableStaticReturnType($attributes = []): ?static + { + return static::factory()->create($attributes); + } + + // Also account for static used within union types. + public function staticLast($attributes = []): object|static {} + public function staticMiddle(): string|static|object {} + public function staticFirst(): static|object {} +} + +// Ensure that static as a scope keyword when preceeded by a colon which is not for a type declaration is still handled. +$callback = $cond ? get_fn_name() : static function ($a) { return $a * 10; }; + +class TypedProperties { + public int $var; + + protected string $stringA, $stringB; + + private bool + $boolA, + $boolB; +} + +// PHP 8.0 constructor property promotion. +class ConstructorPropertyPromotionTest { + public function __construct( + public $x = 0.0, + protected $y = '', + private $z = null, + $normalParam, + ) {} +} + +class ConstructorPropertyPromotionWithTypesTest { + public function __construct(protected float|int $x, public ?string &$y = 'test', private mixed $z) {} +} + +// PHP 8.1 readonly keywords. +class ReadonlyTest { + public readonly int $publicReadonlyProperty; + + protected readonly int $protectedReadonlyProperty; + + readonly protected int $protectedReadonlyProperty; + + readonly private int $privateReadonlyProperty; + + public function __construct(readonly protected float|int $x, public readonly ?string &$y = 'test') {} +} + +// PHP 8.2 readonly classes. +readonly class ReadonlyClassTest {} +readonly class ReadonlyClassTest {} + +// PHP 8.3 readonly anonymous classes. +$anon = new readonly class {}; +$anon = new readonly class {}; + +class FinalTest { + final public static function create(ContainerInterface $container) {} +} + +final class FinalTest2 { +} + +final readonly class FinalTest3 {} + +class FinalTest4 { + final const X = "foo"; + final public const Y = "bar"; +} + +abstract class AbstractTest { + abstract public function foo(); +} + +final class FinalSpacingCorrect { + public final const SPACING_CORRECT = true; +} + +abstract class AbstractSpacingCorrect { + public abstract function spacingCorrect() {} +} + +$closure = static function() { return 'spacing correct'; }; +$closure = static function() { return 'spacing incorrect'; }; + +class ConstantVisibility { + public const PUBLIC_SPACING_CORRECT = true; + protected const PROTECTED_SPACING_CORRECT = true; + private const PRIVATE_SPACING_CORRECT = true; + + public const PUBLIC_SPACING_INCORRECT = true; + protected const PROTECTED_SPACING_INCORRECT = true; + private const PRIVATE_SPACING_INCORRECT = true; +} + +class FinalProperties { + final readonly public ?MyType $spacing_correct; + protected final $spacing_incorrect = 'foo'; +} + +class AsymVisibility { + public(set) string $asymPublic = 'hello'; + public protected(set) final $asymProtected = 'hello'; + private(set) public string|false $asymPrivate = 'hello'; + + public public(set) $asymPublicPublic = 'hello'; + protected(set) public $asymPublicProtected = 'hello'; + protected private(set) $asymProtectedPrivate = 'hello'; +} + +abstract class AbstractProperties { + abstract public ?MyType $spacing_correct {get;} + protected abstract $spacing_incorrect { set; } +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeKeywordSpacingUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeKeywordSpacingUnitTest.2.inc new file mode 100644 index 0000000000..45cfb53431 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ScopeKeywordSpacingUnitTest.2.inc @@ -0,0 +1,6 @@ += 0 { + docs[d] = true + } + } + } + } + changed := false + for d := range docs { + if v, ok := fixVarTag(s.At(d).Value, eol); ok { + s.SetValue(d, v) + changed = true + } + } + return changed +} + +// memberVarDoc returns the docblock of the property at i, -1 when another +// token comes first. +func memberVarDoc(s *tokens.Stream, i int) int { + for j := i - 1; j >= 0; j-- { + t := s.At(j) + switch t.Kind { + case token.Whitespace, token.Ident: + continue + case token.Keyword: + if memberVarSkip[strings.ToLower(t.Value)] { + continue + } + case token.Punct: + if len(t.Value) == 1 && strings.Contains("?|&()\\", t.Value) { + continue + } + case token.AttributeEnd: + if a := s.AttributeStartOf(j); a >= 0 { + j = a + continue + } + case token.DocComment: + return j + } + return -1 + } + return -1 +} + +// fixVarTag rewrites the type of the first @var tag in doc to its suggested form. +func fixVarTag(doc, eol string) (string, bool) { + for _, tag := range phpcsDocTags(doc, eol) { + if tag.Name != "@var" { + continue + } + if tag.StrPos < 0 { + return doc, false + } + parts := varTagParts.FindStringSubmatch(tag.Str) + var suggested []string + for name := range strings.SplitSeq(parts[1], "|") { + if n := phpcsSuggestType(name); !slices.Contains(suggested, n) { + suggested = append(suggested, n) + } + } + want := strings.Join(suggested, "|") + if want == parts[1] { + return doc, false + } + return replaceDocStrings(doc, map[int][2]string{tag.StrPos: {tag.Str, want + parts[2]}}), true + } + return doc, false +} + +var ( + phpcsAllowedTypes = map[string]bool{ + "array": true, "boolean": true, "float": true, "integer": true, "mixed": true, + "object": true, "string": true, "resource": true, "callable": true, + } + phpcsArrayType = regexp.MustCompile(`(?i)^array\(\s*([^\s^=>]*)(\s*=>\s*(.*))?\s*\)`) +) + +// phpcsSuggestType is PHP_CodeSniffer's Common::suggestType. +func phpcsSuggestType(varType string) string { + if varType == "" || phpcsAllowedTypes[varType] { + return varType + } + lower := strings.ToLower(varType) + switch lower { + case "bool", "boolean": + return "boolean" + case "double", "real", "float": + return "float" + case "int", "integer": + return "integer" + case "array()", "array": + return "array" + } + if strings.Contains(lower, "array(") { + m := phpcsArrayType.FindStringSubmatch(varType) + if m == nil { + return "array" + } + type2 := phpcsSuggestType(m[3]) + if type2 != "" { + type2 = " => " + type2 + } + return "array(" + phpcsSuggestType(m[1]) + type2 + ")" + } + if phpcsAllowedTypes[lower] { + return lower + } + return varType +} diff --git a/blink/phpcs-not-ported.txt b/blink/phpcs-not-ported.txt index 4018c4311d..0b7e41c0ad 100644 --- a/blink/phpcs-not-ported.txt +++ b/blink/phpcs-not-ported.txt @@ -1,28 +1,13 @@ PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayDeclarationSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ClassDeclarationSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\SelfMemberReferenceSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\BlockCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FileCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\InlineCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\LongConditionClosingCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\VariableCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ControlSignatureSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForEachLoopDeclarationSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForLoopDeclarationSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\InlineIfDeclarationSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\SwitchDeclarationSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Formatting\OperatorBracketSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationArgumentSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\EmbeddedPhpSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\LowercasePHPFunctionsSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\ConcatenationSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ControlStructureSpacingSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionClosingBraceSpaceSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionSpacingSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\MemberVarSpacingSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeClosingBraceSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeKeywordSpacingSniff