PHPackages                             cmatosbc/hephaestus - 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. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. cmatosbc/hephaestus

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

cmatosbc/hephaestus
===================

A PHP library for functional error handling

1.1.2(1y ago)24GPL-3.0-or-laterPHPPHP ^8.1

Since Nov 21Pushed 1y ago1 watchersCompare

[ Source](https://github.com/cmatosbc/hephaestus)[ Packagist](https://packagist.org/packages/cmatosbc/hephaestus)[ RSS](/packages/cmatosbc-hephaestus/feed)WikiDiscussions main Synced today

READMEChangelog (5)Dependencies (7)Versions (7)Used By (0)

Hephaestus
==========

[](#hephaestus)

[![PHP Lint](https://github.com/cmatosbc/hephaestus/actions/workflows/lint.yml/badge.svg)](https://github.com/cmatosbc/hephaestus/actions/workflows/lint.yml) [![PHPUnit Tests](https://github.com/cmatosbc/hephaestus/actions/workflows/phpunit.yml/badge.svg)](https://github.com/cmatosbc/hephaestus/actions/workflows/phpunit.yml)

God-like error handling library for modern PHP programmers. Hephaestus provides a comprehensive set of tools for elegant error handling, combining functional programming concepts with robust exception management.

Features
--------

[](#features)

- **Option Type**: Rust-inspired `Some/None` type for safe handling of nullable values
- **Enhanced Exceptions**: Advanced error handling with state tracking and exception history
- **Retry Mechanism**: Built-in retry capabilities for transient failures
- **Symfony Integration**: Seamless integration with Symfony framework (optional)
- **Type Safety**: Full PHP 8.1+ type system support

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 7.1 or higher (optional, for bundle integration)

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

[](#installation)

### Basic Installation

[](#basic-installation)

```
composer require cmatosbc/hephaestus
```

### Symfony Bundle Installation

[](#symfony-bundle-installation)

1. Install the package as shown above
2. Register the bundle in `config/bundles.php`:

```
return [
    // ...
    Hephaestus\Bundle\HephaestusBundle::class => ['all' => true],
];
```

3. Configure the bundle in `config/packages/hephaestus.yaml`:

```
hephaestus:
    max_retries: 3
    retry_delay: 1
    logging:
        enabled: true
        channel: 'hephaestus'
```

Core Components
---------------

[](#core-components)

### Option Type

[](#option-type)

The Option type provides a safe way to handle potentially null values:

```
use function Hephaestus\Some;
use function Hephaestus\None;

// Basic usage
$user = Some(['name' => 'Zeus']);
$name = $user->map(fn($u) => $u['name'])
            ->getOrElse('Anonymous'); // Returns "Zeus"

// Pattern matching
$greeting = $user->match(
    some: fn($u) => "Welcome, {$u['name']}!",
    none: fn() => "Welcome, stranger!"
);

// Chaining operations
$drinking_age = Some(['name' => 'Dionysus', 'age' => 21])
    ->filter(fn($u) => $u['age'] >= 21)
    ->map(fn($u) => "{$u['name']} can drink!")
    ->getOrElse("Not old enough");
```

### Enhanced Exception Handling

[](#enhanced-exception-handling)

The `EnhancedException` class provides state tracking and exception history management:

```
use Hephaestus\EnhancedException;

class DatabaseException extends EnhancedException {}

try {
    throw new DatabaseException(
        "Query failed",
        0,
        new \PDOException("Connection lost")
    );
} catch (DatabaseException $e) {
    // Track exception history
    $history = $e->getExceptionHistory();
    $lastError = $e->getLastException();

    // Add context
    $e->saveState(['query' => 'SELECT * FROM users'])
      ->addToHistory(new \Exception("Additional context"));

    // Type-specific error handling
    if ($e->hasExceptionOfType(\PDOException::class)) {
        $pdoErrors = $e->getExceptionsOfType(\PDOException::class);
    }
}
```

### Retry Mechanism

[](#retry-mechanism)

Built-in retry capabilities for handling transient failures:

```
use function Hephaestus\withRetryBeforeFailing;

// Retry an operation up to 3 times
$result = withRetryBeforeFailing(3)(function() {
    return file_get_contents('https://api.example.com/data');
});

// Combine with Option type for safer error handling
function fetchDataSafely($url): Option {
    return withRetryBeforeFailing(3)(function() use ($url) {
        $response = file_get_contents($url);
        return $response === false ? None() : Some(json_decode($response, true));
    });
}

$data = fetchDataSafely('https://api.example.com/data')
    ->map(fn($d) => $d['value'])
    ->getOrElse('default');
```

Symfony Integration
-------------------

[](#symfony-integration)

### Option Factory Service

[](#option-factory-service)

The bundle provides an `OptionFactory` service with built-in retry capabilities:

```
use Hephaestus\Bundle\Service\OptionFactory;

class UserService
{
    public function __construct(private OptionFactory $optionFactory)
    {}

    public function findUser(int $id): Option
    {
        return $this->optionFactory->fromCallable(
            fn() => $this->userRepository->find($id)
        );
    }
}
```

### HTTP-Aware Exceptions

[](#http-aware-exceptions)

The `SymfonyEnhancedException` class provides HTTP-specific error handling:

```
use Hephaestus\Bundle\Exception\SymfonyEnhancedException;

class UserNotFoundException extends SymfonyEnhancedException
{
    public function __construct(int $userId)
    {
        parent::__construct(
            "User not found",
            Response::HTTP_NOT_FOUND
        );
        $this->saveState(['user_id' => $userId]);
    }
}

class UserController
{
    public function show(int $id): Response
    {
        return $this->optionFactory
            ->fromCallable(fn() => $this->userRepository->find($id))
            ->match(
                some: fn($user) => $this->json($user),
                none: fn() => throw new UserNotFoundException($id)
            );
    }
}
```

Key Benefits
------------

[](#key-benefits)

- **Type Safety**: Leverage PHP 8.1+ type system for safer code
- **Functional Approach**: Chain operations with map, filter, and match
- **Explicit Error Handling**: Make potential failures visible in method signatures
- **State Tracking**: Capture and maintain error context and history
- **Resilient Operations**: Built-in retry mechanism for transient failures
- **Framework Integration**: Seamless Symfony integration when needed

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License
-------

[](#license)

This project is licensed under the GNU General Public License v3.0 or later - see the [LICENSE](LICENSE) file for details. This means you are free to use, modify, and distribute this software, but any modifications must also be released under the GPL-3.0-or-later license.

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance37

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

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 ~4 days

Total

5

Last Release

571d ago

PHP version history (2 changes)1.1.0PHP &gt;=8.1

1.1.1PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/118901076?v=4)[Carlos Matos](/maintainers/cmatosbc)[@cmatosbc](https://github.com/cmatosbc)

---

Top Contributors

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

---

Tags

error-handlererror-handlingexception-handlingphpphp-cliphp-debugphp-errorsphp-exceptionphp-exceptionsphp-libraryphp-packagesphp-utilityphp8php80php81symfony-bundle

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/cmatosbc-hephaestus/health.svg)

```
[![Health](https://phpackages.com/badges/cmatosbc-hephaestus/health.svg)](https://phpackages.com/packages/cmatosbc-hephaestus)
```

PHPackages © 2026

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