### Install PHP Insights Source: https://github.com/nunomaduro/phpinsights/blob/master/README.md Install PHP Insights as a development dependency using Composer. ```bash composer require nunomaduro/phpinsights --dev ``` -------------------------------- ### Enable Insights in Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/README.md Configure which insights to enable or add by specifying them in the 'add' section of your configuration. This example shows how to enable the 'Fully Qualified ClassName In Annotation' insight. ```php 'add' => [ \NunoMaduro\PhpInsights\Domain\Metrics\Code\Comments::class => [ \SlevomatCodingStandard\Sniffs\Namespaces\FullyQualifiedClassNameInAnnotationSniff::class ] ] ``` -------------------------------- ### Configure Framework Preset Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/contribute.md Define a preset for a specific framework (e.g., Laravel) by specifying directories to exclude, insights to add, and insights to remove. This example configures exclusions, adds `ForbiddenFinalClasses`, and removes several sniffs. ```php final class Preset implements PresetContract { public static function getName(): string { return 'laravel'; } public static function get(): array { return [ 'exclude' => [ 'config', 'storage', 'resources', 'bootstrap', 'nova', 'database', 'server.php', '_ide_helper.php', '_ide_helper_models.php', 'public', ], 'add' => [ Classes::class => [ ForbiddenFinalClasses::class, ], ], 'remove' => [ AlphabeticallySortedUsesSniff::class, DeclareStrictTypesSniff::class, DisallowMixedTypeHintSniff::class, ForbiddenDefineFunctions::class, ForbiddenNormalClasses::class, ForbiddenTraits::class, TypeHintDeclarationSniff::class, ], 'config' => [ ForbiddenPrivateMethods::class => [ 'title' => 'The usage of private methods is not idiomatic in Laravel.', ], ForbiddenDefineGlobalConstants::class => [ 'ignore' => ['LARAVEL_START'], ], ForbiddenFunctionsSniff::class => [ 'forbiddenFunctions' => [ 'dd' => null, 'dump' => null, ], ], ], ]; } } ``` -------------------------------- ### Install PHPInsights with Composer Bin Plugin Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Use this command to isolate PHPInsights from other dependencies when encountering Composer conflicts. Ensure you have bamarni/composer-bin-plugin installed first. ```bash composer require --dev bamarni/composer-bin-plugin composer bin phpinsights require nunomaduro/phpinsights ./vendor/bin/phpinsights ``` -------------------------------- ### Configure Insight Parameters Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/README.md The 'config' section allows refining default insight configurations. For example, increase line length limits by setting 'lineLimit' and 'absoluteLineLimit'. ```php 'config' => [ \PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff::class => [ 'lineLimit' => 120, 'absoluteLineLimit' => 160 ] ] ``` -------------------------------- ### Default PHP Insights Configuration Structure Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/README.md This is the basic structure of the `phpinsights.php` configuration file. Use it as a starting point for your project's specific needs. ```php 'default', 'exclude' => [ // 'path/to/directory-or-file' ], 'add' => [ // ExampleMetric::class => [ // ExampleInsight::class, // ] ], 'remove' => [ // ExampleInsight::class, ], 'config' => [ // ExampleInsight::class => [ // 'key' => 'value', // ], ], ]; ``` -------------------------------- ### Create a New Insight Class Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/contribute.md Define a new Insight by extending the base Insight class and implementing `hasIssue` and `getTitle` methods. This example prohibits the use of `final` classes. ```php final class ForbiddenFinalClasses extends Insight { public function hasIssue(): bool { return (bool) count($this->collector->getConcreteFinalClasses()); } public function getTitle(): string { return 'The use of `final` classes is prohibited'; } } ``` -------------------------------- ### Add Insight from PHP CS Sniff Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/contribute.md Integrate an existing PHP CS Sniff as an Insight by referencing its class name in the `getInsights` method of the relevant Metric. This example adds `UnusedPropertySniff`. ```php final class Classes implements HasInsights { // ... public function getInsights(): array { return [ UnusedPropertySniff::class, ]; } } ``` -------------------------------- ### Exclude Insight from Specific Files Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/README.md Configure the 'exclude' parameter within an insight's configuration to disallow it on specific files. This example shows how to exclude the 'Unused Parameters' Insight. ```php 'config' => [ \SlevomatCodingStandard\Sniffs\Functions\UnusedParameterSniff::class => [ 'exclude' => [ 'src/Path/To/My/File.php', 'src/Path/To/Other/File.php', ], ], ], ``` -------------------------------- ### Nullable Type for Null Default Value Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Ensures the nullability symbol '?' is used for nullable and optional parameters with a default null value. This example shows a function with incorrect and correct parameter type hinting. ```php function foo( int $foo = null, // ? missing ?int $bar = null // correct ) { // ... } ``` -------------------------------- ### Unreachable Catch Block Example Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This code demonstrates an unreachable catch block, which is flagged by the DeadCatchSniff. The second catch block for InvalidArgumentException will never be reached because Throwable already catches all exceptions. ```php try { doStuff(); } catch (\Throwable $e) { log($e); } catch (\InvalidArgumentException $e) { // unreachable! } ``` -------------------------------- ### Configure Phpdoc Scalar Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Configure the PhpdocScalarFixer to standardize scalar type names in PHPDoc comments. This example specifies types like 'boolean', 'double', 'integer', 'real', and 'str' to be normalized. ```php \PhpCsFixer\Fixer\Phpdoc\PhpdocScalarFixer::class => [ 'types' => [ 'boolean', 'double', 'integer', 'real', 'str', ] ] ``` -------------------------------- ### Copy Default Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/configuration.md Copy the default configuration file to your project root. This is the general method for projects not using a specific framework. ```bash cp vendor/nunomaduro/phpinsights/stubs/config.php phpinsights.php ``` -------------------------------- ### Run PHP Insights with Docker Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Execute PHP Insights using Docker, mounting the current directory as a volume. ```bash docker run -it --rm -v "$(pwd):/app" nunomaduro/phpinsights ``` -------------------------------- ### Run PHP Insights Source: https://github.com/nunomaduro/phpinsights/blob/master/README.md Execute PHP Insights from the command line to analyze your project. ```bash ./vendor/bin/phpinsights ``` -------------------------------- ### Run PHP Insights Binary on Windows Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Execute the PHP Insights binary from your project's vendor directory. This command is used on Windows systems. ```bash # Windows .\vendor\bin\phpinsights.bat ``` -------------------------------- ### Analyse with Artisan (Laravel) Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md In a Laravel project, use the Artisan command to analyze a specific path. ```bash php artisan insights path/to/analyse ``` -------------------------------- ### Copy Symfony Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/configuration.md Copy the Symfony-specific configuration file to your project root. This sets up PHPInsights for a Symfony project. ```bash cp vendor/nunomaduro/phpinsights/stubs/symfony.php phpinsights.php ``` -------------------------------- ### Configure Ordered Imports Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the OrderedImportsFixer to define the order and sorting algorithm for 'use' statements. ```php \PhpCsFixer\Fixer\Import\OrderedImportsFixer::class => [ 'imports_order' => ['class', 'const', 'function'], 'sort_algorithm' => 'alpha', // possible values ['alpha', 'length', 'none'] ] ``` -------------------------------- ### Format Output Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Use the `format` flag to change the output to supported formats like console, json, or checkstyle. ```bash ./vendor/bin/phpinsights analyse --format=json ``` -------------------------------- ### Run PHP Insights Binary Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Execute the PHP Insights binary from your project's vendor directory. This command is used on Mac and Linux systems. ```bash # Mac & Linux ./vendor/bin/phpinsights ``` -------------------------------- ### Configure Return Type Hint Spacing Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Set the number of spaces before the colon for return type hints. This configuration is part of the ReturnTypeHintSpacingSniff. ```php \SlevomatCodingStandard\Sniffs\TypeHints\ReturnTypeHintSpacingSniff::class => [ 'spacesCountBeforeColon' => 0, ] ``` -------------------------------- ### Custom IDE URL Template Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/ide.md For unsupported IDEs, configure a URL template with '%f' for file path and '%l' for line number. This allows PhpInsights to generate custom links. ```php 'myide://open?url=file://%f&line=%l', // ... ]; ``` -------------------------------- ### Analyse Multiple Paths with Artisan (Laravel) Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md In a Laravel project, use the Artisan command with multiple paths to analyze directories and files together. ```bash php artisan insights path/to/dir path/to/file.php ``` -------------------------------- ### Analyse a Directory Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Use this command to analyze a specific directory. Ensure you are in the project root. ```bash ./vendor/bin/phpinsights analyse path/to/analyse ``` -------------------------------- ### Display All Issues Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Use the `-v` option to display all issues per Insight, instead of the default of the first 3. ```bash ./vendor/bin/phpinsights -v ``` -------------------------------- ### Save Output to File Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Pipe the analysis results to a file, commonly used with JSON format. Remember to use the no interaction flag `-n` when piping. ```bash ./vendor/bin/phpinsights analyse --format=json > test.json ``` -------------------------------- ### Analyse a File Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Use this command to analyze a specific PHP file. Ensure you are in the project root. ```bash ./vendor/bin/phpinsights analyse path/to/analyse.php ``` -------------------------------- ### Configure Use Spacing Sniff Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the number of lines before the first use, between use types, and after the last use statement. ```php \SlevomatCodingStandard\Sniffs\Namespaces\UseSpacingSniff::class => [ 'linesCountBeforeFirstUse' => 1, 'linesCountBetweenUseTypes' => 0, 'linesCountAfterLastUse' => 1, ] ``` -------------------------------- ### Configure IDE Link in phpinsights.php Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/ide.md Set the 'ide' configuration option in your phpinsights.php file to specify your IDE. This enables clickable links in the PhpInsights output. ```php 'vscode', // ... ]; ``` -------------------------------- ### Register Lumen Service Provider and Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Register the PHP Insights Service Provider and configure insights within the `bootstrap/app.php` file for Lumen projects. ```php $app->register(\NunoMaduro\PhpInsights\Application\Adapters\Laravel\InsightsServiceProvider::class); $app->configure('insights'); ``` -------------------------------- ### Configure Function Length (ObjectCalisthenics) Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/architecture.md Configure the maximum length for functions using the ObjectCalisthenics sniff. Set the 'maxLength' parameter to define the limit. ```php \ObjectCalisthenics\Sniffs\Files\FunctionLengthSniff::class => [ 'maxLength' => 20, ] ``` -------------------------------- ### Run PHP Insights with Quality Thresholds Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/continuous-integration.md Execute PHP Insights in CI with specific minimum quality, complexity, architecture, and style thresholds. The `--no-interaction` flag is mandatory for CI. ```bash ./vendor/bin/phpinsights --no-interaction --min-quality=80 --min-complexity=90 --min-architecture=75 --min-style=95 ``` ```bash php artisan insights --no-interaction --min-quality=80 --min-complexity=90 --min-architecture=75 --min-style=95 ``` -------------------------------- ### Publish Laravel Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/README.md Publish the configuration file for PHP Insights when using it with Laravel. ```bash php artisan vendor:publish --provider="NunoMaduro\PhpInsights\Application\Adapters\Laravel\InsightsServiceProvider" ``` -------------------------------- ### Configure Element Name Minimal Length Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Configure the minimum length for element names and allowed short names for the ElementNameMinimalLengthSniff. ```php \ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class => [ 'minLength' => 3, 'allowedShortNames' => ['i', 'id', 'to', 'up'], ] ``` -------------------------------- ### Configure Line Length Sniff Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure line length limits and comments ignoring. This configuration applies to the LineLengthSniff. ```php \PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff::class => [ 'lineLimit' => 80, 'absoluteLineLimit' => 100, 'ignoreComments' => false, ] ``` -------------------------------- ### Configure No Mixed Echo Print Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This fixer enforces the use of either 'echo' or 'print' for language constructs. Specify the preferred construct in the configuration. ```php \PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class => [ 'use' => 'echo' // possibles values ['echo', 'print'] ] ``` -------------------------------- ### Configure Function Length (SlevomatCodingStandard) Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/architecture.md Configure the maximum line length for functions using the SlevomatCodingStandard sniff. Set the 'maxLinesLength' parameter to define the limit. ```php \SlevomatCodingStandard\Sniffs\Functions\FunctionLengthSniff::class => [ 'maxLinesLength' => 20, ] ``` -------------------------------- ### Specify Composer File Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Use the `composer` flag to specify a custom composer file path for analysis. ```bash ./vendor/bin/phpinsights analyse --composer=/var/www/composer.json ``` -------------------------------- ### Copy Magento2 Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/configuration.md Copy the Magento2-specific configuration file to your project root. This configures PHPInsights for a Magento2 project. ```bash cp vendor/nunomaduro/phpinsights/stubs/magento2.php phpinsights.php ``` -------------------------------- ### Configure No Extra Blank Lines Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the NoExtraBlankLinesFixer to remove extra blank lines based on specified tokens. Possible values for tokens include 'break', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'switch', 'throw', 'use', 'use_trait'. ```php \PhpCsFixer\Fixer\Whitespace\NoExtraBlankLinesFixer::class => [ 'tokens' => ['extra'], // possibles values ['break', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'switch', 'throw', 'use', 'use_trait'] ] ``` -------------------------------- ### Copy Lumen Configuration Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Manually copy the PHP Insights configuration file into your Lumen project's config directory. ```bash cp vendor/nunomaduro/phpinsights/stubs/laravel.php config/insights.php ``` -------------------------------- ### Configure Namespace Spacing Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Set the number of lines before and after a namespace declaration. This configuration applies to the `NamespaceSpacingSniff`. ```php \SlevomatCodingStandard\Sniffs\Namespaces\NamespaceSpacingSniff::class => [ 'linesCountBeforeNamespace' => 1, 'linesCountAfterNamespace' => 1, ] ``` -------------------------------- ### Run PHP Insights in Laravel Source: https://github.com/nunomaduro/phpinsights/blob/master/README.md Execute PHP Insights using the Artisan command in a Laravel project. ```bash php artisan insights ``` -------------------------------- ### Analyse Multiple Files Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Provide multiple file paths to the analyse command to check several files simultaneously. ```bash ./vendor/bin/phpinsights analyse path/to/file1.php path/to/file2.php ``` -------------------------------- ### Analyse Multiple Directories Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Provide multiple directory paths to the analyse command to check several directories at once. ```bash ./vendor/bin/phpinsights analyse path/to/dir1 path/to/dir2 ``` -------------------------------- ### Configure Switch Statement Indentation Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md This snippet shows how to configure the indentation for switch statements using the SwitchDeclarationSniff. Set the 'indent' value to the desired number of spaces. ```php \PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\SwitchDeclarationSniff::class => [ 'indent' => 4, ] ``` -------------------------------- ### Configure Max Method Cyclomatic Complexity Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/complexity.md Set the maximum allowed cyclomatic complexity for individual methods. Lower scores indicate easier-to-understand code. ```php \NunoMaduro\PhpInsights\Domain\Insights\MethodCyclomaticComplexityIsHigh::class => [ 'maxMethodComplexity' => 5, ] ``` -------------------------------- ### Configure Max Nesting Level Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Configure the maximum allowed nesting level for the MaxNestingLevelSniff. ```php \ObjectCalisthenics\Sniffs\Metrics\MaxNestingLevelSniff::class => [ 'maxNestingLevel' => 2, ] ``` -------------------------------- ### Configure Single Class Element Per Statement Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the SingleClassElementPerStatementFixer to specify which elements (constants, properties) should each be declared on a new statement. ```php \PhpCsFixer\Fixer\ClassNotation\SingleClassElementPerStatementFixer::class => [ 'elements' => [ 'const', 'property', ], ] ``` -------------------------------- ### Configure Array Indentation Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Configure the array indentation level for the ArrayIndentSniff. Defaults to 4 spaces. ```php \PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\ArrayIndentSniff::class => [ 'indent' => 4, ] ``` -------------------------------- ### Configure Indentation for Fixers Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/README.md For insights implementing 'WhitespacesAwareFixerInterface' (from PHP-CS-Fixer), you can configure the indentation to respect using the 'indent' parameter. ```php 'configure' => [ \PhpCsFixer\Fixer\Basic\BracesFixer::class => [ 'indent' => ' ', ], ], ``` -------------------------------- ### Configure Braces Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the `BracesFixer` to enforce brace placement and indentation rules. Options include `allow_single_line_closure` and `position_after_anonymous_constructs`, `position_after_control_structures`, `position_after_functions_and_oop_constructs`. ```php \PhpCsFixer\Fixer\Basic\BracesFixer::class => [ 'allow_single_line_closure' => false, 'position_after_anonymous_constructs' => 'same', // possible values ['same', 'next'] 'position_after_control_structures' => 'same', // possible values ['same', 'next'] 'position_after_functions_and_oop_constructs' => 'same', // possible values ['same', 'next'] ] ``` -------------------------------- ### Configure Declare Equal Normalize Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This snippet shows how to configure the DeclareEqualNormalizeFixer to normalize spacing around the equal sign in declare statements. You can set the 'space' option to 'none' or 'single'. ```php \PhpCsFixer\Fixer\LanguageConstruct\DeclareEqualNormalizeFixer::class => [ 'space' => 'none', // possible values ['none', 'single'] ] ``` -------------------------------- ### Configure Method Per Class Limit Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/architecture.md Define the maximum number of methods allowed within a single class. This configuration is used by the MethodPerClassLimitSniff. ```php \ObjectCalisthenics\Sniffs\Metrics\MethodPerClassLimitSniff::class => [ 'maxCount' => 10, ] ``` -------------------------------- ### Configure No Spaces Around Offset Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the NoSpacesAroundOffsetFixer to enforce rules about spaces around offset braces. The 'positions' can be set to 'inside', 'outside', or both. ```php \PhpCsFixer\Fixer\Whitespace\NoSpacesAroundOffsetFixer::class => [ 'positions' => ['inside', 'outside'], ] ``` -------------------------------- ### Configure Binary Operator Spacing Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure how binary operators are spaced. This fixer ensures consistent spacing around operators like '=>' and '='. ```php \PhpCsFixer\Fixer\Operator\BinaryOperatorSpacesFixer::class => [ 'align_double_arrow' => false, // Whether to apply, remove or ignore double arrows alignment: possibles values [true, false, null] 'align_equals' => false, // Whether to apply, remove or ignore equals alignment: possibles values [true, false, null] 'default' => 'single_space', // default fix strategy: possibles values ['align', 'align_single_space', 'align_single_space_minimal', 'single_space', 'no_space', null] ] ``` -------------------------------- ### Configure Max Average Class Method Cyclomatic Complexity Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/complexity.md Set the maximum allowed average cyclomatic complexity for class methods. Lower scores indicate easier-to-understand code. ```php \NunoMaduro\PhpInsights\Domain\Insights\ClassMethodAverageCyclomaticComplexityIsHigh::class => [ 'maxClassMethodAverageComplexity' => 5.0, ] ``` -------------------------------- ### Configure Spread Operator Spacing Sniff Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the number of spaces required after the spread operator (...). ```php \SlevomatCodingStandard\Sniffs\Operators\SpreadOperatorSpacingSniff::class => [ 'spacesCountAfterOperator' => 0, ] ``` -------------------------------- ### Configure Property Per Class Limit Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/architecture.md Set the maximum number of properties allowed within a single class. This configuration is managed by the PropertyPerClassLimitSniff. ```php \ObjectCalisthenics\Sniffs\Metrics\PropertyPerClassLimitSniff::class => [ 'maxCount' => 10, ] ``` -------------------------------- ### Configure Class Trait and Interface Length Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/architecture.md Set the maximum allowed lines for classes, traits, and interfaces. This configuration is applied to the ClassTraitAndInterfaceLengthSniff. ```php \ObjectCalisthenics\Sniffs\Files\ClassTraitAndInterfaceLengthSniff::class => [ 'maxLength' => 200, ] ``` -------------------------------- ### Fix Errors Automatically with Artisan and --fix Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md In a Laravel project, use the Artisan command with the --fix option to automatically fix issues. ```bash php artisan insights path/to/analyse --fix ``` -------------------------------- ### Configure Unused Use Statements Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Customize the `UnusedUsesSniff` to ignore specific annotations. Configure whether to search within annotations and provide lists of ignored annotation names. ```php \SlevomatCodingStandard\Sniffs\Namespaces\UnusedUsesSniff::class => [ 'searchAnnotations' => false, 'ignoredAnnotationNames' => [], // case sensitive list of annotation names that the sniff should ignore (only the name is ignored, annotation content is still searched). Useful for name collisions like @testCase annotation and TestCase class. 'ignoredAnnotations' => [], // case sensitive list of annotation names that the sniff ignore completely (both name and content are ignored). Useful for name collisions like @group Cache annotation and Cache class ] ``` -------------------------------- ### Configure Doc Comment Spacing Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure spacing rules for doc comments, including lines before/after content, between description and annotations, and between annotation types. This uses the DocCommentSpacingSniff. ```php \SlevomatCodingStandard\Sniffs\Commenting\DocCommentSpacingSniff::class => [ 'linesCountBeforeFirstContent' => 0, 'linesCountBetweenDescriptionAndAnnotations' => 1, 'linesCountBetweenDifferentAnnotationsTypes' => 0, 'linesCountBetweenAnnotationsGroups' => 1, 'linesCountAfterLastContent' => 0, 'annotationsGroups' => [], ] ``` -------------------------------- ### Configure Superfluous Whitespace Sniff Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the SuperfluousWhitespaceSniff to ignore blank lines. This helps in maintaining consistent whitespace across the codebase. ```php \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\SuperfluousWhitespaceSniff::class => [ 'ignoreBlankLines' => false, ] ``` -------------------------------- ### Configure Max Class Cyclomatic Complexity Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/complexity.md Set the maximum allowed cyclomatic complexity for each class. Lower scores indicate easier-to-understand code. ```php \NunoMaduro\PhpInsights\Domain\Insights\CyclomaticComplexityIsHigh::class => [ 'maxComplexity' => 5, ] ``` -------------------------------- ### Fix Errors Automatically (Standalone) Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Launch the fix command directly to fix issues in a specified directory. ```bash vendor/bin/phpinsights fix path/to/analyse ``` -------------------------------- ### Analyse Combined Paths Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Combine directory and file paths in a single analyse command to check a mix of targets. ```bash ./vendor/bin/phpinsights analyse path/to/dir path/to/file.php ``` -------------------------------- ### Configure No Break Comment Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Configure the NoBreakCommentFixer to enforce a specific comment text for intentional fall-through in non-empty case bodies. ```php \PhpCsFixer\Fixer\ControlStructure\NoBreakCommentFixer::class => [ 'comment_text' => 'no break', ] ``` -------------------------------- ### Configure Diff Context in PHPInsights Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Customize the diff output context by setting the 'diff_context' parameter in your phpinsights.php configuration file. This provides more lines of context around changes. ```php 3, // ... ]; ``` -------------------------------- ### Increase Memory Limit Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Workaround for 'Allowed memory size exhausted' errors by increasing the PHP memory limit. ```bash php -d memory_limit=2000M ./vendor/bin/phpinsights ``` -------------------------------- ### Configure No Whitespace Before Comma in Array Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the `NoWhitespaceBeforeCommaInArrayFixer` to control whitespace before commas in array declarations. Set `after_heredoc` to false to remove whitespace between heredoc end and comma. ```php \PhpCsFixer\Fixer\ArrayNotation\NoWhitespaceBeforeCommaInArrayFixer::class => [ 'after_heredoc' => false, // Whether the whitespace between heredoc end and comma should be removed. ] ``` -------------------------------- ### Configure Align Multiline Comment Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md This snippet shows how to configure the AlignMultilineCommentFixer. You can specify the type of comments to apply the rule to. ```php \PhpCsFixer\Fixer\Phpdoc\AlignMultilineCommentFixer::class => [ 'comment_type' => 'phpdocs_only' // possible values ['phpdocs_only', 'phpdocs_like', 'all_multiline'] ] ``` -------------------------------- ### Configure Class Definition Whitespace Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the ClassDefinitionFixer to enforce specific whitespace rules around class, trait, or interface definitions. Adjust multi-line extends, single item, and single line settings. ```php \PhpCsFixer\Fixer\ClassNotation\ClassDefinitionFixer::class => [ 'multi_line_extends_each_single_line' => false, 'single_item_single_line' => false, 'single_line' => false, ] ``` -------------------------------- ### Configure Function Declaration Spacing Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the spacing for function declarations, specifically for closures. This fixer ensures consistent spacing around function declarations. ```php \PhpCsFixer\Fixer\FunctionNotation\FunctionDeclarationFixer::class => [ 'closure_function_spacing' => 'one' // possible values ['one', 'none'] ] ``` -------------------------------- ### Configure Scope Closing Brace Indentation Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Set the indentation for scope closing braces. This configuration applies to the ScopeClosingBraceSniff. ```php \PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ScopeClosingBraceSniff::class => [ 'indent' => 4, ] ``` -------------------------------- ### Configure No Unneeded Control Parentheses Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This fixer removes unnecessary parentheses around control statements. Configure which statements should have their parentheses removed. ```php \PhpCsFixer\Fixer\ControlStructure\NoUnneededControlParenthesesFixer::class => [ 'statements' => [ 'break', 'clone', 'continue', 'echo_print', 'return', 'switch_case', 'yield', ], ] ``` -------------------------------- ### Configure Ordered Class Elements Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md This snippet shows how to configure the OrderedClassElementsFixer to define the order of elements within classes, interfaces, and traits. You can specify the sorting algorithm as well. ```php \PhpCsFixer\Fixer\ClassNotation\OrderedClassElementsFixer::class => [ 'order' => [ 'use_trait', 'constant_public', 'constant_protected', 'constant_private', 'property_public', 'property_protected', 'property_private', 'construct', 'destruct', 'magic', 'phpunit', 'method_public', 'method_protected', 'method_private', ], 'sort_algorithm' => 'none' ] ``` -------------------------------- ### Configure Single Quote Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md This snippet demonstrates the configuration for the SingleQuoteFixer. It allows you to control whether strings containing single quote characters should be converted to single quotes. ```php \PhpCsFixer\Fixer\StringNotation\SingleQuoteFixer::class => [ 'strings_containing_single_quote_chars' => false, ] ``` -------------------------------- ### Configure Method Argument Space Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/architecture.md Configure the MethodArgumentSpaceFixer to control spacing around commas in method arguments and calls. Useful for enforcing consistent formatting across multi-line argument lists. ```php \PhpCsFixer\Fixer\FunctionNotation\MethodArgumentSpaceFixer::class => [ 'after_heredoc' => false, 'ensure_fully_multiline' => false, 'keep_multiple_spaces_after_comma' => false, 'on_multiline' => 'ignore' // possible values ['ignore', 'ensure_single_line', 'ensure_fully_multiline'] ] ``` -------------------------------- ### Warn About TODO Comments Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This sniff identifies and warns about the presence of TODO comments within the code. ```php PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting\TodoSniff ``` -------------------------------- ### Configure Line Endings Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the expected end-of-line character for files. This is useful for maintaining consistent line endings across different operating systems. ```php \PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineEndingsSniff::class => [ 'eolChar' => '\n', ] ``` -------------------------------- ### Tag New Version Source: https://github.com/nunomaduro/phpinsights/blob/master/RELEASE.md Tags the current commit with the new version number and pushes the tag to the remote repository. This marks the release point in the Git history. ```bash git tag {new_version} git push --tags ``` -------------------------------- ### Configure Visibility Required Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md Configures the VisibilityRequiredFixer to enforce visibility declarations on specified class elements. Ensure abstract, final, and static keywords are correctly placed relative to visibility. ```php \PhpCsFixer\Fixer\ClassNotation\VisibilityRequiredFixer::class => [ 'elements' => [ 'property', 'method', ], ] ``` -------------------------------- ### Configure Forbidden Comments Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This sniff allows configuration of forbidden comment patterns. It's recommended to forbid generated or inappropriate messages. The configuration is entirely up to the user. ```php SlevomatCodingStandard\Sniffs\Commenting\ForbiddenCommentsSniff::class => [ 'forbiddenCommentPatterns' => [] ] ``` -------------------------------- ### PHP Insights GitHub Action Workflow Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/continuous-integration.md Integrate PHP Insights into a GitHub Actions workflow to automatically add annotations for issues in pull requests. Requires checkout and setup-php actions. ```yaml #.github/workflows/pr.yml name: CI on: - pull_request jobs: phpinsights: runs-on: ubuntu-latest name: PHP Insights checks steps: - uses: actions/checkout@v2 - uses: shivammathur/setup-php@v2 with: php-version: 8.0 - run: composer install --prefer-dist --no-progress --no-suggest - run: vendor/bin/phpinsights -n --ansi --format=github-action ``` -------------------------------- ### Flush PHPInsights Cache Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Add the --flush-cache flag to your analysis command to completely clear the cached results before running an analysis. This is useful if you suspect cache invalidation issues. ```bash ./vendor/bin/phpinsights --flush-cache ``` -------------------------------- ### Configure Object Operator Indent Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Set the indentation for object operators. This configuration applies to the ObjectOperatorIndentSniff. ```php \PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ObjectOperatorIndentSniff::class => [ 'indent' => 4, ] ``` -------------------------------- ### Commit Version Bump Source: https://github.com/nunomaduro/phpinsights/blob/master/RELEASE.md Commits the updated version number in `src/Domain/Kernel.php`, `docs/package.json`, and `CHANGELOG.md`. Use this command after updating the version numbers in these files. ```bash git commit -m "Bump version to {new_version}" ``` -------------------------------- ### Detect Useless Variable Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This insight class detects the usage of useless variables. -------------------------------- ### Fix Errors Automatically with --fix Option Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/get-started.md Add the --fix option to the analyse command to automatically fix issues. This provides classical output with a summary of fixed issues. ```bash vendor/bin/phpinsights analyse path/to/analyse --fix ``` -------------------------------- ### Clear Local Repository Source: https://github.com/nunomaduro/phpinsights/blob/master/RELEASE.md Clears the local repository by staging all changes, resetting them, and checking out the master branch. This ensures a clean state before proceeding with the release. ```bash git add . git reset --hard git checkout master ``` -------------------------------- ### Attach Insight to a Metric Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/contribute.md Register a custom Insight within a Metric class by adding its class name to the `getInsights` method. This ensures the insight is collected and checked. ```php final class Classes implements HasInsights { // ... public function getInsights(): array { return [ ForbiddenFinalClasses::class, ]; } } ``` -------------------------------- ### Warn About FIXME Comments Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/code.md This sniff identifies and warns about the presence of FIXME comments within the code. ```php PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting\FixmeSniff ``` -------------------------------- ### Configure Cast Spaces Fixer Source: https://github.com/nunomaduro/phpinsights/blob/master/docs/insights/style.md Configure the CastSpacesFixer to enforce single or no space between cast and variable. This is useful for maintaining consistent code style. ```php namespace App\Insights\Style; use \PhpCsFixer\Fixer\CastNotation\CastSpacesFixer; return [ CastSpacesFixer::class => [ 'space' => 'single' // possible values ['single', 'none'] ] ]; ```