SlideShare a Scribd company logo
Static Analysis of PHP
Code
How the Heck did I write so many Bugs?
International PHP Conference Berlin, June 2016
By Rouven Weßling ( )
Ecosystem Developer / Developer Evangelist, Contentful
@RouvenWessling
photo credit: by Achim FischerBrandenburg Gate Berlin (license)
Static Analysis of PHP Code – IPC Berlin 2016
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
Static Analysis of PHP Code – IPC Berlin 2016
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
Static Analysis of PHP Code – IPC Berlin 2016
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 php7cc
Coupling Detector Mondrian PHP
Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP
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 PHP
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
Static Analysis of PHP Code – IPC Berlin 2016
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, ResponseInter
{
}
}
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
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 Entity)
[...]ServicesPdfOrder::23 must not depend on [...]EntityVorkursticket (Service on Entity)
Found 2 Violations
Static Analysis of PHP Code – IPC Berlin 2016
phan
Static Analysis of PHP Code – IPC Berlin 2016
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;
}
Static Analysis of PHP Code – IPC Berlin 2016
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/static-analysis-of-
php-code-ipc-berlin-2016

More Related Content

PDF
What is the Joomla Framework and why do we need it?
PDF
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PDF
vienna.js - Automatic testing of (RESTful) API documentation
PPTX
PHP 7 Crash Course - php[world] 2015
PDF
2021.laravelconf.tw.slides2
PPT
Hacking with hhvm
PDF
The why and how of moving to php 8
PDF
Last train to php 7
What is the Joomla Framework and why do we need it?
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
vienna.js - Automatic testing of (RESTful) API documentation
PHP 7 Crash Course - php[world] 2015
2021.laravelconf.tw.slides2
Hacking with hhvm
The why and how of moving to php 8
Last train to php 7

What's hot (20)

PDF
The why and how of moving to php 7
PDF
Php 7 compliance workshop singapore
ODP
The why and how of moving to php 5.4
PDF
Preparing code for Php 7 workshop
PDF
[COSCUP 2020] How to use llvm frontend library-libtooling
PDF
PHP7 is coming
PPTX
Why choose Hack/HHVM over PHP7
PPTX
Php’s guts
PDF
PHP traits, treat or threat?
PDF
HHVM and Hack: A quick introduction
PDF
50 shades of PHP
PDF
PHP 7.1 : elegance of our legacy
PDF
Modern PHP
PPTX
HipHop Virtual Machine
PDF
How to deploy node to production
PDF
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
ODP
Mastering Namespaces in PHP
PDF
Intro to Hack Language
PPT
How PHP Works ?
PPTX
PHP 5.3
The why and how of moving to php 7
Php 7 compliance workshop singapore
The why and how of moving to php 5.4
Preparing code for Php 7 workshop
[COSCUP 2020] How to use llvm frontend library-libtooling
PHP7 is coming
Why choose Hack/HHVM over PHP7
Php’s guts
PHP traits, treat or threat?
HHVM and Hack: A quick introduction
50 shades of PHP
PHP 7.1 : elegance of our legacy
Modern PHP
HipHop Virtual Machine
How to deploy node to production
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
Mastering Namespaces in PHP
Intro to Hack Language
How PHP Works ?
PHP 5.3
Ad

Viewers also liked (7)

PDF
Dynamic PHP web-application analysis
PPTX
Modern Static Code Analysis in PHP
PPTX
XSSの評価基準とRIPSプラグイン的なものを作った
PDF
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
PDF
Increasing code quality with code reviews (poetry version)
PDF
RIPS - static code analyzer for vulnerabilities in PHP
PPTX
ニューラルネットワークによる音声の分類
Dynamic PHP web-application analysis
Modern Static Code Analysis in PHP
XSSの評価基準とRIPSプラグイン的なものを作った
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
Increasing code quality with code reviews (poetry version)
RIPS - static code analyzer for vulnerabilities in PHP
ニューラルネットワークによる音声の分類
Ad

Similar to Static Analysis of PHP Code – IPC Berlin 2016 (20)

PDF
Review unknown code with static analysis - bredaphp
PDF
Review unknown code with static analysis
PDF
Review unknown code with static analysis Zend con 2017
PDF
PHP Static Code Review
PDF
Review unknown code with static analysis php ipc 2018
PDF
Using PHPStan with Laravel App
PDF
PHP7 - The New Engine for old good train
PDF
Php 7.2 compliance workshop php benelux
PDF
20 PHP Static Analysis and Documentation Generators #burningkeyboards
PPTX
Listen and look at your PHP code
ODP
What's new, what's hot in PHP 5.3
PPTX
Static Code Analysis PHP[tek] 2023
PPTX
Reducing Bugs With Static Code Analysis php tek 2025
PDF
Preparing for the next php version
PPTX
Listen afup 2010
PPTX
Dmytro Dziubenko "Developer's toolchain"
PDF
Review unknown code with static analysis php ce 2018
PDF
Preparing for the next PHP version (5.6)
PPTX
Introducing PHP Latest Updates
PDF
Static analysis saved my code tonight
Review unknown code with static analysis - bredaphp
Review unknown code with static analysis
Review unknown code with static analysis Zend con 2017
PHP Static Code Review
Review unknown code with static analysis php ipc 2018
Using PHPStan with Laravel App
PHP7 - The New Engine for old good train
Php 7.2 compliance workshop php benelux
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Listen and look at your PHP code
What's new, what's hot in PHP 5.3
Static Code Analysis PHP[tek] 2023
Reducing Bugs With Static Code Analysis php tek 2025
Preparing for the next php version
Listen afup 2010
Dmytro Dziubenko "Developer's toolchain"
Review unknown code with static analysis php ce 2018
Preparing for the next PHP version (5.6)
Introducing PHP Latest Updates
Static analysis saved my code tonight

More from Rouven Weßling (8)

PDF
API Days Australia - Automatic Testing of (RESTful) API Documentation
PDF
Adapting our API for multiple platforms
PDF
API Days Paris - Automatic Testing of (RESTful) API Documentation
PDF
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
PDF
Nordic APIs - Automatic Testing of (RESTful) API Documentation
PDF
API World 2016 - API Mashup - Combining for Fun and Profit
PDF
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
KEY
Joomla Day DK 2012
API Days Australia - Automatic Testing of (RESTful) API Documentation
Adapting our API for multiple platforms
API Days Paris - Automatic Testing of (RESTful) API Documentation
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
Nordic APIs - Automatic Testing of (RESTful) API Documentation
API World 2016 - API Mashup - Combining for Fun and Profit
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
Joomla Day DK 2012

Recently uploaded (20)

PDF
Understanding Forklifts - TECH EHS Solution
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
System and Network Administraation Chapter 3
PDF
Digital Strategies for Manufacturing Companies
PPTX
history of c programming in notes for students .pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
System and Network Administration Chapter 2
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Understanding Forklifts - TECH EHS Solution
Designing Intelligence for the Shop Floor.pdf
System and Network Administraation Chapter 3
Digital Strategies for Manufacturing Companies
history of c programming in notes for students .pptx
Design an Analysis of Algorithms II-SECS-1021-03
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Design an Analysis of Algorithms I-SECS-1021-03
Why Generative AI is the Future of Content, Code & Creativity?
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PTS Company Brochure 2025 (1).pdf.......
Upgrade and Innovation Strategies for SAP ERP Customers
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
iTop VPN Free 5.6.0.5262 Crack latest version 2025
CHAPTER 2 - PM Management and IT Context
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
System and Network Administration Chapter 2
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free

Static Analysis of PHP Code – IPC Berlin 2016

  • 1. Static Analysis of PHP Code How the Heck did I write so many Bugs? International PHP Conference Berlin, June 2016 By Rouven Weßling ( ) Ecosystem Developer / Developer Evangelist, Contentful @RouvenWessling photo credit: by Achim FischerBrandenburg Gate Berlin (license)
  • 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 php7cc Coupling Detector Mondrian PHP Assumption PhpCodeAnalyzer PHPCodeFixer php7mar PHP 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 PHP 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, ResponseInter { } }
  • 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. Software has layers There should be rules about those layers Rules are easily broken
  • 34. 1. Define the layers of your architecture 2. Define what layers another layer can access 3. Profit!!!
  • 35. layers: - name: Controller collectors: - type: className regex: .*Controller.* - name: Entity collectors: - type: className regex: AstaRwthVorkursticketBundleEntity.*
  • 36. ruleset: Controller: - Service - Entity - Form Service: - Repository Command: - Entity Entity: - Validator
  • 37. How it works Parses all files in your code Stores which classes access which others classes Checks the graph for rule violations
  • 38. 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 Entity) [...]ServicesPdfOrder::23 must not depend on [...]EntityVorkursticket (Service on Entity) Found 2 Violations
  • 40. phan
  • 42. Type safety for PHP Checks docblocks Signature mismatches Unused code
  • 43. 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
  • 44. /** * @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
  • 45. 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
  • 46. 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
  • 48. Bad news? Requires php-ast Not easy to deal with library code Noisy - not easily integrated in CI.
  • 50. 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
  • 51. int foo(int length) { int x = 0; for (int i = 0; i < length; i++) x += 1 return length/x; }
  • 53. 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.
  • 54. Slides available on Slideshare: http://www.slideshare.net/rwessling/static-analysis-of- php-code-ipc-berlin-2016