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

Recommended

PPTX
iOS-Application-Security-iAmPr3m
Prem Kumar (OSCP)
 
PDF
Orquestando microservicios como lo hace Netflix
Paradigma Digital
 
PDF
Intro to UIKit • Made by Many
kenatmxm
 
PPTX
Secret Management with Hashicorp Vault and Consul on Kubernetes
An Nguyen
 
PPTX
Security misconfiguration
Jiri Danihelka
 
PPTX
DevSecOps : an Introduction
Prashanth B. P.
 
PDF
iOS Application Penetration Testing
n|u - The Open Security Community
 
PPTX
Hacking and securing ios applications
Satish b
 
PPTX
Docker Networking Tip - Macvlan driver
Sreenivas Makam
 
PDF
Firmware Extraction & Fuzzing - Jatan Raval
NSConclave
 
PPTX
ASP.NET Core: The best of the new bits
Ken Cenerelli
 
PDF
API Security Best Practices & Guidelines
Prabath Siriwardena
 
PDF
DNS High-Availability Tools - Open-Source Load Balancing Solutions
Men and Mice
 
PPTX
ArcherySec 2.0 @ BlackHat Arsenal Europe 2020
Anand Tiwari
 
PPTX
Introduccion a Ansible
Osvaldo
 
PDF
Introduction à l’intégration continue avec Jenkins
Eric Hogue
 
PDF
Introduction to DevOps slides.pdf
BoreVishnusai
 
PDF
Kubernetes in 30 minutes (2017/03/10)
lestrrat
 
PPTX
Firebase PPT
JATIN GUPTA
 
PPTX
Linux privilege escalation 101
Rashid feroz
 
PPTX
Using Wildcards with rsyslog's File Monitor imfile
Rainer Gerhards
 
PDF
BEEVA | Introducción a Docker
BEEVA_es
 
PDF
Jenkins with SonarQube
Somkiat Puisungnoen
 
PDF
Les concepts fondamentaux de DITA
Peccatte
 
PDF
A Hands-On Introduction To Docker Containers.pdf
Edith Puclla
 
PDF
Enhancing Network and Runtime Security with Cilium and Tetragon by Raymond De...
ContainerDay Security 2023
 
PDF
Docker slides
Jyotsna Raghuraman
 
PDF
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
PDF
Static Analysis of PHP Code – IPC Berlin 2016
Rouven Weßling
 

More Related Content

What's hot (20)

PPTX
Docker Networking Tip - Macvlan driver
Sreenivas Makam
 
PDF
Firmware Extraction & Fuzzing - Jatan Raval
NSConclave
 
PPTX
ASP.NET Core: The best of the new bits
Ken Cenerelli
 
PDF
API Security Best Practices & Guidelines
Prabath Siriwardena
 
PDF
DNS High-Availability Tools - Open-Source Load Balancing Solutions
Men and Mice
 
PPTX
ArcherySec 2.0 @ BlackHat Arsenal Europe 2020
Anand Tiwari
 
PPTX
Introduccion a Ansible
Osvaldo
 
PDF
Introduction à l’intégration continue avec Jenkins
Eric Hogue
 
PDF
Introduction to DevOps slides.pdf
BoreVishnusai
 
PDF
Kubernetes in 30 minutes (2017/03/10)
lestrrat
 
PPTX
Firebase PPT
JATIN GUPTA
 
PPTX
Linux privilege escalation 101
Rashid feroz
 
PPTX
Using Wildcards with rsyslog's File Monitor imfile
Rainer Gerhards
 
PDF
BEEVA | Introducción a Docker
BEEVA_es
 
PDF
Jenkins with SonarQube
Somkiat Puisungnoen
 
PDF
Les concepts fondamentaux de DITA
Peccatte
 
PDF
A Hands-On Introduction To Docker Containers.pdf
Edith Puclla
 
PDF
Enhancing Network and Runtime Security with Cilium and Tetragon by Raymond De...
ContainerDay Security 2023
 
PDF
Docker slides
Jyotsna Raghuraman
 
Docker Networking Tip - Macvlan driver
Sreenivas Makam
 
Firmware Extraction & Fuzzing - Jatan Raval
NSConclave
 
ASP.NET Core: The best of the new bits
Ken Cenerelli
 
API Security Best Practices & Guidelines
Prabath Siriwardena
 
DNS High-Availability Tools - Open-Source Load Balancing Solutions
Men and Mice
 
ArcherySec 2.0 @ BlackHat Arsenal Europe 2020
Anand Tiwari
 
Introduccion a Ansible
Osvaldo
 
Introduction à l’intégration continue avec Jenkins
Eric Hogue
 
Introduction to DevOps slides.pdf
BoreVishnusai
 
Kubernetes in 30 minutes (2017/03/10)
lestrrat
 
Firebase PPT
JATIN GUPTA
 
Linux privilege escalation 101
Rashid feroz
 
Using Wildcards with rsyslog's File Monitor imfile
Rainer Gerhards
 
BEEVA | Introducción a Docker
BEEVA_es
 
Jenkins with SonarQube
Somkiat Puisungnoen
 
Les concepts fondamentaux de DITA
Peccatte
 
A Hands-On Introduction To Docker Containers.pdf
Edith Puclla
 
Enhancing Network and Runtime Security with Cilium and Tetragon by Raymond De...
ContainerDay Security 2023
 
Docker slides
Jyotsna Raghuraman
 

Similar to Using PHPStan with Laravel App (20)

PDF
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
PDF
Static Analysis of PHP Code – IPC Berlin 2016
Rouven Weßling
 
PPTX
Static Code Analysis PHP[tek] 2023
Scott Keck-Warren
 
PDF
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Denis Ristic
 
PPTX
Reducing Bugs With Static Code Analysis php tek 2025
Scott Keck-Warren
 
PDF
Review unknown code with static analysis
Damien Seguy
 
ODP
What's new, what's hot in PHP 5.3
Jeremy Coates
 
PDF
Dynamic PHP web-application analysis
ax330d
 
PDF
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
PPTX
Listen afup 2010
Gabriele Santini
 
PDF
The why and how of moving to php 8
Wim Godden
 
PPTX
Introducing PHP Latest Updates
Iftekhar Eather
 
PDF
Preparing code for Php 7 workshop
Damien Seguy
 
PDF
Modern php
Charles Anderson
 
PDF
Enter Cookbook: refactoring under a microscope
Kamil Samigullin
 
PPTX
Listen and look at your PHP code
Gabriele Santini
 
PDF
Php 7 compliance workshop singapore
Damien Seguy
 
PDF
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
PDF
Php 7.2 compliance workshop php benelux
Damien Seguy
 
PDF
Preparing for the next PHP version (5.6)
Damien Seguy
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
Static Analysis of PHP Code – IPC Berlin 2016
Rouven Weßling
 
Static Code Analysis PHP[tek] 2023
Scott Keck-Warren
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Denis Ristic
 
Reducing Bugs With Static Code Analysis php tek 2025
Scott Keck-Warren
 
Review unknown code with static analysis
Damien Seguy
 
What's new, what's hot in PHP 5.3
Jeremy Coates
 
Dynamic PHP web-application analysis
ax330d
 
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
Listen afup 2010
Gabriele Santini
 
The why and how of moving to php 8
Wim Godden
 
Introducing PHP Latest Updates
Iftekhar Eather
 
Preparing code for Php 7 workshop
Damien Seguy
 
Modern php
Charles Anderson
 
Enter Cookbook: refactoring under a microscope
Kamil Samigullin
 
Listen and look at your PHP code
Gabriele Santini
 
Php 7 compliance workshop singapore
Damien Seguy
 
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
Php 7.2 compliance workshop php benelux
Damien Seguy
 
Preparing for the next PHP version (5.6)
Damien Seguy
 
Ad

Recently uploaded (20)

PDF
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
PPTX
declaration of Variables and constants.pptx
meemee7378
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
PDF
Best Software Development at Best Prices
softechies7
 
PPTX
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
PPTX
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
DOCX
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
PDF
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
PDF
Complete WordPress Programming Guidance Book
Shabista Imam
 
PPTX
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
PPTX
arctitecture application system design os dsa
za241967
 
PDF
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
PDF
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
PDF
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
PDF
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
PPTX
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
PDF
Decipher SEO Solutions for your startup needs.
mathai2
 
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
declaration of Variables and constants.pptx
meemee7378
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Best Software Development at Best Prices
softechies7
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Complete WordPress Programming Guidance Book
Shabista Imam
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
arctitecture application system design os dsa
za241967
 
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
Decipher SEO Solutions for your startup needs.
mathai2
 
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