PHP code example of posternak / composer-file

1. Go to this page and download the library: Download posternak/composer-file library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

posternak / composer-file example snippets


use Posternak\ComposerFile\ComposerJsonFile;

$file = new ComposerJsonFile('/path/to/composer.json');

// Read a constraint from either `12.1.2"
$file->getPackageVersionConstraint('vendor/missing');      // throws — guard with has() if unsure

// Update an existing constraint
$file->setPackageVersionConstraint('laravel/framework', '^12.9.0');

// Add a new dependency
$file->addPackage('symfony/console', '^7.2');
$file->addPackage('mockery/mockery', '^1.6', dev: true);

// Remove a dependency (no-op if it's not there)
$file->removePackage('thecodingmachine/safe');

// Iterate dependencies as a name => constraint map
foreach ($file->getRequire() as $name => $constraint) {
    echo "$name => $constraint\n";
}
foreach ($file->getRequireDev() as $name => $constraint) {
    // ...
}

use Posternak\ComposerFile\ComposerLockFile;

$lock = new ComposerLockFile('/path/to/composer.lock');

// Installed version of a single package
$lock->getInstalledPackageVersion('laravel/framework');   // "v12.8.1"
$lock->getInstalledPackageVersion('vendor/missing');      // throws — package not installed

// Full lock entry — everything composer.lock records for the package
$lock->getPackageInfo('laravel/framework');
// => ["name" => "laravel/framework", "version" => "v12.8.1", "type" => "library", ...]

// Walk the lock file — all installed, just runtime, or just dev
$lock->getInstalledPackages();          // packages + packages-dev
$lock->getInstalledRuntimePackages();   // packages only
$lock->getInstalledDevPackages();       // packages-dev only

use Posternak\ComposerFile\ComposerJsonFile;

$file = new ComposerJsonFile($argv[1] ?? __DIR__ . '/composer.json');

foreach ($file->getRequire() as $name => $constraint) {
    if (str_starts_with($name, 'laravel/')) {
        $file->setPackageVersionConstraint($name, '^12.9.0');
    }
}