Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Last active August 6, 2021 20:01
Show Gist options
  • Save kmuenkel/c02828ea40ad2202e2b45731a26ab64a to your computer and use it in GitHub Desktop.
Save kmuenkel/c02828ea40ad2202e2b45731a26ab64a to your computer and use it in GitHub Desktop.
Correct for non-UTF-8 characters in response arrays prior to JSON conversion
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Overrides\Illuminate\Routing\ResponseFactory;
use Illuminate\Contracts\View\Factory as ViewFactoryContract;
use Illuminate\Contracts\Routing\ResponseFactory as ResponseFactoryContract;
/**
* Class AppServiceProvider
* @package App\Providers
*/
class AppServiceProvider extends ServiceProvider
public function register()
{
$this->app->singleton(ResponseFactoryContract::class, function ($app) {
return new ResponseFactory($app[ViewFactoryContract::class], $app['redirect']);
});
}
}
<?php
namespace App\Overrides\Illuminate\Routing;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Routing\ResponseFactory as BaseResponseFactory;
class ResponseFactory extends BaseResponseFactory
{
/**
* @inheritDoc
*/
public function make($content = '', $status = 200, array $headers = [])
{
$content = ($self = function ($element) use (&$self) {
$element = $element instanceof Arrayable ? $element->toArray() : $element;
$element = is_array($element) ? array_map($self, $element) : $element;
return is_string($element) ? utf8_encode($element) :$element;
})($content);
return parent::make($content, $status, $headers);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment