PHP code example of uma / json-rpc

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

    

uma / json-rpc example snippets


declare(strict_types=1);

namespace Demo;

use stdClass;
use UMA\JsonRpc;

class Subtractor implements JsonRpc\Procedure
{
    /**
     * {@inheritdoc}
     */
    public function __invoke(JsonRpc\Request $request): JsonRpc\Response
    {
        $params = $request->params();

        if ($params instanceof stdClass) {
            $minuend = $params->minuend;
            $subtrahend = $params->subtrahend;
        } else {
            [$minuend, $subtrahend] = $params;
        }

        return new JsonRpc\Success($request->id(), $minuend - $subtrahend);
    }

    /**
     * {@inheritdoc}
     */
    public function getSpec(): ?stdClass
    {
        return \json_decode(<<<'JSON'
{
  "$schema": "https://json-schema.org/draft-07/schema#",

  "type": ["array", "object"],
  "minItems": 2,
  "maxItems": 2,
  "items": { "type": "integer" },
  "

declare(strict_types=1);

use Demo\Subtractor;
use UMA\DIC\Container;
use UMA\JsonRpc\Server;

$c = new Container();

$c->set(Subtractor::class, function(): Subtractor {
    return new Subtractor();
});

$c->set(Server::class, function(Container $c): Server {
    $server = new Server($c);
    $server->set('subtract', Subtractor::class);

    return $server;
});

declare(strict_types=1);

use UMA\JsonRpc\Server;

$server = $c->get(Server::class);

// RPC call with positional parameters
$response = $server->run('{"jsonrpc":"2.0","method":"subtract","params":[2,3],"id":1}');
// $response is '{"jsonrpc":"2.0","result":-1,"id":1}'

// RPC call with named parameters
$response = $server->run('{"jsonrpc":"2.0","method":"subtract","params":{"minuend":2,"subtrahend":3},"id":1}');
// $response is '{"jsonrpc":"2.0","result":-1,"id":1}'

// Notification (request with no id)
$response = $server->run('{"jsonrpc":"2.0","method":"subtract","params":[2,3]}');
// $response is NULL

// RPC call with invalid params
$response = $server->run('{"jsonrpc":"2.0","method":"subtract","params":{"foo":"bar"},"id":1}');
// $response is '{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params"},"id":1}'

// RPC call with invalid JSON
$response = $server->run('invalid input {?<derp');
// $response is '{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}'

// RPC call on non-existent method
$response = $server->run('{"jsonrpc":"2.0","method":"add","params":[2,3],"id":1}');
// $response is '{"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found"},"id":1}'

$validator = new Opis\JsonSchema\Validator();
$formats = $validator->parser()->getFormatResolver();
$formats->register('integer', 'prime', new PrimeNumberFormat());

$psr11Container->set(Opis\JsonSchema\Validator::class, $validator);
$jsonServer = new UMA\JsonRpc\Server($psr11Container);

// ...

declare(strict_types=1);

namespace Demo;

use UMA\JsonRpc;

class SampleMiddleware implements JsonRpc\Middleware
{
    public function __invoke(JsonRpc\Request $request, JsonRPC\Procedure $next): JsonRpc\Response
    {
        // Code run before procedure

        $response = $next($request);

        // Code run after procedure finished

        return $response;
    }
}

declare(strict_types=1);

use Demo\SampleMiddleware;
use UMA\DIC\Container;
use UMA\JsonRpc\Server;

$c = new Container();

$c->set(SampleMiddleware::class, function(): SampleMiddleware {
    return new SampleMiddleware();
});

$c->set(Server::class, function(Container $c): Server {
    $server = new Server($c);

    // method definitions would go here...

    $server->attach(SampleMiddleware::class);

    return $server;
});

declare(strict_types=1);

namespace Demo;

use Pheanstalk\Pheanstalk;
use UMA\JsonRpc;

/**
 * A middleware that enqueues all incoming notifications to a Beanstalkd tube,
 * thus avoiding their execution overhead.
 */
class AsyncNotificationsMiddleware implements JsonRpc\Middleware
{
    /**
     * @var Pheanstalk
     */
    private $producer;

    public function __construct(Pheanstalk $producer)
    {
        $this->producer = $producer;
    }

    public function __invoke(JsonRpc\Request $request, JsonRPC\Procedure $next): JsonRpc\Response
    {
        if (null === $request->id()) {
            $this->producer->put(\json_encode($request));

            return new JsonRpc\Success(null);
        }

        return $next($request);
    }
}

use UMA\JsonRpc;

class PickyMiddleware implements JsonRpc\Middleware
{
    /**
     * @var string[]
     */
    private $targetMethods;

    public function __construct(array $targetMethods)
    {
        $this->targetMethods = $targetMethods;
    }

    public function __invoke(JsonRpc\Request $request, JsonRPC\Procedure $next): JsonRpc\Response
    {
        if (!in_array($request->method(), $this->targetMethods)) {
            return $next($request);
        }

        // Actual logic goes here
    }
}

$server = new \UMA\JsonRpc\Server($container, 2);
$server->set('add', Adder::class);

$response = $server->run('[
  {"jsonrpc": "2.0", "method": "add", "params": [], "id": 1},
  {"jsonrpc": "2.0", "method": "add", "params": [1,2], "id": 2},
  {"jsonrpc": "2.0", "method": "add", "params": [1,2,3,4], "id": 3}
]');
// $response is '{"jsonrpc":"2.0","error":{"code":-32000,"message":"Too many batch requests sent to server","data":{"limit":2}},"id":null}'