SlideShare a Scribd company logo
PHPStan
Muhammad Shehata
SWE @robustastudio
What is Code Analysis
Static Analysis Jargons
How to Use It
Final Thoughts
What Does PHPStan Bring?
Resources
What is
Code Analysis
Code analysis is the process of
testing and evaluating a
program either statically or
dynamically.
Next slide
Static
Static code analysis is 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
Static Analysis
Jargons
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
Commented Code
No commented out 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
Dedicated Exceptions
Throw dedicated exception 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
Complexity
Having a lot of 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
Cipher Algorithms
Using cryptographic systems
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
What Does
PHPStan Bring?
PHPStan moves PHP closer 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
2
157
191 203 212 226
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
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
03
Types.
Return types, types assigned 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
06
Type Hints.
Reports missing type 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
09 Mixed Type
Be strict 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
How to Use It?
Installation
HOW TO USE IT
Configuration File
PHPStan uses configuration 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
Ignoring Errors: Inline
HOW TO USE IT
Ignoring Errors: Config
HOW TO USE IT
PHPDocs
PHPDocs are essential part 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
Properties and Inline Variables.
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
PHPDocs
HOW TO USE IT
PHPDocs Reference
Combining PHPDoc types with native type hints
The Baseline
HOW TO USE 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.
Generating the
Baseline
If you want 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
Adding PHPStan to
CI Pipeline
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
Final
Thoughts
 PHPStan and code analysis in
general is not a substitute for
testing.
 PHP is moving in the direction of
being more predictable and
relaying less on magic.
Helpful Links about
PHPStan and Other Tools
• PHPStan configuration reference
• PHPDocs usage with PHPStan
• PHPStan extensions library
• List of analysis tools for different languages
RESOURCES
Thank You
Ad

More Related Content

What's hot (20)

Cryptography
CryptographyCryptography
Cryptography
Abhi Prithi
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Unit testing
Unit testingUnit testing
Unit testing
Pooya Sagharchiha
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Software testing ppt
Software testing pptSoftware testing ppt
Software testing ppt
Heritage Institute Of Tech,India
 
Test Complete
Test CompleteTest Complete
Test Complete
RomSoft SRL
 
Functional Testing
Functional TestingFunctional Testing
Functional Testing
Precise Testing Solution
 
What is Integration Testing? | Edureka
What is Integration Testing? | EdurekaWhat is Integration Testing? | Edureka
What is Integration Testing? | Edureka
Edureka!
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
Training on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan SanidhyaTraining on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan Sanidhya
Shravan Sanidhya
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
Elizabeth alexander
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
Niyas Nazar
 
Java security
Java securityJava security
Java security
Ankush Kumar
 
Jdk,jre,jvm
Jdk,jre,jvmJdk,jre,jvm
Jdk,jre,jvm
Kritika Goel
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
Abhilash Nair
 
Code coverage
Code coverageCode coverage
Code coverage
Return on Intelligence
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Unit testing
Unit testingUnit testing
Unit testing
Slideshare
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
What is Integration Testing? | Edureka
What is Integration Testing? | EdurekaWhat is Integration Testing? | Edureka
What is Integration Testing? | Edureka
Edureka!
 
Training on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan SanidhyaTraining on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan Sanidhya
Shravan Sanidhya
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
Niyas Nazar
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
Abhilash Nair
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 

Similar to Using PHPStan with Laravel App (20)

PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...
apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...
apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...
apidays
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Engineering Software Lab
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
Refactoring legacy code driven by tests - ITA
Refactoring legacy code driven by tests -  ITARefactoring legacy code driven by tests -  ITA
Refactoring legacy code driven by tests - ITA
Luca Minudel
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
Chandra Sekhar Saripaka
 
PHP Industrialization
PHP IndustrializationPHP Industrialization
PHP Industrialization
Damien Seguy
 
DEFCON 21: EDS: Exploitation Detection System Slides
DEFCON 21: EDS: Exploitation Detection System SlidesDEFCON 21: EDS: Exploitation Detection System Slides
DEFCON 21: EDS: Exploitation Detection System Slides
Amr Thabet
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
Web application security
Web application securityWeb application security
Web application security
salissal
 
Code review
Code reviewCode review
Code review
Abhishek Sur
 
Java basics
Java basicsJava basics
Java basics
Jitender Jain
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
Mohmad Feroz
 
Php manish
Php manishPhp manish
Php manish
Manish Jain
 
Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurance
Philip Johnson
 
Detection of vulnerabilities in programs with the help of code analyzers
Detection of vulnerabilities in programs with the help of code analyzersDetection of vulnerabilities in programs with the help of code analyzers
Detection of vulnerabilities in programs with the help of code analyzers
PVS-Studio
 
Listen and look at your PHP code
Listen and look at your PHP codeListen and look at your PHP code
Listen and look at your PHP code
Gabriele Santini
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
Colin O'Dell
 
Php 7 crash course
Php 7 crash coursePhp 7 crash course
Php 7 crash course
Khaireddine Hamdi
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...
apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...
apidays LIVE Paris 2021 - Inside API delivery Pipeline, the checklist! - Fran...
apidays
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Engineering Software Lab
 
Refactoring legacy code driven by tests - ITA
Refactoring legacy code driven by tests -  ITARefactoring legacy code driven by tests -  ITA
Refactoring legacy code driven by tests - ITA
Luca Minudel
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
Chandra Sekhar Saripaka
 
PHP Industrialization
PHP IndustrializationPHP Industrialization
PHP Industrialization
Damien Seguy
 
DEFCON 21: EDS: Exploitation Detection System Slides
DEFCON 21: EDS: Exploitation Detection System SlidesDEFCON 21: EDS: Exploitation Detection System Slides
DEFCON 21: EDS: Exploitation Detection System Slides
Amr Thabet
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
Web application security
Web application securityWeb application security
Web application security
salissal
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
Mohmad Feroz
 
Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurance
Philip Johnson
 
Detection of vulnerabilities in programs with the help of code analyzers
Detection of vulnerabilities in programs with the help of code analyzersDetection of vulnerabilities in programs with the help of code analyzers
Detection of vulnerabilities in programs with the help of code analyzers
PVS-Studio
 
Listen and look at your PHP code
Listen and look at your PHP codeListen and look at your PHP code
Listen and look at your PHP code
Gabriele Santini
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
Colin O'Dell
 
Ad

Recently uploaded (20)

Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Odoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education ProcessOdoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education Process
iVenture Team LLP
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
saimabibi60507
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Top 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdfTop 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdf
AffinityCore
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Odoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education ProcessOdoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education Process
iVenture Team LLP
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]
saimabibi60507
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Top 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdfTop 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdf
AffinityCore
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Ad

Using PHPStan with Laravel App

  • 2. What is Code Analysis Static Analysis Jargons How to Use It Final Thoughts What Does PHPStan Bring? Resources
  • 4. Code analysis is the process of testing and evaluating a program either statically or dynamically. Next slide
  • 5. Static Static code analysis is 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
  • 7. 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 commented out 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 dedicated exception 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 lot of 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 cryptographic systems 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
  • 13. PHPStan moves PHP closer 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 212 226 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, types assigned 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 missing type 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 Be strict 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
  • 19. How to Use It?
  • 21. Configuration File PHPStan uses configuration 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
  • 24. PHPDocs PHPDocs are essential part 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 Inline Variables. 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 USE IT PHPDocs Reference Combining PHPDoc types with native type hints
  • 27. The Baseline HOW TO USE 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 you want 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 CI Pipeline 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
  • 31. Final Thoughts  PHPStan and code 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 PHPStan and Other Tools • PHPStan configuration reference • PHPDocs usage with PHPStan • PHPStan extensions library • List of analysis tools for different languages RESOURCES