Last active
December 9, 2021 16:26
-
-
Save pschultz/6554265 to your computer and use it in GitHub Desktop.
Guzzle plugin to force the response charset. Useful ~if~ when webservers lie to you again.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Guzzle\Common\Event; | |
use Guzzle\Http\Message\Header; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
class ForceCharsetPlugin implements EventSubscriberInterface | |
{ | |
private $forcedCharset = 'utf8'; | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
'request.complete' => 'onRequestComplete' | |
); | |
} | |
public function setForcedCharset($charset) | |
{ | |
$this->forcedCharset = $charset; | |
return $this; | |
} | |
public function getForcedCharset() | |
{ | |
return $this->forcedCharset; | |
} | |
public function onRequestComplete(Event $event) | |
{ | |
$response = $event['response']; | |
$header = $response->getHeader('content-type'); | |
$modified = new Header( | |
$header->getName(), | |
array_map(array($this, 'modifyParams'), $header->parseParams()), | |
$header->getGlue() | |
); | |
$response->setHeader('content-type', $modified); | |
} | |
private function modifyParams(array $headerParams) | |
{ | |
$headerParams['charset'] = $this->getForcedCharset(); | |
return urldecode(http_build_query($headerParams, null, ';')); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$plugin = new ForceCharsetPlugin(); | |
$plugin->setForcedCharset('utf8'); | |
// Guzzle only | |
$guzzleClient->addSubscriber($plugin); | |
// With Goutte | |
$goutteClient->getClient()->addSubscriber($plugin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment