SlideShare a Scribd company logo
Listen  and lookatyour  PHP  CODE!Gabriele Santini9/10/2010
Gabriele SantiniArchitect/Consultant at SQLIContributor to PHP_CodeSnifferSo expect a special focus on this…Sonar PHP PluginI have to show you!Ex-mathematician :love business modellinglove architectureslove quality assurance… not an « OS geek »
StaticAnalysisAll youcansay about your program withoutactuallyexecute the codeThe restisalsointeresting, let’s talk about itanother time !Examples ?Syntax check, coding style, anti-patterns, metrics,                OO design analysis, …What must bedonebeforeexecuting the code ?
Levels of analysisLexical analysisRead sources linearlysearching for known patternsConvertthem to a sequence of tokens
Levels of analysisLexical analysisRead sources linearlysearching for known patternsConvertthem to a sequence of tokensSyntacticAnalysisParse the tokens to findtheirlogical structure
Levels of analysisLexical analysisRead sources linearlysearching for known patternsConvertthem to a sequence of tokensSyntacticAnalysisParse the tokens to findtheirlogical structureOpcode (Bytecode) GenerationGenerates an intermediary code that the Zend Enginewillbe able to execute
Lexical AnalysisTokenizer
SyntacticAnalysisUseful to beseen as an ASTAbstract  SyntaxTreeDecompose code in a tree-likeformCan beexecuted once a contextisgivenUsed in compilers
SyntacticAnalysis
OpcodesGenerationMisterytool…
GIVE US THE TOOLS !
PHP_CodeSnifferBy Greg SherwoodPEAR libraryVenerableprojectCode StyleBut also a lot moreWorks at lexical analysislevelHeavily use the tokenizer extension
PHP_CodeSnifferHands onPHP_CodeSnifferSniffsClasses thatdetect ViolationsOne or more type per classGrouped in folders by subject:Commenting, Formatting, WhiteSpaceFiles, ControlStructures, Strings Functions, Classes, NamingConventionsCodeAnalysis, MetricsYou cancreateyourown!
PHP_CodeSnifferStandardsSets of Sniffsthatdefineyourcoding styleInstalled : PEAR, Generic, Zend*, Squiz, MySourcePHPCS
PHP_CodeSniffer 1.3Rulesets XML!
Inside PHP_CodeSnifferSniff class main methodsregister()Make the sniff a listener for the declaredtokensprocess($phpcsFile, $stackPtr)Called by the file duringparsingwhen a declaredtokenisfoundFileRepresents a parsed fileHolds the tokens structure and offersconveniencemethods
Inside PHP_CodeSnifferLife of a SniffDisallowMultipleStatementsSniff
Inside PHP_CodeSnifferLife of a SniffDisallowMultipleStatementsSniff
Inside PHP_CodeSnifferLife of a SniffDisallowMultipleStatementsSniff
Inside PHP_CodeSnifferLife of a SniffDisallowMultipleStatementsSniff$stackPtr
Inside PHP_CodeSnifferLife of a SniffDisallowMultipleStatementsSniff
Inside PHP_CodeSnifferLife of a Sniff (2)
PHP_CodeSnifferAt SQLI we have some framework standardsZend FrameworkBased on Thomas WeidnerworkSymfonyIn collaboration with Fabien PotencierWaiting for a serious release after 1.3 release
PHP_CodeSnifferAt SQLI we have some framework standardsZend FrameworkBased on Thomas WeidnerworkSymfonyIn collaboration with Fabien PotencierWaiting for a serious release after 1.3 releaseThat’snice, but…Where are the standards for the othertools ?I’ldexpect a Drupal, Wordpress, Cake official standard
PHP_CodeSnifferHow far a standard can go in detection ?
PHP_CodeSnifferHow far a standard can go in detection ? Interestingly far for generic PHP Code
PHP_CodeSnifferHow far a standard can go in detection ? Interestingly far for generic PHP CodeVery far if you know yourtool’s structureImagine for example forcing PHP alternative syntax in Symfonyviews…Or checking for escaping in Zend Views !
PHP_DependBy Manuel PichlerFunctional port of JDependOO design analysisMetrics visualisationDependencyanalyzerWorks at the syntacticanalysislevel
PHP_DependHow itworksPHP_Depend first makes an AST off your codeA « personal » one, made by PHP objectsASTComment, ASTClosure, ASTEvalExpression, …This is made by the Builder/Parser componentUsing PHP Reflection
PHP_DependHow itworks (2)ThenPHP_Dependcananswer questions by « visiting » the ASTThis is the task for example of MetricsAnalyzers, thatextendAbstractVisitor IOC,  the visitordecideswhat to do according to AST Class : visitMethod, visitForStatement(), …Analyzer canfirelistenersduringanalyze() callTo getongoing informations about the visitprocess
PHP_DependWhatitgives:The Abstraction/Instability graph
PHP_DependWhatitgives:The Abstraction/Instability graph
PHP_DependWhatitgives:The Pyramid !!
PHPMDBy Manuel PichlerDetectsrules violationsAnalog to PHP_CodesnifferWorks atsyntaxanalysislevelActually on the same ASTDepends on PHP_DependHas rulesets !
PHPMDWhatitgives:Code Size Rulescomplexities, lengths, toomany, … Design RulesOO, exit, evalNamingRulesToo short/long identifiers, oldconstructors, …Unused Code RulesMethods, members, parameters
phplocBy SebastianBergmannSimple tool to give basic metricsFast, direct to the goalWorks mostly on lexical levelBut use bytekit for ELOC if itcan
phpcpdBy SebastianBergmannSimple tool to detectduplicated codeWorks on syntaxanalysislevelUse the tokenizer to minimizedifferencesComments, whitespaces, …Takes a minimum number of lines and tokensEncodes according to thisUses an hash table to find duplicates
vldVulcan LogicDisassemblerBy Derick RethansWorks atbytecodelevelShows generatedbytecodesCalculates possible paths (CFG)Findunreachable codeCouldbeused for code coveragepathmetrics
vldOutput
vldOutput
BytekitBy Stefan Esser (SektionEins)Works at … bytecodelevelSimilar to vldExposes opcodes to a PHP arraybytekit_disassemble_file($filename)Can beuseddirectly for a custom script
BytekitCFG visualisation
Bytekit-cliBy SebastianBergmannPHP Interface to use bytekit to spot violation rulesInitial stateImplementedrules :Check for disallowedopcodes (exampleeval, exit)Check for direct output of variablesIn svn, check for unescapedZendView
PadawanBy Florian AnderiaschFocus on anti-pattern detectionalpha (?)Works on syntaxanalysislevelBased on PHC (PHP compiler)Use an XML dump of the AST PHC generatesMakesxpathsearches on it
PadawanInterestingapproachRules are fairly simple to writeAlreadymanyinteresting tests :Emptyconstructs (if, else, try,..), unsafetypecasts, looprepeated calls, unusedkeys in foreach, …PHC not easy to installRisk on PHC manteinance
PhantmBy Etienne KneussHighlyexperimentalSevere limitation on PHP dynamicfeaturesFalse positivesWorks on syntaxanalysislevelBased on Java tools (Jflex, CUP, Scala)Reports violationsNon  top-leveldeclarations, call-time pass-by-ref, nontrivialinclude calls, assign in conditional, …Exploring  Type Flow AnalysisTries to infer types and check for type safety
ConclusionUse the right tool for the right jobCoding style isbetteranalysedat the lexical levelOO design isbetterviewedaftersyntactic analysesUnreachable code afterbytecodingContribute !Plenty of thingsstill to implementEasy to have new ideasAt least use them (youshould!) and give feedback
RestitutionOnce all thisiscollectedwhat to do withit ?At least, show it in a suitableformAt best, integratethis in your CI system
phpUnderControlBy Manuel PichlerCI for PHPBased on CruiseControlIntegratesnativelyvarioustools :PHPUnit (+XDebug for code coverage), PHP_CodeSnifferPHPDocumentorPMD via PHPUnit (now PHPMD)
phpUnderControlWhatitgives : metrics graphs
phpUnderControlWhatitgives : report lists
phpUnderControlWhatitgives : PHPCodeBrowser
ArbitBy Qafoo (with Manuel Pichler)Basically a projectmulti-servicestoolTicketing systemRepository browserContinuousintegrationAs Manuel is in it, somegraphicalpresentations are unique for thistoolStill alpha
ArbitWhatitgives : more metrics graphs
ArbitWhatitgives : PHP_Dependoverview
ArbitWhatitgives : Annotated sources
Plugins Sonar for PHPBy me Really by the Java guysat SQLIFrédéric Leroy, Akram Ben Aissi, Jérôme Tama Sonar is the state of the art for Open Source QA Reporting in JavaThought for multilanguageCan easelyintegrate all PHP reportingsportedfrom Java toolsJunit => PHPUnitJDepend => PHPDependJava PMD => PHPMD
Plugins Sonar for PHPOk, not alwayssoeaselyCheckStyleis not PHP_CodeSnifferFormats are not identicalMulti-languagedoesn’tmean no work to add one First release on May 20100.2 Alpha state, but workableEasy to install : giveit a try !Last version demo : sonar-php.sqli.comOk, enough, here are the screenshots
Plugins Sonar for PHPDashboard
Plugins Sonar for PHPComponents : treemaps
Plugins Sonar for PHPTime machine
Plugins Sonar for PHPHotspots
Plugins Sonar for PHPViolations
Plugins Sonar for PHPEditing Code Profile
ConclusionSonar reallygoesfurtherBest integrateswithHudsonStillis java…But SonarSourcereallywants to cooperateHow to interactwithphpUnderControl, Arbit ?(actuallyour solution – PIC PHP SQLI- isbased on phpUC + Sonar)This needs to evolve
Listen and look at your PHP code

More Related Content

What's hot (20)

PPTX
What's coming to c# (Tel-Aviv, 2018)
Moaid Hathot
 
PDF
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
Bhavsingh Maloth
 
PPTX
Python programming introduction
Siddique Ibrahim
 
PDF
Get started python programming part 1
Nicholas I
 
PDF
Py tut-handout
Ramachandra Dama
 
PDF
C interview questions and answers
Thesis Scientist Private Limited
 
PPT
Packer Genetics: The selfish code
jduart
 
PDF
Lab4 scripts
quantumleaf
 
PPTX
Introduction to python
Jaya Kumari
 
PDF
Python Foundation – A programmer's introduction to Python concepts & style
Kevlin Henney
 
PDF
The Holistic Programmer
Adam Keys
 
PPT
Ch07 Programming for Security Professionals
phanleson
 
PPTX
Reverse-engineering: Using GDB on Linux
Rick Harris
 
PPTX
Introduction to Python Basics Programming
Collaboration Technologies
 
PDF
ShaREing Is Caring
sporst
 
PDF
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Edureka!
 
PPT
Introduction to python
Ranjith kumar
 
PPT
Os Worthington
oscon2007
 
PDF
Web Programming UNIT VIII notes
Bhavsingh Maloth
 
What's coming to c# (Tel-Aviv, 2018)
Moaid Hathot
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
Bhavsingh Maloth
 
Python programming introduction
Siddique Ibrahim
 
Get started python programming part 1
Nicholas I
 
Py tut-handout
Ramachandra Dama
 
C interview questions and answers
Thesis Scientist Private Limited
 
Packer Genetics: The selfish code
jduart
 
Lab4 scripts
quantumleaf
 
Introduction to python
Jaya Kumari
 
Python Foundation – A programmer's introduction to Python concepts & style
Kevlin Henney
 
The Holistic Programmer
Adam Keys
 
Ch07 Programming for Security Professionals
phanleson
 
Reverse-engineering: Using GDB on Linux
Rick Harris
 
Introduction to Python Basics Programming
Collaboration Technologies
 
ShaREing Is Caring
sporst
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Edureka!
 
Introduction to python
Ranjith kumar
 
Os Worthington
oscon2007
 
Web Programming UNIT VIII notes
Bhavsingh Maloth
 

Viewers also liked (8)

PPTX
Presentation kerrang annotation
Jodieann46
 
KEY
Tiny House Blog
Cammy Davis
 
PPT
Pda larionov
dino83
 
PPTX
Media Evaluation
Jodieann46
 
PPTX
Development of teenagers
Lisa Silmser
 
PPTX
Change in a Star
Jodieann46
 
PPTX
Dow Jones Content101
Georg Ackermann
 
PPTX
Assalamualaikum PROSA
Akbar Priyono Cah Pemalang
 
Presentation kerrang annotation
Jodieann46
 
Tiny House Blog
Cammy Davis
 
Pda larionov
dino83
 
Media Evaluation
Jodieann46
 
Development of teenagers
Lisa Silmser
 
Change in a Star
Jodieann46
 
Dow Jones Content101
Georg Ackermann
 
Assalamualaikum PROSA
Akbar Priyono Cah Pemalang
 
Ad

Similar to Listen and look at your PHP code (20)

PPTX
Code analysis tools (for PHP)
Karlen Kishmiryan
 
PDF
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
PPT
Introduction to PHP - SDPHP
Eric Johnson
 
ODP
Wc13
Pomaxa None
 
PDF
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
PDF
Introduction to PHP (SDPHP)
Eric Johnson
 
PDF
Static Analysis of PHP Code – IPC Berlin 2016
Rouven Weßling
 
PDF
PHP QA Tools
rjsmelo
 
PDF
Joomla Code Quality Control and Automation Testing
Shyam Sunder Verma
 
PDF
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Denis Ristic
 
PDF
Dynamic PHP web-application analysis
ax330d
 
KEY
Php|tek '12 It's More Than Just Style
LB Denker
 
PDF
The return of an old enemy
DonSchado
 
PDF
Continuous Integration In Php
Wilco Jansen
 
PDF
The why and how of moving to php 8
Wim Godden
 
PDF
Getting Started with PHP Extensions
MichaelBrunoLochemem
 
PDF
Review unknown code with static analysis
Damien Seguy
 
ODP
Professional PHP: an open-source alternative for enterprise development [Antw...
Combell NV
 
PPTX
PHPCS (PHP Code Sniffer)
Oleksii Prohonnyi
 
PDF
Using PHPStan with Laravel App
Muhammad Shehata
 
Code analysis tools (for PHP)
Karlen Kishmiryan
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
Introduction to PHP - SDPHP
Eric Johnson
 
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
Introduction to PHP (SDPHP)
Eric Johnson
 
Static Analysis of PHP Code – IPC Berlin 2016
Rouven Weßling
 
PHP QA Tools
rjsmelo
 
Joomla Code Quality Control and Automation Testing
Shyam Sunder Verma
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
Denis Ristic
 
Dynamic PHP web-application analysis
ax330d
 
Php|tek '12 It's More Than Just Style
LB Denker
 
The return of an old enemy
DonSchado
 
Continuous Integration In Php
Wilco Jansen
 
The why and how of moving to php 8
Wim Godden
 
Getting Started with PHP Extensions
MichaelBrunoLochemem
 
Review unknown code with static analysis
Damien Seguy
 
Professional PHP: an open-source alternative for enterprise development [Antw...
Combell NV
 
PHPCS (PHP Code Sniffer)
Oleksii Prohonnyi
 
Using PHPStan with Laravel App
Muhammad Shehata
 
Ad

Listen and look at your PHP code