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
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
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
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
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
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
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
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
phan
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
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;
}
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
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.
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so many Bugs?
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 (20)

PDF
PHP7 is coming
julien pauli
 
PPTX
Why choose Hack/HHVM over PHP7
Yuji Otani
 
PDF
Preparing code for Php 7 workshop
Damien Seguy
 
PDF
Reverse engineering - Shellcodes techniques
Eran Goldstein
 
PDF
Last train to php 7
Damien Seguy
 
PDF
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
Felipe Prado
 
PDF
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
Guilherme Blanco
 
ODP
The why and how of moving to php 5.4
Wim Godden
 
PDF
PHP traits, treat or threat?
Nick Belhomme
 
PDF
HHVM and Hack: A quick introduction
Kuan Yen Heng
 
PDF
50 shades of PHP
Maksym Hopei
 
PPTX
PHP 5.3
Chris Stone
 
PDF
Pimp My Java LavaJUG
Daniel Petisme
 
PDF
Modern PHP
Simon Jones
 
PPTX
Clojure 7-Languages
Pierre de Lacaze
 
PDF
PHP 7.1 : elegance of our legacy
Damien Seguy
 
ODP
The promise of asynchronous PHP
Wim Godden
 
PPTX
HipHop Virtual Machine
Radu Murzea
 
ODP
Mastering Namespaces in PHP
Nick Belhomme
 
PHP7 is coming
julien pauli
 
Why choose Hack/HHVM over PHP7
Yuji Otani
 
Preparing code for Php 7 workshop
Damien Seguy
 
Reverse engineering - Shellcodes techniques
Eran Goldstein
 
Last train to php 7
Damien Seguy
 
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
Felipe Prado
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
Guilherme Blanco
 
The why and how of moving to php 5.4
Wim Godden
 
PHP traits, treat or threat?
Nick Belhomme
 
HHVM and Hack: A quick introduction
Kuan Yen Heng
 
50 shades of PHP
Maksym Hopei
 
PHP 5.3
Chris Stone
 
Pimp My Java LavaJUG
Daniel Petisme
 
Modern PHP
Simon Jones
 
Clojure 7-Languages
Pierre de Lacaze
 
PHP 7.1 : elegance of our legacy
Damien Seguy
 
The promise of asynchronous PHP
Wim Godden
 
HipHop Virtual Machine
Radu Murzea
 
Mastering Namespaces in PHP
Nick Belhomme
 

Viewers also liked (20)

PPTX
Modern Static Code Analysis in PHP
Vladimir Reznichenko
 
PDF
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
Rouven Weßling
 
PPTX
XSSの評価基準とRIPSプラグイン的なものを作った
yamaguchi_2048
 
PDF
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
Shellmates
 
PDF
Adapting our API for multiple platforms
Rouven Weßling
 
PDF
Increasing code quality with code reviews (poetry version)
David Stockton
 
PDF
Dynamic PHP web-application analysis
ax330d
 
PDF
Functions - complex first class citizen
Vytautas Butkus
 
PDF
PHP Static Code Review
Damien Seguy
 
KEY
Php Code Audits (PHP UK 2010)
Damien Seguy
 
PDF
Web UI performance tuning
Andy Pemberton
 
DOC
Coding standards php
sagarrautray777
 
PDF
Coding Best practices (PHP)
Christian Baune
 
PPTX
Modular & Event driven UI Architecture
Vytautas Butkus
 
PDF
PHP CODING STANDARDS
Asheesh Sharma
 
PPTX
Coding Standard And Code Review
Milan Vukoje
 
PDF
RIPS - static code analyzer for vulnerabilities in PHP
Sorina Chirilă
 
PDF
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
PPTX
ニューラルネットワークによる音声の分類
yamaguchi_2048
 
PDF
Refactoring Legacy Code
Adam Culp
 
Modern Static Code Analysis in PHP
Vladimir Reznichenko
 
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
Rouven Weßling
 
XSSの評価基準とRIPSプラグイン的なものを作った
yamaguchi_2048
 
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
Shellmates
 
Adapting our API for multiple platforms
Rouven Weßling
 
Increasing code quality with code reviews (poetry version)
David Stockton
 
Dynamic PHP web-application analysis
ax330d
 
Functions - complex first class citizen
Vytautas Butkus
 
PHP Static Code Review
Damien Seguy
 
Php Code Audits (PHP UK 2010)
Damien Seguy
 
Web UI performance tuning
Andy Pemberton
 
Coding standards php
sagarrautray777
 
Coding Best practices (PHP)
Christian Baune
 
Modular & Event driven UI Architecture
Vytautas Butkus
 
PHP CODING STANDARDS
Asheesh Sharma
 
Coding Standard And Code Review
Milan Vukoje
 
RIPS - static code analyzer for vulnerabilities in PHP
Sorina Chirilă
 
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
ニューラルネットワークによる音声の分類
yamaguchi_2048
 
Refactoring Legacy Code
Adam Culp
 
Ad

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

PDF
Review unknown code with static analysis - bredaphp
Damien Seguy
 
PDF
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
PDF
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Denis Ristic
 
PDF
Review unknown code with static analysis
Damien Seguy
 
PDF
Using PHPStan with Laravel App
Muhammad Shehata
 
PPTX
Listen afup 2010
Gabriele Santini
 
PDF
Hunt for dead code
Damien Seguy
 
ODP
What's new, what's hot in PHP 5.3
Jeremy Coates
 
PPTX
Introducing PHP Latest Updates
Iftekhar Eather
 
PDF
Code review workshop
Damien Seguy
 
PPTX
Dmytro Dziubenko "Developer's toolchain"
Fwdays
 
PDF
PHP QA Tools
rjsmelo
 
PPTX
Listen and look at your PHP code
Gabriele Santini
 
PDF
Preparing for the next PHP version (5.6)
Damien Seguy
 
PDF
"PHP Code Avengers: Structuring, Refactoring, and Superhero Practices", Vlad...
Fwdays
 
PDF
Review unknown code with static analysis php ipc 2018
Damien Seguy
 
PDF
Review unknown code with static analysis php ce 2018
Damien Seguy
 
PDF
PHP unserialization vulnerabilities: What are we missing?
Sam Thomas
 
PDF
PHP7 - The New Engine for old good train
Xinchen Hui
 
PDF
PHP Performance Trivia
Nikita Popov
 
Review unknown code with static analysis - bredaphp
Damien Seguy
 
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Denis Ristic
 
Review unknown code with static analysis
Damien Seguy
 
Using PHPStan with Laravel App
Muhammad Shehata
 
Listen afup 2010
Gabriele Santini
 
Hunt for dead code
Damien Seguy
 
What's new, what's hot in PHP 5.3
Jeremy Coates
 
Introducing PHP Latest Updates
Iftekhar Eather
 
Code review workshop
Damien Seguy
 
Dmytro Dziubenko "Developer's toolchain"
Fwdays
 
PHP QA Tools
rjsmelo
 
Listen and look at your PHP code
Gabriele Santini
 
Preparing for the next PHP version (5.6)
Damien Seguy
 
"PHP Code Avengers: Structuring, Refactoring, and Superhero Practices", Vlad...
Fwdays
 
Review unknown code with static analysis php ipc 2018
Damien Seguy
 
Review unknown code with static analysis php ce 2018
Damien Seguy
 
PHP unserialization vulnerabilities: What are we missing?
Sam Thomas
 
PHP7 - The New Engine for old good train
Xinchen Hui
 
PHP Performance Trivia
Nikita Popov
 
Ad

More from Rouven Weßling (7)

PDF
API Days Australia - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
PDF
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
PDF
Nordic APIs - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
PDF
API World 2016 - API Mashup - Combining for Fun and Profit
Rouven Weßling
 
PDF
vienna.js - Automatic testing of (RESTful) API documentation
Rouven Weßling
 
PDF
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
Rouven Weßling
 
KEY
Joomla Day DK 2012
Rouven Weßling
 
API Days Australia - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
Nordic APIs - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
API World 2016 - API Mashup - Combining for Fun and Profit
Rouven Weßling
 
vienna.js - Automatic testing of (RESTful) API documentation
Rouven Weßling
 
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
Rouven Weßling
 
Joomla Day DK 2012
Rouven Weßling
 

Recently uploaded (20)

PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 

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...
  • 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
  • 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
  • 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
  • 47. phan
  • 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; }
  • 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.
  • 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