Search code examples
composer-phpaudit

How to use composer audit programmatically


I love the new composer audit functionality added to 2.4 (cf. php composer.phar audit; PHP.Watch).

Now I would love to be able to programmatically call that functionality for a given composer.lock file (or if needed the associated composer.json as well)

By programmatically I mean either a static class or a PHP object which I have to create to do something like:

$auditor = new ComposerAuditor();
$result = $auditor->audit($composerJson, $composerLock);

$result would then contain an array, object or whatever which contains all the audit results.

Is this possible?


Solution

  • The class that performs the auditing itself is marked as internal, and so probably not a great idea (or supported) to use directly.

    Composer can output the results of the audit as JSON however, with composer audit -f json and so you could easily call that, then capture & parse the output.

    # portion of a Symfony console command reading 
    # a composer file from elsewhere on the local disc
    $process = new Process(['php','/usr/local/bin/composer','audit', '--format=json', '--no-interaction']);
    $process->setWorkingDirectory($path);
    $process->run();
    
    $arr = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);