PHP code example of xtompie / result

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


use Xtompie\Result\Result;

$rand = rand(0, 1);
$result = $rand%2 == 0 ? Result::ofSuccess($rand) : Result::ofErrorMsg("the number $rand is not even");
if ($result->success()) {
    echo "OK: {$result->value()}";
}
else if ($result->fail()) {
    echo "Error: {$result->errors()->first()->message()}";
}

Result::ofSuccess(); // success without value
Result::ofValue(mixed $value); // success with value
Result::ofFail(); // fail without errors
Result::ofError(Error $error); // fail with one error
Result::ofErrorMsg(?string $message, ?string $key = null, ?string $space = null); // fail with one error
Result::ofErrors(ErrorCollection $errors); // fail with errors
Result::ofCombine(Result ...$results):
// combined many results, fail when any of results fail
// when fail errors are merged
// when success, first value is used

namespace App\User\Application\Service\CreateUser;

use Xtompie\Result\Result;

class CreateUserResult extends Result
{
    public static function ofUserId(strign $userId): static
    {
        return parent::ofValue($userId);
    }

    public function userId(): string
    {
        return $this->value();
    }
}

class CreateUserService
{
    public function __invoke(string $email): Result
    {
        if (strlen($email) === 0) {
            return Result::ofErrorMsg('Email CreateUser\CreateUserService;
use App\User\UI\Request\Request;

class ApiUsersPostController
{
    public function __construct(
        protected CreateUserService $createUserService,
        protected Request $request,
    ) {}

    public function __invoke()
    {
        $result = ($this->createUserService)((string)$this->request->input('email'));
        if ($result->fail()) {
            return [
                'success' => false,
                'error' => [
                    'msg' => $result->errors()->first()?->message(),
                    'key' => $result->errors()->first()?->key(),
                    'space' => $result->errors()->first()?->space(),
                ],
            ];
        }

        return [
            'success' => true,
            'body' => [
                'id' => $result->userId(),
            ],
        ];
    }
}