Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Jsonrpc Bundle Laravel Package

agentsib/jsonrpc-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require agentsib/jsonrpc-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Agentsib\JsonRpcBundle\AgentsibJsonRpcBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration: Edit config/packages/agentsib_json_rpc.yaml (auto-generated):

    agentsib_json_rpc:
        enabled: true
        routes:
            prefix: '/api/jsonrpc'
    
  3. First Use Case: Create a controller to expose a JSON-RPC endpoint:

    use Agentsib\JsonRpcBundle\Controller\JsonRpcController;
    
    class MyJsonRpcController extends JsonRpcController
    {
        public function myMethodAction($param1, $param2 = null)
        {
            return ['result' => $param1 . ($param2 ?: '')];
        }
    }
    

    Register the route in config/routes.yaml:

    agentsib_json_rpc:
        resource: "@AgentsibJsonRpcBundle/Resources/config/routing.yml"
        prefix: /api
    
  4. Testing: Send a POST request to /api/jsonrpc with a payload:

    {
        "jsonrpc": "2.0",
        "method": "myMethod",
        "params": ["Hello"],
        "id": 1
    }
    

Implementation Patterns

Controller Integration

  • Extend JsonRpcController for all JSON-RPC endpoints.

  • Method Naming:

    • Action methods must end with Action (e.g., getUserAction).
    • Public methods are automatically exposed as JSON-RPC endpoints.
    • Use underscores for readability (e.g., get_user_data_action).
  • Parameter Handling:

    public function calculateAction($a, $b = null, array $options = [])
    {
        // $options will be parsed from JSON-RPC "params" array
    }
    

Routing

  • Prefix Configuration: Override the default /api/jsonrpc prefix in config/packages/agentsib_json_rpc.yaml:

    agentsib_json_rpc:
        routes:
            prefix: '/custom/rpc'
    
  • Custom Routes: Extend the bundle’s routing file (Resources/config/routing.yml) or override it entirely:

    my_custom_rpc:
        path: /rpc/v1
        methods: [POST]
        defaults: { _controller: 'AgentsibJsonRpcBundle:Default:jsonRpc' }
    

Authentication/Authorization

  • Symfony Security Integration: Use Symfony’s built-in security system (e.g., @IsGranted("ROLE_ADMIN")) in controller methods. Example:

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
    
    /**
     * @Security("is_granted('ROLE_ADMIN')")
     */
    public function adminMethodAction()
    {
        return ['data' => 'secret'];
    }
    
  • Custom Auth Middleware: Override the bundle’s JsonRpcListener to add custom logic:

    // src/EventListener/CustomJsonRpcListener.php
    namespace App\EventListener;
    
    use Agentsib\JsonRpcBundle\Event\JsonRpcEvent;
    use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
    
    class CustomJsonRpcListener
    {
        public function onJsonRpc(FilterControllerEvent $event)
        {
            $request = $event->getRequest();
            if (!$request->headers->has('X-API-KEY')) {
                throw new \RuntimeException('Invalid API key');
            }
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\CustomJsonRpcListener:
            tags:
                - { name: kernel.event_listener, event: jsonrpc.on_request, method: onJsonRpc }
    

Error Handling

  • Custom Error Responses: Throw exceptions with custom error codes:

    throw new \RuntimeException('Invalid input', 40001);
    

    The bundle will convert this to a JSON-RPC error response:

    {
        "jsonrpc": "2.0",
        "error": {
            "code": 40001,
            "message": "Invalid input"
        },
        "id": 1
    }
    
  • Global Error Mapping: Override the error mapper in services.yaml:

    services:
        agentsib_json_rpc.error_mapper:
            class: App\Service\CustomErrorMapper
            arguments: ['@agentsib_json_rpc.error_mapper.inner']
    

Notifications (Non-Result Calls)

  • Fire-and-Forget: Use null as the id in the request to indicate a notification:
    {
        "jsonrpc": "2.0",
        "method": "logEvent",
        "params": {"event": "user_login"},
        "id": null
    }
    
    Handle in controller:
    public function logEventAction($data)
    {
        // No return value expected
        file_put_contents('log.txt', json_encode($data));
    }
    

Gotchas and Tips

Configuration Quirks

  • Auto-Generated Config: The bundle generates config/packages/agentsib_json_rpc.yaml on first install. Always check for overrides here before debugging.

  • Route Overrides: If routes aren’t working, ensure:

    1. The bundle is enabled in config/bundles.php.
    2. The routing.yml file exists in Resources/config/ (create if missing).
    3. No conflicting routes exist in config/routes.yaml.

Debugging

  • Request Dumping: Enable Symfony’s profiler (APP_DEBUG=true) to inspect incoming JSON-RPC requests in the toolbar.

  • Common Issues:

    • Method Not Found: Ensure the controller method ends with Action and is public.
    • Parameter Parsing: Complex objects (e.g., arrays) must be JSON-serializable. Use json_decode($request->getContent(), true) for manual parsing if needed.
    • CORS: Add CORS headers manually if needed (the bundle doesn’t handle CORS by default).

Performance Tips

  • Batch Processing: For high-throughput APIs, consider batching multiple JSON-RPC calls into a single request:
    {
        "jsonrpc": "2.0",
        "method": "batchMethod",
        "params": {
            "calls": [
                {"method": "method1", "params": [1]},
                {"method": "method2", "params": [2]}
            ]
        },
        "id": 1
    }
    
    Implement in controller:
    public function batchMethodAction($data)
    {
        $results = [];
        foreach ($data['calls'] as $call) {
            $results[$call['method']] = $this->{$call['method']}(...$call['params']);
        }
        return $results;
    }
    

Extension Points

  • Custom Serializers: Override the serializer service to handle custom data types:

    services:
        agentsib_json_rpc.serializer:
            class: App\Serializer\CustomJsonRpcSerializer
            arguments: ['@jms_serializer']
    
  • Middleware: Add custom middleware to the JSON-RPC pipeline:

    services:
        app.json_rpc.middleware:
            class: App\Middleware\JsonRpcMiddleware
            tags:
                - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
    
  • Logging: Enable request/response logging by extending the JsonRpcListener:

    public function onJsonRpc(FilterControllerEvent $event)
    {
        $request = $event->getRequest();
        $this->logger->info('JSON-RPC Request', [
            'method' => $request->request->get('method'),
            'params' => $request->request->get('params'),
        ]);
    }
    

Security

  • Input Validation: Always validate input in controller methods. Example with Symfony Validator:

    use Symfony\Component\Validator\Validator\ValidatorInterface;
    
    public function createUserAction($data, ValidatorInterface $validator)
    {
        $errors = $validator->validate($data);
        if (count($errors)) {
            throw new \InvalidArgumentException((string) $errors);
        }
        // Process data
    }
    
  • Rate Limiting: Combine with Symfony’s rate_limiter component or use a middleware like SymfonyRateLimiterBundle.

Migration Notes

  • Symfony 2 → 4/5:
    • Replace Symfony2 references with Symfony in service configurations.
    • Update route definitions to use YAML syntax compatible with Symfony 4/5.
    • Ensure autowiring is configured in config/services.yaml if using dependency injection.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky