PHP code example of timfennis / apply

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

    

timfennis / apply example snippets


$list = [5, 6, 7, 8, 9, 10];

$gt4 = fn($n) => $n > 4;
$gt5 = fn($n) => $n > 5;

all($gt4)($list); // true because all items are greater than 4
all($gt5)($list); // false because not all items are greater than 5

$list = [5, 6, 7, 8, 9, 10];

$gt7 = fn($n) => $n > 7;
$gt20 = fn($n) => $n > 20;

any($gt7)($list); // true because all items are greater than 7
any($gt20)($list); // false because none of the items are greater than 20

$numbers = [1,2,3];
map(Functions::identity)($numbers); // [1,2,3]
map(constant(4))($numbers); // [4,4,4]

function loadFromAPI() {
    throw new InvalidAuthenticationCredentialsException('Your authentication credentials are invalid');
}

$tryLoad = Attempt::of(fn() => loadFromAPI());
$result = $tryLoad->getOrDefault(null); // returns null

if ($tryLoad->isFailure()) {
    // true it went wrong!
}

$tryLoad = Attempt::of(fn() => rollTheDice());

$number = $tryLoad->fold(
    fn(Throwable $t) => 0,
    fn(int $successValue) => $successValue + 1
);


/**
 * @return Either<string, Response>
 */
function loadFromApi(): Either {
    try { 
        return new Right(httpGet("http://example.com"));
    } catch (RequestException $e) {
        return new Left("Request Error");
    } catch (ResponseException $e) {
        return new Left("Response Error");
    }
}


$computeA = fn() => Option::fromValue(1);
$computeB = fn() => Option::fromValue(5);

$sum = $computeA()->flatMap(static function ($a) use ($computeB) {
    return $computeB()->flatMap(static function ($b) use ($a) {
        return new Some($a + $b);
    });
});

$sum; // Some(6)

$computeA = fn() => Option::fromValue(1);
$computeB = fn() => Option::fromValue(5);

$sum = Option::binding(static function () use ($computeA, $computeB) {
    $a = yield $computeA();
    $b = yield $computeB();
    return $a + $b;
}); 

$sum; // Some(6)