Transform PHP string

Viewed 95

This is the response payload from the REST interface: ".my-test-class {\n\tbackground-color: blue;\n\tcolor: white;\n}"

I would like this to be:

.my-test-class {
    background-color: blue;
    color: white;
}

Without the double quotes and without the escape characters.. something like this.. just plain CSS.. and I would like to transform this on the server-side.

The method behind the GET does this:

public function get_custom_css()
{
  $custom_css = wp_get_custom_css();

  $response = new WP_HTTP_Response($custom_css, 200, [
    "Content-Type" => "text/css; charset=UTF-8"
  ]);

  return rest_ensure_response($response);
}

Doing a $custom_css = trim($custom_css, '"'); to get rid of the double quotes did not work as the first character is the dot ($custom_css[0] == '.'). The double quotes seem to be applied later.

I receive the response via Angular like this:

this.httpClient.get('http://my.domain.com/wordpress/?rest_route=/custom/css', {
  responseType: 'text'
})
  .subscribe((css: string): void => {
    const styleElement: HTMLStyleElement = document.createElement<'style'>('style');

    const textNode: Text = document.createTextNode(css);
    styleElement.appendChild(textNode);

    document.head.appendChild(styleElement);
  });

And the result is this:

<style>".my-test-class {\n\tbackground-color: blue;\n\tcolor: white;\n}"</style>

Which of course is not valid CSS and therefore not applied correctly.

Update (2020-12-22)

As suggested in @imvain2s answer, I decided to omit new line and tab characters. I see no reason in keeping them in the final CSS. So I am now using this to remove the escape sequences:

$custom_css = preg_replace('/[\r\n\t]+/', '', $custom_css);

As it is done in line 5403 in the _sanitize_text_fields function (link)

The result is now:

<style>".my-test-class {background-color: blue;color: white;}"</style>

It still has these double quotes and my guess is that WordPress adds them when the response is send back.

I found other articles and questions speaking about "magic quotes" (see here), but I am not yet sure if these are related.

1 Answers

If I'm understanding the function correctly, you should be able to apply the CSS on the response.

Also, since new lines and tabs aren't needed in actual CSS, I just removed the string versions of them.

    public function get_custom_css()
    {
      $custom_css = wp_get_custom_css();
    
      $response = new WP_HTTP_Response($custom_css, 200, [
        "Content-Type" => "text/css; charset=UTF-8"
      ]);
      
    $response = rest_ensure_response($response);
    
    $response = trim($response, '"');
    $response = str_replace("\\n","",$response);
    $response = str_replace("\\t","",$response);

/*
  or to keep the new lines and tabs
    $response = str_replace("\\n","\n",$response);
    $response = str_replace("\\t","\t",$response);
*/
    
      return $response;
    }
Related