### Install phpgrep Binary Source: https://github.com/vkcom/noverify/blob/master/src/phpgrep/README.md Installs the phpgrep command-line tool using go get. Ensure your $GOPATH/bin is in your system's $PATH for the command to be available. ```bash go get -v github.com/quasilyte/phpgrep/cmd/phpgrep ``` -------------------------------- ### Run NoVerify Playground Locally Source: https://github.com/vkcom/noverify/blob/master/playground/README.md Execute this command from the root of the project to build and start the playground. Ensure you have the necessary build tools installed. The playground will be accessible at http://localhost:8080/. ```shell make playground -B ``` -------------------------------- ### Install NoVerify via Go Source: https://context7.com/vkcom/noverify/llms.txt Install the tool using the Go toolchain or build directly from the source repository. ```bash # Install using go install go install github.com/VKCOM/noverify@latest # Build from source git clone https://github.com/vkcom/noverify cd noverify make build ``` -------------------------------- ### Install via Go Source: https://github.com/vkcom/noverify/blob/master/docs/install.md Install NoVerify using the Go toolchain. ```shell $ go install github.com/VKCOM/noverify@latest ``` -------------------------------- ### Verify Installation Source: https://context7.com/vkcom/noverify/llms.txt Check the installed version of the NoVerify binary. ```bash # Check version noverify version ``` -------------------------------- ### Verify Binary Installation Source: https://github.com/vkcom/noverify/blob/master/docs/install.md Check that the NoVerify binary is correctly installed and executable. ```bash noverify version ``` -------------------------------- ### Install PHP Zip Extension Source: https://github.com/vkcom/noverify/blob/master/docs/install.md Commands to install the required ext-zip extension on Ubuntu and macOS. ```shell sudo apt install php8.0-zip ``` ```shell brew update brew install php@8.0 brew link php@8.0 brew link php@8.0 --force ``` -------------------------------- ### Install NoVerify via Composer Source: https://github.com/vkcom/noverify/blob/master/docs/install.md Install the package as a development dependency and download the binary. ```shell composer require --dev vkcom/noverify ``` ```shell ./vendor/bin/noverify-get ``` ```shell ./vendor/bin/noverify ``` ```shell ./vendor/bin/noverify-get --version 0.3.0 ``` -------------------------------- ### Example PHP files for diff analysis Source: https://github.com/vkcom/noverify/blob/master/docs/diff.md Sample files used to demonstrate how --git-full-diff detects errors in unchanged files. ```php // 1.php class Foo { public static function f() { echo 1; } } ``` ```php // 2.php Foo::f(); ``` -------------------------------- ### Install project dependencies Source: https://github.com/vkcom/noverify/blob/master/docs/getting_started.md Install all project dependencies using Composer. This step is crucial for NoVerify to correctly analyze code by finding function and class definitions. ```bash composer install ``` ```bash composer install --ignore-platform-reqs ``` -------------------------------- ### Build Noverify Project Source: https://github.com/vkcom/noverify/blob/master/CONTRIBUTING.md Clone the repository and run 'make build' to compile the project. Ensure you have Go version 1.16 or higher installed. The binary will be in the ./build folder. ```bash git clone https://github.com/vkcom/noverify cd noverify make build ``` -------------------------------- ### Git Pre-push Hook Example Source: https://context7.com/vkcom/noverify/llms.txt Example of a Git pre-push hook script that uses NoVerify to check changes between local and remote commits. ```bash #!/bin/sh # .git/hooks/pre-push commit_end=$(git rev-parse --abbrev-ref HEAD) commit_begin=$(git rev-parse -q --verify origin/$commit_end) if [ -z "$commit_begin" ]; then commit_begin=ORIGIN_MASTER fi noverify check \ --git=.git \ --git-commit-from=$commit_begin \ --git-commit-to=$commit_end \ --git-work-tree=. \ --critical='unused,strictCmp,undefined' exit $? ``` -------------------------------- ### Strict-mixed mode example: before Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md Demonstrates code behavior before enabling strict-mixed mode, where accessing methods/properties on mixed types is allowed without warnings. ```php // noverify check ./src function f($a) { $a->foo(); // ok $a->boo; // ok } ``` -------------------------------- ### PHP code simplification suggestions Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/parsedown/golden.txt Examples of code patterns that can be simplified for better performance or readability. ```php if (preg_match('/^<\/\w[\w-]*+[ ]*+>/s', $Excerpt['text'], $matches)) ``` ```php if (substr($Excerpt['text'], 1, 1) !== ' ' and strpos($Excerpt['text'], ';') !== false ``` -------------------------------- ### Strict-mixed mode example: after Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md Illustrates code behavior after enabling strict-mixed mode, showing that accessing undefined methods or properties on mixed types now generates errors. ```php // noverify check --strict-mixed ./src function f1($a) { $a->foo(); // error: undefined method 'foo' $a->boo; // error: undefined property 'boo' } ``` -------------------------------- ### Linter Output Example Source: https://github.com/vkcom/noverify/blob/master/docs/baseline.md Example of the warning output generated by NoVerify when a new error is detected. ```text WARNING offBy1: Probably intended to use count-1 as an index at swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php:98 echo $a[count($a)]; ^^^^^^^^^^^^^ ``` -------------------------------- ### Combine Rules with Labels Source: https://github.com/vkcom/noverify/blob/master/docs/dynamic_rules.md Use goto-style labels starting with 'any_' or 'seq_' to match multiple patterns within a single rule definition. ```php /** * @comment Reports comparisons where the literal is on the left. * @before false === $a * @after $a === false */ function yodaStyle() { /** * @maybe Yoda style comparison * @fix $a === false */ false === $a; } ``` ```php /** * @comment Reports comparisons where the literal is on the left. * @before false === $a * @after $a === false */ function yodaStyle() { /** * @maybe Yoda style comparison * @fix $a === false */ any_identical: { false === $a; true === $a; } } ``` -------------------------------- ### Compliant code example Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md A basic PHP code snippet demonstrating a compliant conditional assignment. ```php $v = 0; // Default value. if ($cond) { $v = 10; } return $v; ``` -------------------------------- ### Run NoVerify as Language Server Source: https://github.com/vkcom/noverify/blob/master/docs/writing-new-ide-plugin.md Use this command to start `noverify` in language server mode. Specify the number of cores to use for processing. ```sh $ noverify check -lang-server -cores=4 ``` -------------------------------- ### Git merge-base command examples Source: https://github.com/vkcom/noverify/blob/master/docs/diff.md Commands illustrating how NoVerify determines the merge base for commit analysis. ```shell git merge-base ORIGIN_MASTER from_commit ``` -------------------------------- ### Use Short Array Syntax in PHP Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/output-test/golden.txt This example demonstrates the use of the short array syntax '[]' which is preferred over the older 'array()' syntax in PHP. ```php $_ = array(); // warning in last line ``` -------------------------------- ### Example NoVerify Error Reports Source: https://github.com/vkcom/noverify/blob/master/docs/finding-false-positives.md Sample output showing access level errors reported by NoVerify. ```text ERROR accessLevel: Cannot access protected property \Monolog\Handler\ProcessableHandlerTrait->processors at ./src/Monolog/Handler/GroupHandler.php:64 if ($this->processors) { ^^^^^^^^^^ ERROR accessLevel: Cannot access protected method \Monolog\Handler\ProcessableHandlerTrait->processRecord() at ./src/Monolog/Handler/GroupHandler.php:65 $record = $this->processRecord($record); ^^^^^^^^^^^^^ ``` -------------------------------- ### Define a Mustache template Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/mustache/README.md A canonical Mustache template example using variables and conditional sections. ```html+jinja Hello {{name}} You have just won {{value}} dollars! {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} ``` -------------------------------- ### Define a Yoda style comparison pattern Source: https://github.com/vkcom/noverify/blob/master/docs/dynamic_rules.md Example of a syntax pattern used to identify Yoda style comparisons. ```php if (false === $a) {} ``` -------------------------------- ### Lint Noverify Code Source: https://github.com/vkcom/noverify/blob/master/CONTRIBUTING.md Run the golangci-lint analysis using 'make lint'. This command installs the linter if necessary and checks code quality against the ./.golangci.yml configuration. ```bash make lint ``` -------------------------------- ### PHP Unreachable Code Warning Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt Example of code identified as unreachable. ```php return null; ``` -------------------------------- ### phpgrep Example: Filter by Integer Type and Value Source: https://github.com/vkcom/noverify/blob/master/src/phpgrep/README.md Demonstrates searching for function calls with a single integer argument, excluding a specific value. The output shows the file, line number, and the matched code. ```php priv() + $this->prot() + $this->pub(); } } echo (new B)->sum(); // actual PHP prints 6 `) } ``` -------------------------------- ### Test Code Injection Source: https://github.com/vkcom/noverify/blob/master/docs/baseline.md Example code snippet added to a file to verify that the linter correctly identifies new errors. ```php $a = [1]; echo $a[count($a)]; ``` -------------------------------- ### PHP imagecolorallocate Null Safety and Safety Warnings Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt Examples of potential null safety and safety violations when passing variables to imagecolorallocate. ```php $b = hexdec(substr($color, 4, 2)); return imagecolorallocate($image, $r, $g, $b); ``` -------------------------------- ### PHP String Search Function Usage Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/embeddedrules/golden.txt Examples of string search functions triggering warnings for deprecated integer needle arguments or unsafe function calls. ```php $_ = strripos($str, getIntOrString(true)); // ok ``` ```php $_ = strstr($str, 10); ``` ```php $_ = strstr($str, getInt()); ``` ```php $_ = strstr($str, getIntOrString(true)); // ok ``` ```php $_ = strchr($str, 10); ``` ```php $_ = strchr($str, getInt()); ``` ```php $_ = strchr($str, getIntOrString(true)); // ok ``` ```php $_ = strrchr($str, 10); ``` ```php $_ = strrchr($str, getInt()); ``` ```php $_ = strrchr($str, getIntOrString(true)); // ok ``` ```php $_ = stristr($str, 10); ``` ```php $_ = stristr($str, getInt()); ``` ```php $_ = stristr($str, getIntOrString(true)); // ok ``` -------------------------------- ### Build from Source Source: https://github.com/vkcom/noverify/blob/master/docs/install.md Clone the repository and compile the binary using make. ```shell git clone https://github.com/vkcom/noverify cd noverify make build ``` ```shell make build BIN_NAME=noverify.bin ``` -------------------------------- ### Create a rules.php file Source: https://github.com/vkcom/noverify/blob/master/docs/dynamic_rules.md A sample rules file structure using PHPDoc annotations to define inspection metadata and a pattern for matching Yoda style comparisons. ```php priv() at _file0.php:13 return $this->priv() + $this->prot() + $this->pub(); ^^^^ linttest.go:124: unexpected report 1: ERROR accessLevel: Cannot access protected method \A->prot() at _file0.php:13 return $this->priv() + $this->prot() + $this->pub(); ^^^^ linttest.go:135: >>> issues reported: linttest.go:137: ERROR accessLevel: Cannot access private method \A->priv() at _file0.php:13 return $this->priv() + $this->prot() + $this->pub(); ^^^^ linttest.go:137: ERROR accessLevel: Cannot access protected method \A->prot() at _file0.php:13 return $this->priv() + $this->prot() + $this->pub(); ^^^^ linttest.go:139: <<< FAIL FAIL github.com/VKCOM/noverify/src/linttest 1.174s FAIL ``` -------------------------------- ### Run Full Project Analysis Source: https://context7.com/vkcom/noverify/llms.txt Analyze a directory and view the resulting reports. ```bash # Analyze the lib folder noverify check ./lib # Example output: # WARNING strictCmp: Non-strict string comparison (use ===) at lib/Parser.php:417 # $nofws = ('nofws' == $this->canon); # ^^^^^^^^^^^^^^^^^^^^^^^ # WARNING parentConstructor: Missing parent::__construct() call at lib/Entity.php:27 # public function __construct($data = null) # ^^^^^^^^^^^ # 2021/07/08 16:13:19 Found 113 critical and 10 minor reports ``` -------------------------------- ### Clone a test project Source: https://github.com/vkcom/noverify/blob/master/docs/getting_started.md Clone the swiftmailer repository to your local machine. Navigate into the cloned directory to proceed. ```bash git clone https://github.com/i582/swiftmailer.git cd swiftmailer ``` -------------------------------- ### Type-Based Custom Rules Source: https://context7.com/vkcom/noverify/llms.txt Example of filtering rules based on expression types. ```php ENT_QUOTES)); echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!" ``` -------------------------------- ### Run Noverify Tests Source: https://github.com/vkcom/noverify/blob/master/CONTRIBUTING.md Execute all tests in the ./tests folder using 'make test'. This command utilizes Go's standard testing framework. ```bash make test ``` -------------------------------- ### Display help for check command Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md Command to list all available options for the check command. ```bash noverify check help ``` -------------------------------- ### PHP Code with Unused Variable Source: https://github.com/vkcom/noverify/blob/master/docs/diff.md Example of a PHP function containing an unused variable. This will be flagged by NoVerify in diff mode if introduced. ```php data)) ``` ```php array_key_exists($k, $this->data) ``` -------------------------------- ### Class member order: Properties before methods Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt In the `QRCode` class, properties like `$qr_format_info` should be declared before methods to maintain a consistent and organized class structure. ```php private $qr_format_info = [ ``` -------------------------------- ### Class member order: Properties before methods Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt In the `QRCode` class, properties like `$qr_exp` should be declared before methods to maintain a consistent and organized class structure. ```php private $qr_exp = [ ``` -------------------------------- ### List Available Checkers Source: https://context7.com/vkcom/noverify/llms.txt Display all available rules that can be used in analysis. ```bash # Show all available checks noverify checkers ``` -------------------------------- ### Specify PHP File Extensions Source: https://context7.com/vkcom/noverify/llms.txt Define which file extensions should be processed as PHP files. ```bash # Analyze specific extensions noverify check --php-extensions='php,phtml,inc' ./src ``` -------------------------------- ### Class member order: Properties before methods Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt In the `QRCode` class, properties like `$qr_alignment_patterns` should be declared before methods to maintain a consistent and organized class structure. ```php private $qr_alignment_patterns = [ ``` -------------------------------- ### Class member order: Properties before methods Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt In the `QRCode` class, properties like `$qr_ec_polynomials` should be declared before methods to maintain a consistent and organized class structure. ```php private $qr_ec_polynomials = [ ``` -------------------------------- ### Class member order: Properties before methods Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt In the `QRCode` class, properties like `$qr_ec_params` should be declared before methods to maintain a consistent and organized class structure. ```php private $qr_ec_params = [ ``` -------------------------------- ### Create a view context class Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/mustache/README.md Defines a class to serve as a view context, allowing for dynamic data and method-based values. ```php value - ($this->value * 0.4); } public $in_ca = true; } ``` -------------------------------- ### Run All Tests After Fix Source: https://github.com/vkcom/noverify/blob/master/docs/finding-false-positives.md After implementing a fix, re-run all tests using `go test` to ensure the changes have resolved the issue and haven't introduced new ones. A successful run will show an 'ok' status. ```bash go test github.com/VKCOM/noverify/src/linttest ``` -------------------------------- ### Check Noverify Code and Tests Source: https://github.com/vkcom/noverify/blob/master/CONTRIBUTING.md Convenience command 'make check' runs the linter first, followed by the tests. This ensures code quality and correctness. ```bash make check ``` -------------------------------- ### Run Analysis with Baseline Source: https://context7.com/vkcom/noverify/llms.txt Commands to analyze code using a baseline file to ignore existing errors or use a conservative baseline to reduce false positives. ```bash noverify check --baseline='baseline.json' ./lib ``` ```bash noverify check --output-baseline --conservative-baseline --output='baseline.json' ./lib ``` ```bash noverify check --baseline='baseline.json' --conservative-baseline ./lib ``` -------------------------------- ### Build and Run Custom Checker Source: https://context7.com/vkcom/noverify/llms.txt Commands to build a custom NoVerify linter and run it with custom checks against source files. ```bash # Build custom linter go build -o custom-noverify ./custom/main.go # Run with custom checks ./custom-noverify check ./src ``` -------------------------------- ### phpgrep Help Usage Source: https://github.com/vkcom/noverify/blob/master/src/phpgrep/README.md Displays the help message for the phpgrep command, outlining its usage, arguments, and exit status. ```bash Usage: phpgrep [flags...] target pattern [filters...] Where: flags are command-line flags that are listed in -help (see below) target is a file or directory name where search is performed pattern is a string that describes what is being matched filters are optional arguments bound to the pattern Examples: # Find f calls with a single variable argument. phpgrep file.php 'f(${"var"})' # Like previous example, but searches inside entire # directory recursively and variable names are restricted # to $id, $uid and $gid. # Also uses -v flag that makes phpgrep output more info. phpgrep -v ~/code/php 'f(${"x:var"})' 'x=id,uid,gid' Exit status: 0 if something is matched 1 if nothing is matched 2 if error occured # ... rest of output ``` -------------------------------- ### Class member order: Properties before methods Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt In the `QRCode` class, properties like `$qr_remainder_bits` should be declared before methods to maintain a consistent and organized class structure. ```php private $qr_remainder_bits = [ ``` -------------------------------- ### Run NoVerify Analysis Source: https://github.com/vkcom/noverify/blob/master/docs/finding-false-positives.md Commands to clone a repository and execute NoVerify analysis on a specific directory. ```bash # 1. Clone monolog repository locally. git clone https://github.com/Seldaek/monolog.git # 2. Enter the downloaded directory cd monolog # 3. Run noverify over the source directory noverify ./src/Monolog ``` -------------------------------- ### Define and Run Custom PHP Rules Source: https://context7.com/vkcom/noverify/llms.txt Structure for defining custom rules using phpgrep and commands to execute them. ```php prop2; // prop2 is undefined. ``` ```php class Foo { public string $prop; } (new Foo)->prop; ``` -------------------------------- ### Configure NoVerify in VS Code settings Source: https://github.com/vkcom/noverify/blob/master/docs/vscode-plugin.md Define the path to the NoVerify binary and specify additional command-line arguments in the VS Code settings file. ```json { "php-noverify.noverifyPath": "", "php-noverify.noverifyExtraArgs": [ "check", "-cores=4" ] } ``` -------------------------------- ### Render a view context object Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/mustache/README.md Uses the Mustache engine to render a template using an object instance as the context. ```php ENT_QUOTES)); $chris = new Chris; echo $m->render($template, $chris); ``` -------------------------------- ### Fix instance method call in PHP Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Use the arrow operator `->` for instance methods, not the double colon `::` which is for static methods. ```php $object::instance_method() // instance_method is not a static method. ``` ```php $object->instance_method() ``` -------------------------------- ### phpgrep Recipe: Find New Calls Without Parentheses Source: https://github.com/vkcom/noverify/blob/master/src/phpgrep/README.md Detects instances where the 'new' keyword is used to instantiate a class without the subsequent parentheses, which is syntactically incorrect in most PHP versions. ```bash # Find new calls without parentheses. $ phpgrep srcdir 'new $t' ``` -------------------------------- ### Format Commit Messages Source: https://github.com/vkcom/noverify/blob/master/CONTRIBUTING.md Follow this format for all commit messages. 'pkgs' should be the package name or comma-separated package names affected by the change. ```text pkgs: short desc A more detailed description. ``` -------------------------------- ### Unused Arguments Variable Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/underscore/golden.txt Illustrates an unused '$args' variable. Use '$_' to ignore unused variables or configure the linter. ```php $args = self::_wrapArgs(func_get_args(), 1); ``` -------------------------------- ### Simplify array_push to array assignment Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/embeddedrules/golden.txt Use array assignment syntax instead of array_push for better performance. ```php array_push($array, $val); ``` ```php array_push($array, 10); ``` -------------------------------- ### Unsafe stream_set_read_buffer Call Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt Setting the read buffer to 0 with `stream_set_read_buffer` might lead to unexpected behavior or performance issues. Use with caution. ```php stream_set_read_buffer($client, 0); ``` -------------------------------- ### Cache Configuration Source: https://context7.com/vkcom/noverify/llms.txt Manage NoVerify's cache directory using `--cache-dir` or disable caching entirely with `--disable-cache`. ```bash # Change cache directory noverify check --cache-dir='./cache' ./src # Disable caching noverify check --disable-cache ./src ``` -------------------------------- ### Safe String Padding in PHP Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/math/golden.txt Ensure the `string` and `length` arguments for `str_pad` are safe to prevent errors. ```php $value = \str_pad($value, $targetLength, '0', STR_PAD_LEFT); ``` -------------------------------- ### Unsafe stream_set_write_buffer Call Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt Setting the write buffer to 0 with `stream_set_write_buffer` might lead to unexpected behavior or performance issues. Use with caution. ```php stream_set_write_buffer($client, 0); ``` -------------------------------- ### Match PHP variables Source: https://github.com/vkcom/noverify/blob/master/src/phpgrep/pattern_language.md Use variables to match AST nodes. Identical variable names must match the same AST node, while $_ acts as a wildcard. ```php $x = $y; // Matches any assignment $x = $x; // Matches only self-assignments ``` ```php $_ = $_ // Matches any assignment (because $_ is special) ``` -------------------------------- ### PHP Version Mode Source: https://context7.com/vkcom/noverify/llms.txt Use the `--php7` flag to parse code as PHP 7, which is useful for projects using PHP 8 reserved words. ```bash # Parse code as PHP 7 (for projects using PHP 8 reserved words) noverify check --php7 ./src ``` -------------------------------- ### Handle image resources Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt Operations involving image resource handling that triggered safety warnings. ```php imagepng($image); ``` ```php imagedestroy($image); ``` ```php $image = imagecreatetruecolor($width, $height); ``` ```php imagesavealpha($image, true); ``` ```php imagefill($image, 0, 0, $bgcolor); ``` ```php imagefilledrectangle($image, $rx, $ry, $rx + $rw - 1, $ry + $rh - 1, $mc); ``` -------------------------------- ### Array Slice Usage in Underscore Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/underscore/golden.txt Demonstrates the use of array_slice for splitting collections. Pay attention to the offset parameter for potential safety concerns. ```php $collection = ($calculated_value < $midpoint_calculated_value) ? array_slice($collection, 0, $midpoint, true) : array_slice($collection, $midpoint, null, true); ``` -------------------------------- ### Simplify Array Push to Block Stack Assignment Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/mustache/golden.txt Simplifies `array_push` to direct block stack assignment for better readability and performance. ```php $this->blockStack[] = $value; ``` -------------------------------- ### Run Analysis with Baseline Source: https://github.com/vkcom/noverify/blob/master/docs/baseline.md Executes the linter while suppressing errors listed in the provided baseline file. ```bash noverify check --baseline='baseline.json' ./lib ``` -------------------------------- ### PHP Switch Version Group Default Warning Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt Warning for missing default branch in version group switch. ```php switch ($version_group) { ``` -------------------------------- ### Report undefined classes Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Identifies usages of classes or interfaces that have not been defined. ```php $foo = new UndefinedClass; ``` ```php $foo = new DefinedClass; ``` -------------------------------- ### Ensure interface contract implementation Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Reports classes that fail to implement all required methods from an interface they declare to implement. ```php class MyObj implements Serializable { public function serialize() { /* ... */ } // Lost implementation of the unserialize method. } ``` ```php class MyObj implements Serializable { public function serialize() { /* ... */ } public function unserialize(string $s) { /* ... */ } } ``` -------------------------------- ### phpgrep Recipe: Find Potential Operator Precedence Issues Source: https://github.com/vkcom/noverify/blob/master/src/phpgrep/README.md Highlights code where bitwise operations might have incorrect precedence when compared with equality or inequality operators, suggesting the use of parentheses for clarity. ```bash # Find potential operator precedence issues. $ phpgrep srcdir '$x & $mask == $y' # Should be ($x & $mask) == $y $ phpgrep srcdir '$x & $mask != $y' # Should be ($x & $mask) != $y ``` -------------------------------- ### Avoid Using exit Function Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt The `exit` function should be avoided. Use `die` or other appropriate termination methods instead. ```php exit(1); ``` ```php exit(0); ``` ```php exit(1); ``` -------------------------------- ### Simplify switch statements to if Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Identifies `switch` statements that can be simplified into equivalent `if` conditions. ```php switch ($a) { case 1: echo 1; break; } ``` ```php if ($a == 1) { echo 1; } ``` -------------------------------- ### Run analysis with custom rules Source: https://github.com/vkcom/noverify/blob/master/docs/dynamic_rules.md Command to execute NoVerify analysis using a specific rule file and filtering by the rule name. ```bash noverify check --allow-checks='yodaStyle' --rules='rules.php' ./lib ``` -------------------------------- ### Manual Git fetch command Source: https://github.com/vkcom/noverify/blob/master/docs/diff.md Command to manually fetch master branch for use with --git-skip-fetch. ```shell git fetch --no-tags -q origin master:ORIGIN_MASTER ``` -------------------------------- ### Run NoVerify with autofix for assignOp check Source: https://github.com/vkcom/noverify/blob/master/docs/getting_started.md Execute NoVerify with the 'assignOp' check enabled and apply automatic fixes to the identified issues. Rerunning the check afterward should show no errors for this specific check. ```bash noverify check --allow-checks='assignOp' ./lib ``` ```bash noverify check --allow-checks='assignOp' --fix ./lib ``` -------------------------------- ### Exclude files from checking Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md Index files for type inference without performing analysis on them. ```bash noverify check --index-only-files='./tests' ./ ``` -------------------------------- ### Potentially Not Safe Call to stream_set_read_buffer() Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt This warning indicates a potentially unsafe call to 'stream_set_read_buffer()'. Ensure the stream resource '$fp' is valid and the buffer size is appropriate. ```php stream_set_read_buffer($fp, 0); ``` -------------------------------- ### Potentially Not Safe Call to stream_set_write_buffer() Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt This warning indicates a potentially unsafe call to 'stream_set_write_buffer()'. Ensure the stream resource '$fp' is valid and the buffer size is appropriate. ```php stream_set_write_buffer($fp, 0); ``` -------------------------------- ### Undefined Property Access for '_template_settings' Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/underscore/golden.txt This error points to an 'undefinedProperty' issue when accessing '_template_settings'. Ensure this property is set before attempting to retrieve it. ```php $ts = $class_name::getInstance()->_template_settings; ``` -------------------------------- ### Run NoVerify check command Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md The base command structure for running NoVerify analysis on specific files or folders. ```bash noverify check --option1=xxx --option2=yyy ... [folder_or_file] [folder_or_file] ... ``` -------------------------------- ### Optimize String Emptiness Checks in PHP Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Recommends replacing `strlen(...)` checks for string emptiness with direct comparison to an empty string (`!== ""`). This is often more readable and potentially more efficient. ```php if (strlen($string)) { ... } ``` ```php if ($string !== "") { ... } ``` -------------------------------- ### Unsafe fclose with fopen Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt Calling `fclose` on a stream opened with `fopen` in this manner can be unsafe. Consider alternative resource management. ```php fclose(fopen("php://fd/" . $fd, 'r+')); ``` -------------------------------- ### Define a rule with expression or statement Source: https://github.com/vkcom/noverify/blob/master/docs/dynamic_rules.md Implement a rule using a PHPDoc severity attribute and a phpgrep pattern. ```php function strictCmp() { /** * @warning Non-strict string comparison (use ===) */ $x == $y; } ``` ```php function forLoop() { /** * @warning Potentially infinite 'for' loop */ for ($i = $start; $i < $length; $i--) { ${"*"};} } ``` -------------------------------- ### Detect empty switch statements Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Reports `switch` statements that have an empty body, suggesting they should contain at least one case. ```php switch ($a) {} ``` ```php switch ($a) { case 1: // do something break; } ``` -------------------------------- ### Optimize count comparisons in PHP Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Avoid comparing `count(...)` with `>= 0` as it's always true. Use `!= 0` for checking if a count is non-zero. ```php if (count($arr) >= 0) { ... } ``` ```php if (count($arr) != 0) { ... } ``` -------------------------------- ### Automatically Fix Issues Source: https://context7.com/vkcom/noverify/llms.txt Apply automatic fixes for supported issues. ```bash # Fix all auto-fixable issues noverify check --fix ./src # Fix only specific checks noverify check --allow-checks='assignOp' --fix ./lib # Example: Before fix # $compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children); # After fix # $compoundLevel ??= $this->getCompoundLevel($children); ``` -------------------------------- ### Modulo Assignment Rewrite Suggestion Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/idn/golden.txt Suggests rewriting a standard modulo operation assignment to a compound modulo assignment for conciseness. ```php $i = $i % $outputLength; ``` -------------------------------- ### Undefined Method Call Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt This error indicates a call to an undefined method 'run()' on an object of mixed type. Ensure the object has the 'run' method or that the type is correctly inferred. ```php $instance->run($req['params']); ``` -------------------------------- ### Enable strict-mixed mode Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md Activate strict checking for methods and properties accessed on variables with 'mixed' or 'object' types. This mode provides warnings for potentially undefined access. ```shell noverify check --strict-mixed ./src ``` -------------------------------- ### Apply floor function Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt Usage of floor on a variable that may not be null-safe. ```php $scale = (($scale > 1) ? floor($scale) : 1); ``` -------------------------------- ### PHP Switch Default Branch Warning Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/qrcode/golden.txt Warning for missing default branch in a switch statement. ```php switch ($mode) { ``` -------------------------------- ### Discouraged Use of exit() Function Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/phprocksyd/golden.txt This warning advises against using the 'exit()' function. Consider using alternatives like 'return' or throwing exceptions for better control flow and error handling. ```php exit(0); ``` ```php exit(1); ``` ```php exit(0); ``` -------------------------------- ### Correct catch order in PHP try-catch blocks Source: https://github.com/vkcom/noverify/blob/master/docs/checkers_doc.md Ensure that more specific exceptions are caught before more general ones in `try-catch` blocks to prevent dead code. ```php try { // Some code. } catch (Exception $e) { // This will catch both Exception and TimeoutException. } catch (TimeoutException $e) { // This is a dead code. } ``` ```php try { // Some code. } catch (TimeoutException $e) { // Ok, it can catch TimeoutException. } catch (Exception $e) { // Ok, it will catch everything else. } ``` -------------------------------- ### Specify Type Hint for Block Parameter in PHP Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/parsedown/golden.txt The 'array' type hint for the $Block parameter is too generic. Consider a more specific type if possible. ```php protected function blockTable($Line, array $Block = null) ``` ```php protected function blockTableContinue($Line, array $Block) ``` ```php protected function paragraphContinue($Line, array $Block) ``` -------------------------------- ### Apply Rules to Path Groups with @path-group Source: https://github.com/vkcom/noverify/blob/master/docs/dynamic_rules.md Apply rules to files matching paths defined in a named group using the `@path-group` tag. This can be combined with the `@path` tag for additional specificity. ```php /** * @path-group-name test * @path my/site/ads_ * @path your/site/bad */ _init_test_group_(); /** * @name varEval * @warning don't eval from variable * @path-group test * @path my/site/admin_ */ eval(${"var"}); ``` -------------------------------- ### Run NoVerify check on a directory Source: https://github.com/vkcom/noverify/blob/master/docs/getting_started.md Perform a basic NoVerify check on all files within the specified directory. NoVerify will also index the vendor folder for analysis. ```bash noverify check ./lib ``` -------------------------------- ### Assignment Operation Rewrite Suggestion Source: https://github.com/vkcom/noverify/blob/master/src/tests/golden/testdata/idn/golden.txt Suggests rewriting a standard addition assignment to a compound addition assignment for conciseness. Ensure type casting is handled correctly. ```php $n = $n + (int) ($i / $outputLength); ``` -------------------------------- ### Enable all checks Source: https://github.com/vkcom/noverify/blob/master/docs/configuration.md Enable all available checks, including those disabled by default. ```shell noverify check --allow-all-checks ./ ``` -------------------------------- ### Create noverify.sh Script for Diff Mode Source: https://github.com/vkcom/noverify/blob/master/docs/diff.md This script prepares Git commit ranges and executes NoVerify in diff mode. Ensure it's executable before running. ```bash #!/bin/sh # Preparing the beginning and end of the commits that will be analyzed commit_end=`git rev-parse --abbrev-ref HEAD` commit_begin=`git rev-parse -q --verify origin/$commit_end` if [ -z "$commit_begin" ]; then commit_begin=ORIGIN_MASTER fi # Call noverify noverify check\ --git=.git\ --git-commit-from=$commit_begin\ --git-commit-to=$commit_end\ --git-work-tree=. ```