{"id":15490138,"url":"https://github.com/yoanm/php-jsonrpc-server-sdk","last_synced_at":"2025-04-15T01:43:58.986Z","repository":{"id":48983834,"uuid":"127533253","full_name":"yoanm/php-jsonrpc-server-sdk","owner":"yoanm","description":"Server SDK to convert a json-rpc request string into json-rpc response string","archived":false,"fork":false,"pushed_at":"2024-10-01T05:05:39.000Z","size":3124,"stargazers_count":5,"open_issues_count":3,"forks_count":3,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-19T09:04:34.987Z","etag":null,"topics":["json-rpc","php","sdk"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yoanm.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-03-31T13:13:31.000Z","updated_at":"2024-09-25T04:13:27.000Z","dependencies_parsed_at":"2024-03-29T10:24:32.291Z","dependency_job_id":"1d571326-2749-494c-8abc-0f1b4fa7f923","html_url":"https://github.com/yoanm/php-jsonrpc-server-sdk","commit_stats":{"total_commits":144,"total_committers":4,"mean_commits":36.0,"dds":0.04166666666666663,"last_synced_commit":"1dd13f66edffc2c95fa969fa94634ed4d10130cb"},"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanm%2Fphp-jsonrpc-server-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanm%2Fphp-jsonrpc-server-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanm%2Fphp-jsonrpc-server-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanm%2Fphp-jsonrpc-server-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yoanm","download_url":"https://codeload.github.com/yoanm/php-jsonrpc-server-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248991526,"owners_count":21194893,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json-rpc","php","sdk"],"created_at":"2024-10-02T07:09:29.195Z","updated_at":"2025-04-15T01:43:58.969Z","avatar_url":"https://github.com/yoanm.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PHP JSON-RPC server sdk\n\n[![License](https://img.shields.io/github/license/yoanm/php-jsonrpc-server-sdk.svg)](https://github.com/yoanm/php-jsonrpc-server-sdk)\n[![Code size](https://img.shields.io/github/languages/code-size/yoanm/php-jsonrpc-server-sdk.svg)](https://github.com/yoanm/php-jsonrpc-server-sdk)\n[![Dependabot Status](https://api.dependabot.com/badges/status?host=github\\\u0026repo=yoanm/php-jsonrpc-server-sdk)](https://dependabot.com)\n\n[![Scrutinizer Build Status](https://img.shields.io/scrutinizer/build/g/yoanm/php-jsonrpc-server-sdk.svg?label=Scrutinizer\\\u0026logo=scrutinizer)](https://scrutinizer-ci.com/g/yoanm/php-jsonrpc-server-sdk/build-status/master)\n[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/yoanm/php-jsonrpc-server-sdk/master.svg?logo=scrutinizer)](https://scrutinizer-ci.com/g/yoanm/php-jsonrpc-server-sdk/?branch=master)\n[![Codacy Badge](https://app.codacy.com/project/badge/Grade/8f39424add044b43a70bdb238e2f48db)](https://www.codacy.com/gh/yoanm/php-jsonrpc-server-sdk/dashboard?utm_source=github.com\\\u0026utm_medium=referral\\\u0026utm_content=yoanm/php-jsonrpc-server-sdk\\\u0026utm_campaign=Badge_Grade)\n\n[![CI](https://github.com/yoanm/php-jsonrpc-server-sdk/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/yoanm/php-jsonrpc-server-sdk/actions/workflows/CI.yml)\n[![codecov](https://codecov.io/gh/yoanm/php-jsonrpc-server-sdk/branch/master/graph/badge.svg?token=NHdwEBUFK5)](https://codecov.io/gh/yoanm/php-jsonrpc-server-sdk)\n\n[![Latest Stable Version](https://img.shields.io/packagist/v/yoanm/jsonrpc-server-sdk.svg)](https://packagist.org/packages/yoanm/jsonrpc-server-sdk)\n[![Packagist PHP version](https://img.shields.io/packagist/php-v/yoanm/jsonrpc-server-sdk.svg)](https://packagist.org/packages/yoanm/jsonrpc-server-sdk)\n\nSimple server SDK to convert a json-rpc request string into json-rpc response string.\n\nSee [yoanm/symfony-jsonrpc-http-server](https://github.com/yoanm/symfony-jsonrpc-http-server) for automatic dependency injection.\n\nSee [yoanm/jsonrpc-params-symfony-validator-sdk](https://github.com/yoanm/php-jsonrpc-params-symfony-validator-sdk) for params validation.\n\nSee [yoanm/jsonrpc-server-doc-sdk](https://github.com/yoanm/php-jsonrpc-server-doc-sdk) for documentation generation.\n\n## How to use\n\nSdk requires only two things :\n\n*   A method resolver : must implements [JsonRpcMethodResolverInterface](./src/Domain/JsonRpcMethodResolverInterface.php), resolving logic's is your own.\n*   Methods : JsonRpc methods which implements [JsonRpcMethodInterface](./src/Domain/JsonRpcMethodInterface.php)\n\nSdk optionally provide :\n\n*   Events dispatch\n*   Params validation\n\n### Simple Example\n\n#### JSON-RPC Method\n\n```php\nuse Yoanm\\JsonRpcServer\\Domain\\JsonRpcMethodInterface;\n\nclass DummyMethod implements JsonRpcMethodInterface\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function apply(array $paramList = null)\n    {\n        // Handle the request\n        ...\n        // Then return a result\n        return [\n            'status' =\u003e 'done',\n        ];\n        // Or\n        return null;\n        // Or\n        return 12345;\n    }\n}\n```\n\n#### Array method resolver (simple example)\n\n*You can use [the one used for behat tests](./features/bootstrap/App/BehatMethodResolver.php) or this [Psr11 method resolver](https://github.com/yoanm/php-jsonrpc-server-sdk-psr11-resolver) as example*\n\n```php\nuse Yoanm\\JsonRpcServer\\Domain\\JsonRpcMethodInterface;\nuse Yoanm\\JsonRpcServer\\Domain\\JsonRpcMethodResolverInterface;\n\nclass ArrayMethodResolver implements JsonRpcMethodResolverInterface\n{\n    /** @var JsonRpcMethodInterface[] */\n    private $methodList = [];\n\n    /**\n     * {@inheritdoc}\n     */\n    public function resolve(string $methodName) : ?JsonRpcMethodInterface\n    {\n        return array_key_exists($methodName, $this-\u003emethodList)\n            ? $this-\u003emethodList[$methodName]\n            : null\n        ;\n    }\n\n    /**\n     * @param JsonRpcMethodInterface $method\n     * @param string                 $methodName\n     */\n    public function addMethod(JsonRpcMethodInterface $method, string $methodName)\n    {\n        $this-\u003emethodList[$methodName] = $method;\n    }\n}\n```\n\nThen add your method to the resolver and create the endpoint :\n\n```php\nuse Yoanm\\JsonRpcServer\\App\\Creator\\ResponseCreator;\nuse Yoanm\\JsonRpcServer\\App\\Handler\\ExceptionHandler;\nuse Yoanm\\JsonRpcServer\\App\\Handler\\JsonRpcRequestHandler;\nuse Yoanm\\JsonRpcServer\\App\\Serialization\\JsonRpcCallDenormalizer;\nuse Yoanm\\JsonRpcServer\\App\\Serialization\\JsonRpcCallResponseNormalizer;\nuse Yoanm\\JsonRpcServer\\App\\Serialization\\JsonRpcCallSerializer;\nuse Yoanm\\JsonRpcServer\\App\\Serialization\\JsonRpcRequestDenormalizer;\nuse Yoanm\\JsonRpcServer\\App\\Serialization\\JsonRpcResponseErrorNormalizer;\nuse Yoanm\\JsonRpcServer\\App\\Serialization\\JsonRpcResponseNormalizer;\nuse Yoanm\\JsonRpcServer\\Infra\\Endpoint\\JsonRpcEndpoint;\n\n$resolver = new ArrayMethodResolver();\n$resolver-\u003eaddMethod('dummy-method', new DummyMethod());\n\n$jsonRpcSerializer = new JsonRpcCallSerializer(\n    new JsonRpcCallDenormalizer(\n        new JsonRpcRequestDenormalizer()\n    ),\n    new JsonRpcCallResponseNormalizer(\n        new JsonRpcResponseNormalizer() \n        // Or `new JsonRpcResponseNormalizer(new JsonRpcResponseErrorNormalizer())` for debug purpose\n        // To also dump arguments, be sure 'zend.exception_ignore_args' ini option is not at true/1\n    )\n);\n$responseCreator = new ResponseCreator();\n$requestHandler = new JsonRpcRequestHandler($resolver, $responseCreator);\n$exceptionHandler = new ExceptionHandler($responseCreator);\n\n$endpoint = new JsonRpcEndpoint($jsonRpcSerializer, $requestHandler, $exceptionHandler);\n```\n\nOnce endpoint is ready, you can send it request string :\n\n```php\n$requestString = \u003c\u003c\u003cJSONRPC\n{\n    \"jsonrpc\": \"2.0\",\n    \"id\": 1\n    \"method\": \"dummy-method\"\n}\nJSONRPC;\n\n$responseString = $endpoint-\u003eindex($requestString);\n```\n\n`$responseString` will be the following string depending of method returned value :\n\n*   ```json\n    {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"status\":\"done\"}}\n    ```\n\n*   ```json\n    {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":null}\n    ```\n\n*   ```json\n    {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":12345}\n    ```\n\n### Events dispatch example\n\n#### Simple event dispatcher\n\n*You can use [the one used for behat tests](./features/bootstrap/App/BehatRequestLifecycleDispatcher.php) as example*\n\n```php\nuse Yoanm\\JsonRpcServer\\Domain\\Event\\JsonRpcServerEvent;\nuse Yoanm\\JsonRpcServer\\Domain\\JsonRpcServerDispatcherInterface;\n\n/**\n * Class SimpleDispatcher\n */\nclass SimpleDispatcher implements JsonRpcServerDispatcherInterface\n{\n    /** @var callable[] */\n    private $listenerList = [];\n\n    /**\n     * {@inheritdoc}\n     */\n    public function dispatchJsonRpcEvent(string $eventName, JsonRpcServerEvent $event = null) : void\n    {\n        if (!array_key_exists($eventName, $this-\u003elistenerList)) {\n            return;\n        }\n\n        foreach ($this-\u003elistenerList[$eventName] as $listener) {\n            $listener($event, $eventName);\n        }\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function addJsonRpcListener(string $eventName, $listener) : void\n    {\n        $this-\u003elistenerList[$eventName][] = $listener;\n    }\n}\n```\n\nThen bind your listeners to your dispatcher:\n\n```php\nuse Yoanm\\JsonRpcServer\\Domain\\Event\\Acknowledge\\OnRequestReceivedEvent;\nuse Yoanm\\JsonRpcServer\\Domain\\Event\\Acknowledge\\OnResponseSendingEvent;\nuse Yoanm\\JsonRpcServer\\Domain\\Event\\Action\\OnMethodSuccessEvent;\n\n$dispatcher = new SimpleDispatcher();\n\n$listener = function ($event, $eventName) {\n    echo sprintf(\n        'Received %s with event class \"%s\"',\n        $eventName,\n        get_class($event)\n    );\n};\n\n$dispatcher-\u003eaddJsonRpcListener(OnRequestReceivedEvent::EVENT_NAME, $listener);\n$dispatcher-\u003eaddJsonRpcListener(OnResponseSendingEvent::EVENT_NAME, $listener);\n$dispatcher-\u003eaddJsonRpcListener(OnMethodSuccessEvent::EVENT_NAME, $listener);\n```\n\nAnd bind dispatcher like following :\n\n```php\n$endpoint-\u003esetJsonRpcServerDispatcher($dispatcher);\n$requestHandler-\u003esetJsonRpcServerDispatcher($dispatcher);\n$exceptionHandler-\u003esetJsonRpcServerDispatcher($dispatcher);\n```\n\n#### Events dispatched\n\n##### Basic request lifecycle\n\n*   `json_rpc_server_skd.on_request_received` / [`Acknowledge\\OnRequestReceivedEvent`](./src/Domain/Event/Acknowledge/OnRequestReceivedEvent.php)\n\n    Dispatched when a request has been passed to the endpoint and successfully deserialized.\n\n    \u003e N.B. : Lonely cases where this event is not dispatched are when the request string is not a valid JSON-RPC request.\n    \u003e\n    \u003e It include :\n    \u003e\n    \u003e *   Parse error exception (malformed json string)\n    \u003e *   For simple request only, in case of Invalid request (not an object / missing required properties / ...).\n    \u003e\n    \u003e     *:warning: For batch request containing Invalid SubRequest, this event will still be dispatched*\n\n*   Either\n\n    *   `json_rpc_server_skd.on_method_success` / [`Action\\OnMethodSuccessEvent`](./src/Domain/Event/Action/OnMethodSuccessEvent.php)\n\n        Dispatched **only in case JSON-RPC method has been successfully executed**.\n\n    *   `json_rpc_server_skd.on_method_failure` / [`Action\\OnMethodFailureEvent`](./src/Domain/Event/Action/OnMethodFailureEvent.php)\n\n        Dispatched **only in case JSON-RPC method throw an exception during execution**.\n\n*   `json_rpc_server_skd.on_response_sending` / [`Acknowledge\\OnResponseSendingEvent`](./src/Domain/Event/Acknowledge/OnResponseSendingEvent.php)\n\n    Dispatched when a response has been successfully serialized by the endpoint and will be returned.\n\n##### Additional events\n\n###### Batch request\n\n*   `json_rpc_server_skd.on_batch_sub_request_processing` / [`Acknowledge\\OnBatchSubRequestProcessingEvent`](./src/Domain/Event/Acknowledge/OnBatchSubRequestProcessingEvent.php)\n\n    Dispatched before that a sub request will be processed.\n\n*   `json_rpc_server_skd.on_batch_sub_request_processed` / [`Acknowledge\\OnBatchSubRequestProcessedEvent`](./src/Domain/Event/Acknowledge/OnBatchSubRequestProcessedEvent.php)\n\n    Dispatched after that a sub request has been processed (regardless of the success or failure of the sub request method execution).\n\n###### Exception\n\n`json_rpc_server_skd.on_exception` / [`Action\\OnExceptionEvent`](./src/Domain/Event/Action/OnExceptionEvent.php)\n\nDispatched when an exception occurred during sdk execution\n\n##### Action vs Acknowledge events\n\n###### Acknowledge\n\nThey have only an acknowledge purpose.\n\nThey are grouped under `Yoanm\\JsonRpcServer\\Domain\\Event\\Acknowledge` namespace.\n\n###### Action\n\nThey allow you to override stuffs.\n\nThey are grouped under `Yoanm\\JsonRpcServer\\Domain\\Event\\Action` namespace.\n\nHere, the list :\n\n*   [`Action\\OnMethodSuccessEvent`](./src/Domain/Event/Action/OnMethodSuccessEvent.php) allow you to update/change the result of the method.\n*   [`Action\\OnMethodFailureEvent`](./src/Domain/Event/Action/OnMethodFailureEvent.php) allow you to update/change the exception thrown by the method.\n*   [`Action\\OnExceptionEvent`](./src/Domain/Event/Action/OnExceptionEvent.php) allow you to update/change the exception thrown.\n\n### Params validation example\n\n*You can use this [JSON-RPC params symfony validator](https://github.com/yoanm/php-jsonrpc-params-symfony-validator-sdk) as example*\n\nTo validate params for a given method, do the following :\n\n```php\nuse Yoanm\\JsonRpcServer\\Domain\\JsonRpcMethodInterface;\nuse Yoanm\\JsonRpcServer\\Domain\\JsonRpcMethodParamsValidatorInterface;\nuse Yoanm\\JsonRpcServer\\Domain\\Model\\JsonRpcRequest;\n\n$validator = new class implements JsonRpcMethodParamsValidatorInterface\n{\n    public function validate(JsonRpcRequest $jsonRpcRequest, JsonRpcMethodInterface $method) : array\n    {\n        if (!(/** Skip unexpected method */)) {\n            return [];\n        }\n\n        // Create your violations based on what you want\n        $paramList = $jsonRpcRequest-\u003egetParamList();\n        $violation = \"???\";\n\n        return [$violation];\n    }\n};\n\n$requestHandler-\u003esetMethodParamsValidator($validator);\n```\n\n## Contributing\n\nSee [contributing note](./CONTRIBUTING.md)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyoanm%2Fphp-jsonrpc-server-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyoanm%2Fphp-jsonrpc-server-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyoanm%2Fphp-jsonrpc-server-sdk/lists"}