PHP code example of cmatosbc / hephaestus

1. Go to this page and download the library: Download cmatosbc/hephaestus 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/ */

    

cmatosbc / hephaestus example snippets


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

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");

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);
    }
}

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');

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)
        );
    }
}

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)
            );
    }
}