PHP code example of skollro / otherwise

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

    

skollro / otherwise example snippets


$result = match([1, 2, 3])
    ->when(function ($value) {
        return in_array(2, $value);
    }, '2 was found')
    ->otherwise('2 was not found');

// $result is "2 was found"

use Skollro\Otherwise\Match;
use function Skollro\Otherwise\match;

$match = match($value);
$match = Match::value($value);

$result = match('A', 'Some value')
    ->when('B', function ($value) {
        return "{$value} is always false: A != B";
    })
    ->when(true, function ($value, $param) {
        return "This is always true ({$param})";
    })
    ->when(function ($value) {
        return strlen($value) == 1;
    }, 'This is not the first match')
    ->otherwise('B');

// $result is "This is always true (Some value)" because it's the first condition that evaluates to true

$result = match(new A)
    ->whenInstanceOf(B::class, 'This is false')
    ->whenInstanceOf(A::class, 'This is true')
    ->when(function ($value) {
        return $value instanceof A;
    }, 'This is not the first match')
    ->otherwise('C');

// $result is "This is true" because it's the first condition that evaluates to true

$result = match('A')
    ->when(false, 'This is always false')
    ->whenThrow('A', Exception::class)
    ->otherwise('C');

// Exception is thrown

$result = match('A')
    ->when(false, 'This is always false')
    ->otherwise('B');

// $result is "B"

$result = match('A', 'Some value')
    ->when(false, 'This is always false')
    ->otherwise(function ($value, $param) {
        return "{$value} ({$param})";
    });

// $result is "A (Some value)"

$result = match('A')
    ->when(false, 'This is always false')
    ->otherwise('strlen');

// $result is 1

// recommended: an instance of the exception is only created if needed
$result = match('A')
    ->when(false, 'This is always false')
    ->otherwiseThrow(Exception::class);

$result = match('A', 'Some value')
    ->when(false, 'This is always false')
    ->otherwiseThrow(function ($value, $param) {
        throw new Exception("Message {$value} ({$param})");
    });

// not recommended
$result = match('A')
    ->when(false, 'This is always false')
    ->otherwiseThrow(new Exception);