diff --git a/README.md b/README.md index fc3511e..9db93f6 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ To attach the behavior put the following code in your model: // Define the attributes you want to be serialized 'attributes' => ['serializedData', 'moreSerializedData'], + + // Enable this option if your DB is not in UTF-8 + // (more info at http://www.jackreichert.com/2014/02/02/handling-a-php-unserialize-offset-error/) + // 'encode' => true, ], ]; } diff --git a/SerializedAttributes.php b/SerializedAttributes.php index bbb30ae..7afd7ad 100644 --- a/SerializedAttributes.php +++ b/SerializedAttributes.php @@ -13,8 +13,17 @@ */ class SerializedAttributes extends Behavior { + /** + * @var string[] Attributes you want to be serialized + */ public $attributes = []; + /** + * @var bool Encode serialized data to protect them from corruption (when your DB is not in UTF-8) + * @see http://www.jackreichert.com/2014/02/02/handling-a-php-unserialize-offset-error/ + */ + public $encode = false; + private $oldAttributes = []; public function events() @@ -36,6 +45,9 @@ public function serializeAttributes() if (is_array($this->owner->$attribute) && count($this->owner->$attribute) > 0) { $this->owner->$attribute = serialize($this->owner->$attribute); + if ($this->encode) { + $this->owner->$attribute = base64_encode($this->owner->$attribute); + } } elseif (empty($this->owner->$attribute)) { $this->owner->$attribute = null; } else { @@ -53,6 +65,9 @@ public function deserializeAttributes() $this->owner->setAttribute($attribute, []); $this->owner->setOldAttribute($attribute, []); } elseif (is_scalar($this->owner->$attribute)) { + if ($this->encode) { + $this->owner->$attribute = base64_decode($this->owner->$attribute); + } $value = @unserialize($this->owner->$attribute); if ($value !== false) { $this->owner->setAttribute($attribute, $value);