jaxon-php / jaxon-core

The Jaxon core library
https://www.jaxon-php.org
BSD 3-Clause "New" or "Revised" License
65 stars 28 forks source link

Encode Response to UTF-8 before calling json_encode() #62

Closed Waxter81 closed 4 years ago

Waxter81 commented 4 years ago

I know this "issue" was discussed and closed in #18 , but I would like to reopen it to ask you (🙏) considering again the encoding of the Response to UTF-8 when the encoding is ISO-8859-1.

I have a lot of code migrated from XAJAX where it was not necessary to encode manually this response, and only a few lines extra in getOutput() in Response Class would be very helpful for me.

The behaviour If we forget to encode the Response is annoying because Jaxon request fails silently with no error message, even with debug enabled.

Something like this:

    public function getOutput()
    {
        $response = [
            'jxnobj' => [],
        ];

        if(($this->returnValue))
        {
            $response['jxnrv'] = $this->returnValue;
        }

        foreach($this->aCommands as $xCommand)
        {
            //25/12/2019 --> Encoding ISO-8859-1 to UTF8
            if($this->getOption('core.encoding') == 'ISO-8859-1') {
                $response['jxnobj'][] = $this->utf8_converter($xCommand);
            }
            else $response['jxnobj'][] = $xCommand;
        }

        return json_encode($response);
    }

With some utf converter function like this:

    private function utf8_converter($mArg)
    {
        if(is_array($mArg)) {
            array_walk_recursive($mArg, function(&$item, $key){
                if(!mb_detect_encoding($item, 'utf-8', true)){
                    $item = utf8_encode($item);
                }
            });
        }
        elseif(is_string($mArg))
        {
            $mArg = utf8_encode($mArg);
        }

        return $mArg;
    }

Thank you!

feuzeu commented 4 years ago

I've made a change to allow you to get the commands in a response. Check the 3.1.8 release.

You can therefore apply any change you need on the command before they are sent back to the browser.

jaxon()->callback()->after(function($target, $bEndRequest) {
    $response = jaxon()->di()->getResponseManager()->getResponse();
    $commands = $response->getCommands();
    // Apply any change you want on the commands
    foreach($commands as $command)
    {
        ....
    }
    // Reset the changed commands in the response
    $response->clearCommands()->appendResponse($commands);
});

I hope this will help in solving your issue.

Waxter81 commented 4 years ago

Thank you!!

But I think you have to change clearCommands() Method

$this->aCommands[] = []; to $this->aCommands = [];

Changing this, I solved my issue and all responses are previously converted to UTF-8.

PD: Do you have any link for donations?