PHP code example of iak / result

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

    

iak / result example snippets


return $placeOrder->handle($cart, $address)
    ->chain(fn (Order $order) => $charge->handle($order, $card))
    ->match(
        success: fn (Receipt $receipt) => response()->json($receipt),
        failure: fn (OrderError|PaymentError $error) => response()->json(['error' => $error->message()], 422),
    );

try {
    $order = $placeOrder->handle($request->cart(), $request->address());
} catch (KitchenClosedException) {
    return back()->withErrors(['order' => 'The kitchen is closed right now.']);
} catch (OutOfStockException) {
    return back()->withErrors(['order' => 'Some items are out of stock.']);
} catch (DeliveryUnavailableException) {
    return back()->withErrors(['order' => "We don't deliver to this address yet."]);
}

return redirect()->route('orders.show', $order);

enum OrderError
{
    case KitchenClosed;
    case OutOfStock;
    case DeliveryUnavailable;

    public function message(): string
    {
        return match ($this) {
            self::KitchenClosed       => 'The kitchen is closed right now.',
            self::OutOfStock          => 'Some items are out of stock.',
            self::DeliveryUnavailable => "We don't deliver to this address yet.",
        };
    }
}

use Iak\Result\Result;

class PlaceOrder
{
    /** @return Result<Order, OrderError> */
    public function handle(Cart $cart, Address $address): Result
    {
        if (! $this->kitchen->isOpen()) {
            return Result::failure(OrderError::KitchenClosed);
        }

        if (! $cart->allItemsAvailable()) {
            return Result::failure(OrderError::OutOfStock);
        }

        if (! $this->zones->covers($address)) {
            return Result::failure(OrderError::DeliveryUnavailable);
        }

        return Result::success(Order::create($cart, $address));
    }
}

public function store(StoreOrderRequest $request, PlaceOrder $placeOrder)
{
    return $placeOrder->handle($request->cart(), $request->address())->match(
        success: fn (Order $order) => redirect()->route('orders.show', $order),
        failure: fn (OrderError $error) => back()->withErrors(['order' => $error->message()]),
    );
}

return Result::success($order);

return Result::success();

return Result::failure(OrderError::OutOfStock);
return Result::failure(new AddressOutsideZone($address, $nearestZone));
return Result::failure($caughtException);

$result = Result::all([
    'order'   => $placeOrder->handle($cart, $address),
    'invoice' => $createInvoice->handle($cart),
]);

// success: ['order' => Order, 'invoice' => Invoice]
// failure: whichever failed first

if ($result->isSuccess()) {
    $order = $result->value(); // safe — and your static analyser agrees
}

if ($result->isFailure()) {
    return back()->withErrors(['order' => $result->error()->message()]);
}

$order = $result->value();

$order = $result->value();

expect($result->error())->toBe(OrderError::OutOfStock);

$order = $result->expect('cart was validated in the previous step');

$error = $result->expectError('the gateway was stubbed to fail in this test');

$eta = $estimateDelivery->handle($address)->valueOr(45);

$eta = $estimateDelivery->handle($address)
    ->valueOrElse(fn (EstimateError $error) => $error->conservativeGuess());

$result->map(fn (Order $order) => $order->total);
// Result<Order, OrderError> becomes Result<Money, OrderError>

$gateway->charge($card)
    ->mapError(fn (GatewayError $error) => PaymentError::fromGateway($error));

return $placeOrder->handle($cart, $address)
    ->tap(fn (Order $order) => Log::info('order placed', ['id' => $order->id]));

return $placeOrder->handle($cart, $address)
    ->tap(fn (Order $order) => Log::info('order placed', ['id' => $order->id]))
    ->tapError(fn (OrderError $error) => Metrics::increment('orders.rejected'));

return $placeOrder->handle($cart, $address)                       // Result<Order, OrderError>
    ->chain(fn (Order $order) => $charge->handle($order, $card))  // Result<Receipt, OrderError|PaymentError>
    ->match(
        success: fn (Receipt $receipt) => response()->json($receipt),
        failure: fn (OrderError|PaymentError $error) => response()->json(['error' => $error->message()], 422),
    );

$receipt = $chargeCard->handle($order, $card)
    ->orElse(fn (PaymentError $error) => $chargeWallet->handle($order));

return $result->match(
    success: fn (Order $order) => redirect()->route('orders.show', $order),
    failure: fn (OrderError $error) => back()->withErrors(['order' => $error->message()]),
);

$result->match(
    success: fn (Receipt $receipt) => response()->json($receipt),
    failure: fn (OrderError|PaymentError $error) => match (true) {
        $error instanceof OrderError   => back()->withErrors(['order' => $error->message()]),
        $error instanceof PaymentError => $this->redirectToPaymentRetry($error),
    },
);

interface DomainError
{
    public function message(): string;
}

// enum OrderError implements DomainError { ... }
// enum PaymentError implements DomainError { ... }

failure: fn (DomainError $error) => back()->withErrors(['order' => $error->message()]),