PHPackages                             mcstreetguy/composer-parser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. mcstreetguy/composer-parser

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

mcstreetguy/composer-parser
===========================

A composer.json and lockfile parser.

v1.1.0(6y ago)824.0k↓18.8%2[4 issues](https://github.com/MCStreetguy/ComposerParser/issues)4MITPHP

Since Apr 5Pushed 2y ago2 watchersCompare

[ Source](https://github.com/MCStreetguy/ComposerParser)[ Packagist](https://packagist.org/packages/mcstreetguy/composer-parser)[ Docs](https://github.com/MCStreetguy/ComposerLockParser)[ RSS](/packages/mcstreetguy-composer-parser/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (1)Versions (4)Used By (4)

Composer Parser
===============

[](#composer-parser)

**A dependency-free parser library for composer.json and composer.lock files.**

- [Composer Parser](#composer-parser)
    - [Installation](#installation)
    - [Usage](#usage)
        - [Parsing](#parsing)
            - [Exception Handling](#exception-handling)
            - [Doing it the manual way](#doing-it-the-manual-way)
                - [Sub-components](#sub-components)
        - [Data Retrieval](#data-retrieval)
            - [Special Classes](#special-classes)
                - [PackageMap](#packagemap)
                - [NamespaceMap](#namespacemap)
        - [Global Configuration](#global-configuration)
    - [Versioning](#versioning)
    - [Testing](#testing)
    - [Authors](#authors)
        - [Acknowledgement](#acknowledgement)
    - [License](#license)

Installation
------------

[](#installation)

```
composer require mcstreetguy/composer-parser
```

Usage
-----

[](#usage)

### Parsing

[](#parsing)

I recommend using the provided magic Factory method for parsing:

```
use MCStreetguy\ComposerParser\Factory as ComposerParser;

$composerJson = ComposerParser::parse('/path/to/composer.json');
$lockfile = ComposerParser::parse('/path/to/composer.lock');
```

Even if this is the easiest way to retrieve an instance, it may be that you for some reason cannot rely on these automations (e.g. if you got a differing filename). In this case you can also call the parse methods directly:

```
$composerJson = ComposerParser::parseComposerJson('/some/file');
$lockfile = ComposerParser::parseLockfile('/another/file');
```

*Please note* that ComposerParser will not complain about any missing fields, instead it fills all missing values with default ones to ensure integrity.

#### Exception Handling

[](#exception-handling)

During instatiation through the Factory, two exceptions may occur:

```
try {
    $composerJson = ComposerParser::parse('/path/to/composer.json');
} catch (InvalidArgumentException $e) {
    // The given file could not be found or is not readable
} catch (RuntimeException $e) {
    // The given file contained an invalid JSON string
}
```

#### Doing it the manual way

[](#doing-it-the-manual-way)

If you can not rely on the Factory for any reason, you can also instantiate the class directly.
**This is however not recommended and may lead to unexpected behaviour.**

```
use \MCStreetguy\ComposerParse\ComposerJson;

$rawData = file_get_contents('/path/to/composer.json');
$parsedData = json_decode($rawData, true);

$composerJson = new ComposerJson($parsedData);
```

As you can see the constructor needs an array with the parsed json data. This applies to all constructor methods throughout the library.

##### Sub-components

[](#sub-components)

You can also create sub-components directly. In this case you have to keep in mind, that their constructors only accept the isolated data from the composer manifest (e.g. the `Author` class expects you to pass only the contents of one of the objects in the `author`-field).

```
use \MCStreetguy\ComposerParse\Json\Author;

$rawData = file_get_contents('/path/to/composer.json');
$parsedData = json_decode($rawData, true);

$author = new Author($parsedData['authors'][0]);
```

### Data Retrieval

[](#data-retrieval)

All class instances provide getters for their properties. The structure is directly adapted from [the composer.json schema](https://getcomposer.org/doc/04-schema.md). The corresponding property names of wrapper classes have been converted to camelCase (see the [PSR-1 standard](https://www.php-fig.org/psr/psr-1/#4-class-constants-properties-and-method) for further information).

For any property you can use the provided getter methods.

```
$license = $composerJson->getLicense();
$version = $composerJson->getVersion();
```

It's also possible to directly access properties. *Please note* that this is read-only!

```
$description = $composerJson->description;
$require = $composerJson->require;
```

You may also call `empty()` or `isset()` on the class properties.
To check if the whole wrapper is empty (useful for nested classes) there is an `isEmpty()` method inherited:

```
if ($composerJson->config->isEmpty()) {
    // Do something
}
```

#### Special Classes

[](#special-classes)

ComposerParser uses some special classes for parts of the json schema.

##### PackageMap

[](#packagemap)

The PackageMap class is used for the fields `require`, `require-dev`, `conflict`, `replace`, `provide` and `suggest`. It converts a json structure like this:

```
{
    "require": {
        "vendor/package": "^2.3",
        "foo/bar": "dev-master"
    }
}
```

into an array structure like this:

```
$require = [
    [
        "package" => "vendor/package",
        "version" => "^2.3"
    ],
    [
        "package" => "foo/bar",
        "version" => "dev-master"
    ]
]
```

Additionally it implements the Iterator and ArrayAccess interfaces, thus you may directly access it's contents or put it in a foreach loop:

```
$require = $composerJson->getRequire();

$fooBar = $require[1];

foreach ($require as $requirement) {
    $package = $requirement['package'];
    $version = $requirement['version'];

    echo "I need $package at version $version!";
}
```

If you for some reason need the original mapped data you can retrieve it as following:

```
$map = $require->getData();
```

##### NamespaceMap

[](#namespacemap)

The NamespaceMap is used for the fields `autoload.psr-0` and `autoload.psr-4`. In fact this class is identical to the [PackageMap](#packagemap). The only difference are the map keys:

```
{
    "psr-4": {
        "MCStreetguy\\ComposerParser\\": "src/"
    }
}
```

```
$psr4 = [
    [
        "namespace" => "MCStreetguy\\ComposerParser\\",
        "source" => "src/"
    ]
]
```

### Global Configuration

[](#global-configuration)

By default, the library tries to load your global configuration file, if there is any. It follows the location rules for the composer home directory [as defined in the documentation](https://getcomposer.org/doc/03-cli.md#composer-home). If there is no readable global configuration file present, this step is silently skipped.

Just as composer itself, the following precedence rule applies to global configuration files:

> In case global configuration matches local configuration, the local configuration in the project's composer.json always wins. *([source: https://getcomposer.org/doc/03-cli.md#composer-home-config-json](https://getcomposer.org/doc/03-cli.md#composer-home-config-json))*

You may suppress this behaviour by passing `true` as second parameter to the `parse`, `parseComposerJson` and `parseLockfile` methods.

Versioning
----------

[](#versioning)

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/MCStreetguy/ComposerParser/tags).

Testing
-------

[](#testing)

If you contribute to this project, you have to ensure that your changes don't mess up the existing functionality. Therefore this repository comes with a PhpUnit testing configuration, that you can execute by running `make test`. See [their documentation](https://phpunit.readthedocs.io/en/8.2/installation.html) on more information on how to install the tool.

Authors
-------

[](#authors)

- **Maximilian Schmidt** - *Owner* - [MCStreetguy](https://github.com/MCStreetguy/)

See also the list of [contributors](https://github.com/MCStreetguy/ComposerParser/contributors) who participated in this project.

### Acknowledgement

[](#acknowledgement)

Special thanks go to [antonkomarev](https://github.com/antonkomarev) who helped discovering and fixing several deeply nested bugs in the libraries architecture.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance10

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 75% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~80 days

Total

3

Last Release

2440d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8970747?v=4)[Maximilian Schmidt](/maintainers/MCStreetguy)[@MCStreetguy](https://github.com/MCStreetguy)

---

Top Contributors

[![MCStreetguy](https://avatars.githubusercontent.com/u/8970747?v=4)](https://github.com/MCStreetguy "MCStreetguy (15 commits)")[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (5 commits)")

---

Tags

composercomposer-jsoncomposer-lockfile-parserjson-parserlockfilepackage-managementparserwrapper-library

### Embed Badge

![Health badge](/badges/mcstreetguy-composer-parser/health.svg)

```
[![Health](https://phpackages.com/badges/mcstreetguy-composer-parser/health.svg)](https://phpackages.com/packages/mcstreetguy-composer-parser)
```

###  Alternatives

[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k89.3M627](/packages/jms-serializer-bundle)[hassankhan/config

Lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files

97513.5M170](/packages/hassankhan-config)[meyfa/php-svg

Read, edit, write, and render SVG files with PHP

54613.9M42](/packages/meyfa-php-svg)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
