PHP code example of xtompie / guard

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

    

xtompie / guard example snippets


use Xtompie\Guard\Guard;

$user = Guard::of(request()->input('id'))
    ->filter(fn($id) => ctype_digit($id))
    ->map(fn($id) => User::find($id))
    ->not(fn() => abort(404))
    ->is(fn($user) => info("User found {$user->id}"))
    ->get();

use Xtompie\Guard\Guard;

Guard::of(null)->assert()->get(); // NoValueException will be thrown

use Xtompie\Guard\Guard;

echo Guard::of(null)->get('default'); // -> default

use Xtompie\Guard\Guard;

function divide($a, $b) {
    $b = Guard::of($b)
        ->map(fn($i) => (int)$i)
        ->reject(fn($i) => $i === 0)
        ->assert(\UnexpectedValueException::class)
        ->get();
    return $a / $b;
}

use Xtompie\Guard\Guard;

$options = [
    'a' => 'A',
    'b' => 'B',
];
$key = 'c';
echo Guard::of($options)->let()[$key]->get();

use Xtompie\Guard\Guard;

echo Guard::of(new \stdClass())
    ->let()->nonExistingMethod()
    ->let()->nonExistingProperty
    ->let()['nonExistingOffset']
    ->get('Undefined')
;

namespace MyApp\Util;

use Xtompie\Guard\Guard as BaseGuard;

class Guard extends BaseGuard
{
    public function or404()
    {
        $this->not(fn() => abort(404));
    }

    public function reject0()
    {
        return $this->reject(fn($i) => $i === 0);
    }
}

echo gettype(Guard::of(0)->reject0()->get());