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');