The document discusses code analysis, specifically focusing on static and dynamic analysis methods for evaluating program correctness. It introduces PHPStan, a static analysis tool for PHP that offers various checks and enhancements to improve code quality, and outlines how to implement it in development workflows. Additionally, it emphasizes that while PHPStan aids in maintaining code quality, it should not replace testing procedures.
Introduction to PHPStan and an overview of code analysis, including definitions and structure.
Defines code analysis, differentiating between static and dynamic analysis methods.
Introduces terminology related to static analysis, covering naming conventions, code structure, and complexity.
Discusses security issues encountered during static code analysis, such as cryptography and cookie security.
Explains how PHPStan improves code correctness, describing error detection in PHP applications.Details on how to install, configure, and integrate PHPStan into a CI pipeline for effective code analysis.Final thoughts on PHPStan's role in testing and code analysis, along with additional resources for further learning.
Code analysis isthe process of testing and evaluating a program either statically or dynamically. Next slide
5.
Static Static code analysisis a method of evaluating a program by examining the source code before its execution. It is done by analyzing a set of code against a set of coding rules. Analysis Dynamic Dynamic analysis is the process of testing and evaluating a program — while software is running. It addresses the diagnosis and correction of bugs, memory issues, and crashes of a program during its execution. Analysis
Naming. Variables and methods’names, are they too short or too long? Do they follow a naming convention like camel-case? Type Hinting. Some tools can suggest a name consistent with the return type. For example a getFoo() method that returns a boolean better be named isFoo(). Lines of Code. Measures the line of codes in your class or method against a maximum value. In addition to the number of method's parameter or class' number of public methods and properties. Measurements STATIC ANALYSIS JARGONS
8.
Commented Code No commentedout block of code, as long as you are using a version control system, you can remove unused code and if needed, it's recoverable. Return Statements How many return statements do you have through out your method? Many return statements make it difficult to understand the method. Return Types Makes sure that return type matches the expected. Having many return types possibilities confuses the analyzers. Code Structure I STATIC ANALYSIS JARGONS
9.
Dedicated Exceptions Throw dedicatedexception instead of generic run-time exceptions that can be cached by client code. No Static Calls Avoid using static calls in your code and instead use dependency injection. Factory methods is the only exception. DRY Checks for code duplication either in repeating literal values or whole blocks of code. Code Structure II STATIC ANALYSIS JARGONS
10.
Complexity Having a lotof control structures in one method AKA the pyramid of doom. Possible fixes include: • Early return statements • Merging nested if statements in combination with helper functions that make the condition readable. STATIC ANALYSIS JARGONS
11.
Cipher Algorithms Using cryptographicsystems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. Cookies Always create sensitive cookies with the “secure” flag so it’s not sent over an unencrypted HTTP request. Dynamic Execution Some APIs allow the execution of dynamic code by providing it as strings at runtime. Most of the time their use is frowned upon as they also increase the risk of Injected Code Security Issues STATIC ANALYSIS JARGONS
PHPStan moves PHPcloser to compiled languages in the sense that the correctness of each line of the code can be checked before you run the actual line. PHPStan repository README.md
14.
2 157 191 203 212226 351 378 429 516 0 100 200 300 400 500 600 Level 0 Level 1 Level 2 Level 3 Level 4 Level 5 Level 6 Level 7 Level 8 Level 9 Errors Errors Detected in a Laravel App. WHAT DOES PHPSTAN BRING That has been analyzed with SonarQube since day one
15.
00 Basic Checks. Unknown classes,unknown functions, unknown methods called on $this, wrong number of arguments passed to those methods and functions, always undefined variables 01 $this Unknowns. Possibly undefined variables, unknown magic methods and properties on classes with __call and __get 02 Methods Unknown methods checked on all expressions (not just $this), validating PHPDocs Rule Levels WHAT DOES PHPSTAN BRING
16.
03 Types. Return types, typesassigned to properties. 04 Dead Code. Basic dead code checking - always false instanceof and other type checks, dead else branches, unreachable code after return; etc. 05 Arguments. Checking types of arguments passed to methods and functions. Rule Levels II WHAT DOES PHPSTAN BRING
17.
06 Type Hints. Reports missingtype hints. 07 Union Types. Reports partially wrong union types - if you call a method that only exists on some types in a union type, level 7 starts to report that. 08 Nullable Types. report calling methods and accessing properties on nullable types. Rule Levels III WHAT DOES PHPSTAN BRING
18.
09 Mixed Type Bestrict about the mixed type - the only allowed operation you can do with it is to pass it to another mixed WHAT DOES PHPSTAN BRING Rule Levels IV
Configuration File PHPStan usesconfiguration file, phpstan.neon or phpstan.neon.dist, that allows you to: HOW TO USE IT - Define the paths that will be analyzed. - Set the rule level. - Exclude paths. - Include PHPStan extensions. - Ignore errors. - Define the maximum number of parallel processes Config Reference
PHPDocs PHPDocs are essentialpart to PHPStan robust. PHP in its most recent versions introduced native type hints, but it still leaves a lot of room for PHPDocs to augment the information. HOW TO USE IT
25.
Properties and InlineVariables. PHPDocs can be written above class properties to denote their type, or in variable assignment as a last resort. Magic Properties. For custom __get/__set methods logic, a @property PHPDoc tag can be placed above a class. It can also define read/write access. Magic Methods. For custom __call methods logic, a @method PHPDoc tag can be placed above a class
26.
PHPDocs HOW TO USEIT PHPDocs Reference Combining PHPDoc types with native type hints
27.
The Baseline HOW TOUSE IT Introducing PHPStan to the CI pipeline, increasing strictness level or upgrading to a newer version can be overwhelming. PHPStan allows you to declare the currently reported list of errors as “the baseline” and stop reporting them in subsequent runs. It allows you to be interested in violations only in new and changed code.
28.
Generating the Baseline If youwant to export the current list of errors and use it as the baseline, run PHPStan with --generate-baseline option It generates the list of errors with the number of occurrences per file and saves it as phpstan-baseline.neon HOW TO USE IT
29.
Adding PHPStan to CIPipeline Adding PHPStan to the CI pipeline and running it regularly on merge requests and main branches will increase our code quality. In addition to helping in code review. HOW TO USE IT
Final Thoughts PHPStan andcode analysis in general is not a substitute for testing. PHP is moving in the direction of being more predictable and relaying less on magic.
32.
Helpful Links about PHPStanand Other Tools • PHPStan configuration reference • PHPDocs usage with PHPStan • PHPStan extensions library • List of analysis tools for different languages RESOURCES