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

PDF
Static Analysis of PHP Code – IPC Berlin 2016
PDF
What is the Joomla Framework and why do we need it?
PDF
The why and how of moving to php 8
PPTX
PHP 7 Crash Course - php[world] 2015
PDF
The why and how of moving to php 7
PDF
2021.laravelconf.tw.slides2
PPT
Hacking with hhvm
PDF
Php 7 compliance workshop singapore
Static Analysis of PHP Code – IPC Berlin 2016
What is the Joomla Framework and why do we need it?
The why and how of moving to php 8
PHP 7 Crash Course - php[world] 2015
The why and how of moving to php 7
2021.laravelconf.tw.slides2
Hacking with hhvm
Php 7 compliance workshop singapore

What's hot (20)

PDF
PHP7 is coming
PPTX
Why choose Hack/HHVM over PHP7
PDF
Preparing code for Php 7 workshop
PDF
Reverse engineering - Shellcodes techniques
PDF
Last train to php 7
PDF
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
PDF
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
ODP
The why and how of moving to php 5.4
PDF
PHP traits, treat or threat?
PDF
HHVM and Hack: A quick introduction
PDF
50 shades of PHP
PPTX
PHP 5.3
PDF
Pimp My Java LavaJUG
PDF
Modern PHP
PPTX
Clojure 7-Languages
PDF
PHP 7.1 : elegance of our legacy
ODP
The promise of asynchronous PHP
PPTX
HipHop Virtual Machine
ODP
Mastering Namespaces in PHP
PHP7 is coming
Why choose Hack/HHVM over PHP7
Preparing code for Php 7 workshop
Reverse engineering - Shellcodes techniques
Last train to php 7
DEF CON 27 - AMIT WAISEL and HILA COHEN - malproxy
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
The why and how of moving to php 5.4
PHP traits, treat or threat?
HHVM and Hack: A quick introduction
50 shades of PHP
PHP 5.3
Pimp My Java LavaJUG
Modern PHP
Clojure 7-Languages
PHP 7.1 : elegance of our legacy
The promise of asynchronous PHP
HipHop Virtual Machine
Mastering Namespaces in PHP
Ad

Viewers also liked (20)

PPTX
Modern Static Code Analysis in PHP
PDF
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
PPTX
XSSの評価基準とRIPSプラグイン的なものを作った
PDF
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
PDF
Adapting our API for multiple platforms
PDF
Increasing code quality with code reviews (poetry version)
PDF
Dynamic PHP web-application analysis
PDF
Functions - complex first class citizen
PDF
PHP Static Code Review
KEY
Php Code Audits (PHP UK 2010)
PDF
Web UI performance tuning
DOC
Coding standards php
PDF
Coding Best practices (PHP)
PPTX
Modular & Event driven UI Architecture
PDF
PHP CODING STANDARDS
PPTX
Coding Standard And Code Review
PDF
RIPS - static code analyzer for vulnerabilities in PHP
PDF
JavaScript and UI Architecture Best Practices
PPTX
ニューラルネットワークによる音声の分類
PDF
Refactoring Legacy Code
Modern Static Code Analysis in PHP
php[world] 2016 - API Mashup - Combining APIs for Fun and Profit
XSSの評価基準とRIPSプラグイン的なものを作った
BSides Algiers - PHP Static Code Analysis - Abdeldjalil Belakhdar
Adapting our API for multiple platforms
Increasing code quality with code reviews (poetry version)
Dynamic PHP web-application analysis
Functions - complex first class citizen
PHP Static Code Review
Php Code Audits (PHP UK 2010)
Web UI performance tuning
Coding standards php
Coding Best practices (PHP)
Modular & Event driven UI Architecture
PHP CODING STANDARDS
Coding Standard And Code Review
RIPS - static code analyzer for vulnerabilities in PHP
JavaScript and UI Architecture Best Practices
ニューラルネットワークによる音声の分類
Refactoring Legacy Code
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
PDF
Review unknown code with static analysis Zend con 2017
PDF
20 PHP Static Analysis and Documentation Generators #burningkeyboards
PDF
Review unknown code with static analysis
PDF
Using PHPStan with Laravel App
PPTX
Listen afup 2010
PDF
Hunt for dead code
ODP
What's new, what's hot in PHP 5.3
PPTX
Introducing PHP Latest Updates
PDF
Code review workshop
PPTX
Dmytro Dziubenko "Developer's toolchain"
PDF
PHP QA Tools
PPTX
Listen and look at your PHP code
PDF
Preparing for the next PHP version (5.6)
PDF
"PHP Code Avengers: Structuring, Refactoring, and Superhero Practices", Vlad...
PDF
Review unknown code with static analysis php ipc 2018
PDF
Review unknown code with static analysis php ce 2018
PDF
PHP unserialization vulnerabilities: What are we missing?
PDF
PHP7 - The New Engine for old good train
PDF
PHP Performance Trivia
Review unknown code with static analysis - bredaphp
Review unknown code with static analysis Zend con 2017
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Review unknown code with static analysis
Using PHPStan with Laravel App
Listen afup 2010
Hunt for dead code
What's new, what's hot in PHP 5.3
Introducing PHP Latest Updates
Code review workshop
Dmytro Dziubenko "Developer's toolchain"
PHP QA Tools
Listen and look at your PHP code
Preparing for the next PHP version (5.6)
"PHP Code Avengers: Structuring, Refactoring, and Superhero Practices", Vlad...
Review unknown code with static analysis php ipc 2018
Review unknown code with static analysis php ce 2018
PHP unserialization vulnerabilities: What are we missing?
PHP7 - The New Engine for old good train
PHP Performance Trivia

More from Rouven Weßling (7)

PDF
API Days Australia - Automatic Testing of (RESTful) API Documentation
PDF
API Days Paris - Automatic Testing of (RESTful) API Documentation
PDF
Nordic APIs - Automatic Testing of (RESTful) API Documentation
PDF
API World 2016 - API Mashup - Combining for Fun and Profit
PDF
vienna.js - Automatic testing of (RESTful) API documentation
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
API Days Paris - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API Documentation
API World 2016 - API Mashup - Combining for Fun and Profit
vienna.js - Automatic testing of (RESTful) API documentation
vienna.html - Turn your Blog into Facebook Instant Articles + Contentful Intro
Joomla Day DK 2012

Recently uploaded (20)

PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
System and Network Administration Chapter 2
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Materi-Enum-and-Record-Data-Type (1).pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Presentation of Computer CLASS 2 .pptx
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PDF
Build Multi-agent using Agent Development Kit
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Best Practices for Rolling Out Competency Management Software.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
System and Network Administration Chapter 2
Upgrade and Innovation Strategies for SAP ERP Customers
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Materi-Enum-and-Record-Data-Type (1).pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Presentation of Computer CLASS 2 .pptx
Online Work Permit System for Fast Permit Processing
Odoo POS Development Services by CandidRoot Solutions
The Role of Automation and AI in EHS Management for Data Centers.pdf
Transform Your Business with a Software ERP System
ManageIQ - Sprint 268 Review - Slide Deck
PTS Company Brochure 2025 (1).pdf.......
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
Build Multi-agent using Agent Development Kit
ISO 45001 Occupational Health and Safety Management System
How to Choose the Right IT Partner for Your Business in Malaysia
Best Practices for Rolling Out Competency Management Software.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...
  • 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