PHP CompatInfo Book

Laurent Laville

Revision History
Revision 5.0.122018-02-01LL

Table of Contents

I. Getting Started
1. Download
2. Configuration
3. Structure
4. Execution
5. Summary
6. Next
II. User Guide
7. Installation
7.1. Requirements
7.2. Composer
7.3. PHAR
8. The Json Configuration File
8.1. section Source Providers
8.2. section Plugins
8.3. section Analysers
9. The Command-Line
9.1. Command-Line Options
10. Summary
III. Migration Guide v3
11. CLI
11.1. Progress Bar
References
11.2. Print parses results
11.3. Caching results
12. Configuration file
12.1. Global options
12.2. Cache options
12.3. References options
12.4. PHP settings
12.5. Excluding Files or Elements from parsing
12.6. Listeners
12.7. Plugins options
13. Server API
13.1. Parsing recursive directories
13.2. Using cache feature
13.3. Listeners
13.4. Exploring parsing results
IV. Migration Guide v4
14. CLI
14.1. Progress Bar
References
14.2. Print parses results
14.3. Caching results
15. Configuration file
15.1. Defaults
15.2. Plugins
16. Server API
16.1. Using cache feature
16.2. Listeners
16.3. Exploring parsing results
V. Developer Guide
17. API
17.1. Data Source Identification
18. Plugins
18.1. Events
18.2. Register Plugins
19. Cache Plugin
19.1. Register Plugin
19.2. Doctrine Adapter
19.3. File cache
20. Log Plugin
20.1. Register Plugin
20.2. Default logger
20.3. Using your private logger
20.4. Using Monolog
21. Notifier Plugin
21.1. Register Plugin
22. Build your Analysers
22.1. Visitor pattern
22.2. Print results
23. Build your Filters
23.1. Your first filter
23.2. SAPI usage
VI. References included

List of Examples

18.1. Add a listener that will echo out files when they are parsed

This complete guide documents PHP CompatInfo 5.0.12, published on 2018-02-01.

This work is licensed under the Attribution-Share Alike 3.0 Unported license.

Part I. Getting Started

Chapter 1. Download

We distribute a PHP Archive (PHAR) that contains all required dependencies of PHP CompatInfo bundled in a single file.

Download the latest version

Make it executable, and put it into your $PATH.

$ chmod +x phpcompatinfo-5.0.12.phar
$ mv phpcompatinfo-5.0.12.phar /usr/local/bin/phpcompatinfo

$ phpcompatinfo --version

You can also immediately use the PHAR after you have downloaded it.

$ wget http://bartlett.laurent-laville.org/get/phpcompatinfo-5.0.12.phar
$ php phpcompatinfo-5.0.12.phar --version

With both methods then you have this output :

phpCompatInfo version 5.0.12 DB version 1.29.0 built Feb 01 2018 22:12:58 CET

Other alternative installations are possible. Please refer to the Chapter 7, Installation for details on how to do this.

Chapter 2. Configuration

With the minimalist JSON file phpcompatinfo.json

{
    "source-providers": [
        {
            "in": ". as current",
            "name": "/\\.(php|inc|phtml)$/"
        }
    ],
    "plugins": [
    ],
    "analysers": [
    ],
    "services": [
    ]
}

Put it in your project’s folder. Alternative locations are possible. Please refer to the Chapter 8, The Json Configuration File for details on how to do this.

[Note]

The JSON configuration file is no more required for basic usage. Reserved to advanced users.

Chapter 3. Structure

source-providers
this entry provide list of your data sources to parse.
plugins
this entry list all plugins added to the core base code of PHP Reflect.
analysers
this entry list all analysers that may be used with the analyser:run command.
services
this entry list all services that may be used with this application.

Chapter 4. Execution

With the CompatInfo source code, invoke the following command :

$ phpcompatinfo analyser:run .

and you should obtain something like this :

Data Source Analysed

Directories                                         11
Files                                               13

Extensions Analysis

    Extension Matches REF      EXT min/Max PHP min/Max PHP all
    Core              Core                 4.0.0       5.3.0
    PDO               PDO      5.1.0       5.1.0
    curl              curl     4.0.2       4.0.2
    intl              intl     2.0.0b1     5.3.7
    libxml            libxml   5.1.0       5.1.0
    openssl           openssl  5.2.0       5.2.0
    pcre              pcre     4.0.0       4.0.0
    spl               spl      5.1.0       5.1.0
    standard          standard 4.0.0       4.0.0       5.3.2
    Total [9]                              5.3.7

Namespaces Analysis

    Namespace                             Matches REF  EXT min/Max PHP min/Max PHP all
    +global                                       Core             4.0.0
    Bartlett\CompatInfo                           user             5.3.0
    Bartlett\CompatInfo\Analyser                  user             5.3.0
    Bartlett\CompatInfo\Api                       user             5.3.0       5.3.2
    Bartlett\CompatInfo\Api\V3                    user             5.3.0
    Bartlett\CompatInfo\Collection                user             5.3.0
    Bartlett\CompatInfo\Console                   user             5.3.0
    Bartlett\CompatInfo\Console\Formatter         user             5.3.0
    Bartlett\CompatInfo\Output                    user             5.3.0
    Bartlett\CompatInfo\PhpParser                 user             5.3.0
    Bartlett\CompatInfo\Reference                 user             5.3.0
    Bartlett\CompatInfo\Util                      user             5.3.0
    Total [12]                                                     5.3.0       5.3.2

Interfaces Analysis

    Interface                                        Matches REF  EXT min/Max PHP min/Max PHP all
    Bartlett\CompatInfo\Reference\ReferenceInterface 1       user             5.3.0
    Total [1]                                                                 5.3.0

No trait found

Classes Analysis

    Class                                                              Matches REF  EXT min/Max PHP min/Max PHP all
    Bartlett\CompatInfo\Analyser\CompatibilityAnalyser                         user             5.3.0
    Bartlett\CompatInfo\Api\Reference                                          user             5.3.0       5.3.2
    Bartlett\CompatInfo\Api\V3\Reference                                       user             5.3.0
    Bartlett\CompatInfo\Collection\ReferenceCollection                 1       user             5.3.0
    Bartlett\CompatInfo\Console\Application                                    user             5.3.0
    Bartlett\CompatInfo\Console\Formatter\CompatibilityOutputFormatter         user             5.3.0
    Bartlett\CompatInfo\Environment                                    4       user             5.3.0
    Bartlett\CompatInfo\Output\Reference                                       user             5.3.0
    Bartlett\CompatInfo\PhpParser\ConditionalCodeNodeProcessor         1       user             5.3.0
    Bartlett\CompatInfo\Reference\ExtensionFactory                     2       user             5.3.0
    Bartlett\CompatInfo\Reference\SqliteStorage                        1       user             5.3.0
    Bartlett\CompatInfo\Util\Version                                   10      user             5.3.0
  U Bartlett\Reflect\Analyser\AbstractAnalyser                         1       user             5.3.0
  U Bartlett\Reflect\Api\BaseApi                                       1       user             5.3.0
  U Bartlett\Reflect\Api\V3\Common                                     1       user             5.3.0
  U Bartlett\Reflect\Console\Application                               1       user             5.3.0
  U Bartlett\Reflect\Console\Formatter\OutputFormatter                 2       user             5.3.0
  U Bartlett\Reflect\PhpParser\NodeProcessorAbstract                   1       user             5.3.0
  U Doctrine\Common\Collections\AbstractLazyCollection                 1       user             5.3.0
  U Doctrine\Common\Collections\ArrayCollection                        1       user             5.3.0
    PDO                                                                2       PDO  5.1.0       5.1.0
  U PhpParser\Node                                                     21      user             5.3.0
  U PhpParser\Node\Name                                                1       user             5.3.0
    RuntimeException                                                   1       spl  5.1.0       5.1.0
  U Symfony\Component\Console\Helper\TableSeparator                    3       user             5.3.0
  U Symfony\Component\Console\Output\OutputInterface                   4       user             5.3.0
    parent                                                             5       Core 5.0.0       5.0.0
    self                                                               11      Core 5.0.0       5.0.0
    stdClass                                                           1       Core 4.0.0       4.0.0
    Total [29]                                                                                  5.3.0       5.3.2

Functions Analysis

    Function                    Matches REF      EXT min/Max PHP min/Max
    array_key_exists            7       standard 4.0.7       4.0.7
    array_map                   2       standard 4.0.6       4.0.6
    array_merge                 3       standard 4.0.0       4.0.0
    array_pop                   6       standard 4.0.0       4.0.0
    array_shift                 2       standard 4.0.0       4.0.0
    array_slice                 1       standard 4.0.0       4.0.0
    array_values                1       standard 4.0.0       4.0.0
    closure-73-75                       user                 5.3.0
    copy                        1       standard 4.0.0       4.0.0
    count                       14      standard 4.0.0       4.0.0
 C  curl_version                1       curl     4.0.2       4.0.2
    defined                     4       Core     4.0.0       4.0.0
    dirname                     3       standard 4.0.0       4.0.0
    each                        2       Core     4.0.0       4.0.0
    end                         3       standard 4.0.0       4.0.0
    explode                     2       standard 4.0.0       4.0.0
    extension_loaded            1       Core     4.0.0       4.0.0
    file_exists                 2       standard 4.0.0       4.0.0
    function_exists             1       Core     4.0.0       4.0.0
    in_array                    10      standard 4.0.0       4.0.0
    is_array                    1       standard 4.0.0       4.0.0
    is_callable                 1       standard 4.0.6       4.0.6
    is_string                   10      standard 4.0.0       4.0.0
    ksort                       3       standard 4.0.0       4.0.0
    ltrim                       1       standard 4.0.0       4.0.0
    mkdir                       1       standard 4.0.0       4.0.0
    phpversion                  2       standard 4.0.0       4.0.0
    preg_match                  2       pcre     4.0.0       4.0.0
    sha1_file                   2       standard 4.3.0       4.3.0
    sprintf                     26      standard 4.0.0       4.0.0
    str_replace                 1       standard 4.0.0       4.0.0
    strcasecmp                  4       Core     4.0.0       4.0.0
    stream_resolve_include_path 1       standard 5.3.2       5.3.2
    strpos                      2       standard 4.0.0       4.0.0
    strtolower                  1       standard 4.0.0       4.0.0
    substr                      2       standard 4.0.0       4.0.0
    sys_get_temp_dir            1       standard 5.2.1       5.2.1
    ucfirst                     5       standard 4.0.0       4.0.0
    version_compare             9       standard 4.0.7       4.0.7
    Total [39]                                               5.3.2

Constants Analysis

    Constant               Matches REF     EXT min/Max PHP min/Max
 C  INTL_ICU_VERSION       2       intl    2.0.0b1     5.3.7
    LIBXML_DOTTED_VERSION  1       libxml  5.1.0       5.1.0
    LIBXML_VERSION         1       libxml  5.1.0       5.1.0
 C  OPENSSL_VERSION_NUMBER 1       openssl 5.2.0       5.2.0
 C  OPENSSL_VERSION_TEXT   1       openssl 5.2.0       5.2.0
    PHP_EOL                5       Core    4.3.10      4.3.10
    PHP_VERSION            4       Core    4.0.0       4.0.0
    __DIR__                1       Core    5.3.0       5.3.0
    false                  14      Core    4.0.0       4.0.0
    null                   15      Core    4.0.0       4.0.0
    true                   10      Core    4.0.0       4.0.0
    Total [11]                                         5.3.0

Conditions Analysis

    Condition                       Matches REF     EXT min/Max PHP min/Max
    defined(INTL_ICU_VERSION)       2       intl    2.0.0b1     5.3.7
    defined(OPENSSL_VERSION_NUMBER) 1       openssl 5.2.0       5.2.0
    defined(OPENSSL_VERSION_TEXT)   1       openssl 5.2.0       5.2.0
    function_exists(curl_version)   1       curl    4.0.2       4.0.2
    Total [4]                                                   5.3.7

Requires PHP 5.3.2 (min), PHP 5.3.2 (all)

Chapter 5. Summary

Let’s review what we’ve done :

  • downloaded the latest stable PHAR version.
  • prepared a minimalist JSON configuration file that is OPTIONAL to run CompatInfo commands.
  • executed your first parse on the CompatInfo data source.

Chapter 6. Next

Choose your way depending of your skill level.

Part II. User Guide

[Note]

First visit, you are highly recommended to follow chapters in following order.

  1. Installing all necessary CompatInfo components. See Chapter 7, Installation
  2. Configuring your project and get ready for your first parsing. See Chapter 8, The Json Configuration File
  3. Running your first parses with the Command-Line interface. See Chapter 9, The Command-Line
[Caution]

All you have to know if you want to upgrade from a previous version 2.x easily.

See ???

[Note]

Basic CompatInfo features does not match your needs. Learn how to extend or change some features/behaviors.

See Part V, “Developer Guide”

Chapter 7. Installation

CompatInfo may be installed in several ways, choose your favorite.

[Warning]

Please read the Part III, “Migration Guide v3” in case you are upgrading from a version 2.x of PHP CompatInfo.

7.1. Requirements

Before you install PHP CompatInfo, you will need an operating system with PHP 5.4.0 or later installed,

CompatInfo requires the json, libxml, pdo (sqlite driver), pcre, and spl extensions. These extensions are usually compiled and enabled by default.

7.2. Composer

Put a file named composer.json at the root of your project, with the content below:

{
    "require": {
        "bartlett/php-compatinfo": "5.0.12"
    }
}

And ask Composer to install the dependencies:

$ php composer.phar install
[Tip]

With composer install or create-project commands, if you want to disable installation of require-dev packages (doctrine/cache, psr/log, monolog/monolog, bartlett/phpunit-loggertestlistener), don’t forget to specify the --no-dev option.

[Tip]

You can also use Composer to create a new project from an existing CompatInfo package. This is the equivalent of doing a git clone checkout followed by a composer install of the vendors.

$ php composer.phar create-project bartlett/php-compatinfo /path/to/install 5.0.12

Where /path/to/install is your install directory.

7.3. PHAR

The recommended way for newbies, or just to have a look on features of this library, is to download a PHP Archive that contain all required dependencies of PHP CompatInfo bundled in a single file.

$ wget http://bartlett.laurent-laville.org/get/phpcompatinfo-5.0.12.phar
$ chmod +x phpcompatinfo-5.0.12.phar
$ mv phpcompatinfo-5.0.12.phar /usr/local/bin/phpcompatinfo
$ phpcompatinfo

You can also immediately use the PHAR after you have downloaded it.

$ wget http://bartlett.laurent-laville.org/get/phpcompatinfo-5.0.12.phar
$ php phpcompatinfo-5.0.12.phar

Chapter 8. The Json Configuration File

[Warning]

CompatInfo may used an optional config file in JSON format. It could be found either in the current, $HOME/.config/, or /etc directory.

By setting the BARTLETTRC environment variable it is possible to set the filename of phpcompatinfo.json to something else.

E.g: BARTLETTRC=my-phpcompatinfo.json

And by setting the BARTLETT_SCAN_DIR environment variable it is possible to change directories where to search for the json config file.

E.g: BARTLETT_SCAN_DIR=.:/var/configs:/tmp/bartlett (for Linux)

E.g: BARTLETT_SCAN_DIR=.;\var\configs;\tmp\bartlett (for Windows)

Take care of different PATH_SEPARATOR and DIRECTORY_SEPARATOR in each platform.

The minimalist JSON file phpcompatinfo.json is :

{
    "source-providers": [
        {
            "in": ". as current",
            "name": "/\\.(php|inc|phtml)$/"
        }
    ],
    "plugins": [
    ],
    "analysers": [
    ],
    "services": [
    ]
}
source-providers
this entry provide list of your data sources to parse.
plugins
this entry list all plugins added to the core base code of PHP CompatInfo.
analysers
this entry list all analysers that may be used with the analyser:run command.
services
this entry list all services that may be used with this application.

8.1. section Source Providers

There are lot of way to filter your data source. Each rule follow the syntax of Symfony Finder Component.

The Location is the only mandatory criteria. It tells the Finder which directory to use for the search.

In a simple directory. 

    {
        "in": ". as current"
    }

[Note]

If you want to identify a data source easily by a short name, the alias (right of as) is compared with the --alias option constraint.

Search in several locations. 

    {
        "in": ". as current",
        "in": "src/"
    }

Use wildcard characters to search in the directories matching a pattern: 

    {
        "in": "src/Bartlett/R*"
    }

Search directly in archives (phar, zip, tar) with the phar:// protocol. 

    {
        "in": "phar://path/to/archive.zip"
    }

Restrict files by name and/or extension. 

    {
        "in": "phar://path/to/archive.zip",
        "name": "*.php"
    }

Restrict files by size

    {
        "in": "phar://path/to/archive.zip",
        "name": "*.php",
        "size": "< 10K"
    }

Restrict files by last modified dates. 

    {
        "in": ". as current",
        "date": "since yesterday"
    }

By default, the Finder recursively traverse directories.

Restrict the depth of traversing. 

    {
        "in": ". as current",
        "depth": "< 3"
    }

Restrict location by only one directory. 

    {
        "in": ". as current",
        "exclude": "vendor"
    }

Restrict location by 1 or more directories. 

    {
        "in": ". as current",
        "exclude": ["vendor", "tests"]
    }

8.2. section Plugins

There are a number of optional plugins you can use along with CompatInfo to add more capabilities.

Take an example with the Logger plugin.

In your phpcompatinfo.json configuration file, add in plugins section the following entry:

    {
        "name": "Logger",
        "class": "Bartlett\\Reflect\\Plugin\\LogPlugin"
    }
  • The name key is (since version 4.0.0-alpha1) comment only.
  • The class key identify the name of the class that implement the plugin features (must be fully qualified).
[Note]

The LogPlugin used by default the Bartlett\Reflect\Plugin\Log\DefaultLogger class that write results to error_log

8.2.1. Cache Plugin

[Warning]

Available only since version 3.3.0

In your phpcompatinfo.json configuration file, add in plugins section the following entry:

    {
        "name": "Cache",
        "class": "Bartlett\\Reflect\\Plugin\\CachePlugin",
        "options": {
            "adapter": "DoctrineCacheAdapter",
            "backend": {
                "class": "Doctrine\\Common\\Cache\\FilesystemCache",
                "args": [
                    "%{TEMP}/bartlett/cache"
                ]
            }
        }
    }
[Tip]

You may use any environment variable that will be replaced, at run-time, by their value. E.g: TEMP, HOME

[Note]

Since release 3.3.0, the HOME syntax is compatible Linux/Windows.

[Caution]

Take care to use the same configuration as in PHP Reflect, or you should not share the cache results.

[Tip]

If you want to used the same options (Doctrine adapter with file cache) as above, you can used shortcut syntax like this.

    {
        "name": "Cache",
        "class": "Bartlett\\Reflect\\Plugin\\CachePlugin",
        "options": []
    }

In previous configuration we used the Doctrine Cache adapter and its File system backend. See the same configuration applied with other SAPI, in Section 19.3, “File cache”

8.2.2. Log Plugin

[Warning]

Available only since version 3.4.0

In your phpcompatinfo.json configuration file, add in plugins section the following entry:

    {
        "name": "Log",
        "class": "Bartlett\\Reflect\\Plugin\\LogPlugin"
    }

Where options key identify an optional class logger (fully qualified. E.g YourNamespace\YourLogger).

When options key is not provided, log plugin used the default Reflect logger bundled with distribution. See Bartlett\Reflect\Plugin\Log\DefaultLogger that write results to the error log system.

See the Developer Guide for definition examples of some loggers Section 20.3, “Using your private logger” or Section 20.4, “Using Monolog”

8.3. section Analysers

There are default analysers you can use, but you are free to add your owns.

In your phpcompatinfo.json configuration file, add in analysers section (for example) the following entry:

    {
        "name": "MyAnalyser",
        "class": "Your\\Analysers\\MyAnalyser"
    }
  • The name key is (since version 4.0.0-alpha1) comment only.
  • The class key identify the name of the class that implement your analyser (must be fully qualified).

Your analyser should implement both interfaces Bartlett\Reflect\Analyser\AnalyserInterface and PhpParser\NodeVisitor.

Then to use it in command line :

$ phpcompatinfo analyser:run /path/to/datasource my
[Note]

my identify your analyser (prefix in lower case of MyAnalyser class)

Chapter 9. The Command-Line

The command-line interface is the easiest way to try and learn the basic CompatInfo features.

[Note]

For all users.

9.1. Command-Line Options

Without plugins and analysers sections in your phpcompatinfo.json configuration file, when you invoke the phpcompatinfo command, you should obtain the following commands and options :

        _            ____                            _   ___        __
  _ __ | |__  _ __  / ___|___  _ __ ___  _ __   __ _| |_|_ _|_ __  / _| ___
 | '_ \| '_ \| '_ \| |   / _ \| '_ ` _ \| '_ \ / _` | __|| || '_ \| |_ / _ \
 | |_) | | | | |_) | |__| (_) | | | | | | |_) | (_| | |_ | || | | |  _| (_) |
 | .__/|_| |_| .__/ \____\___/|_| |_| |_| .__/ \__,_|\__|___|_| |_|_|  \___/
 |_|         |_|                        |_|

phpCompatInfo version 5.0.12 DB version 1.29.0 built Feb 01 2018 22:12:58 CET

Usage:
 command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --no-plugins      Disables all plugins.
      --profile         Display timing and memory usage information.
      --progress        Show progress bar.
      --output=OUTPUT   Write results to file or URL.
      --manifest        Show which versions of dependencies are bundled.
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
 help                  Displays help for a command
 list                  Lists commands
analyser
 analyser:list         List all analysers available.
 analyser:run          Analyse a data source and display results.
cache
 cache:clear           Clear cache (any adapter and backend).
config
 config:validate       Validates a JSON configuration file.
diagnose
 diagnose:run          Diagnoses the system to identify common errors.
diagram
 diagram:class         Generates diagram about a user class present in a data source.
 diagram:package       Generates diagram about namespaces in a data source.
plugin
 plugin:list           List all plugins installed.
reference
 reference:list        List all references supported.
 reference:show        Show information about a reference.
reflection
 reflection:class      Reports information about a user class present in a data source.
 reflection:function   Reports information about a user function present in a data source.

Auto-Diagnose:

Checking php settings:
- Requires PHP 5.4.0 or better OK
- php.ini file loaded C:\UwAmp\bin\php\php-5.6.32\php.ini
- date extension loaded YES
- json extension loaded YES
- pcre extension loaded YES
- phar extension loaded YES
- reflection extension loaded YES
- spl extension loaded YES
- tokenizer extension loaded YES

config:validate

Validates an optional JSON config file.

$ phpcompatinfo config:validate
"/etc/phpcompatinfo.json" config file is valid.

diagnose:run

Diagnoses the system to identify common errors.

$ phpcompatinfo diagnose:run
Checking php settings:
- Requires PHP 5.4.0 or better OK
- php.ini file loaded C:\UwAmp\bin\php\php-5.6.32\php.ini
- date extension loaded YES
- json extension loaded YES
- pcre extension loaded YES
- phar extension loaded YES
- reflection extension loaded YES
- spl extension loaded YES
- tokenizer extension loaded YES
[Tip]

Use verbose level 2 for more details, and level 3 to get raw response

diagram:class

Generates diagram about a user class present in a data source.

$ phpcompatinfo diagram:class Bartlett\Reflect\Plugin\LogPlugin ./src

diagram:package

Generates diagram about namespaces in a data source.

$ phpcompatinfo diagram:package --engine=graphviz ./src

plugin:list

List all plugins configured (and correctly installed) in plugins section of your phpcompatinfo.json config file.

Without plugins, you will get. 

$ phpcompatinfo plugin:list

No plugin installed.

With only Cache plugin configured, you will get. 

$ phpcompatinfo plugin:list

 Plugin Class                           Events Subscribed
 Bartlett\Reflect\Plugin\CachePlugin    reflect.progress
                                        reflect.success
                                        reflect.complete

analyser:list

List all analysers configured in analysers section of your phpcompatinfo.json config file, and available by default.

With only default analysers, you will get. 

$ phpcompatinfo analyser:list

 Analyser Name Analyser Class
 loc           Bartlett\Reflect\Analyser\LocAnalyser
 reflection    Bartlett\Reflect\Analyser\ReflectionAnalyser
 structure     Bartlett\Reflect\Analyser\StructureAnalyser
 compatibility Bartlett\CompatInfo\Analyser\CompatibilityAnalyser

analyser:run

Parse a data source and display results. May vary depending of the data source and analyser used.

With compatibility analyser and the CompatInfo source code, you will get something like. 

$ phpcompatinfo analyser:run .

Possible alternative (if you use the default json config file). 

$ phpcompatinfo analyser:run --alias current

Data Source Analysed

Directories                                         11
Files                                               13

Extensions Analysis

    Extension Matches REF      EXT min/Max PHP min/Max PHP all
    Core              Core                 4.0.0       5.3.0
    PDO               PDO      5.1.0       5.1.0
    curl              curl     4.0.2       4.0.2
    intl              intl     2.0.0b1     5.3.7
    libxml            libxml   5.1.0       5.1.0
    openssl           openssl  5.2.0       5.2.0
    pcre              pcre     4.0.0       4.0.0
    spl               spl      5.1.0       5.1.0
    standard          standard 4.0.0       4.0.0       5.3.2
    Total [9]                              5.3.7

Namespaces Analysis

    Namespace                             Matches REF  EXT min/Max PHP min/Max PHP all
    +global                                       Core             4.0.0
    Bartlett\CompatInfo                           user             5.3.0
    Bartlett\CompatInfo\Analyser                  user             5.3.0
    Bartlett\CompatInfo\Api                       user             5.3.0       5.3.2
    Bartlett\CompatInfo\Api\V3                    user             5.3.0
    Bartlett\CompatInfo\Collection                user             5.3.0
    Bartlett\CompatInfo\Console                   user             5.3.0
    Bartlett\CompatInfo\Console\Formatter         user             5.3.0
    Bartlett\CompatInfo\Output                    user             5.3.0
    Bartlett\CompatInfo\PhpParser                 user             5.3.0
    Bartlett\CompatInfo\Reference                 user             5.3.0
    Bartlett\CompatInfo\Util                      user             5.3.0
    Total [12]                                                     5.3.0       5.3.2

Interfaces Analysis

    Interface                                        Matches REF  EXT min/Max PHP min/Max PHP all
    Bartlett\CompatInfo\Reference\ReferenceInterface 1       user             5.3.0
    Total [1]                                                                 5.3.0

No trait found

Classes Analysis

    Class                                                              Matches REF  EXT min/Max PHP min/Max PHP all
    Bartlett\CompatInfo\Analyser\CompatibilityAnalyser                         user             5.3.0
    Bartlett\CompatInfo\Api\Reference                                          user             5.3.0       5.3.2
    Bartlett\CompatInfo\Api\V3\Reference                                       user             5.3.0
    Bartlett\CompatInfo\Collection\ReferenceCollection                 1       user             5.3.0
    Bartlett\CompatInfo\Console\Application                                    user             5.3.0
    Bartlett\CompatInfo\Console\Formatter\CompatibilityOutputFormatter         user             5.3.0
    Bartlett\CompatInfo\Environment                                    4       user             5.3.0
    Bartlett\CompatInfo\Output\Reference                                       user             5.3.0
    Bartlett\CompatInfo\PhpParser\ConditionalCodeNodeProcessor         1       user             5.3.0
    Bartlett\CompatInfo\Reference\ExtensionFactory                     2       user             5.3.0
    Bartlett\CompatInfo\Reference\SqliteStorage                        1       user             5.3.0
    Bartlett\CompatInfo\Util\Version                                   10      user             5.3.0
  U Bartlett\Reflect\Analyser\AbstractAnalyser                         1       user             5.3.0
  U Bartlett\Reflect\Api\BaseApi                                       1       user             5.3.0
  U Bartlett\Reflect\Api\V3\Common                                     1       user             5.3.0
  U Bartlett\Reflect\Console\Application                               1       user             5.3.0
  U Bartlett\Reflect\Console\Formatter\OutputFormatter                 2       user             5.3.0
  U Bartlett\Reflect\PhpParser\NodeProcessorAbstract                   1       user             5.3.0
  U Doctrine\Common\Collections\AbstractLazyCollection                 1       user             5.3.0
  U Doctrine\Common\Collections\ArrayCollection                        1       user             5.3.0
    PDO                                                                2       PDO  5.1.0       5.1.0
  U PhpParser\Node                                                     21      user             5.3.0
  U PhpParser\Node\Name                                                1       user             5.3.0
    RuntimeException                                                   1       spl  5.1.0       5.1.0
  U Symfony\Component\Console\Helper\TableSeparator                    3       user             5.3.0
  U Symfony\Component\Console\Output\OutputInterface                   4       user             5.3.0
    parent                                                             5       Core 5.0.0       5.0.0
    self                                                               11      Core 5.0.0       5.0.0
    stdClass                                                           1       Core 4.0.0       4.0.0
    Total [29]                                                                                  5.3.0       5.3.2

Functions Analysis

    Function                    Matches REF      EXT min/Max PHP min/Max
    array_key_exists            7       standard 4.0.7       4.0.7
    array_map                   2       standard 4.0.6       4.0.6
    array_merge                 3       standard 4.0.0       4.0.0
    array_pop                   6       standard 4.0.0       4.0.0
    array_shift                 2       standard 4.0.0       4.0.0
    array_slice                 1       standard 4.0.0       4.0.0
    array_values                1       standard 4.0.0       4.0.0
    closure-73-75                       user                 5.3.0
    copy                        1       standard 4.0.0       4.0.0
    count                       14      standard 4.0.0       4.0.0
 C  curl_version                1       curl     4.0.2       4.0.2
    defined                     4       Core     4.0.0       4.0.0
    dirname                     3       standard 4.0.0       4.0.0
    each                        2       Core     4.0.0       4.0.0
    end                         3       standard 4.0.0       4.0.0
    explode                     2       standard 4.0.0       4.0.0
    extension_loaded            1       Core     4.0.0       4.0.0
    file_exists                 2       standard 4.0.0       4.0.0
    function_exists             1       Core     4.0.0       4.0.0
    in_array                    10      standard 4.0.0       4.0.0
    is_array                    1       standard 4.0.0       4.0.0
    is_callable                 1       standard 4.0.6       4.0.6
    is_string                   10      standard 4.0.0       4.0.0
    ksort                       3       standard 4.0.0       4.0.0
    ltrim                       1       standard 4.0.0       4.0.0
    mkdir                       1       standard 4.0.0       4.0.0
    phpversion                  2       standard 4.0.0       4.0.0
    preg_match                  2       pcre     4.0.0       4.0.0
    sha1_file                   2       standard 4.3.0       4.3.0
    sprintf                     26      standard 4.0.0       4.0.0
    str_replace                 1       standard 4.0.0       4.0.0
    strcasecmp                  4       Core     4.0.0       4.0.0
    stream_resolve_include_path 1       standard 5.3.2       5.3.2
    strpos                      2       standard 4.0.0       4.0.0
    strtolower                  1       standard 4.0.0       4.0.0
    substr                      2       standard 4.0.0       4.0.0
    sys_get_temp_dir            1       standard 5.2.1       5.2.1
    ucfirst                     5       standard 4.0.0       4.0.0
    version_compare             9       standard 4.0.7       4.0.7
    Total [39]                                               5.3.2

Constants Analysis

    Constant               Matches REF     EXT min/Max PHP min/Max
 C  INTL_ICU_VERSION       2       intl    2.0.0b1     5.3.7
    LIBXML_DOTTED_VERSION  1       libxml  5.1.0       5.1.0
    LIBXML_VERSION         1       libxml  5.1.0       5.1.0
 C  OPENSSL_VERSION_NUMBER 1       openssl 5.2.0       5.2.0
 C  OPENSSL_VERSION_TEXT   1       openssl 5.2.0       5.2.0
    PHP_EOL                5       Core    4.3.10      4.3.10
    PHP_VERSION            4       Core    4.0.0       4.0.0
    __DIR__                1       Core    5.3.0       5.3.0
    false                  14      Core    4.0.0       4.0.0
    null                   15      Core    4.0.0       4.0.0
    true                   10      Core    4.0.0       4.0.0
    Total [11]                                         5.3.0

Conditions Analysis

    Condition                       Matches REF     EXT min/Max PHP min/Max
    defined(INTL_ICU_VERSION)       2       intl    2.0.0b1     5.3.7
    defined(OPENSSL_VERSION_NUMBER) 1       openssl 5.2.0       5.2.0
    defined(OPENSSL_VERSION_TEXT)   1       openssl 5.2.0       5.2.0
    function_exists(curl_version)   1       curl    4.0.2       4.0.2
    Total [4]                                                   5.3.7

Requires PHP 5.3.2 (min), PHP 5.3.2 (all)
[Note]

The PHP all column tell us which version is required when all code features are used

Since version 4.2, you can filter results with a user closure. 

$ phpcompatinfo analyser:run --filter=YourFilters.php .

[Note]

Learn more on chapter Chapter 23, Build your Filters

reflection:class

Reports information about a user class present in a data source.

With the CompatInfo source code (./src), and Bartlett\CompatInfo\Environment class. 

$ phpcompatinfo reflection:class Bartlett\CompatInfo\Environment ./src

Class [ <user> class Bartlett\CompatInfo\Environment ] {
  @@ C:\home\github\php-compat-info\src\Bartlett\CompatInfo\Environment.php 28 - 73

  - Constants [0] {
  }

  - Properties [0] {
  }

  - Methods [2] {
    Method [ <user> public method initRefDb ] {
      @@ C:\home\github\php-compat-info\src\Bartlett\CompatInfo\Environment.php 35 - 55

      - Parameters [0] {
      }
    }

    Method [ <user> public method versionRefDb ] {
      @@ C:\home\github\php-compat-info\src\Bartlett\CompatInfo\Environment.php 62 - 72

      - Parameters [0] {
      }
    }
  }
}

Chapter 10. Summary

Let’s review what we’ve learned about the command-line interface :

  • It’s a Symfony Console Component that can be extended to infinite via plugins and analysers.
  • You can examine inside a reference and filters elements.

Part III. Migration Guide v3

CLI CLI

Begin first with the commands of CompatInfo in CLI mode.

See Chapter 11, CLI

XML XML

How you can customize CompatInfo in CLI mode only.

See Chapter 12, Configuration file

XML API

Due to namespaces, API are incompatible in versions 2 and 3. Here are code to do the same things.

See Chapter 13, Server API

Chapter 11. CLI

11.1. Progress Bar

Since version 2.12, there is a new progress bar (ALA PHPUnit).

PHP_CompatInfo 2.12.0 by Laurent Laville

....CC......................................................  60 / 128 ( 46%)
....C..C..........................................C....C.... 120 / 128 ( 93%)
.C.....C
  • each C character tell us that there is a source file with conditional code.

With version 3.2, the progress bar (ALA Symfony Console Progress Helper) is activated with the first verbose level (-v). For example :

$ phpcompatinfo -v analyser:run <SOURCE>

Renders

    3/128 [>---------------------------]   0% Elapsed: 2 secs

References

If we want to display list of references supported, here is how to do with both versions :

Version 2.26

$ phpcompatinfo list-references

Version 3.2

$ phpcompatinfo reference:list

Now, if you want to details each reference one by one identified by its name (<REF> in following examples), and got :

  • Extensions

Version 2.26

$ phpcompatinfo list --reference=ALL extensions
or
$ phpcompatinfo list-extensions --reference=ALL

Version 3.2

$ phpcompatinfo reference:list

  • Interfaces

Version 2.26

$ phpcompatinfo list --reference=ALL interfaces <REF>
or
$ phpcompatinfo list-interfaces --reference=ALL <REF>

Version 3.2

$ phpcompatinfo reference:show --interfaces <REF>

  • Classes

Version 2.26

$ phpcompatinfo list --reference=ALL classes <REF>
or
$ phpcompatinfo list-classes --reference=ALL <REF>

Version 3.2

$ phpcompatinfo reference:show --classes <REF>

  • Functions

Version 2.26

$ phpcompatinfo list --reference=ALL functions <REF>
or
$ phpcompatinfo list-functions --reference=ALL <REF>

Version 3.2

$ phpcompatinfo reference:show --functions <REF>

  • Constants

Version 2.26

$ phpcompatinfo list --reference=ALL constants <REF>
or
$ phpcompatinfo list-constants --reference=ALL <REF>

Version 3.2

$ phpcompatinfo reference:show --constants <REF>

  • INI entries
[Caution]

Feature not provided by version 2.26

Version 3.2

$ phpcompatinfo reference:show --ini <REF>

And if you want to filter results on PHP version, do for example :

Version 2.26

$ phpcompatinfo list --reference=ALL classes <REF> --filter-version="php_5.1.0" --filter-operator="ge"

Version 3.2

$ phpcompatinfo reference:show --classes <REF> --php=">= 5.1.0"

11.2. Print parses results

Where <SOURCE> identify the data source, directly in CompatInfo 2.26, and via the JSON configuration file in version 3.2

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive <SOURCE>
or
$ phpcompatinfo print --reference=ALL --recursive --report summary <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE>
or
$ phpcompatinfo analyser:run <SOURCE> summary

And with additionals reports :

  • extension

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report extension <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> extension

  • namespace

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report namespace <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> namespace

  • trait

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report trait <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> trait

  • interface

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report interface <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> interface

  • class

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report class <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> class

  • function

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report function <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> function

  • constant

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report constant <SOURCE>

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> constant

  • global

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report global <SOURCE>

[Caution]

Feature not provided by version 3.2

  • condition

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report condition <SOURCE>

Version 3.4

$ phpcompatinfo analyser:run <SOURCE> condition

  • token

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report token <SOURCE>

[Caution]

Feature not provided by version 3.2

  • xml

Version 2.26

$ phpcompatinfo print --reference=ALL --recursive --report xml <SOURCE>

[Caution]

Feature not provided by version 3.2

  • source

Version 2.26

$ phpcompatinfo -v print --reference=ALL --report source <SOURCE>

Version 3.2

$ phpcompatinfo provider:display <SOURCE>

11.3. Caching results

[Caution]
  • Version 2.26 may cache results to speed-up later analysis.
  • Version 3.2 is able (optionally) to cache results only with other SAPI than CLI.
  • Version 3.3 is able to cache results on all API including CLI.

Chapter 12. Configuration file

12.1. Global options

  • File extensions was restricted by default in both versions to php, inc and html.
[Warning]

In CompatInfo 3.2, the Finder recursively traverse directories, while it’s not true in version 2.26

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo
    recursive="false"
    fileExtensions="php, inc, phtml"
    >

    <!-- ... -->
</phpcompatinfo>

JSON configuration 3.2

{
    "source-providers": [
        {
            "in": ". as current",
            "name": "/\\.(php|inc|phtml)$/"
        }
    ],
}

  • Progress bar

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo
    consoleProgress="true"
    verbose="false"
    >

    <!-- ... -->
</phpcompatinfo>

Use the first verbose level (-v) with phpcompatinfo while running the analyser:run command.

  • Caching results

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo
    cacheDriver="file"
    >

    <!-- ... -->
</phpcompatinfo>

[Warning]

Version 3.2 is able to cache parsing results only with other SAPI than CLI. See the Developer Guide.

12.2. Cache options

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo>

    <cache id="file">
        <options>
            <gc_probability>1</gc_probability>
            <gc_maxlifetime>86400</gc_maxlifetime>
        </options>
    </cache>

</phpcompatinfo>

[Caution]

Version 3.2 does not provide yet ability to cache parsing results in CLI mode.

12.3. References options

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo>

    <references>
        <reference name="Core" />
        <reference name="standard" />
    </references>

</phpcompatinfo>

[Caution]

Version 3.2 does not provide ability to load reference depending of rules in the configuration file.

All references are either pre-loaded (Prefetch Strategy) or loaded only when detected (AutoDiscover Strategy).

See Part VI, “References included”

12.4. PHP settings

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo>

    <php>
        <ini name="memory_limit" value="140M" />
        <ini name="short_open_tag" />
        <ini name="zend.ze1_compatibility_mode" value="false" />
    </php>

</phpcompatinfo>

[Caution]

Version 3.2 does not provide ability to change PHP settings at run-time.

12.5. Excluding Files or Elements from parsing

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo>

    <excludes>
        <exclude id="demo">
            <directory name=".*\/Zend\/.*" />
            <file name=".*\.php5" />
            <extension name="xdebug" />
            <interface name="SplSubject" />
            <trait name="^S" />
            <class name=".*Compat.*" />
            <function name="ereg.*" />
            <function name="debug_print_backtrace" />
            <constant name="T_USE" />
        </exclude>
    </excludes>

</phpcompatinfo>

[Warning]

Version 3.2 does not provide ability to exclude elements (class, trait, …), but you can exclude files or directories with the Finder. See source-providers in the JSON configuration file. See Chapter 8, The Json Configuration File

12.6. Listeners

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo>

    <listeners>
        <listener class="className" file="/path/to/filename">
            <arguments>
            </arguments>
        </listener>
    </listeners>

</phpcompatinfo>

[Note]

Version 3.2 provide this feature with the Symfony EventDispatcher component.

See Section 15.2, “Plugins”

12.7. Plugins options

XML configuration 2.26

<?xml version="1.0" encoding="utf-8" ?>
<phpcompatinfo>

    <plugins>
        <reference name="MyReference"
            class="PEAR_CompatInfo"
            file="/path/to/PEARCompatInfo.php">
            <arguments>
            </arguments>
        </reference>
    </plugins>

</phpcompatinfo>

[Caution]

Version 3.2 does not provide ability to select a custom References list.

All references are either pre-loaded (Prefetch Strategy) or loaded only when detected (AutoDiscover Strategy).

See Part VI, “References included”

Chapter 13. Server API

13.1. Parsing recursive directories

[Warning]

By default,

  • recursive option is set to false in CompatInfo 2.26, while the Finder recursively traverse directories in version 3.2
  • cacheDriver option is set to file in CompatInfo 2.26, while version 3.2 did not added the cache plugin.

Version 2.26

<?php
require_once 'Bartlett/PHP/CompatInfo/Autoload.php';

$source  = '/path/to/source';
$options = array(
    'cacheDriver' => 'null',
    'recursive'   => true
);

$compatinfo = new PHP_CompatInfo($options);
$compatinfo->parse($source);

Version 3.2

<?php
require_once 'vendor/autoload.php';

use Bartlett\CompatInfo;

use Bartlett\Reflect\ProviderManager;
use Bartlett\Reflect\Provider\SymfonyFinderProvider;

use Symfony\Component\Finder\Finder;

$dirs = '/path/to/source';

$finder = new Finder();
$finder->files()
    ->name('*.php')
    ->in($dirs);

$provider = new SymfonyFinderProvider($finder);

$pm = new ProviderManager;
$pm->set('dataSourceIdent', $provider);

$compatinfo = new CompatInfo;
$compatinfo->setProviderManager($pm);
$compatinfo->parse();

13.2. Using cache feature

Version 2.26

<?php
require_once 'Bartlett/PHP/CompatInfo/Autoload.php';

$source  = '/path/to/source';
$options = array(
    'cacheDriver' => 'file',
    'recursive'   => true
);

$compatinfo = new PHP_CompatInfo($options);
$compatinfo->parse($source);

[Tip]

It’s not mandatory to specify cacheDriver option what is by default set to false.

Version 3.2

<?php
require_once 'vendor/autoload.php';

use Bartlett\CompatInfo;

use Bartlett\Reflect\ProviderManager;
use Bartlett\Reflect\Provider\SymfonyFinderProvider;
use Bartlett\Reflect\Plugin\Cache\CachePlugin;
use Bartlett\Reflect\Plugin\Cache\DefaultCacheStorage;
use Bartlett\Reflect\Cache\DoctrineCacheAdapter;

use Doctrine\Common\Cache\FilesystemCache;

use Symfony\Component\Finder\Finder;

$dirs = '/path/to/source';

$finder = new Finder();
$finder->files()
    ->name('*.php')
    ->in($dirs);

$provider = new SymfonyFinderProvider($finder);

$pm = new ProviderManager;
$pm->set('dataSourceIdent', $provider);

$backend = new FilesystemCache(sys_get_temp_dir() . '/phpcompatinfo');
$doctrineCache = new DoctrineCacheAdapter($backend);
$cache = new DefaultCacheStorage($doctrineCache);

$compatinfo = new CompatInfo;
$compatinfo->setProviderManager($pm);
$compatinfo->addPlugin( new CachePlugin($cache) );
$compatinfo->parse();

13.3. Listeners

[Caution]

While CompatInfo 2.26 audit all events (does not provide ability to filter them, unless by writing a new listener), version 3.2 let you choose and connect a function by event. See ???

Version 2.26

<?php
require_once 'Bartlett/PHP/CompatInfo/Autoload.php';

$source  = '/path/to/source';
$options = array(
    'cacheDriver' => 'null',
    'recursive'   => true
);

$fileListener = new PHP_CompatInfo_Listener_File();

$compatinfo = new PHP_CompatInfo($options);
$compatinfo->attach($fileListener);
$compatinfo->parse($source);

Version 3.2

<?php
require_once 'vendor/autoload.php';

use Bartlett\CompatInfo;

use Bartlett\Reflect\ProviderManager;
use Bartlett\Reflect\Provider\SymfonyFinderProvider;

use Symfony\Component\Finder\Finder;

$dirs = '/path/to/source';

$finder = new Finder();
$finder->files()
    ->name('*.php')
    ->in($dirs);

$provider = new SymfonyFinderProvider($finder);

$pm = new ProviderManager;
$pm->set('dataSourceIdent', $provider);

$compatinfo = new CompatInfo;
$compatinfo->setProviderManager($pm);

$compatinfo->getEventDispatcher()->addListener(
    'reflect.progress',
    function (GenericEvent $e) {
        printf(
            'Parsing Data source "%s" in progress ... File "%s"' . PHP_EOL,
            $e['source'],
            $e['file']->getPathname()
        );
    }
);
$compatinfo->parse();

13.4. Exploring parsing results

Version 2.26

<?php
require_once 'Bartlett/PHP/CompatInfo/Autoload.php';

$source  = '/path/to/source';
$options = array(
    'cacheDriver' => 'null',
    'recursive'   => true
);

$compatinfo = new PHP_CompatInfo($options);
$compatinfo->parse($source);

$versions   = $compatinfo->getVersions();
$classes    = $compatinfo->getClasses();
$functions  = $compatinfo->getFunctions();
$extensions = $compatinfo->getExtensions();

Version 3.2

<?php
require_once 'vendor/autoload.php';

use Bartlett\CompatInfo;
use Bartlett\CompatInfo\Analyser;

use Bartlett\Reflect\ProviderManager;
use Bartlett\Reflect\Provider\SymfonyFinderProvider;
use Bartlett\Reflect\Plugin\Analyser\AnalyserPlugin;

use Symfony\Component\Finder\Finder;

$dirs = '/path/to/source';

$finder = new Finder();
$finder->files()
    ->name('*.php')
    ->in($dirs);

$provider = new SymfonyFinderProvider($finder);

$sourceId = 'dataSourceIdent';

$pm = new ProviderManager;
$pm->set($sourceId, $provider);

$compatinfo = new CompatInfo;
$compatinfo->setProviderManager($pm);
$compatinfo->addPlugin(
    new AnalyserPlugin(
        array(
            new Analyser\SummaryAnalyser(),
        )
    )
);
$compatinfo->parse();

$metrics = $compatinfo->getMetrics();

$versions   = $metrics[$sourceId]['sa.versions'];
$classes    = $metrics[$sourceId]['sa.classes'];
$functions  = $metrics[$sourceId]['sa.functions'];
$extensions = $metrics[$sourceId]['sa.extensions'];

[Note]

sa. prefix corresponds to class constant METRICS_PREFIX of SummaryAnalyser.

Part IV. Migration Guide v4

CLI CLI

Begin first with the commands of CompatInfo in CLI mode.

See Chapter 11, CLI

JSON JSON

How you can customize CompatInfo for all SAPI.

See Chapter 12, Configuration file

API API

API are incompatible in versions 3 and 4. Here are code to do the same things.

See Chapter 13, Server API

Chapter 14. CLI

14.1. Progress Bar

With adoption of Symfony/Console 2.5 or greater, the progress bar feature is used instead of the progress bar helper.

The progress bar is displayed only if you invoke commands with the --progress option.

For example :

$ phpcompatinfo --progress analyser:run <SOURCE>

Renders depends of verbosity level.

For example, on verbose level 1, progress will be displayed as a throbber:

        8 [-------->-------------------]  1 sec

For example, on verbose level 2:

    7  1 sec File Bartlett\CompatInfo\Console\Formatter\CompatibilityOutputFormatter.php in progress...

For example, on verbose level 3:

    4  1 sec 6.8 MiB File Bartlett\CompatInfo\Analyser\CompatibilityAnalyser.php in progress...

References

If we want to display list of references supported, here is how to do with both versions :

Version 3.2

$ phpcompatinfo reference:list

Version 4.0

$ phpcompatinfo reference:list

Now, if you want to details each reference one by one identified by its name (<REF> in following examples), and got :

  • Releases
[Caution]

Feature not provided by version 3.2

Version 4.0

$ phpcompatinfo reference:show --releases <REF>

  • Interfaces

Version 3.2

$ phpcompatinfo reference:show --interfaces <REF>

Version 4.0

$ phpcompatinfo reference:show --interfaces <REF>

  • Classes

Version 3.2

$ phpcompatinfo reference:show --classes <REF>

Version 4.0

$ phpcompatinfo reference:show --classes <REF>

  • Functions

Version 3.2

$ phpcompatinfo reference:show --functions <REF>

Version 4.0

$ phpcompatinfo reference:show --functions <REF>

  • Constants

Version 3.2

$ phpcompatinfo reference:show --constants <REF>

Version 4.0

$ phpcompatinfo reference:show --constants <REF>

  • INI entries

Version 3.2

$ phpcompatinfo reference:show --ini <REF>

Version 4.0

$ phpcompatinfo reference:show --ini <REF>

14.2. Print parses results

Where <SOURCE> identify the data source, directly or via the JSON configuration file.

Version 3.2

$ phpcompatinfo analyser:run <SOURCE> --php

Version 4.0

$ phpcompatinfo analyser:run <SOURCE>

14.3. Caching results

[Caution]
  • Version 3.2 may cache results to speed-up later analysis.
  • Version 4.0 is also able to cache results.

    But it seems not necessary, especially if you unload xdebug extension (that slows down execution at least by 50%).

Chapter 15. Configuration file

15.1. Defaults

JSON configuration 3.2

{
    "source-providers": [
        {
            "in": ". as current",
            "name": "/\\.(php|inc|phtml)$/"
        }
    ],
    "plugins": [
        {
            "name": "Analyser",
            "class": "Bartlett\\Reflect\\Plugin\\Analyser\\AnalyserPlugin"
        }
    ],
    "analysers" : [
        {
            "name": "Namespace",
            "class": "Bartlett\\CompatInfo\\Analyser\\NamespaceAnalyser"
        },
        {
            "name": "Extension",
            "class": "Bartlett\\CompatInfo\\Analyser\\ExtensionAnalyser"
        },
        {
            "name": "Interface",
            "class": "Bartlett\\CompatInfo\\Analyser\\InterfaceAnalyser"
        },
        {
            "name": "Trait",
            "class": "Bartlett\\CompatInfo\\Analyser\\TraitAnalyser"
        },
        {
            "name": "Class",
            "class": "Bartlett\\CompatInfo\\Analyser\\ClassAnalyser"
        },
        {
            "name": "Function",
            "class": "Bartlett\\CompatInfo\\Analyser\\FunctionAnalyser"
        },
        {
            "name": "Constant",
            "class": "Bartlett\\CompatInfo\\Analyser\\ConstantAnalyser"
        },
        {
            "name": "Summary",
            "class": "Bartlett\\CompatInfo\\Analyser\\SummaryAnalyser"
        },
        {
            "name": "Condition",
            "class": "Bartlett\\CompatInfo\\Analyser\\CodeCondAnalyser"
        },
        {
            "name": "Composer",
            "class": "Bartlett\\CompatInfo\\Analyser\\ComposerAnalyser"
        },
        {
            "name": "Structure",
            "class": "Bartlett\\Reflect\\Analyser\\StructureAnalyser"
        }
    ]
}

Minimal JSON configuration 4.0

{
    "source-providers": [
    ],
    "plugins": [
    ],
    "analysers" : [
    ],
    "services" : [
    ]
}

[Note]

In version 4.0, all (default) analysers are available. It’s no more required to declare them in the JSON config file, especially because this file is now became optional.

15.2. Plugins

[Warning]

Cache plugin may be find in different location (class) between versions 3.2 and 4.0

Version 3.2

{
    "plugins": [
        {
            "name": "Analyser",
            "class": "Bartlett\\Reflect\\Plugin\\Analyser\\AnalyserPlugin"
        },
        {
            "name": "Cache",
            "class": "Bartlett\\Reflect\\Plugin\\Cache\\CachePlugin",
            "options": {
                "adapter": "DoctrineCacheAdapter",
                "backend": {
                    "class": "Doctrine\\Common\\Cache\\FilesystemCache",
                    "args": [
                        "%{TEMP}/bartlett/cache"
                    ]
                }
            }
        }
    ],
}

Version 4.0

{
    "plugins": [
        {
            "name": "Cache",
            "class": "Bartlett\\Reflect\\Plugin\\CachePlugin",
            "options": {
                "adapter": "DoctrineCacheAdapter",
                "backend": {
                    "class": "Doctrine\\Common\\Cache\\FilesystemCache",
                    "args": [
                        "%{TEMP}/bartlett/cache"
                    ]
                }
            }
        }
    ],
}

[Note]

AnalyserPlugin was removed in 4.0. We have just to include a new analyser in the analysers section to make it available.

Chapter 16. Server API

16.1. Using cache feature

Version 3.2

<?php
require_once 'vendor/autoload.php';

use Bartlett\CompatInfo;

use Bartlett\Reflect\ProviderManager;
use Bartlett\Reflect\Provider\SymfonyFinderProvider;
use Bartlett\Reflect\Plugin\Cache\CachePlugin;
use Bartlett\Reflect\Plugin\Cache\DefaultCacheStorage;
use Bartlett\Reflect\Cache\DoctrineCacheAdapter;

use Doctrine\Common\Cache\FilesystemCache;

use Symfony\Component\Finder\Finder;

$dirs = '/path/to/source';

$finder = new Finder();
$finder->files()
    ->name('*.php')
    ->in($dirs);

$provider = new SymfonyFinderProvider($finder);

$pm = new ProviderManager;
$pm->set('dataSourceIdent', $provider);

$backend = new FilesystemCache(sys_get_temp_dir() . '/phpcompatinfo');
$doctrineCache = new DoctrineCacheAdapter($backend);
$cache = new DefaultCacheStorage($doctrineCache);

$compatinfo = new CompatInfo;
$compatinfo->setProviderManager($pm);
$compatinfo->addPlugin( new CachePlugin($cache) );
$compatinfo->parse();

Version 4.0

<?php
$loader = require_once dirname(__DIR__) . '/vendor/autoload.php';
$loader->addClassMap(
    array(
        'YourNamespace\CachePlugin'
            =>  __DIR__ . '/YourNamespace/CachePlugin.php',
    )
);

use Bartlett\Reflect\Environment;
use Bartlett\Reflect\Client;

use Symfony\Component\EventDispatcher\GenericEvent;

// set our own location of JSON config file
putenv("BARTLETT_SCAN_DIR=" . __DIR__ . '/YourNamespace');

// set our own JSON config file
putenv("BARTLETTRC=yournamespace.json");

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

// perform request, on a data source with default analyser (structure)
$dataSource = dirname(__DIR__) . '/src';
$analysers  = array('structure');

// equivalent to CLI command `phpcompatinfo analyser:run ../src`
$metrics = $api->run($dataSource, $analysers);

var_export($metrics);

See full example in bartlett/php-reflect package.

16.2. Listeners

Version 3.2

<?php
require_once 'vendor/autoload.php';

use Bartlett\CompatInfo;

use Bartlett\Reflect\ProviderManager;
use Bartlett\Reflect\Provider\SymfonyFinderProvider;

use Symfony\Component\Finder\Finder;

$dirs = '/path/to/source';

$finder = new Finder();
$finder->files()
    ->name('*.php')
    ->in($dirs);

$provider = new SymfonyFinderProvider($finder);

$pm = new ProviderManager;
$pm->set('dataSourceIdent', $provider);

$compatinfo = new CompatInfo;
$compatinfo->setProviderManager($pm);

$compatinfo->getEventDispatcher()->addListener(
    'reflect.progress',
    function (GenericEvent $e) {
        printf(
            'Parsing Data source "%s" in progress ... File "%s"' . PHP_EOL,
            $e['source'],
            $e['file']->getPathname()
        );
    }
);
$compatinfo->parse();

Version 4.0

<?php
require_once 'vendor/autoload.php';

use Bartlett\Reflect\Client;
use Bartlett\Reflect\Events;

use Symfony\Component\EventDispatcher\GenericEvent;

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

$dispatcher = $api->getEventDispatcher();

$dispatcher->addListener(
    Events::PROGRESS,
    function (GenericEvent $e) {
        printf(
            'Parsing Data source "%s" in progress ... File "%s"' . PHP_EOL,
            $e['source'],
            $e['file']->getPathname()
        );
    }
);

// perform request, on a data source with default analyser (compatibility)
$dataSource = "/path/to/source';
$analysers  = array('compatibility');

// equivalent to CLI command `phpcompatinfo analyser:run /path/to/source`
$metrics = $api->run($dataSource, $analysers);

var_export($metrics);

16.3. Exploring parsing results

Version 3.2

<?php
require_once 'Bartlett/PHP/CompatInfo/Autoload.php';

$source  = '/path/to/source';
$options = array(
    'cacheDriver' => 'null',
    'recursive'   => true
);

$compatinfo = new PHP_CompatInfo($options);
$compatinfo->parse($source);

$versions   = $compatinfo->getVersions();
$classes    = $compatinfo->getClasses();
$functions  = $compatinfo->getFunctions();
$extensions = $compatinfo->getExtensions();

Version 4.0

<?php
require_once 'vendor/autoload.php';

use Bartlett\Reflect\Client;

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

// perform request, on a data source with default analyser (compatibility)
$dataSource = '/path/to/source';
$analysers  = array('compatibility');

// equivalent to CLI command `phpcompatinfo analyser:run /path/to/source`
$response = $api->run($dataSource, $analysers);

$metrics    = $response['Bartlett\CompatInfo\Analyser\CompatibilityAnalyser'];
$versions   = $metrics['versions'];
$classes    = $metrics['classes'];
$functions  = $metrics['functions'];
$extensions = $metrics['extensions'];

Part V. Developer Guide

API API

CompatInfo comes with a complete API.

See Chapter 17, API

Plugins Plugins

CompatInfo uses a Symfony EventDispatcher Component to allow you to easily extend the features list.

See ???

Analysers Analysers

CompatInfo uses analysers that implements the Visitor pattern in a simple and effective way to make the render of your results truly customizable.

See Chapter 22, Build your Analysers

Filters Filters

CompatInfo can filter results, since version 4.2, to make the render of your results truly customizable.

See Chapter 23, Build your Filters

Chapter 17. API

17.1. Data Source Identification

Basic or Complex Strategy to identify the Data Source.

[Warning]

Now, and for the following chapters, we will not mention how you load the classes. Depending of the install strategy you’ve adopted, Composer or other, don’t forget to load your autoloader.

Compare to version 2, CompatInfo 4 offers two simple strategies to identify the data source.

First, is to give the relative or absolute path to file or directory to parse (without limitation).

Second, is to specify options to customize parsing process, to the Symfony Finder Component.

17.1.1. Basic Strategy

With all SAPI, no JSON config file is required (as it was for CompatInfo 3). You have just to give the relative or absolute path to file or directory to parse.

It’s also possible to specify any archive (phar, zip, tar, tgz, gz, rar) as file source.

Example with a simple file or directory (absolute path). 

$ phpcompatinfo analyser:run /absolute/path/to/source

Example with a simple file or directory (relative path). 

$ phpcompatinfo analyser:run ./relative/path/to/source

17.1.2. Complex Strategy

Still as it was with CompatInfo 3, you will need to configure your data source in a JSON file.

Syntax is closed to the Symfony Finder Component that is used to limit data source contents to parse.

Example to parse an archive. 

{
    "source-providers": [
        {
            "in": "phar:///var/dist/owncloud-7.0.2.tar as owncloud7",
            "name": "*.php",
            "exclude": ["3rdparty"]
        }
    ],
    "plugins": [
    ],
    "analysers" : [
    ]
}

[Important]

Do not forget the phar:// protocol in front of archive identification.

[Tip]

Use alias named here owncloud7 to identify data source entry in the JSON config file, rather than the full path phar:///var/dist/owncloud-7.0.2.tar.

Example to parse a directory. 

{
    "source-providers": [
        {
            "in": "/home/github/phing/ as phing2",
            "path": ["bin", "classes"],
            "exclude": ["test"],
            "name": "*.php"
        }
    ],
    "plugins": [
    ],
    "analysers" : [
    ]
}

Learn more about directives, see Section 8.1, “section Source Providers”

Whatever SAPI you use, all metrics (for each analysers asked) are available at end of parse, in the same format.

With CLI, and CompatInfo source code, to get a compatibility report, you have to invoke the following command :

$ phpcompatinfo analyser:run /home/github/php-compat-info/src

With others SAPI, use example https://raw.githubusercontent.com/llaville/php-compat-info/master/examples/api_analyser_run.php

and you should obtain something like this :

Data Source Analysed

Directories                                         11
Files                                               13

Extensions Analysis

    Extension Matches REF      EXT min/Max PHP min/Max PHP all
    Core              Core                 4.0.0       5.3.0
    PDO               PDO      5.1.0       5.1.0
    curl              curl     4.0.2       4.0.2
    intl              intl     2.0.0b1     5.3.7
    libxml            libxml   5.1.0       5.1.0
    openssl           openssl  5.2.0       5.2.0
    pcre              pcre     4.0.0       4.0.0
    spl               spl      5.1.0       5.1.0
    standard          standard 4.0.0       4.0.0       5.3.2
    Total [9]                              5.3.7

Namespaces Analysis

    Namespace                             Matches REF  EXT min/Max PHP min/Max PHP all
    +global                                       Core             4.0.0
    Bartlett\CompatInfo                           user             5.3.0
    Bartlett\CompatInfo\Analyser                  user             5.3.0
    Bartlett\CompatInfo\Api                       user             5.3.0       5.3.2
    Bartlett\CompatInfo\Api\V3                    user             5.3.0
    Bartlett\CompatInfo\Collection                user             5.3.0
    Bartlett\CompatInfo\Console                   user             5.3.0
    Bartlett\CompatInfo\Console\Formatter         user             5.3.0
    Bartlett\CompatInfo\Output                    user             5.3.0
    Bartlett\CompatInfo\PhpParser                 user             5.3.0
    Bartlett\CompatInfo\Reference                 user             5.3.0
    Bartlett\CompatInfo\Util                      user             5.3.0
    Total [12]                                                     5.3.0       5.3.2

Interfaces Analysis

    Interface                                        Matches REF  EXT min/Max PHP min/Max PHP all
    Bartlett\CompatInfo\Reference\ReferenceInterface 1       user             5.3.0
    Total [1]                                                                 5.3.0

No trait found

Classes Analysis

    Class                                                              Matches REF  EXT min/Max PHP min/Max PHP all
    Bartlett\CompatInfo\Analyser\CompatibilityAnalyser                         user             5.3.0
    Bartlett\CompatInfo\Api\Reference                                          user             5.3.0       5.3.2
    Bartlett\CompatInfo\Api\V3\Reference                                       user             5.3.0
    Bartlett\CompatInfo\Collection\ReferenceCollection                 1       user             5.3.0
    Bartlett\CompatInfo\Console\Application                                    user             5.3.0
    Bartlett\CompatInfo\Console\Formatter\CompatibilityOutputFormatter         user             5.3.0
    Bartlett\CompatInfo\Environment                                    4       user             5.3.0
    Bartlett\CompatInfo\Output\Reference                                       user             5.3.0
    Bartlett\CompatInfo\PhpParser\ConditionalCodeNodeProcessor         1       user             5.3.0
    Bartlett\CompatInfo\Reference\ExtensionFactory                     2       user             5.3.0
    Bartlett\CompatInfo\Reference\SqliteStorage                        1       user             5.3.0
    Bartlett\CompatInfo\Util\Version                                   10      user             5.3.0
  U Bartlett\Reflect\Analyser\AbstractAnalyser                         1       user             5.3.0
  U Bartlett\Reflect\Api\BaseApi                                       1       user             5.3.0
  U Bartlett\Reflect\Api\V3\Common                                     1       user             5.3.0
  U Bartlett\Reflect\Console\Application                               1       user             5.3.0
  U Bartlett\Reflect\Console\Formatter\OutputFormatter                 2       user             5.3.0
  U Bartlett\Reflect\PhpParser\NodeProcessorAbstract                   1       user             5.3.0
  U Doctrine\Common\Collections\AbstractLazyCollection                 1       user             5.3.0
  U Doctrine\Common\Collections\ArrayCollection                        1       user             5.3.0
    PDO                                                                2       PDO  5.1.0       5.1.0
  U PhpParser\Node                                                     21      user             5.3.0
  U PhpParser\Node\Name                                                1       user             5.3.0
    RuntimeException                                                   1       spl  5.1.0       5.1.0
  U Symfony\Component\Console\Helper\TableSeparator                    3       user             5.3.0
  U Symfony\Component\Console\Output\OutputInterface                   4       user             5.3.0
    parent                                                             5       Core 5.0.0       5.0.0
    self                                                               11      Core 5.0.0       5.0.0
    stdClass                                                           1       Core 4.0.0       4.0.0
    Total [29]                                                                                  5.3.0       5.3.2

Functions Analysis

    Function                    Matches REF      EXT min/Max PHP min/Max
    array_key_exists            7       standard 4.0.7       4.0.7
    array_map                   2       standard 4.0.6       4.0.6
    array_merge                 3       standard 4.0.0       4.0.0
    array_pop                   6       standard 4.0.0       4.0.0
    array_shift                 2       standard 4.0.0       4.0.0
    array_slice                 1       standard 4.0.0       4.0.0
    array_values                1       standard 4.0.0       4.0.0
    closure-73-75                       user                 5.3.0
    copy                        1       standard 4.0.0       4.0.0
    count                       14      standard 4.0.0       4.0.0
 C  curl_version                1       curl     4.0.2       4.0.2
    defined                     4       Core     4.0.0       4.0.0
    dirname                     3       standard 4.0.0       4.0.0
    each                        2       Core     4.0.0       4.0.0
    end                         3       standard 4.0.0       4.0.0
    explode                     2       standard 4.0.0       4.0.0
    extension_loaded            1       Core     4.0.0       4.0.0
    file_exists                 2       standard 4.0.0       4.0.0
    function_exists             1       Core     4.0.0       4.0.0
    in_array                    10      standard 4.0.0       4.0.0
    is_array                    1       standard 4.0.0       4.0.0
    is_callable                 1       standard 4.0.6       4.0.6
    is_string                   10      standard 4.0.0       4.0.0
    ksort                       3       standard 4.0.0       4.0.0
    ltrim                       1       standard 4.0.0       4.0.0
    mkdir                       1       standard 4.0.0       4.0.0
    phpversion                  2       standard 4.0.0       4.0.0
    preg_match                  2       pcre     4.0.0       4.0.0
    sha1_file                   2       standard 4.3.0       4.3.0
    sprintf                     26      standard 4.0.0       4.0.0
    str_replace                 1       standard 4.0.0       4.0.0
    strcasecmp                  4       Core     4.0.0       4.0.0
    stream_resolve_include_path 1       standard 5.3.2       5.3.2
    strpos                      2       standard 4.0.0       4.0.0
    strtolower                  1       standard 4.0.0       4.0.0
    substr                      2       standard 4.0.0       4.0.0
    sys_get_temp_dir            1       standard 5.2.1       5.2.1
    ucfirst                     5       standard 4.0.0       4.0.0
    version_compare             9       standard 4.0.7       4.0.7
    Total [39]                                               5.3.2

Constants Analysis

    Constant               Matches REF     EXT min/Max PHP min/Max
 C  INTL_ICU_VERSION       2       intl    2.0.0b1     5.3.7
    LIBXML_DOTTED_VERSION  1       libxml  5.1.0       5.1.0
    LIBXML_VERSION         1       libxml  5.1.0       5.1.0
 C  OPENSSL_VERSION_NUMBER 1       openssl 5.2.0       5.2.0
 C  OPENSSL_VERSION_TEXT   1       openssl 5.2.0       5.2.0
    PHP_EOL                5       Core    4.3.10      4.3.10
    PHP_VERSION            4       Core    4.0.0       4.0.0
    __DIR__                1       Core    5.3.0       5.3.0
    false                  14      Core    4.0.0       4.0.0
    null                   15      Core    4.0.0       4.0.0
    true                   10      Core    4.0.0       4.0.0
    Total [11]                                         5.3.0

Conditions Analysis

    Condition                       Matches REF     EXT min/Max PHP min/Max
    defined(INTL_ICU_VERSION)       2       intl    2.0.0b1     5.3.7
    defined(OPENSSL_VERSION_NUMBER) 1       openssl 5.2.0       5.2.0
    defined(OPENSSL_VERSION_TEXT)   1       openssl 5.2.0       5.2.0
    function_exists(curl_version)   1       curl    4.0.2       4.0.2
    Total [4]                                                   5.3.7

Requires PHP 5.3.2 (min), PHP 5.3.2 (all)

This is the default render. But, if you want to compare with other SAPI, activate the debug verbose mode (-vvv) to get the raw response. You should obtain something like this :

Raw response
Array
(
    [files] => Array
        (
            [0] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Reference/ExtensionFactory.php
            [1] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Api/V3/Reference.php
            [2] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Analyser/CompatibilityAnalyser.php
            [3] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Api/Reference.php
            [4] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Collection/ReferenceCollection.php
            [5] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Console/Application.php
            [6] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Console/Formatter/CompatibilityOutputFormatter.php
            [7] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Environment.php
            [8] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Output/Reference.php
            [9] => /home/github/php-compat-info/src/Bartlett/CompatInfo/PhpParser/ConditionalCodeNodeProcessor.php
            [10] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Reference/ReferenceInterface.php
            [11] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Reference/SqliteStorage.php
            [12] => /home/github/php-compat-info/src/Bartlett/CompatInfo/Util/Version.php
        )

    [Bartlett\CompatInfo\Analyser\CompatibilityAnalyser] => Array
        (
            [versions] => Array
                (
                    [php.min] => 5.3.2
                    [php.max] =>
                    [php.all] => 5.3.2
                )

            [extensions] => Array
                (
                    ...

                )

            [namespaces] => Array
                (
                    ...

                )

            [interfaces] => Array
                (
                    ...

                )

            [traits] => Array
                (
                )

            [classes] => Array
                (
                    ...

                )

            [methods] => Array
                (
                    ...

                )

            [functions] => Array
                (
                    ...

                )

            [constants] => Array
                (
                    ...

                )

            [conditions] => Array
                (
                    ...

                )

        )

)
  • First entry in array is the list of parsed files
  • Second entry in array is the compatibility analyser result

Each analyser as its own data structure and results, but you will always get the fully qualified class name that identify origin of analyser used.

Example with two analysers (structure and compatibility). 

$ phpcompatinfo analyser:run /home/github/php-compat-info/src structure compatibility

Raw response
Array
(
    [files] => Array
        (
            ...
        )

    [Bartlett\Reflect\Analyser\StructureAnalyser] => Array
        (
            ...
        )

    [Bartlett\CompatInfo\Analyser\CompatibilityAnalyser] => Array
        (
            ...
        )

)

Chapter 18. Plugins

18.1. Events

CompatInfo uses a Symfony EventDispatcher Component to allow you to easily extend the features list.

The EventDispatcher component allow CompatInfo components to communicate with each other by dispatching events and listening to them.

18.1.1. Event Dispatcher

CompatInfo implement interface Bartlett\Reflect\Event\DispatcherInterface. You can add event listeners and event subscribers to this object.

listeners

Callable functions that are registered on an event dispatcher for specific events.

subscribers

Classes that tell an event dispatcher what methods to listen to and what functions on the class to invoke when the event is triggered. Event subscribers subscribe event listeners to an event dispatcher.

18.1.2. Getting an EventDispatcher

You can get the EventDispatcher of Bartlett\Reflect\Event\DispatcherInterface by calling the getEventDispatcher() method.

Here is an example :

<?php

use Bartlett\Reflect\Client;

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

$dispatcher = $api->getEventDispatcher();

18.1.3. Adding Event Listeners

After you have the event dispatcher, you can register event listeners that listen to specific events.

Example 18.1. Add a listener that will echo out files when they are parsed

<?php

use Bartlett\Reflect\Client;

use Symfony\Component\EventDispatcher\GenericEvent;

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

$dispatcher = $api->getEventDispatcher();

$dispatcher->addListener(
    'reflect.progress',
    function (GenericEvent $e) {
        printf(
            'Parsing Data source "%s" in progress ... File "%s"' . PHP_EOL,
            $e['source'],
            $e['file']->getPathname()
        );
    }
);

18.1.4. Event Subscribers

Event subscribers are classes that implement interface Symfony\Component\EventDispatcher\EventSubscriberInterface. They are used to register one or more event listeners to methods of the class. Event subscribers tell event dispatcher exactly which events to listen to and what method to invoke on the class.

CompatInfo plugins follow the event subscribers behaviors. Have a look on NotifierPlugin :

<?php

use Bartlett\Reflect\Events;

class NotifierPlugin implements PluginInterface, EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        $events = array(
            Events::PROGRESS => 'onNotification',
            Events::ERROR    => 'onNotification',
            Events::COMPLETE => 'onNotification',
        );
        return $events;
    }
}

This plugin registers event listeners to the reflect.complete event of a Reflect parse request.

When the reflect.complete event is emitted, the onNotification instance method of the plugin is invoked.

18.1.5. Events lifecycle

Event Action Informations available

reflect.progess

Before to parse a new file of the data source.

source data source identifier or its alias file current file parsed in the data source

reflect.success

After parsing the current file ( A cached request will not trigger this event )

source data source identifier or its alias file current file parsed in the data source ast the Abstract Syntax Tree result of PHP-Parser

reflect.error

When PHP Parser raise an error

source data source identifier or its alias file current file parsed in the data source error PHP Parser error message

reflect.complete

When a parse request is over.

source data source identifier or its alias

18.2. Register Plugins

[Note]

In Reflect API 2, and other SAPI than CLI, you have to register a plugin, if you want to use it.

In Reflect API 3, it’s no more necessary. All valid plugins defined in the JSON configuration file are automatically registered.

[Important]

You must define environment variables BARTLETT_SCAN_DIR and BARTLETTRC, otherwise the JSON config file will not found it.

If you don’t want to use any plugins, and de-activated all at once, follow this pattern.

<?php

use Bartlett\Reflect\Environment;
use Bartlett\Reflect\Client;

// set default values for BARTLETT_SCAN_DIR
Environment::setScanDir()

// set default value for BARTLETTRC
putenv("BARTLETTRC=phpcompatinfo.json");

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

// de activate all plugins
$api->activatePlugins(false);

// perform request, on a data source with default analyser (compatibility)
$dataSource = dirname(__DIR__) . '/src';
$analysers  = array('compatibility');

// equivalent to CLI command `phpcompatinfo analyser:run ../src`
$metrics = $api->run($dataSource, $analysers);

Chapter 19. Cache Plugin

19.1. Register Plugin

If you want to use the Doctrine cache component, skip this section.

If you want to use your own version of cache plugin, use following pattern.

<?php

namespace YourNamespace;

use Bartlett\Reflect\Plugin\CachePlugin as BaseCachePlugin;

class CachePlugin extends BaseCachePlugin
{
    // all additional code you need
}

And the configuration in JSON file :

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Cache",
            "class": "YourNamespace\\CachePlugin",
            "options": []
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

19.2. Doctrine Adapter

Use one of the most famous caching solution, provided by the Doctrine project.

Use this shortcut version that is strictly equivalent to next in section file cache.

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Cache",
            "class": "Bartlett\\Reflect\\Plugin\\CachePlugin",
            "options": []
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

19.3. File cache

Doctrine File backend to store your Reflect results in the local file system.

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Cache",
            "class": "Bartlett\\Reflect\\Plugin\\CachePlugin",
            "options": {
                "adapter": "DoctrineCacheAdapter",
                "backend": {
                    "class": "Doctrine\\Common\\Cache\\FilesystemCache",
                    "args": [
                        "%{TEMP}/bartlett/cache"
                    ]
                }
            }
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

In the source code above, we use the standard Doctrine File cache provider, and store results in the default system temporary directory ( see php sys_get_temp_dir() function ).

Chapter 20. Log Plugin

20.1. Register Plugin

If you want to use default logger Bartlett\Reflect\Plugin\Log\DefaultLogger, skip this section.

If you want to use your own version of log plugin, use following pattern.

<?php

namespace YourNamespace;

use Bartlett\Reflect\Plugin\LogPlugin as BaseLogPlugin;

class LogPlugin extends BaseLogPlugin
{
    // all additional code you need
}

And the configuration in JSON file :

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Logger",
            "class": "YourNamespace\\LogPlugin",
            "options": []
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

20.2. Default logger

Use a solution similar to ErrorLogHandler of Monolog project.

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Logger",
            "class": "Bartlett\\Reflect\\Plugin\\LogPlugin",
            "options": []
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

It logs records at Psr\Log\LogLevel::INFO level or highter, identified by channel name DefaultLoggerChannel.

20.3. Using your private logger

Use your own logger, that must be compatible PSR-3.

<?php

namespace YourNamespace;

use Psr\Log\AbstractLogger;

class YourLogger extends AbstractLogger
{
    public function log($level, $message, array $context = array())
    {
    }
}

And identify it in the JSON config file, as follow

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Logger",
            "class": "YourNamespace\\LogPlugin"
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

Or even

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Logger",
            "class": "Bartlett\\Reflect\\Plugin\\LogPlugin",
            "options": "YourNamespace\\YourLogger"
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

See full example at https://raw.githubusercontent.com/llaville/php-compat-info/master/examples/api_analyser_run_with_logger.php

20.4. Using Monolog

Use one of the most famous logging solution compatible PSR-3.

[Warning]

If you want to use Monolog with CompatInfo on CLI mode, then you should use a wrapper like this.

<?php

namespace YourNamespace;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class YourLogger extends Logger
{
    public function __construct($name = 'YourLoggerChannel')
    {
        $stream = new StreamHandler('/var/logs/phpcompatinfo.log');
        parent::__construct($name, array($stream));
    }
}

And with JSON config file as follow

{
    "source-providers": [
    ],
    "plugins": [
        {
            "name": "Logger",
            "class": "Bartlett\\Reflect\\Plugin\\LogPlugin",
            "options": "YourNamespace\\YourLogger"
        }
    ],
    "analysers" : [
    ],
    "services": [
    ]
}

Chapter 21. Notifier Plugin

21.1. Register Plugin

Two ways depending of SAPI used.

If you’re on Windows or Mac platform, you may have Growl. If you’re on Linux, the default bundled growl notifier is not for you. Skip this section.

[Note]
  • Growl for Windows
  • Growl for Mac

You’ll add to configure your plugin in your phpcompatinfo.json file, as follow :

    {
        "name": "Notifier",
        "class": "Bartlett\\Reflect\\Plugin\\NotifierPlugin",
        "options" : "Bartlett\\CompatInfo\\Plugin\\Notifier\\GrowlNotifier"
    }
  • The name key is (since version 3.0.0-alpha1) comment only.
  • The class key identify the name of the class that implement the plugin (must be fully qualified).
  • The options key identify the name of the class that implement the notifier (must be fully qualified).

Default behaviors are :

  • do not notify reflect.progress and reflect.success events (enabled option set to false)
  • notify reflect.error and reflect.complete events, and keep them displayed (sticky option set to true).
  • used the new gntp protocol rather than udp basic protocol.

If one or all of those behaviors does not match your need, here is how to change it.

Creates your own growl notifier class, (E.g: YourNamespace\MyGrowlNotifier) and put it in somewhere in your include_path.

<?php

namespace YourNamespace;

use Bartlett\Reflect\Plugin\Notifier\GrowlNotifier as BaseGrowlNotifier;

class MyGrowlNotifier extends BaseGrowlNotifier
{
    public function __construct($application = 'myPhpCompatInfo', $notifications = array(),
        $password = '', $options = array()
    {
        parent::__construct($application, $notifications, $password, $options);
    }
}

We have changed the Growl Application Name to myPhpCompatInfo, and used the udp protocol.

[Tip]

See http://growl.laurent-laville.org/ to learn more about PEAR/Net_Growl package.

21.1.1. With CLI

You have just to run the analyser:run command, and you will be notified when parse is completed.

21.1.2. Other SAPI

This is the standard analyser run process as defined in following script. Default behavior is to activate all plugins that can be registered in the PluginManager.

<?php

use Bartlett\Reflect\Environment;
use Bartlett\Reflect\Client;

// set default values for BARTLETT_SCAN_DIR
Environment::setScanDir()

// set default value for BARTLETTRC
putenv("BARTLETTRC=phpcompatinfo.json");

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

// perform request, on a data source with default analyser (structure)
$dataSource = dirname(__DIR__) . '/src';
$analysers  = array('structure');

// equivalent to CLI command `phpcompatinfo analyser:run ../src`
$metrics = $api->run($dataSource, $analysers);

var_export($metrics);

Chapter 22. Build your Analysers

Analysers implements the Visitor pattern in a simple and effective way to make the render of your results truly customizable.

22.1. Visitor pattern

Each Analyser class must implement two interfaces Bartlett\Reflect\Analyser\AnalyserInterface, and PhpParser\NodeVisitor.

Your first own analyser may start like that :

<?php

namespace YourNamespace;

use Bartlett\Reflect\Analyser\AnalyserInterface;
use PhpParser\NodeVisitor;

class YourAnalyser implements AnalyserInterface, NodeVisitor
{
    //
    // AnalyserInterface methods
    //

    public function getSubject()
    {
    }

    public function getCurrentFile()
    {
    }

    public function getTokens()
    {
    }

    public function setSubject(Reflect $reflect)
    {
    }

    public function setTokens(array $tokens)
    {
    }

    public function setCurrentFile($path)
    {
    }

    public function getMetrics()
    {
    }

    public function getName()
    {
    }

    public function getNamespace()
    {
    }

    public function getShortName()
    {
    }

    //
    // NodeVisitor methods
    //
    public function beforeTraverse(array $nodes)
    {
    }

    public function enterNode(Node $node)
    {
    }

    public function leaveNode(Node $node)
    {
    }

    public function afterTraverse(array $nodes)
    {
    }
}
[Tip]

An abstract class Bartlett\Reflect\Analyser\AbstractAnalyser that implement all required interfaces may be used to initialize common data in a simple way.

Your analyser became as simple like that:

<?php

namespace YourNamespace;

use Bartlett\Reflect\Analyser\AbstractAnalyser;

class YourAnalyser extends AbstractAnalyser
{
}

22.2. Print results

Once all nodes of AST built by PHP-Parser were traversed, you have to publish your results with the getMetrics() method.

Results must be organized as a key/values pair array, where key is the fully qualified name of your analyser (E.g: YourNamespace\YourAnalyser), and values are your metrics (free organization).

At end of API analyser/run, your metrics are returned, and may be exploited as you want. You are free to create a custom render or not. If no output formatter is provided in namespace YourNamespace\Console\Formatter, a simple PHP print_r() format is returned.

[Note]

This is the default format in debug mode (verbose level 3 in CLI).

Here is a pattern of skeleton.

<?php

namespace YourNamespace\Console\Formatter;

use Symfony\Component\Console\Output\OutputInterface;

class YourAnalyserOutputFormatter
{
    // $output   === instance of console output
    // $response === your metrics returned by the +YourNamespace\YourAnalyser\getMetrics()+

    public function __invoke(OutputInterface $output, $response)
    {
    }
}

Chapter 23. Build your Filters

If you want to restrict final results to one ore more criteria, the filter feature is what you are waiting for.

[Note]

This feature was introduced in CompatInfo 4.2.0, following user request GH-197.

23.1. Your first filter

Here, our goal is to keep only interfaces, traits, classes, functions, constants that are greater or equal PHP 5.0.0

Script YourFilters.php

<?php
$closure = function ($data) {
    foreach ($data as $title => &$groups) {
        if (strpos($title, 'CompatibilityAnalyser') === false) {
            continue;
        }
        // looking into Compatibility Analyser metrics only
        foreach ($groups as $group => &$values) {
            if (!in_array($group, array('interfaces', 'traits', 'classes', 'functions', 'constants'))) {
                continue;
            }
            foreach ($values as $name => $metrics) {
                if (version_compare($metrics['php.min'], '5.0.0', 'lt')) {
                    unset($values[$name]);
                }
            }
        }
    }
    return $data;
};
return $closure;

[Warning]

The filter’s file that host the $closure, must be resolvable through the include_path.

[Caution]

Be carefull, with filter source code, or unwanted results may occured.

[Tip]

You have ability to remove definitively (unset), or remove partially (false), values in response through the filter.

[Note]

Only one filter is allowed at same run, but you can combine one or more analyser rules.

23.2. SAPI usage

On CLI, invoke the analyser:run command with the --filter option. E.g:

$ phpcompatinfo analyser:run --filter=YourFilters.php src

On other SAPI, follow example pattern like:

<?php

use Bartlett\Reflect\Client;

// creates an instance of client
$client = new Client();

// request for a Bartlett\Reflect\Api\Analyser
$api = $client->api('analyser');

// perform request, on a data source with default analyser
$dataSource = dirname(__DIR__) . '/src';
$analysers  = array('compatibility');

// filter rules on final results
$closure = function ($data) {
    foreach ($data as $title => &$groups) {
        if (strpos($title, 'CompatibilityAnalyser') === false) {
            continue;
        }
        // looking into Compatibility Analyser metrics only
        foreach ($groups as $group => &$values) {
            if (!in_array($group, array('interfaces', 'traits', 'classes', 'functions', 'constants'))) {
                continue;
            }
            foreach ($values as $name => $metrics) {
                if (version_compare($metrics['php.min'], '5.0.0', 'lt')) {
                    unset($values[$name]);
                }
            }
        }
    }
    return $data;
};

// with embeded $closure code
$metrics = $api->run($dataSource, $analysers, null, false, $closure);

// OR equivalent to CLI command `phpcompatinfo analyser:run --filter=YourFilters.php ../src`
$metrics = $api->run($dataSource, $analysers, null, false, $closure = 'YourFilters.php');

Part VI. References included

Statistics v2

  • 2.0.0 support 61 references
  • 2.1.0 support 63 references
  • 2.2.0 support 65 references
  • 2.3.0 support 67 references
  • 2.5.0 support 75 references
  • 2.8.0 support 80 references
  • 2.10.0 support 83 references
  • 2.13.0 support 84 references
  • 2.15.0 support 86 references
  • 2.16.0 support 95 references
  • 2.23.0 support 98 references
  • 2.25.0 support 99 references
  • 2.26.0 support 100 references

Statistics v3

  • 3.0.0 support 100 references
  • 3.3.0 support 102 references

Statistics v4

  • 4.0.0 support 105 references
  • 4.5.0 support 105 references

Statistics v5

  • 5.0.0 support 105 references