Skip to content

Commit

Permalink
Encode serialized data to protect them from corruption (when your DB …
Browse files Browse the repository at this point in the history
…is not in UTF-8). Closes #1.
  • Loading branch information
baibaratsky committed Jul 22, 2015
1 parent f7a0ab6 commit c3bf33b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
],
];
}
Expand Down
15 changes: 15 additions & 0 deletions SerializedAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 {
Expand All @@ -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);
Expand Down

0 comments on commit c3bf33b

Please sign in to comment.