SlideShare a Scribd company logo
1 of 66
Listen  and lookatyour  PHP  CODE! Gabriele Santini9/10/2010
Gabriele Santini Architect/Consultant at SQLI Contributor to PHP_CodeSniffer So expect a special focus on this… Sonar PHP Plugin I have to show you! Ex-mathematician : love business modelling love architectures love quality assurance … not an « OS geek »
StaticAnalysis All youcansay about your program withoutactuallyexecute the code The 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 analysis Lexical analysis Read sources linearlysearching for known patterns Convertthem to a sequence of tokens
Levels of analysis Lexical analysis Read sources linearlysearching for known patterns Convertthem to a sequence of tokens SyntacticAnalysis Parse the tokens to findtheirlogical structure
Levels of analysis Lexical analysis Read sources linearlysearching for known patterns Convertthem to a sequence of tokens SyntacticAnalysis Parse the tokens to findtheirlogical structure Opcode (Bytecode) Generation Generates an intermediary code that the Zend Enginewillbe able to execute
Lexical Analysis Tokenizer
SyntacticAnalysis Useful to beseen as an AST Abstract  SyntaxTree Decompose code in a tree-likeform Can beexecuted once a contextisgiven Used in compilers
SyntacticAnalysis
OpcodesGeneration Misterytool…
GIVE US THE TOOLS !
PHP_CodeSniffer By Greg Sherwood PEAR library Venerableproject Code Style But also a lot more Works at lexical analysislevel Heavily use the tokenizer extension
PHP_CodeSniffer ,[object Object],[object Object]
PHP_CodeSniffer Standards Sets of Sniffsthatdefineyourcoding style Installed :  PEAR,  Generic,  Zend*,  Squiz, MySource PHPCS
PHP_CodeSniffer 1.3 Rulesets XML!
Inside PHP_CodeSniffer Sniff class main methods register() Make the sniff a listener for the declaredtokens process($phpcsFile, $stackPtr) Called by the file duringparsingwhen a declaredtokenisfound File Represents a parsed file Holds the tokens structure and offersconveniencemethods
Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff $stackPtr
Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
Inside PHP_CodeSniffer Life of a Sniff (2)
PHP_CodeSniffer At SQLI we have some framework standards Zend Framework Based on Thomas Weidnerwork Symfony In collaboration with Fabien Potencier Waiting for a serious release after 1.3 release
PHP_CodeSniffer At SQLI we have some framework standards Zend Framework Based on Thomas Weidnerwork Symfony In collaboration with Fabien Potencier Waiting for a serious release after 1.3 release That’snice, but… Where are the standards for the othertools ? I’ldexpect a Drupal, Wordpress, Cake official standard
PHP_CodeSniffer How far a standard can go in detection ?
PHP_CodeSniffer How far a standard can go in detection ?  Interestingly far for generic PHP Code
PHP_CodeSniffer How far a standard can go in detection ?  Interestingly far for generic PHP Code Very far if you know yourtool’s structure Imagine for example forcing PHP alternative syntax in Symfonyviews… Or checking for escaping in Zend Views !
PHP_Depend By Manuel Pichler Functional port of JDepend OO design analysis Metrics visualisation Dependencyanalyzer Works at the syntacticanalysislevel
PHP_Depend How itworks PHP_Depend first makes an AST off your code A « personal » one, made by PHP objects ASTComment, ASTClosure, ASTEvalExpression, … This is made by the Builder/Parser component Using PHP Reflection
PHP_Depend How itworks (2) ThenPHP_Dependcananswer questions by « visiting » the AST This is the task for example of MetricsAnalyzers, thatextendAbstractVisitor  IOC,  the visitordecideswhat to do according to AST Class : visitMethod, visitForStatement(), … Analyzer canfirelistenersduringanalyze() call To getongoing informations about the visitprocess
PHP_Depend Whatitgives: The Abstraction/Instability graph
PHP_Depend Whatitgives: The Abstraction/Instability graph
PHP_Depend Whatitgives: The Pyramid !!
PHPMD By Manuel Pichler Detectsrules violations Analog to PHP_Codesniffer Works atsyntaxanalysislevel Actually on the same AST Depends on PHP_Depend Has rulesets !
PHPMD Whatitgives: Code Size Rules complexities, lengths, toomany, …  Design Rules OO, exit, eval NamingRules Too short/long identifiers, oldconstructors, … Unused Code Rules Methods, members, parameters
phploc By SebastianBergmann Simple tool to give basic metrics Fast, direct to the goal Works mostly on lexical level But use bytekit for ELOC if itcan
phpcpd By SebastianBergmann Simple tool to detectduplicated code Works on syntaxanalysislevel Use the tokenizer to minimizedifferences Comments, whitespaces, … Takes a minimum number of lines and tokens Encodes according to this Uses an hash table to find duplicates
vld Vulcan LogicDisassembler By Derick Rethans Works atbytecodelevel Shows generatedbytecodes Calculates possible paths (CFG) Findunreachable code Couldbeused for code coveragepathmetrics
vld Output
vld Output
Bytekit By Stefan Esser (SektionEins) Works at … bytecodelevel Similar to vld Exposes opcodes to a PHP array bytekit_disassemble_file($filename) Can beuseddirectly for a custom script
Bytekit CFG visualisation
Bytekit-cli By SebastianBergmann PHP Interface to use bytekit to spot violation rules Initial state Implementedrules : Check for disallowedopcodes (exampleeval, exit) Check for direct output of variables In svn, check for unescapedZendView
Padawan By Florian Anderiasch Focus on anti-pattern detection alpha (?) Works on syntaxanalysislevel Based on PHC (PHP compiler) Use an XML dump of the AST PHC generates Makesxpathsearches on it
Padawan Interestingapproach Rules are fairly simple to write Alreadymanyinteresting tests : Emptyconstructs (if, else, try,..), unsafetypecasts, looprepeated calls, unusedkeys in foreach, … PHC not easy to install Risk on PHC manteinance
Phantm By Etienne Kneuss Highlyexperimental Severe limitation on PHP dynamicfeatures False positives Works on syntaxanalysislevel Based on Java tools (Jflex, CUP, Scala) Reports violations Non  top-leveldeclarations, call-time pass-by-ref, nontrivialinclude calls, assign in conditional, … Exploring  Type Flow Analysis Tries to infer types and check for type safety
Conclusion Use the right tool for the right job Coding style isbetteranalysedat the lexical level OO design isbetterviewedaftersyntactic analyses Unreachable code afterbytecoding Contribute ! Plenty of thingsstill to implement Easy to have new ideas At least use them (youshould!) and give feedback
Restitution Once all thisiscollectedwhat to do withit ? At least, show it in a suitableform At best, integratethis in your CI system
phpUnderControl By Manuel Pichler CI for PHP Based on CruiseControl Integratesnativelyvarioustools : PHPUnit (+XDebug for code coverage),  PHP_CodeSniffer PHPDocumentor PMD via PHPUnit (now PHPMD)
phpUnderControl Whatitgives : metrics graphs
phpUnderControl Whatitgives : report lists
phpUnderControl Whatitgives : PHPCodeBrowser
Arbit By Qafoo (with Manuel Pichler) Basically a projectmulti-servicestool Ticketing system Repository browser Continuousintegration As Manuel is in it, somegraphicalpresentations are unique for thistool Still alpha
Arbit Whatitgives : more metrics graphs
Arbit Whatitgives : PHP_Dependoverview
Arbit Whatitgives : Annotated sources
Plugins Sonar for PHP By me  Really by the Java guysat SQLI Frédéric Leroy, Akram Ben Aissi, Jérôme Tama  Sonar is the state of the art for Open Source QA Reporting in Java Thought for multilanguage Can easelyintegrate all PHP reportingsportedfrom Java tools Junit => PHPUnit JDepend => PHPDepend Java PMD => PHPMD
Plugins Sonar for PHP Ok, not alwayssoeasely CheckStyleis not PHP_CodeSniffer Formats are not identical Multi-languagedoesn’tmean no work to add one  First release on May 2010 0.2 Alpha state, but workable Easy to install : giveit a try ! Last version demo : sonar-php.sqli.com Ok, enough, here are the screenshots
Plugins Sonar for PHP Dashboard
Plugins Sonar for PHP Components : treemaps
Plugins Sonar for PHP Time machine
Plugins Sonar for PHP Hotspots
Plugins Sonar for PHP Violations
Plugins Sonar for PHP Editing Code Profile
Conclusion Sonar reallygoesfurther Best integrateswithHudson Stillis java… But SonarSourcereallywants to cooperate How 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

What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)Moaid Hathot
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHBhavsingh Maloth
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introductionSiddique Ibrahim
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1Nicholas I
 
Packer Genetics: The selfish code
Packer Genetics: The selfish codePacker Genetics: The selfish code
Packer Genetics: The selfish codejduart
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonJaya Kumari
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
The Holistic Programmer
The Holistic ProgrammerThe Holistic Programmer
The Holistic ProgrammerAdam Keys
 
Ch07 Programming for Security Professionals
Ch07 Programming for Security ProfessionalsCh07 Programming for Security Professionals
Ch07 Programming for Security Professionalsphanleson
 
Reverse-engineering: Using GDB on Linux
Reverse-engineering: Using GDB on LinuxReverse-engineering: Using GDB on Linux
Reverse-engineering: Using GDB on LinuxRick Harris
 
ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caringsporst
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Edureka!
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonRanjith kumar
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthingtonoscon2007
 
Web Programming UNIT VIII notes
Web Programming UNIT VIII notesWeb Programming UNIT VIII notes
Web Programming UNIT VIII notesBhavsingh Maloth
 

What's hot (20)

What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
 
Py tut-handout
Py tut-handoutPy tut-handout
Py tut-handout
 
C interview questions and answers
C interview questions and answersC interview questions and answers
C interview questions and answers
 
Python
PythonPython
Python
 
Packer Genetics: The selfish code
Packer Genetics: The selfish codePacker Genetics: The selfish code
Packer Genetics: The selfish code
 
Lab4 scripts
Lab4 scriptsLab4 scripts
Lab4 scripts
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
The Holistic Programmer
The Holistic ProgrammerThe Holistic Programmer
The Holistic Programmer
 
Ch07 Programming for Security Professionals
Ch07 Programming for Security ProfessionalsCh07 Programming for Security Professionals
Ch07 Programming for Security Professionals
 
Reverse-engineering: Using GDB on Linux
Reverse-engineering: Using GDB on LinuxReverse-engineering: Using GDB on Linux
Reverse-engineering: Using GDB on Linux
 
Introduction to Python Basics Programming
Introduction to Python Basics ProgrammingIntroduction to Python Basics Programming
Introduction to Python Basics Programming
 
ShaREing Is Caring
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caring
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthington
 
Web Programming UNIT VIII notes
Web Programming UNIT VIII notesWeb Programming UNIT VIII notes
Web Programming UNIT VIII notes
 

Viewers also liked

Presentation kerrang annotation
Presentation kerrang annotationPresentation kerrang annotation
Presentation kerrang annotationJodieann46
 
Pda larionov
Pda larionovPda larionov
Pda larionovdino83
 
Media Evaluation
Media EvaluationMedia Evaluation
Media EvaluationJodieann46
 
Development of teenagers
Development of teenagersDevelopment of teenagers
Development of teenagersLisa Silmser
 
Change in a Star
Change in a StarChange in a Star
Change in a StarJodieann46
 

Viewers also liked (8)

Presentation kerrang annotation
Presentation kerrang annotationPresentation kerrang annotation
Presentation kerrang annotation
 
Tiny House Blog
Tiny House BlogTiny House Blog
Tiny House Blog
 
Pda larionov
Pda larionovPda larionov
Pda larionov
 
Media Evaluation
Media EvaluationMedia Evaluation
Media Evaluation
 
Development of teenagers
Development of teenagersDevelopment of teenagers
Development of teenagers
 
Change in a Star
Change in a StarChange in a Star
Change in a Star
 
Dow Jones Content101
Dow Jones Content101Dow Jones Content101
Dow Jones Content101
 
Assalamualaikum PROSA
Assalamualaikum PROSAAssalamualaikum PROSA
Assalamualaikum PROSA
 

Similar to Listen and look at your PHP code

The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8Wim Godden
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7Wim Godden
 
Code analysis tools (for PHP)
Code analysis tools (for PHP)Code analysis tools (for PHP)
Code analysis tools (for PHP)Karlen Kishmiryan
 
Development workflow
Development workflowDevelopment workflow
Development workflowSigsiu.NET
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...Maarten Balliauw
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSCisco Russia
 
Pharo: A Reflective System
Pharo: A Reflective SystemPharo: A Reflective System
Pharo: A Reflective SystemPharo
 
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)Brian Brazil
 
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Laterjohn-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types LaterPositive Hack Days
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-pythonYuvaraja Ravi
 
Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer CertificationVskills
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...Maarten Balliauw
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...Rouven Weßling
 
Php Development Stack
Php Development StackPhp Development Stack
Php Development Stackshah_neeraj
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabusSugantha T
 
Open frameworks 101_fitc
Open frameworks 101_fitcOpen frameworks 101_fitc
Open frameworks 101_fitcbenDesigning
 

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

PHP Internals
PHP InternalsPHP Internals
PHP Internals
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7
 
Code analysis tools (for PHP)
Code analysis tools (for PHP)Code analysis tools (for PHP)
Code analysis tools (for PHP)
 
Development workflow
Development workflowDevelopment workflow
Development workflow
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OS
 
Pharo: A Reflective System
Pharo: A Reflective SystemPharo: A Reflective System
Pharo: A Reflective System
 
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
OpenMetrics: What Does It Mean for You (PromCon 2019, Munich)
 
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Laterjohn-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
 
Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer Certification
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
WoMakersCode 2016 - Shit Happens
WoMakersCode 2016 -  Shit HappensWoMakersCode 2016 -  Shit Happens
WoMakersCode 2016 - Shit Happens
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
 
Php Development Stack
Php Development StackPhp Development Stack
Php Development Stack
 
Php Development Stack
Php Development StackPhp Development Stack
Php Development Stack
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
 
Cpcs302 1
Cpcs302  1Cpcs302  1
Cpcs302 1
 
Open frameworks 101_fitc
Open frameworks 101_fitcOpen frameworks 101_fitc
Open frameworks 101_fitc
 

Listen and look at your PHP code

  • 1. Listen and lookatyour PHP CODE! Gabriele Santini9/10/2010
  • 2. Gabriele Santini Architect/Consultant at SQLI Contributor to PHP_CodeSniffer So expect a special focus on this… Sonar PHP Plugin I have to show you! Ex-mathematician : love business modelling love architectures love quality assurance … not an « OS geek »
  • 3. StaticAnalysis All youcansay about your program withoutactuallyexecute the code The restisalsointeresting, let’s talk about itanother time ! Examples ? Syntax check, coding style, anti-patterns, metrics, OO design analysis, … What must bedonebeforeexecuting the code ?
  • 4. Levels of analysis Lexical analysis Read sources linearlysearching for known patterns Convertthem to a sequence of tokens
  • 5. Levels of analysis Lexical analysis Read sources linearlysearching for known patterns Convertthem to a sequence of tokens SyntacticAnalysis Parse the tokens to findtheirlogical structure
  • 6. Levels of analysis Lexical analysis Read sources linearlysearching for known patterns Convertthem to a sequence of tokens SyntacticAnalysis Parse the tokens to findtheirlogical structure Opcode (Bytecode) Generation Generates an intermediary code that the Zend Enginewillbe able to execute
  • 8. SyntacticAnalysis Useful to beseen as an AST Abstract SyntaxTree Decompose code in a tree-likeform Can beexecuted once a contextisgiven Used in compilers
  • 11. GIVE US THE TOOLS !
  • 12. PHP_CodeSniffer By Greg Sherwood PEAR library Venerableproject Code Style But also a lot more Works at lexical analysislevel Heavily use the tokenizer extension
  • 13.
  • 14. PHP_CodeSniffer Standards Sets of Sniffsthatdefineyourcoding style Installed : PEAR, Generic, Zend*, Squiz, MySource PHPCS
  • 16. Inside PHP_CodeSniffer Sniff class main methods register() Make the sniff a listener for the declaredtokens process($phpcsFile, $stackPtr) Called by the file duringparsingwhen a declaredtokenisfound File Represents a parsed file Holds the tokens structure and offersconveniencemethods
  • 17. Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
  • 18. Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
  • 19. Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
  • 20. Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff $stackPtr
  • 21. Inside PHP_CodeSniffer Life of a Sniff DisallowMultipleStatementsSniff
  • 22. Inside PHP_CodeSniffer Life of a Sniff (2)
  • 23. PHP_CodeSniffer At SQLI we have some framework standards Zend Framework Based on Thomas Weidnerwork Symfony In collaboration with Fabien Potencier Waiting for a serious release after 1.3 release
  • 24. PHP_CodeSniffer At SQLI we have some framework standards Zend Framework Based on Thomas Weidnerwork Symfony In collaboration with Fabien Potencier Waiting for a serious release after 1.3 release That’snice, but… Where are the standards for the othertools ? I’ldexpect a Drupal, Wordpress, Cake official standard
  • 25. PHP_CodeSniffer How far a standard can go in detection ?
  • 26. PHP_CodeSniffer How far a standard can go in detection ? Interestingly far for generic PHP Code
  • 27. PHP_CodeSniffer How far a standard can go in detection ? Interestingly far for generic PHP Code Very far if you know yourtool’s structure Imagine for example forcing PHP alternative syntax in Symfonyviews… Or checking for escaping in Zend Views !
  • 28. PHP_Depend By Manuel Pichler Functional port of JDepend OO design analysis Metrics visualisation Dependencyanalyzer Works at the syntacticanalysislevel
  • 29. PHP_Depend How itworks PHP_Depend first makes an AST off your code A « personal » one, made by PHP objects ASTComment, ASTClosure, ASTEvalExpression, … This is made by the Builder/Parser component Using PHP Reflection
  • 30. PHP_Depend How itworks (2) ThenPHP_Dependcananswer questions by « visiting » the AST This is the task for example of MetricsAnalyzers, thatextendAbstractVisitor IOC, the visitordecideswhat to do according to AST Class : visitMethod, visitForStatement(), … Analyzer canfirelistenersduringanalyze() call To getongoing informations about the visitprocess
  • 31. PHP_Depend Whatitgives: The Abstraction/Instability graph
  • 32. PHP_Depend Whatitgives: The Abstraction/Instability graph
  • 34. PHPMD By Manuel Pichler Detectsrules violations Analog to PHP_Codesniffer Works atsyntaxanalysislevel Actually on the same AST Depends on PHP_Depend Has rulesets !
  • 35. PHPMD Whatitgives: Code Size Rules complexities, lengths, toomany, … Design Rules OO, exit, eval NamingRules Too short/long identifiers, oldconstructors, … Unused Code Rules Methods, members, parameters
  • 36. phploc By SebastianBergmann Simple tool to give basic metrics Fast, direct to the goal Works mostly on lexical level But use bytekit for ELOC if itcan
  • 37. phpcpd By SebastianBergmann Simple tool to detectduplicated code Works on syntaxanalysislevel Use the tokenizer to minimizedifferences Comments, whitespaces, … Takes a minimum number of lines and tokens Encodes according to this Uses an hash table to find duplicates
  • 38. vld Vulcan LogicDisassembler By Derick Rethans Works atbytecodelevel Shows generatedbytecodes Calculates possible paths (CFG) Findunreachable code Couldbeused for code coveragepathmetrics
  • 41. Bytekit By Stefan Esser (SektionEins) Works at … bytecodelevel Similar to vld Exposes opcodes to a PHP array bytekit_disassemble_file($filename) Can beuseddirectly for a custom script
  • 43. Bytekit-cli By SebastianBergmann PHP Interface to use bytekit to spot violation rules Initial state Implementedrules : Check for disallowedopcodes (exampleeval, exit) Check for direct output of variables In svn, check for unescapedZendView
  • 44. Padawan By Florian Anderiasch Focus on anti-pattern detection alpha (?) Works on syntaxanalysislevel Based on PHC (PHP compiler) Use an XML dump of the AST PHC generates Makesxpathsearches on it
  • 45. Padawan Interestingapproach Rules are fairly simple to write Alreadymanyinteresting tests : Emptyconstructs (if, else, try,..), unsafetypecasts, looprepeated calls, unusedkeys in foreach, … PHC not easy to install Risk on PHC manteinance
  • 46. Phantm By Etienne Kneuss Highlyexperimental Severe limitation on PHP dynamicfeatures False positives Works on syntaxanalysislevel Based on Java tools (Jflex, CUP, Scala) Reports violations Non top-leveldeclarations, call-time pass-by-ref, nontrivialinclude calls, assign in conditional, … Exploring Type Flow Analysis Tries to infer types and check for type safety
  • 47. Conclusion Use the right tool for the right job Coding style isbetteranalysedat the lexical level OO design isbetterviewedaftersyntactic analyses Unreachable code afterbytecoding Contribute ! Plenty of thingsstill to implement Easy to have new ideas At least use them (youshould!) and give feedback
  • 48. Restitution Once all thisiscollectedwhat to do withit ? At least, show it in a suitableform At best, integratethis in your CI system
  • 49. phpUnderControl By Manuel Pichler CI for PHP Based on CruiseControl Integratesnativelyvarioustools : PHPUnit (+XDebug for code coverage), PHP_CodeSniffer PHPDocumentor PMD via PHPUnit (now PHPMD)
  • 53. Arbit By Qafoo (with Manuel Pichler) Basically a projectmulti-servicestool Ticketing system Repository browser Continuousintegration As Manuel is in it, somegraphicalpresentations are unique for thistool Still alpha
  • 54. Arbit Whatitgives : more metrics graphs
  • 55. Arbit Whatitgives : PHP_Dependoverview
  • 56. Arbit Whatitgives : Annotated sources
  • 57. Plugins Sonar for PHP By me  Really by the Java guysat SQLI Frédéric Leroy, Akram Ben Aissi, Jérôme Tama Sonar is the state of the art for Open Source QA Reporting in Java Thought for multilanguage Can easelyintegrate all PHP reportingsportedfrom Java tools Junit => PHPUnit JDepend => PHPDepend Java PMD => PHPMD
  • 58. Plugins Sonar for PHP Ok, not alwayssoeasely CheckStyleis not PHP_CodeSniffer Formats are not identical Multi-languagedoesn’tmean no work to add one First release on May 2010 0.2 Alpha state, but workable Easy to install : giveit a try ! Last version demo : sonar-php.sqli.com Ok, enough, here are the screenshots
  • 59. Plugins Sonar for PHP Dashboard
  • 60. Plugins Sonar for PHP Components : treemaps
  • 61. Plugins Sonar for PHP Time machine
  • 62. Plugins Sonar for PHP Hotspots
  • 63. Plugins Sonar for PHP Violations
  • 64. Plugins Sonar for PHP Editing Code Profile
  • 65. Conclusion Sonar reallygoesfurther Best integrateswithHudson Stillis java… But SonarSourcereallywants to cooperate How to interactwithphpUnderControl, Arbit ? (actuallyour solution – PIC PHP SQLI- isbased on phpUC + Sonar) This needs to evolve