sbovyrin/jsonrpc

This package is abandoned and no longer maintained. No replacement package was suggested.

Package to simplify your API developing based on JSON-RPC

2.0.3 2018-06-20 21:58 UTC

This package is not auto-updated.

Last update: 2019-05-09 22:38:53 UTC


README

This package is fully-compatible with json-rpc specification except request with named parameters.

Get started

Example: you send json-rpc request:

send to Server --> {"jsonrpc": "2.0", "method": "User.get", "params": [1], "id": 1}

Field method of the request has value User.get, this means you want to call get method of User service.

// UserService.php

namespace app\services;

class UserService
{
  // ...

  /**
   * Get user by id
   * @param int $id
   * @return User|null
   */
  public function get(int $id): ?User
  {
    // find user by id
    // return the user
  }

  // ...
}

Now you have to create instance of JsonRpc\JsonRpc and pass your method stores to its constructor. Then pass received json string to exec method.

$services = [
  'User' => 'app\services\UserService',
  // ...
];

$jsonRpc = new JsonRpc\JsonRpc($services)
$result = $jsonRpc->exec($jsonRequest);

If you want to create API docs, you have to call getAvailableMethods method that returns array of defined public methods of your services.

$allPublicMethodsOfServices = $jsonRpc->getAvailableMethods();
// return:
// [
//     'Auth': [
//         [
//             "method": "get",
//             "description": "Get user by id",
//             "params": [
//                 "$id: int"
//             ],
//             "return": "User|null"
//         ],
//         ...
//     ],
//     ...
// ]

Docs

JsonRpc\JsonRpc

__construct

  • Initialize JSON-RPC client with defined list of your method stores (services)
  • Params:
    • $methodStores: array

exec

  • Execute JSON-RPC request
  • Params:
    • $request: string
    • $beforeFn: callable
      • default value: null
  • Return: array|void

getAvailableMethods

  • Return documentation of your API. Scan all public methods of your stores and its phpDocBlock.
  • Return: array

getAvailableMethods ignore methods with defined @internal key in phpDocBlock

JSON-RPC errors that may appear

Internal errors

  • Parse error. Code: -32700. Request json is incorrect.
  • Invalid request. Code: -32600. JSON-RPC scheme fields are incorrect or method value has incorrect pattern.
  • Method not found. Code: -32601. Appears when requested method is not found.
  • Passed invalid params. Code: -32602. Appears when passed params have incorrect number or type.

Server errors

  • Something went wrong. Code: -32000. Any server error.
  • Validation falied. Code: -32001. Entity validation failed.
  • Forbidden. Code: -32002. User doesn't have access to an action.
  • Not found. Code: -32003. Entity is not found.

Issue

If you find a bug, please file an issue on my issue tracker on GitHub.