Enable UTF8 encoding to/from as well in messages

This commit is contained in:
Deon George
2021-12-01 22:45:51 +11:00
parent f1780e61ea
commit 3a1c6d55c6
6 changed files with 51 additions and 33 deletions

View File

@@ -5,6 +5,8 @@
*/
namespace App\Traits;
use Illuminate\Support\Arr;
trait EncodeUTF8
{
private function decode(array $values): void
@@ -14,28 +16,30 @@ trait EncodeUTF8
$class = get_class($this);
foreach ($properties as $property) {
if ($property->isStatic()) {
if ($property->isStatic())
continue;
}
$name = $property->getName();
$decode = in_array($name,self::cast_utf8);
if ($property->isPrivate()) {
if ($property->isPrivate())
$name = "\0{$class}\0{$name}";
} elseif ($property->isProtected()) {
elseif ($property->isProtected())
$name = "\0*\0{$name}";
}
if (! array_key_exists($name,$values)) {
if (! array_key_exists($name,$values))
continue;
}
$property->setAccessible(true);
$property->setValue(
$this,$decode ? utf8_decode($values[$name]) : $values[$name]
);
try {
$property->setValue(
$this,$decode ? utf8_decode($values[$name]) : $values[$name]
);
} catch (\Exception $e) {
dd(['e'=>$e->getMessage(),'name'=>$name,'values'=>$values[$name],'decode'=>$decode]);
}
}
}
@@ -49,34 +53,44 @@ trait EncodeUTF8
foreach ($properties as $property) {
// Dont serialize the validation error
if ($property->name == 'errors')
if (($property->name == 'errors') || $property->isStatic())
continue;
if ($property->isStatic()) {
continue;
}
$property->setAccessible(true);
if (! $property->isInitialized($this)) {
if (! $property->isInitialized($this))
continue;
}
$name = $property->getName();
$encode = in_array($name,self::cast_utf8);
if ($property->isPrivate()) {
if ($property->isPrivate())
$name = "\0{$class}\0{$name}";
} elseif ($property->isProtected()) {
elseif ($property->isProtected())
$name = "\0*\0{$name}";
}
$property->setAccessible(true);
$value = $property->getValue($this);
$values[$name] = $encode ? utf8_encode($value) : $value;
}
return $values;
}
public function getAttribute($key)
{
static $encoded = [];
if (in_array($key,self::cast_utf8) && Arr::get($this->attributes,$key) && (! Arr::get($encoded,$key))) {
$this->attributes[$key] = utf8_decode($this->attributes[$key]);
$encoded[$key] = TRUE;
}
return parent::getAttribute($key);
}
public function setAttribute($key,$value)
{
return parent::setAttribute($key,in_array($key,self::cast_utf8) ? utf8_encode($value) : $value);
}
}