PHP code example of shipsaas / never-throw

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

    

shipsaas / never-throw example snippets


class BookShipperOkData
{
    public function __construct(
        public Booking $booking
    ) {}
}

enum BookingErrors {
    case NO_SHIPPER_AVAILABLE;
    case OVERWEIGHT_PACKAGE;
    case INVALID_ADDRESS;
}

// Error
class BookShipperErrorData
{
    public function __construct(
        public BookingErrors $code
    ) {}
}

use NeverThrow\Ok;
use NeverThrow\Err;
use NeverThrow\ResultInterface;

/**
 * @return ResultInterface<BookShipperOkData, BookShipperErrorData>
 */
public function createBooking(User $user, BookingOrder $order): ResultInterface
{
    $hasAnyShipperAvailable = $this->shipperService->hasAnyShipperAvailable();
    if (!$hasAnyShipperAvailable) {
        return new Err(BookingErrors::NO_SHIPPER_AVAILABLE);
    }
    
    $isOverweight = !$this->weightService->isValid($order);
    if ($isOverweight) {
        return new Err(BookingErrors::OVERWEIGHT_PACKAGE);
    }
    
    $booking = $this->book($user, $order);
   
    return new Ok($booking);
}

$bookingResult = $this->service->createBooking($user, $order);

if ($bookingResult->isError()) {
    $errorCode = $bookingResult->unwrapErr()->code;

    // handle error
    return showError(match ($errorCode) {
        BookingErrors::NO_SHIPPER_AVAILABLE => 'No shipper available at the moment. Please wait',
        BookingErrors::OVERWEIGHT_PACKAGE => 'Your package is overweight',
    });
}

return showBooking([
    'booking' => $bookingResult->unwrapOk()->booking,
]);

function transfer(): Transaction
{
    if (!$this->hasEnoughBalance()) {
        throw new InsufficientBalanceError();
    }
    
    if (!$this->isValidRecipient()) {
        throw new InvalidRecipientError();
    }
    
    if (!$this->isValidTransferAmount()) {
        throw new InvalidTransferMoneyError();
    }
    
    $transaction = $this->transferService->transfer(...);
    if (!$transaction) {
        throw new TransferFailedError();
    }
    
    return $transaction;
}