We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

getJsonRawBody strange behavior

I have this injectable adding JSON body to the request:

    public function beforeDispatch(Event $event, Dispatcher $dispatcher): bool
    {
        var_dump($this->request->getRawBody());

        try {
            $this->request->body = $this->request->getJsonRawBody();
            // $this->request->body = json_decode($this->request->getRawBody());
        } catch (Exception $e) {
            echo $e->getMessage();
            $this->request->body = [];
        }

        var_dump($this->request->body);

        return true;
    }

Now, I'll use Paw to send an HTTP request with NO body and I get the expected response:

    /var/www/server/src/Plugins/Http/Http.php:35:string '' (length=0)
    json_decode error: Syntax error
    /var/www/server/src/Plugins/Http/Http.php:45:
    array (size=0)
      empty

However, when I add JSON to the request body, I'll get:

    /var/www/server/src/Plugins/Http/Http.php:35:string '{
      "email": "213"
    }' (length=20)
    json_decode error: Syntax error
    /var/www/server/src/Plugins/Http/Http.php:45:
    array (size=0)
      empty

This is strange because getRawBody() obtains the correct JSON body but getRawJsonBody() throws a Syntax error. What's even stranger is that, if I wait a few seconds and send the same request again, it will work properly with this response:

    /var/www/server/src/Plugins/Http/Http.php:35:string '{
      "email": "213"
    }' (length=20)
    /var/www/server/src/Plugins/Http/Http.php:45:
    array (size=1)
      'email' => string '213' (length=3)

If I replace getJsonRawBody() with PHP's json_decode, it will always work.

Any idea on what's going on?

If I replace getJsonRawBody() with PHP's json_decode, it will always work. Any idea on what's going on?

Phalcon Version 4? I think we have similar problems https://github.com/phalcon/cphalcon/issues/14936