Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active June 7, 2018 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m8rge/b18400fc8ded88776ff6 to your computer and use it in GitHub Desktop.
Save m8rge/b18400fc8ded88776ff6 to your computer and use it in GitHub Desktop.
SerializeAttributeBehavior
The MIT License (MIT)
Copyright (c) 2018 Andrew Putilov
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<?php
use yii\base\Behavior;
use yii\db\ActiveRecord;
class SerializeAttributeBehavior extends Behavior
{
/**
* @var string[]
*/
public $fields = [];
/**
* @inheritdoc
* @throws \RuntimeException
*/
public function attach($owner)
{
if (!($owner instanceof ActiveRecord)) {
throw new \RuntimeException('Owner must be instance of ' . ActiveRecord::class);
}
parent::attach($owner);
$this->ownerInit();
}
public function ownerInit(): void
{
foreach ($this->fields as $fieldName) {
if (!empty($this->owner->$fieldName) && is_array($this->owner->$fieldName)) {
$this->owner->$fieldName = new \ArrayObject($this->owner->$fieldName);
} else {
$this->owner->$fieldName = new \ArrayObject();
}
}
}
/**
* @inheritdoc
*/
public function events(): array
{
return [
ActiveRecord::EVENT_AFTER_FIND => 'unserialize',
ActiveRecord::EVENT_BEFORE_UPDATE => 'serialize',
ActiveRecord::EVENT_AFTER_UPDATE => 'unserialize',
ActiveRecord::EVENT_BEFORE_INSERT => 'serialize',
ActiveRecord::EVENT_AFTER_INSERT => 'unserialize',
];
}
/**
* @throws \RuntimeException
*/
public function prepareAndValidate(): void
{
foreach ($this->fields as $fieldName) {
if (is_array($this->owner->$fieldName)) {
$this->owner->$fieldName = new \ArrayObject($this->owner->$fieldName);
}
if (!$this->owner->$fieldName instanceof \ArrayObject) {
throw new SerializeException("$fieldName must be instance of \\ArrayObject");
}
}
}
public function serialize(): void
{
$this->prepareAndValidate();
foreach ($this->fields as $fieldName) {
$this->owner->$fieldName = json_encode($this->owner->$fieldName, JSON_UNESCAPED_UNICODE);
}
}
/**
* @throws SerializeException
*/
public function unserialize(): void
{
foreach ($this->fields as $fieldName) {
if ($this->owner->$fieldName === null) {
$this->owner->$fieldName = new \ArrayObject();
} elseif (is_string($this->owner->$fieldName)) {
$unserialized = json_decode($this->owner->$fieldName, true);
if (is_array($unserialized)) {
$this->owner->$fieldName = new \ArrayObject($unserialized);
} else {
throw new SerializeException("$fieldName not contains serialized array");
}
} else {
throw new SerializeException("$fieldName is not serialized string");
}
}
}
}
<?php
class SerializeException extends \RuntimeException
{
}
<?php
class History extends ActiveRecord
{
public function behaviors()
{
return [
[
'class' => SerializedFields::class,
'fields' => ['data'],
],
];
}
public function rules()
{
return [
['data', 'safe'],
];
}
}
// then you can
$history = new History([
'data' => [
'param1' => 'value1',
'param2' => 'value2',
],
]);
// or
$history->data['param1'] = 'value3';
// or even
unset($history->data['param2']);
// or
$history->data = ['param' => 'value'];
// then
$history->save();
// after save your attribute remains untouched
echo $history->data['param'];
// pass attribute to function with array param
array_keys((array)$history->data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment