PHPackages                             mbsoft31/graph-core - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. mbsoft31/graph-core

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mbsoft31/graph-core
===================

A lightweight, performant, and dependency-free graph data structure library for PHP.

v1.1.0(7mo ago)040↓100%2MITPHPPHP ^8.2CI passing

Since Sep 23Pushed 7mo agoCompare

[ Source](https://github.com/mbsoft31/graph-core)[ Packagist](https://packagist.org/packages/mbsoft31/graph-core)[ Docs](https://github.com/mbsoft31/graph-core)[ RSS](/packages/mbsoft31-graph-core/feed)WikiDiscussions main Synced 1mo ago

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

mbsoft/graph-core
=================

[](#mbsoftgraph-core)

[![PHP Version](https://camo.githubusercontent.com/962aced9b09d89716dbebf186ff899754a096ff1068b6b7988675c2d9fab9331/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c75652e737667)](https://php.net)[![License](https://camo.githubusercontent.com/074b89bca64d3edc93a1db6c7e3b1636b874540ba91d66367c0e5e354c56d0ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e737667)](LICENSE)[![Latest Version on Packagist](https://camo.githubusercontent.com/09f087c0aa26645195f5a8ef1125290d6c61e09e3e677e78872096ab5053e7b1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d62736f667433312f67726170682d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mbsoft/graph-core)[![GitHub Tests Action Status](https://camo.githubusercontent.com/c68d616562d0aa1b0179a33d0ce57dde0667ccd311b411eb98ffc863a2b839aa/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d62736f667433312f67726170682d636f72652f63692e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265)](https://github.com/mbsoft31/graph-core/actions)[![Total Downloads](https://camo.githubusercontent.com/eada8316ebfcf0f393cbfc666746e81509876a07ee3c12dcec40cdae78995a2b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d62736f667433312f67726170682d636f72652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mbsoft31/graph-core)

A lightweight, performant, and dependency-free graph data structure library for PHP. This library provides a clean, modern API for working with directed and undirected graphs, with support for node and edge attributes, subgraph views, and multiple export formats.

✨ Features
----------

[](#-features)

- 🚀 **High Performance**: Uses integer indexing internally for O(1) adjacency lookups
- 🎯 **Clean API**: Well-designed interfaces following SOLID principles
- 📊 **Directed &amp; Undirected**: Full support for both graph types
- 🏷️ **Rich Attributes**: Store arbitrary data on nodes and edges
- 👁️ **Subgraph Views**: Create efficient filtered views without copying data
- 📤 **Multiple Export Formats**: Cytoscape.js JSON, GraphML, GEXF
- 🔒 **Type-Safe**: Leverages PHP 8.2+ features for type safety
- 📦 **Zero Dependencies**: No external dependencies (except ext-dom for XML exports)
- ✅ **Well-Tested**: Comprehensive test coverage with Pest

📋 Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- ext-dom (for XML export formats)

📦 Installation
--------------

[](#-installation)

Install via Composer:

```
composer require mbsoft/graph-core
```

🚀 Quick Start
-------------

[](#-quick-start)

### Basic Usage

[](#basic-usage)

```
use Mbsoft\Graph\Domain\Graph;

// Create a directed graph
$graph = new Graph(directed: true);

// Add nodes with attributes
$graph->addNode('A', ['label' => 'Node A', 'color' => 'red']);
$graph->addNode('B', ['label' => 'Node B', 'color' => 'blue']);
$graph->addNode('C', ['label' => 'Node C', 'color' => 'green']);

// Add edges with weights
$graph->addEdge('A', 'B', ['weight' => 1.5]);
$graph->addEdge('B', 'C', ['weight' => 2.0]);
$graph->addEdge('C', 'A', ['weight' => 0.5]);

// Query the graph
echo count($graph->nodes()); // 3
echo count($graph->edges()); // 3

// Check connections
if ($graph->hasEdge('A', 'B')) {
    $weight = $graph->edgeAttrs('A', 'B')['weight'];
    echo "Edge A->B has weight: $weight\n";
}

// Get neighbors
$successors = $graph->successors('A');   // ['B']
$predecessors = $graph->predecessors('C'); // ['B']
```

### Undirected Graphs

[](#undirected-graphs)

```
use Mbsoft\Graph\Domain\Graph;

// Create an undirected graph
$graph = new Graph(directed: false);

$graph->addEdge('A', 'B', ['type' => 'friendship']);
$graph->addEdge('B', 'C', ['type' => 'friendship']);

// In undirected graphs, edges work both ways
$graph->hasEdge('A', 'B'); // true
$graph->hasEdge('B', 'A'); // true (same edge)

// Successors and predecessors are the same (neighbors)
$graph->successors('B');   // ['A', 'C']
$graph->predecessors('B'); // ['A', 'C']
```

### Creating Graphs from Edge Lists

[](#creating-graphs-from-edge-lists)

```
use Mbsoft\Graph\Domain\Graph;

$edges = [
    ['A', 'B', ['weight' => 1.0]],
    ['B', 'C', ['weight' => 2.0]],
    ['C', 'D', ['weight' => 1.5]],
    ['D', 'A', ['weight' => 3.0]],
];

$graph = Graph::fromEdgeList($edges, directed: true);
```

🔍 Advanced Features
-------------------

[](#-advanced-features)

### Subgraph Views

[](#subgraph-views)

Create efficient, read-only views of a subset of nodes:

```
use Mbsoft\Graph\Domain\Graph;
use Mbsoft\Graph\Domain\SubgraphView;

// Create a graph
$graph = new Graph();
$graph->addEdge('A', 'B');
$graph->addEdge('B', 'C');
$graph->addEdge('C', 'D');
$graph->addEdge('D', 'E');

// Create a view containing only nodes A, B, and C
$subgraph = new SubgraphView($graph, ['A', 'B', 'C']);

// The view only shows edges within the selected nodes
$subgraph->nodes();  // ['A', 'B', 'C']
$subgraph->edges();  // Only A->B and B->C edges
$subgraph->hasEdge('C', 'D'); // false (D not in view)
```

### Modifying Attributes

[](#modifying-attributes)

```
// Update node attributes (merge with existing)
$graph->addNode('A', ['new_attr' => 'value']);

// Replace all node attributes
$graph->setNodeAttrs('A', ['only' => 'this']);

// Update edge attributes
$graph->setEdgeAttrs('A', 'B', ['weight' => 5.0, 'label' => 'Strong']);
```

📤 Export Formats
----------------

[](#-export-formats)

### Cytoscape.js JSON

[](#cytoscapejs-json)

Export graphs for visualization with [Cytoscape.js](https://js.cytoscape.org/):

```
use Mbsoft\Graph\IO\CytoscapeJsonExporter;

$exporter = new CytoscapeJsonExporter();
$json = $exporter->export($graph);

// Result structure:
// [
//     'elements' => [
//         'nodes' => [
//             ['data' => ['id' => 'A', 'label' => 'Node A', ...]],
//             ...
//         ],
//         'edges' => [
//             ['data' => ['source' => 'A', 'target' => 'B', 'weight' => 1.5]],
//             ...
//         ]
//     ]
// ]

file_put_contents('graph.json', json_encode($json));
```

### GraphML (XML)

[](#graphml-xml)

Export to GraphML format for use with tools like Gephi, yEd, or NetworkX:

```
use Mbsoft\Graph\IO\GraphMLExporter;

$exporter = new GraphMLExporter();
$xml = $exporter->export($graph);

file_put_contents('graph.graphml', $xml);
```

### GEXF (XML)

[](#gexf-xml)

Export to GEXF format for Gephi and other network analysis tools:

```
use Mbsoft\Graph\IO\GexfExporter;

$exporter = new GexfExporter();
$xml = $exporter->export($graph);

file_put_contents('graph.gexf', $xml);
```

🏗️ Architecture
---------------

[](#️-architecture)

### Interfaces

[](#interfaces)

- **`GraphInterface`**: Read-only graph operations
- **`MutableGraphInterface`**: Extends GraphInterface with modification methods
- **`ExporterInterface`**: Common interface for all export formats

### Core Classes

[](#core-classes)

- **`Graph`**: The main mutable graph implementation
- **`SubgraphView`**: Efficient filtered view of a graph
- **`Node`**: Immutable value object for nodes
- **`Edge`**: Immutable value object for edges
- **`IndexMap`**: Internal bidirectional mapping for performance

🧪 Testing
---------

[](#-testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test:coverage
```

Run static analysis:

```
composer analyse
```

🎯 Use Cases
-----------

[](#-use-cases)

This library is perfect for:

- **Network Analysis**: Social networks, communication networks, infrastructure
- **Dependency Graphs**: Package dependencies, task scheduling, build systems
- **Pathfinding**: Route planning, game AI, logistics optimization
- **Data Visualization**: Creating interactive graph visualizations
- **Knowledge Graphs**: Semantic networks, ontologies, concept maps
- **Workflow Management**: Process flows, state machines, decision trees

⚡ Performance Considerations
----------------------------

[](#-performance-considerations)

The library is optimized for performance:

- **Integer Indexing**: Internally uses integer indices for O(1) lookups
- **Lazy Evaluation**: Subgraph views don't copy data
- **Memory Efficient**: Adjacency lists only store actual connections
- **Cache Friendly**: Data structures optimized for CPU cache locality

### Benchmarks

[](#benchmarks)

Performance with a 1,000 node graph:

- Node lookup: &lt; 0.001ms
- Edge check: &lt; 0.001ms
- Get successors: &lt; 0.01ms
- Add edge: &lt; 0.01ms

📚 Example Applications
----------------------

[](#-example-applications)

### Social Network Analysis

[](#social-network-analysis)

```
$socialNetwork = new Graph(directed: false);

// Add users
$socialNetwork->addNode('alice', ['name' => 'Alice', 'age' => 28]);
$socialNetwork->addNode('bob', ['name' => 'Bob', 'age' => 32]);
$socialNetwork->addNode('charlie', ['name' => 'Charlie', 'age' => 25]);

// Add friendships
$socialNetwork->addEdge('alice', 'bob', ['since' => '2020']);
$socialNetwork->addEdge('bob', 'charlie', ['since' => '2019']);

// Find friends of friends
$bobsFriends = $socialNetwork->successors('bob'); // ['alice', 'charlie']
```

### Task Dependency Graph

[](#task-dependency-graph)

```
$tasks = new Graph(directed: true);

// Add tasks
$tasks->addNode('compile', ['duration' => 30]);
$tasks->addNode('test', ['duration' => 45]);
$tasks->addNode('package', ['duration' => 15]);
$tasks->addNode('deploy', ['duration' => 20]);

// Add dependencies
$tasks->addEdge('compile', 'test');
$tasks->addEdge('test', 'package');
$tasks->addEdge('package', 'deploy');

// Find what needs to be done before deployment
$deployPrereqs = $tasks->predecessors('deploy'); // ['package']
```

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

📝 License
---------

[](#-license)

This library is open-sourced software licensed under the [MIT license](LICENSE).

🙏 Acknowledgments
-----------------

[](#-acknowledgments)

- Inspired by NetworkX (Python) and JGraphT (Java)
- Built with modern PHP best practices
- Tested with Pest PHP testing framework

📮 Support
---------

[](#-support)

For bugs and feature requests, please use the [GitHub issues page](https://github.com/mbsoft/graph-core/issues).

🔗 See Also
----------

[](#-see-also)

- [mbsoft/graph-builder](https://github.com/mbsoft/graph-builder) - Fluent builders and factories (Phase 2)
- [mbsoft/graph-algorithms](https://github.com/mbsoft/graph-algorithms) - Graph algorithms (Phase 3)
- [mbsoft/graph-viz](https://github.com/mbsoft/graph-viz) - Visualization components (Phase 4)

###  Health Score

36

—

LowBetter than 81% of packages

Maintenance67

Regular maintenance activity

Popularity9

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~2 days

Total

2

Last Release

226d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/288f14daea877ea6b5b49d25bf1647f75eab2870b3e143e2a35b17a0666f1bd8?d=identicon)[mbsoft](/maintainers/mbsoft)

---

Top Contributors

[![mbsoft31](https://avatars.githubusercontent.com/u/14237661?v=4)](https://github.com/mbsoft31 "mbsoft31 (15 commits)")

---

Tags

networkAlgorithmgraphdata structureGraphMLcytoscapegexf

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mbsoft31-graph-core/health.svg)

```
[![Health](https://phpackages.com/badges/mbsoft31-graph-core/health.svg)](https://phpackages.com/packages/mbsoft31-graph-core)
```

###  Alternatives

[novus/nvd3

A reusable charting library written in d3.js

7.2k207.7k2](/packages/novus-nvd3)[graphp/graph

GraPHP is the mathematical graph/network library written in PHP.

711292.6k3](/packages/graphp-graph)[rubix/ml

A high-level machine learning and deep learning library for the PHP language.

2.2k1.4M28](/packages/rubix-ml)[s1lentium/iptools

PHP Library for manipulating network addresses (IPv4 and IPv6)

2446.2M24](/packages/s1lentium-iptools)[donatello-za/rake-php-plus

Yet another PHP implementation of the Rapid Automatic Keyword Extraction algorithm (RAKE).

271865.1k10](/packages/donatello-za-rake-php-plus)[amenadiel/jpgraph

Composer Friendly, full refactor of JpGraph, library to make graphs and charts

1492.2M7](/packages/amenadiel-jpgraph)

PHPackages © 2026

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