PHP code example of skie / rop

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

    

skie / rop example snippets


use ROP\Result;

// Create success result
$success = Result::success(42);
$value = $success->getValue();    // 42
$error = $success->getError();    // null
$isSuccess = $success->isSuccess(); // true

// Create failure result
$failure = Result::failure("Invalid input");
$value = $failure->getValue();    // null
$error = $failure->getError();    // "Invalid input"
$isSuccess = $failure->isSuccess(); // false

use ROP\Railway;

$result = Railway::of(42)
    ->map(fn($x) => $x * 2)
    ->bind(fn($x) => validateNumber($x));

use ROP\Pipe;

// Compose functions
$pipeline = Pipe::of(
    fn($x) => $x + 1,
    fn($x) => $x * 2,
    fn($x) => "Result: $x"
);

// Execute pipeline
$result = $pipeline(5);  // "Result: 12"

// With Railway
$railway = Railway::of(5)
    ->bind(Pipe::of(
        fn($x) => $x + 1,
        fn($x) => validateNumber($x),
        fn($x) => saveToDatabase($x)
    ));

use ROP\Railway;

// Simple value transformation
$result = Railway::of(42)
    ->map(fn($x) => $x * 2)
    ->map(fn($x) => $x + 1)
    ->match(
        fn($value) => "Success: $value",
        fn($error) => "Error: $error"
    );

// Error handling
$result = Railway::of($userData)
    ->map(fn($data) => new User($data))         // transform data
    ->bind(fn($user) => validateUser($user))    // might fail
    ->bind(fn($user) => saveToDatabase($user))  // might fail
    ->tee(fn($user) => sendWelcomeEmail($user)) // side effect
    ->match(
        fn($user) => ['success' => true, 'id' => $user->id],
        fn($error) => ['success' => false, 'error' => $error]
    );

// Success path
$success = Railway::of($value);

// Failure path
$failure = Railway::fail($error);

// From existing Result
$railway = Railway::fromResult($result);

$result = Railway::of(42)
    ->map(fn($x) => $x * 2);  // transforms success value

// Transform both success and error values
$result = Railway::of(42)
    ->doubleMap(
        fn($value) => $value * 2,           // success transformer
        fn($error) => "Error: $error"       // error transformer
    );

// Real-world example: API response formatting
$apiResult = fetchUserData($userId)          // Railway<User, ApiError>
    ->doubleMap(
        fn(User $user) => [                 // success case
            'status' => 'success',
            'data' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email
            ]
        ],
        fn(ApiError $error) => [            // error case
            'status' => 'error',
            'code' => $error->getCode(),
            'message' => $error->getMessage()
        ]
    );

// Localization example
$message = Railway::of($value)
    ->doubleMap(
        fn($val) => translate("success.$val"),
        fn($err) => translate("error.$err")
    );

// Type conversion example
$result = validateInput($data)              // Railway<int, string>
    ->doubleMap(
        fn(int $n) => new SuccessResponse($n),
        fn(string $err) => new ErrorResponse($err)
    );

// Chain operations that might fail
$result = Railway::of($input)
    ->bind(fn($x) => validateInput($x))   // returns Railway
    ->bind(fn($x) => processData($x));    // returns Railway

// Try/catch wrapper
$result = Railway::of($riskyData)
    ->tryCatch(
        fn($data) => riskyOperation($data),
        fn(\Throwable $e) => "Failed: " . $e->getMessage()
    );

// Combine multiple operations
$result = Railway::plus(
    fn($r1, $r2) => $r1 + $r2,        // success combiner
    fn($errors) => implode(", ", $errors),  // error combiner
    $railway1,
    $railway2
);

$result = Railway::of($user)
    ->tee(fn($u) => logger("Processing user: {$u->id}"))
    ->bind(fn($u) => updateUser($u))
    ->tee(fn($u) => logger("User updated: {$u->id}"));

$message = $railway->match(
    success: fn($value) => "Success: $value",
    failure: fn($error) => "Error: $error"
);

use ROP\Railway;

// Regular function
$double = fn($x) => $x * 2;

// Lift into Railway
$liftedDouble = Railway::lift($double);

// Use lifted function
$result = Railway::of(21)
    ->bind($liftedDouble);  // Railway<42, never>

// Compose multiple lifted functions
$result = Railway::of($input)
    ->bind(Railway::lift(validateInput))
    ->bind(Railway::lift(transform))
    ->bind(Railway::lift(save));

// Form validation example
$lidateRequired($email));    // Railway<string, ValidationError>

$emailCheck = Railway::of($form->email)
    ->bind(fn($email) => validateEmail($email));      // Railway<string, ValidationError>

$result = $   // Railway<bool, FileError>

$contentReader = Railway::of($path)
    ->bind(fn($p) => readFileContents($p));          // Railway<string, FileError>

$result = $existsCheck
    ->unite($permissionCheck)
    ->unite($contentReader);


// Combine user and profile data
$userResult = fetchUser($id);        // Railway<User, DbError>
$profileResult = fetchProfile($id);   // Railway<Profile, DbError>

$combined = $userResult->plusWith(
    // Combine success values
    fn(User $user, Profile $profile) => [
        'id' => $user->id,
        'name' => $user->name,
        'avatar' => $profile->avatar
    ],
    // Combine errors
    fn(array $errors) => implode(', ', $errors),
    $profileResult
);

// Parallel validation example
$emailValidation = validateEmail($email);     // Railway<string, ValidationError>
$passwordValidation = validatePassword($pwd);  // Railway<string, ValidationError>

$result = $emailValidation->plusWith(
    fn($email, $password) => new Credentials($email, $password),
    fn($errors) => new ValidationErrors($errors),
    $passwordValidation
);

$result = Railway::plus(
    // Combine success values
    fn($user, $profile) => new UserProfile($user, $profile),
    // Combine errors
    fn($errors) => new CombinedError($errors),
    $userResult,
    $profileResult
);

/** @var Railway<User, ValidationError> */
$result = Railway::of($userData)
    ->map(fn(array $data): User => new User($data))
    ->bind(fn(User $user): Railway => validateUser($user));

/** @var Railway<Order, DbError|ValidationError> */
$order = Railway::of($orderData)
    ->bind(fn($data) => validateOrder($data))  // might return ValidationError
    ->bind(fn($data) => saveOrder($data));     // might return DbError