SlideShare a Scribd company logo
Static Analysis of PHP
Code
How the Heck did I write so many Bugs?
PHPCon Poland, September 2016
By Rouven Weßling ( )
Ecosystem Developer / Developer Evangelist, Contentful
@RouvenWessling
photo credit: byWarsaw Kamil Porembiński (license)
A content management developer platform with an API
at its core.
What is Static
Analysis?
Analysing software without
executing it.
Dynamic Analysis
xdebug
xhprof
PHP Analyzer
PHP Vulnerability Hunter
Assertions
Why use Static
Analysis?
Spend less time on unit tests...
...and code review
class ClientTest extends PHPUnit_Framework_TestCase
{
public function testGetSynchronizationManager()
{
$client = new Client('b4c0n73n7fu1', 'cfexampleapi');
$this->assertInstanceOf(Manager::class, $client->getSynchronizationManager());
}
}
Easy to integrate in Continuous
Integration
Find issues that can not be found
through unit tests
PHP 7
Abstract Syntax Tree
Scalar Types
Strict Types
PHP is dynamic
Reflection
Variable variables
Referencing classes/functions/properties by string
The more static your code is, the
easier it's to reason about.
Some tools
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter RIPS Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter RIPS Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter RIPS Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter RIPS Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter RIPS Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa php7c
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
phpmd phan phpcs phpunit phploc phpcpd phpsa PHP
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH
Semantic Versioning Checker PHP Inspection PHP
lint PHP Depend PhpMetrics PHPCheckstyle PHP
Reaper PHP vuln hunter Parse SonarQube Side
Channel
Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP
semver checker
PHP lint
php -l
Compiles PHP script with the actual PHP compiler
It's already installed on your computer
Can be used to test compatibility with multiple PHP
versions
<?php
namespace ContentfulLog
use PsrHttpMessageRequestInterface;
use PsrHttpMessageResponseInterface;
class NullLogger implements LoggerInterface
{
public function getTimer()
{
return new NullTimer;
}
public function log($api, RequestInterface $request, StandardTimer $timer, Respons
{
}
}
PHP 7.0.3 | 10 parallel jobs
.................................X...... 40/40 (100 %)
Checked 40 files in 0.5 seconds
Syntax error found in 1 file
------------------------------------------------------------
Parse error: src/Log/NullLogger.php:9
7| namespace ContentfulLog
8|
> 9| use PsrHttpMessageRequestInterface;
10| use PsrHttpMessageResponseInterface;
11|
Unexpected 'use' (T_USE), expecting '{'
Make your life easier
Use PHP-Parallel-Lint
phploc
Gather stats about your projects
Get an idea of the complexity
See long term trends
phploc 3.0.1 by Sebastian Bergmann.
Directories 6
Files 40
Size
Lines of Code (LOC) 5683
Comment Lines of Code (CLOC) 2562 (45.08%)
Non-Comment Lines of Code (NCLOC) 3121 (54.92%)
Logical Lines of Code (LLOC) 951 (16.73%)
Classes 868 (91.27%)
Average Class Length 21
Minimum Class Length 0
Maximum Class Length 190
Average Method Length 2
Minimum Method Length 0
Maximum Method Length 25
Functions 0 (0.00%)
Average Function Length 0
Not in classes or functions 83 (8.73%)
Cyclomatic Complexity
Average Complexity per LLOC 0.28
Average Complexity per Class 7.65
Minimum Class Complexity 1.00
Maximum Class Complexity 62.00
Average Complexity per Method 1.82
Minimum Method Complexity 1.00
Maximum Method Complexity 11.00
If you're getting serious about Cyclomatic Complexity,
use phpmd.
Dependencies
Global Accesses 0
Global Constants 0 (0.00%)
Global Variables 0 (0.00%)
Super-Global Variables 0 (0.00%)
Attribute Accesses 536
Non-Static 535 (99.81%)
Static 1 (0.19%)
Method Calls 319
Non-Static 308 (96.55%)
Static 11 (3.45%)
Structure
Namespaces 7
Interfaces 3
Traits 0
Classes 37
Abstract Classes 3 (8.11%)
Concrete Classes 34 (91.89%)
Methods 272
Scope
Non-Static Methods 272 (100.00%)
Static Methods 0 (0.00%)
Visibility
Public Methods 221 (81.25%)
Non-Public Methods 51 (18.75%)
Functions 6
Named Functions 0 (0.00%)
Anonymous Functions 6 (100.00%)
Constants 2
Global Constants 0 (0.00%)
Class Constants 2 (100.00%)
Deptrac
Software has layers
There should be rules about those layers
Rules are easily broken
1. Define the layers of your architecture
2. Define what layers another layer can access
3. Profit!!!
layers:
- name: Controller
collectors:
- type: className
regex: .*Controller.*
- name: Entity
collectors:
- type: className
regex: AstaRwthVorkursticketBundleEntity.*
ruleset:
Controller:
- Service
- Entity
- Form
Service:
- Repository
Command:
- Entity
Entity:
- Validator
How it works
Parses all files in your code
Stores which classes access which others classes
Checks the graph for rule violations
deptrac is alpha, not production ready.
please help us and report feedback / bugs.
Start to create an AstMap for 24 Files.
........................
AstMap created.
start emitting dependencies "InheritanceDependencyEmitter"
start emitting dependencies "BasicDependencyEmitter"
end emitting dependencies
start flatten dependencies
end flatten dependencies
collecting violations.
formatting dependencies.
[...]ServicesPdfOrder::5 must not depend on [...]EntityVorkursticket (Service on Enti
[...]ServicesPdfOrder::23 must not depend on [...]EntityVorkursticket (Service on Ent
Found 2 Violations
phan
Type safety for PHP
Checks docblocks
Signature mismatches
Unused code
How it works
Makes 2 passes over the codebase
1. Build a list of all classes, functions, methods, etc.
2. Go trough each function and follow the type of
each variable
/**
* @param Locale|string|null $locale
*
* @return string
*/
public function getDescription($locale = null)
{
$localeCode = $this->getLocaleFromInput($locale);
// This checks happens after the call to getLocaleFromInput to make sure
// the Exception for invalid locales is still thrown.
if ($this->description === null) {
return null;
}
return $this->description->$localeCode;
}
src/Delivery/Asset.php:74 PhanTypeMismatchReturn Returning type null
but getDescription() is declared to return string
class ContentType
{
/**
* The fields, keyed by ID.
*
* @var object
*/
private $fields = [];
}
src/Delivery/ContentType.php:34 PhanTypeMismatchProperty Assigning array to
property but contentfuldeliverycontenttype::fields is object
public function __call($name, $arguments)
{
// Lots of code here
if ($result instanceof Link) {
return $client->resolveLink($result);
}
return array_map(function ($value) use ($client) {
if ($value instanceof Link) {
return $client->resolveLink($value);
}
return $value;
}, $result);
}
src/Delivery/DynamicEntry.php:126
PhanTypeMismatchArgumentInternal Argument 2 (input1) is
contentfuldeliverylink but array_map() takes array
Not a bug
Don't trust blindly
Bad news?
Requires php-ast
Not easy to deal with library code
Noisy - not easily integrated in CI.
The future
phan is using brute force for type checking
Roughly as good as the compiler for a statically
typed language
Works, but a Control Flow Graph could give even
deeper insight
int foo(int length) {
int x = 0;
for (int i = 0; i < length; i++)
x += 1
return length/x;
}
Bottom line
There are dozens of tools - pick what's necessary for
you
Make them part of your Continuous Integration setup
Never trust. Make sure you understand where the
error is coming from.
Slides available on Slideshare:
http://www.slideshare.net/rwessling
Please leave feedback on joind.in
( ) or tweet me
( )
https://joind.in/talk/8f19b
@RouvenWessling

More Related Content

What's hot

PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
Nick Belhomme
 

What's hot (20)

PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7
 
Preparing code for Php 7 workshop
Preparing code for Php 7 workshopPreparing code for Php 7 workshop
Preparing code for Php 7 workshop
 
Reverse engineering - Shellcodes techniques
Reverse engineering - Shellcodes techniquesReverse engineering - Shellcodes techniques
Reverse engineering - Shellcodes techniques
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
 
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxyDEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
 
The why and how of moving to php 5.4
The why and how of moving to php 5.4The why and how of moving to php 5.4
The why and how of moving to php 5.4
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
HHVM and Hack: A quick introduction
HHVM and Hack: A quick introductionHHVM and Hack: A quick introduction
HHVM and Hack: A quick introduction
 
50 shades of PHP
50 shades of PHP50 shades of PHP
50 shades of PHP
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
Pimp My Java LavaJUG
Pimp My Java LavaJUGPimp My Java LavaJUG
Pimp My Java LavaJUG
 
Modern PHP
Modern PHPModern PHP
Modern PHP
 
Anti Debugging
Anti DebuggingAnti Debugging
Anti Debugging
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
 
PHP 7.1 : elegance of our legacy
PHP 7.1 : elegance of our legacyPHP 7.1 : elegance of our legacy
PHP 7.1 : elegance of our legacy
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
HipHop Virtual Machine
HipHop Virtual MachineHipHop Virtual Machine
HipHop Virtual Machine
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHP
 

Viewers also liked

BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
BSides Algiers - PHP Static Code Analysis - Abdeldjalil BelakhdarBSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
Shellmates
 
Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)
David Stockton
 
Dynamic PHP web-application analysis
Dynamic PHP web-application analysisDynamic PHP web-application analysis
Dynamic PHP web-application analysis
ax330d
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
Damien Seguy
 
Web UI performance tuning
Web UI performance tuningWeb UI performance tuning
Web UI performance tuning
Andy Pemberton
 
RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
Sorina Chirilă
 
ニューラルネットワークによる音声の分類
ニューラルネットワークによる音声の分類ニューラルネットワークによる音声の分類
ニューラルネットワークによる音声の分類
yamaguchi_2048
 

Viewers also liked (20)

Modern Static Code Analysis in PHP
Modern Static Code Analysis in PHPModern Static Code Analysis in PHP
Modern Static Code Analysis in PHP
 
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
php[world] 2016 - API Mashup - Combining APIs for Fun and Profitphp[world] 2016 - API Mashup - Combining APIs for Fun and Profit
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
 
XSSの評価基準とRIPSプラグイン的なものを作った
XSSの評価基準とRIPSプラグイン的なものを作ったXSSの評価基準とRIPSプラグイン的なものを作った
XSSの評価基準とRIPSプラグイン的なものを作った
 
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
BSides Algiers - PHP Static Code Analysis - Abdeldjalil BelakhdarBSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
 
Adapting our API for multiple platforms
Adapting our API for multiple platformsAdapting our API for multiple platforms
Adapting our API for multiple platforms
 
Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)
 
Dynamic PHP web-application analysis
Dynamic PHP web-application analysisDynamic PHP web-application analysis
Dynamic PHP web-application analysis
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
Web UI performance tuning
Web UI performance tuningWeb UI performance tuning
Web UI performance tuning
 
Coding standards php
Coding standards phpCoding standards php
Coding standards php
 
Coding Best practices (PHP)
Coding Best practices (PHP)Coding Best practices (PHP)
Coding Best practices (PHP)
 
Modular & Event driven UI Architecture
Modular & Event driven UI ArchitectureModular & Event driven UI Architecture
Modular & Event driven UI Architecture
 
PHP CODING STANDARDS
PHP CODING STANDARDSPHP CODING STANDARDS
PHP CODING STANDARDS
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
ニューラルネットワークによる音声の分類
ニューラルネットワークによる音声の分類ニューラルネットワークによる音声の分類
ニューラルネットワークによる音声の分類
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 

Similar to PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?

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
 

Similar to PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs? (20)

Review unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphpReview unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphp
 
Listen afup 2010
Listen afup 2010Listen afup 2010
Listen afup 2010
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards
 
Php manish
Php manishPhp manish
Php manish
 
Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?Is your code ready for PHP 7 ?
Is your code ready for PHP 7 ?
 
Using PHPStan with Laravel App
Using PHPStan with Laravel AppUsing PHPStan with Laravel App
Using PHPStan with Laravel App
 
Advanced malwareanalysis training session2 botnet analysis part1
Advanced malwareanalysis training session2 botnet analysis part1Advanced malwareanalysis training session2 botnet analysis part1
Advanced malwareanalysis training session2 botnet analysis part1
 
Joomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation TestingJoomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation Testing
 
The Veil-Framework
The Veil-FrameworkThe Veil-Framework
The Veil-Framework
 
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
 
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1  Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
 
Statyczna analiza kodu PHP
Statyczna analiza kodu PHPStatyczna analiza kodu PHP
Statyczna analiza kodu PHP
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explained
 
More about PHP
More about PHPMore about PHP
More about PHP
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.x
 
Introduction to web and php mysql
Introduction to web and php mysqlIntroduction to web and php mysql
Introduction to web and php mysql
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.x
 
PHP Development Tools
PHP  Development ToolsPHP  Development Tools
PHP Development Tools
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical Hacking
 

More from Rouven Weßling

More from Rouven Weßling (7)

API Days Australia - Automatic Testing of (RESTful) API Documentation
API Days Australia  - Automatic Testing of (RESTful) API DocumentationAPI Days Australia  - Automatic Testing of (RESTful) API Documentation
API Days Australia - Automatic Testing of (RESTful) API Documentation
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
Nordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API DocumentationNordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API Documentation
 
API World 2016 - API Mashup - Combining for Fun and Profit
API World 2016 - API Mashup - Combining for Fun and ProfitAPI World 2016 - API Mashup - Combining for Fun and Profit
API World 2016 - API Mashup - Combining for Fun and Profit
 
vienna.js - Automatic testing of (RESTful) API documentation
vienna.js - Automatic testing of (RESTful) API documentationvienna.js - Automatic testing of (RESTful) API documentation
vienna.js - Automatic testing of (RESTful) API documentation
 
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Introvienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
 
Joomla Day DK 2012
Joomla Day DK 2012Joomla Day DK 2012
Joomla Day DK 2012
 

Recently uploaded

JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
Max Lee
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Benefits of Employee Monitoring Software
Benefits of  Employee Monitoring SoftwareBenefits of  Employee Monitoring Software
Benefits of Employee Monitoring Software
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 

PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?

  • 1. Static Analysis of PHP Code How the Heck did I write so many Bugs? PHPCon Poland, September 2016 By Rouven Weßling ( ) Ecosystem Developer / Developer Evangelist, Contentful @RouvenWessling photo credit: byWarsaw Kamil Porembiński (license)
  • 2. A content management developer platform with an API at its core.
  • 5. Dynamic Analysis xdebug xhprof PHP Analyzer PHP Vulnerability Hunter Assertions
  • 7. Spend less time on unit tests...
  • 9.
  • 10. class ClientTest extends PHPUnit_Framework_TestCase { public function testGetSynchronizationManager() { $client = new Client('b4c0n73n7fu1', 'cfexampleapi'); $this->assertInstanceOf(Manager::class, $client->getSynchronizationManager()); } }
  • 11. Easy to integrate in Continuous Integration
  • 12.
  • 13. Find issues that can not be found through unit tests
  • 14. PHP 7 Abstract Syntax Tree Scalar Types Strict Types
  • 15. PHP is dynamic Reflection Variable variables Referencing classes/functions/properties by string
  • 16. The more static your code is, the easier it's to reason about.
  • 18. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter RIPS Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 19. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter RIPS Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 20. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter RIPS Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 21. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter RIPS Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 22. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter RIPS Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 23. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 24. phpmd phan phpcs phpunit phploc phpcpd phpsa php7c Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 25. phpmd phan phpcs phpunit phploc phpcpd phpsa PHP Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PH Semantic Versioning Checker PHP Inspection PHP lint PHP Depend PhpMetrics PHPCheckstyle PHP Reaper PHP vuln hunter Parse SonarQube Side Channel Analyzer TaintPHP Deptrac PhpDependencyAnalysis PHP semver checker
  • 27.
  • 28. Compiles PHP script with the actual PHP compiler It's already installed on your computer Can be used to test compatibility with multiple PHP versions
  • 29. <?php namespace ContentfulLog use PsrHttpMessageRequestInterface; use PsrHttpMessageResponseInterface; class NullLogger implements LoggerInterface { public function getTimer() { return new NullTimer; } public function log($api, RequestInterface $request, StandardTimer $timer, Respons { } }
  • 30. PHP 7.0.3 | 10 parallel jobs .................................X...... 40/40 (100 %) Checked 40 files in 0.5 seconds Syntax error found in 1 file ------------------------------------------------------------ Parse error: src/Log/NullLogger.php:9 7| namespace ContentfulLog 8| > 9| use PsrHttpMessageRequestInterface; 10| use PsrHttpMessageResponseInterface; 11| Unexpected 'use' (T_USE), expecting '{'
  • 31. Make your life easier Use PHP-Parallel-Lint
  • 33. Gather stats about your projects Get an idea of the complexity See long term trends
  • 34. phploc 3.0.1 by Sebastian Bergmann. Directories 6 Files 40 Size Lines of Code (LOC) 5683 Comment Lines of Code (CLOC) 2562 (45.08%) Non-Comment Lines of Code (NCLOC) 3121 (54.92%) Logical Lines of Code (LLOC) 951 (16.73%) Classes 868 (91.27%) Average Class Length 21 Minimum Class Length 0 Maximum Class Length 190 Average Method Length 2 Minimum Method Length 0 Maximum Method Length 25 Functions 0 (0.00%) Average Function Length 0 Not in classes or functions 83 (8.73%)
  • 35. Cyclomatic Complexity Average Complexity per LLOC 0.28 Average Complexity per Class 7.65 Minimum Class Complexity 1.00 Maximum Class Complexity 62.00 Average Complexity per Method 1.82 Minimum Method Complexity 1.00 Maximum Method Complexity 11.00
  • 36. If you're getting serious about Cyclomatic Complexity, use phpmd.
  • 37. Dependencies Global Accesses 0 Global Constants 0 (0.00%) Global Variables 0 (0.00%) Super-Global Variables 0 (0.00%) Attribute Accesses 536 Non-Static 535 (99.81%) Static 1 (0.19%) Method Calls 319 Non-Static 308 (96.55%) Static 11 (3.45%)
  • 38. Structure Namespaces 7 Interfaces 3 Traits 0 Classes 37 Abstract Classes 3 (8.11%) Concrete Classes 34 (91.89%) Methods 272 Scope Non-Static Methods 272 (100.00%) Static Methods 0 (0.00%) Visibility Public Methods 221 (81.25%) Non-Public Methods 51 (18.75%) Functions 6 Named Functions 0 (0.00%) Anonymous Functions 6 (100.00%) Constants 2 Global Constants 0 (0.00%) Class Constants 2 (100.00%)
  • 40. Software has layers There should be rules about those layers Rules are easily broken
  • 41. 1. Define the layers of your architecture 2. Define what layers another layer can access 3. Profit!!!
  • 42. layers: - name: Controller collectors: - type: className regex: .*Controller.* - name: Entity collectors: - type: className regex: AstaRwthVorkursticketBundleEntity.*
  • 43. ruleset: Controller: - Service - Entity - Form Service: - Repository Command: - Entity Entity: - Validator
  • 44. How it works Parses all files in your code Stores which classes access which others classes Checks the graph for rule violations
  • 45. deptrac is alpha, not production ready. please help us and report feedback / bugs. Start to create an AstMap for 24 Files. ........................ AstMap created. start emitting dependencies "InheritanceDependencyEmitter" start emitting dependencies "BasicDependencyEmitter" end emitting dependencies start flatten dependencies end flatten dependencies collecting violations. formatting dependencies. [...]ServicesPdfOrder::5 must not depend on [...]EntityVorkursticket (Service on Enti [...]ServicesPdfOrder::23 must not depend on [...]EntityVorkursticket (Service on Ent Found 2 Violations
  • 46.
  • 47. phan
  • 48.
  • 49. Type safety for PHP Checks docblocks Signature mismatches Unused code
  • 50. How it works Makes 2 passes over the codebase 1. Build a list of all classes, functions, methods, etc. 2. Go trough each function and follow the type of each variable
  • 51. /** * @param Locale|string|null $locale * * @return string */ public function getDescription($locale = null) { $localeCode = $this->getLocaleFromInput($locale); // This checks happens after the call to getLocaleFromInput to make sure // the Exception for invalid locales is still thrown. if ($this->description === null) { return null; } return $this->description->$localeCode; } src/Delivery/Asset.php:74 PhanTypeMismatchReturn Returning type null but getDescription() is declared to return string
  • 52. class ContentType { /** * The fields, keyed by ID. * * @var object */ private $fields = []; } src/Delivery/ContentType.php:34 PhanTypeMismatchProperty Assigning array to property but contentfuldeliverycontenttype::fields is object
  • 53. public function __call($name, $arguments) { // Lots of code here if ($result instanceof Link) { return $client->resolveLink($result); } return array_map(function ($value) use ($client) { if ($value instanceof Link) { return $client->resolveLink($value); } return $value; }, $result); } src/Delivery/DynamicEntry.php:126 PhanTypeMismatchArgumentInternal Argument 2 (input1) is contentfuldeliverylink but array_map() takes array Not a bug
  • 55. Bad news? Requires php-ast Not easy to deal with library code Noisy - not easily integrated in CI.
  • 57. phan is using brute force for type checking Roughly as good as the compiler for a statically typed language Works, but a Control Flow Graph could give even deeper insight
  • 58. int foo(int length) { int x = 0; for (int i = 0; i < length; i++) x += 1 return length/x; }
  • 59.
  • 60. Bottom line There are dozens of tools - pick what's necessary for you Make them part of your Continuous Integration setup Never trust. Make sure you understand where the error is coming from.
  • 61.
  • 62. Slides available on Slideshare: http://www.slideshare.net/rwessling Please leave feedback on joind.in ( ) or tweet me ( ) https://joind.in/talk/8f19b @RouvenWessling